Ad

Why Does Ws.run_forever() Return True Instead Of The Api Values In This Case?

I'm trying to get the klines value of BTC-USDT from binance but I can't seem to fetch the right values

def on_message(ws, message):
    print("received a message")
    print(json.loads(message))     

def on_close(ws):
    print("closed connection")        

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


ws = websocket.WebSocketApp('https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=1s', on_open=on_open,on_message=on_message, on_close=on_close)
ws.run_forever()

Why does ws.run_forever() return True instead of the values?

Ad

Answer

The websocket api base url is wss://stream.binance.com:9443, not the http/rest api url. That's why you didn't receive anything from websocket.

Also run_forever() will just block without return anything. The "value" you need will be given as a argument of on_message.

def on_message(ws, message):
     print("received a message:")
     print(json.loads(message))

def on_close(ws):
     print("closed connection")

def on_open(ws):
     print("opened")
    
    
ws = websocket.WebSocketApp('wss://stream.binance.com:9443/ws/[email protected]_1m', on_open=on_open,on_message=on_message, on_close=on_close)
# please check binance document to write the correct stream name
ws.run_forever()

Or, if you need some information not as a stream:

# REST API example

import httpx
resp = httpx.get('https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=1m&limit=1')
print(resp.json())
Ad
source: stackoverflow.com
Ad