How to save order book and trades data for crypto futures

To save data in text format for crypto futures order book and trades from binance we can use the following python snippet:
(if you are interested to have -10% on binance trading fees you can use the following code: WFH7DYED )

import os
import sys
import re
from binance.client import Client
binance = Client(<YOUR API KEY>,<YOUR API SECRET>)
from twisted.internet import task, reactor
from datetime import timezone, datetime

timeout = 60*1 # Sixty seconds
def get_valid_filename(s):
    s = str(s).strip().replace(' ', '_')
    return re.sub(r'(?u)[^-\w.]', '', s)

def doWork():
    print(datetime.now())
    for currency in ["ETHUSDT"]:#,"BTC/USDT"]:
        fname='F'+get_valid_filename(currency)+'_bapi_'
        print(binance.futures_time()['serverTime'],'|',int(datetime.now(tz=timezone.utc).timestamp() * 1000),'| ',binance.futures_aggregate_trades(symbol=currency,limit=limit,startTime=int(int(datetime.now(tz=timezone.utc).timestamp() * 1000)-timeout*1000)),'|',int(datetime.now(tz=timezone.utc).timestamp() * 1000),file=open(fname+"trades.txt", "a"))
        print(binance.futures_time()['serverTime'],'|',int(datetime.now(tz=timezone.utc).timestamp() * 1000),'| ',binance.futures_order_book(symbol=currency, limit=50),'|',int(datetime.now(tz=timezone.utc).timestamp() * 1000),file=open(fname+"orderbook.txt", "a")) #fetch_order_book

l = task.LoopingCall(doWork)
l.start(timeout) # call every sixty seconds

reactor.run()

This program will run loop to save the Ethereum perpetual futures data for trades and order book to files every minute.
We also log the times as the local time would be different from the binance server time.

Posted in crypto Tagged with: ,