How to get ALL (or multiple) pair's historical klines from Binance API in ONE request?

Question:

I have a trading bot that trades multiple pairs (30-40). It uses the previous 5m candle for the price input. Therefore, I get 5m history for ALL pairs one by one. Currently, the full cycle takes about 10 minutes, so the 5m candles get updated once in 10m, which is no good.

Any ideas on how to speed things up?

Asked By: sellthehype

||

Answers:

I think the best option for you will be websocket connection. You cannot recieve kline data once per eg. 5 minutes, but you can recieve every change in candle like you see it in graph. Binance API provide only this, but in compound with websocket connection it will by realy fast, not 10 minutes.

After recieve data you only must to specify when candle was closed, you can do it from timestamps that are in json data (‘t’ and ‘T’). [documentation here]

You must install websockets library.

pip install websockets

And here is some sample code how it can work.

import asyncio
import websockets


async def candle_stick_data():
    url = "wss://stream.binance.com:9443/ws/" #steam address
    first_pair = 'bnbbtc@kline_1m' #first pair
    async with websockets.connect(url+first_pair) as sock:
        pairs = '{"method": "SUBSCRIBE", "params": ["xrpbtc@kline_1m","ethbtc@kline_1m" ],  "id": 1}' #other pairs

        await sock.send(pairs)
        print(f"> {pairs}")
        while True:
            resp = await sock.recv()
            print(f"< {resp}")

asyncio.get_event_loop().run_until_complete(candle_stick_data())

Output:

< {"e":"kline","E":1599828802835,"s":"XRPBTC","k":{"t":1599828780000,"T":1599828839999,"s":"XRPBTC","i":"1m","f":76140140,"L":76140145,"o":"0.00002346","c":"0.00002346","h":"0.00002346","l":"0.00002345","v":"700.00000000","n":6,"x":false,"q":"0.01641578","V":"78.00000000","Q":"0.00182988","B":"0"}}
< {"e":"kline","E":1599828804297,"s":"BNBBTC","k":{"t":1599828780000,"T":1599828839999,"s":"BNBBTC","i":"1m","f":87599856,"L":87599935,"o":"0.00229400","c":"0.00229610","h":"0.00229710","l":"0.00229400","v":"417.88000000","n":80,"x":false,"q":"0.95933156","V":"406.63000000","Q":"0.93351653","B":"0"}}
< {"e":"kline","E":1599828804853,"s":"ETHBTC","k":{"t":1599828780000,"T":1599828839999,"s":"ETHBTC","i":"1m","f":193235180,"L":193235214,"o":"0.03551300","c":"0.03551700","h":"0.03551800","l":"0.03551300","v":"21.52300000","n":35,"x":false,"q":"0.76437246","V":"11.53400000","Q":"0.40962829","B":"0"}}
< {"e":"kline","E":1599828806303,"s":"BNBBTC","k":{"t":1599828780000,"T":1599828839999,"s":"BNBBTC","i":"1m","f":87599856,"L":87599938,"o":"0.00229400","c":"0.00229620","h":"0.00229710","l":"0.00229400","v":"420.34000000","n":83,"x":false,"q":"0.96497998","V":"406.63000000","Q":"0.93351653","B":"0"}}
Answered By: rozumir

Just to follow up on that answer. You can see the candle closing as the websocket return data for every tick has a boolean property for if the candle is closed or not i.e. on a 5min timeframe if the candle closed on the 5min mark

Answered By: Adam Harte

Another follow up to the rozumir’s answer. If you use "async for" loop and "try-except" you can guarantee a reconnect after disconnect. Since binance disconnects websocket connections after 24 hours, this can be very handful. Sample code for websockets 10.4 is:

import asyncio
import websockets

async def candle_stick_data():

    url = "wss://stream.binance.com:9443/ws/" #steam address
    first_pair = 'btcusdt@kline_15m' #first pair

    async for sock in websockets.connect(url+first_pair):

        try:
            pairs = '{"method": "SUBSCRIBE", "params:["ethusdt@kline_15m","algousdt@kline_15m","nearusdt@kline_15m","atomusdt@kline_15m"],  "id": 1}' #other pairs
        
            await sock.send(pairs)
            print(f"> {pairs}")
            while True:
            
                resp = await sock.recv()                
                print(f"< {resp}")
                            
        except websockets.ConnectionClosed:
            continue

asyncio.run(candle_stick_data())
Answered By: hakan b