Shady Alkhouri
Shady Alkhouri

Reputation: 43

Binance stream trade via websocket problem

I am getting no response from the Binance api when executing the following code, is there anything that I could have missed here? do I need to create an account in order to get stream data through the api?

import json
import websocket

socket='wss://stream.binance.com:9443'

def on_open(ws):
    print("opened")
    subscribe_message = {
        "method": "SUBSCRIBE",
        "params":
        [
         "btcusdt@trade",
         "btcusdt@depth"
         ],
         "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()

Upvotes: 4

Views: 20019

Answers (2)

xilopaint
xilopaint

Reputation: 745

In order to make your code work you just need to add /ws at the end of the websocket url:

socket = 'wss://stream.binance.com:9443/ws'

Upvotes: 6

Oliver
Oliver

Reputation: 115

What I can see is, that you are not using the path after the hostname and port!

See here what is missing: https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#general-wss-information

Raw streams are accessed at /ws/streamName>

Combined streams are accessed at /stream?streams=streamName1/streamName2/streamName3

If you want to subscribe to streams via websocket.send() then you have to create a combined stream first and then send the payload to subscribe the streams.

But you dont have to reinvent the wheel. There are different ready implementations for python.

I recommend you this lib I have written: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api

This will save you a lot of work :)

Best regards, Oliver

Upvotes: 0

Related Questions