How do I get multiple candlestick-streams from Binance Websocket in python? (different coins)
Solution 1:
You can get multiple cryptocurrency pairs and, if you want, different time frames on the same Binance websocket stream (see the url in the code bellow). If you still need to have several simultaneous websockets, read the library documentation: https://websocket-client.readthedocs.io/en/latest/examples.html#dispatching-multiple-websocketapps
In the code I have corrected the arguments of the callbacks, the url of the stream, and some details of the information of the candlestick data structure . I've tested it in google colabs and it works. (previously run !pip3 install websocket-client )
import json
import websocket
# websocket.enableTrace(True) #uncomment for debug
def on_open(ws):
print("open")
def on_message(ws,message):
json_message = json.loads(message)
candle = json_message['data']['k']
print(message)
is_candle_closed = candle['x']
if is_candle_closed:
print(json.dumps(candle, indent=2))
def on_close(ws, close_status_code, close_msg):
print("closed")
SOCK = "wss://stream.binance.com:9443/stream?streams=ethusdt@kline_1m/btcusdt@kline_1m/bnbusdt@kline_1m/ethbtc@kline_1m"
ws = websocket.WebSocketApp(SOCK, on_open=on_open,on_close=on_close, on_message=on_message)
ws.run_forever()