How to get USDT future data from Binance python API

Dr. Bankruptcy
2 min readApr 1, 2022

--

You need data for research and test trading strategy. Binance is a good source to have good data. Here we will show how to get data of all USDT pairs from Binance python API.

First you need the Binance API installed.

pip install python-binance

Then import the necessary libraries and list all the column names stated in the Binance documentation. If you haven any library missing, just install them by pip.

from binance.client import Client
from binance.enums import HistoricalKlinesType
from datetime import datetime
import pandas as pd
pd.set_option('display.max_rows', 500)
import os
import requests,json
api_key = ""
secret= ""
client = Client(api_key, secret)colnames = ['time','Open','High','Low','Close','Volume','Close time','Quote asset volume','Number of trades','Taker buy base asset volume','Taker buy quote asset volume','Ignore']

Next, we get all the pairs ending with ‘USDT’.

#get all usdt pairs
BASE_URL = 'https://api.binance.com'
resp = requests.get(BASE_URL+'/api/v1/ticker/allBookTickers')
ticker_list = json.loads(resp.content)
symbols=[ticker for ticker in ticker_list if str(ticker['symbol'][-4:])=='USDT']

Now we have a ticker_list containing all the pairs ending with ‘USDT’, we can call them one by one.

save_path = './1m_data' # you can choose you file name
interval = '1m' # it supports 1m, 1H,1D, etc..
start = '01/01/2021 00:00:00' #start date
end = '31/12/2021 23:59:59' #end date
for symbol in symbols:
print('getting ' + symbol)
try:
klines_generator = client.get_historical_klines_generator(
symbol=symbol,
interval=interval,
start_str=start,
end_str=end,
klines_type=HistoricalKlinesType.FUTURES
) #we will get the generator first
klines_list = list(klines_generator) # you can either save the generator directly or convert it to data
df = pd.DataFrame(klines_list, columns=colnames) #save as a pandas dataframe
df.to_csv(os.path.join(save_path, symbol + '_' + interval + '.csv'), index=False) #save the file
except:
pass

Now you have the data you need, let’s start testing your strategy!

--

--