How do I get multiple candlestick-streams from Binance Websocket in python? (different coins)

Viewed 1101

I'am trying to recieve the live data from multiple coins via the Binance Websocket.

Here is some sample data. My goal is to to something with the live data.

import json
import websocket

TRADE_SYMBOL = "ETHBUSD"
TRADE_SYMBOL2 = "BTCUSD"

message1 = ""
message2= ""


def on_open(ws):
    print("open")

def on_message(ws,message):
    json_message = json.loads(message) 
    candle = json_message['k']  
    print(message)

    is_candle_closed = candle['x']


def on_close():
    print("closed")
    

SOCK = "wss://stream.binance.com:9443/ws/{}@kline_1m".format(TRADE_SYMBOL.lower())   
SOCK2 = "wss://stream.binance.com:9443/ws/{}@kline_1m".format(TRADE_SYMBOL2.lower())   
ws = websocket.WebSocketApp(SOCK, on_open=on_open,on_close=on_close, on_message=on_message)
ws2 = websocket.WebSocketApp(SOCK2, on_open=on_open,on_close=on_close, on_message=on_message)

on_open(ws)
on_open(ws2)
on_message(ws,message1)
on_message(ws,message2)

ws.run_forever()
ws2.run_forever()

Thank you guys in advance! Stay safe

2 Answers

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()

The problem is When I use this, I get a 502 Bad Gateway message

Solved It seems I had space before and after =

Related