Getting kline data from Binance REST API

The following code can be used to get kline data from Binance.

from datetime import datetime, timezone
import requests        # for making http requests to binance
import json            # for parsing what binance sends back to us
import pandas as pd    # for storing and manipulating the data we get back


root_url = 'https://api.binance.com/api/v1/klines'

coin = 'BTC'
symbol = coin + 'USDT'

interval = '1d'
limit = '1000'

date = datetime(2020, 9, 3, 0, 0, 0, tzinfo=timezone.utc)  
startDate = int(datetime.timestamp(date)) * 1000
startTime = str(startDate)
    
url = root_url + '?symbol=' + symbol + '&interval=' + interval + '&startTime=' + startTime + '&limit=' + limit
data = json.loads(requests.get(url).text)
df = pd.DataFrame(data)
df.columns = ['date', 'open', 'high', 'low', 'close', 'v', 'close_time', 'qav',
                'num_trades', 'taker_base_vol', 'taker_quote_vol', 'ignore']

df['date'] = [datetime.utcfromtimestamp(x/1000.0) for x in df.date]
   
df = df.set_index('date')

In the root URL data can replace api. Apparently v1, v2, v3 or v4 all function the same. If no start date is provided the most recent entries are sent. Default LIMIT is 500, 1000 is the maximum for one request. Consult the API docs for available frequencies.

Leave a Reply

Your email address will not be published. Required fields are marked *