0

I'm trying to connect to the Binance stream but when I run the code it outputs: "closed connection". What can I do to join the stream?

import websocket
import json

socket = 'wss://fstream.binance.com/ws'


def on_open(ws):
    subscribe_message = {"method": "SUBSCRIBE", "params":["btcusdt@trade"],"id": 1}
    ws.send(json.dumps(subscribe_message))


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


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

ws = websocket.WebSocketApp(socket, on_open=on_open, on_message=on_message, on_close=on_close)
ws.run_forever()

1 Answers1

0

Welcome to stackoverflow.

By looking at the wss://fstream.binance.com/ws, I can see that you are trying to connect to Futures API.

It clearly says in the API doc that any raw streams are accessed at /ws/<streamName>

you are not specifying the streamName in url that's why the error.

Just change the url to connect to correct stream & same code should work for you:

ws = websocket.WebSocketApp(socket + '/btcusdt@trade', on_open=on_open, on_message=on_message, on_close=on_close)

If it helps, please mark answer as accepted.

Tarique
  • 1,273
  • 9
  • 15