Cassano
Cassano

Reputation: 323

How to connect to User Data Stream Binance?

I need to listen to User Data Stream, whenever there's an Order Event - order execution, cancelation, and so on - I'd like to be able to listen to those events and create notifications.

So I got my "listenKey" and I'm not sure if it was done the right way but I executed this code and it gave me something like listenKey.

Code to get listenKey:

def get_listen_key_by_REST(binance_api_key):
    url = 'https://api.binance.com/api/v1/userDataStream'
    response = requests.post(url, headers={'X-MBX-APIKEY': binance_api_key}) 
    json = response.json()
    return json['listenKey']

print(get_listen_key_by_REST(API_KEY))

And the code to listen to User Data Stream - which doesn't work, I get no json response.

socket = f"wss://fstream-auth.binance.com/ws/btcusdt@markPrice?listenKey=<listenKeyhere>"

def on_message(ws, message):
    json_message = json.loads(message)
    print(json_message)

def on_close(ws):
    print(f"Connection Closed")
    # restart()

def on_error(ws, error):
    print(f"Error")
    print(error)

ws = websocket.WebSocketApp(socket, on_message=on_message, on_close=on_close, on_error=on_error)

I have read the docs to no avail. I'd appreciate it if someone could point me in the right direction.

Upvotes: 7

Views: 6733

Answers (2)

Bjorgum
Bjorgum

Reputation: 2310

You can create a basic async user socket connection from the docs here along with other useful info for the Binance API. Here is a simple example:

import asyncio
from binance import AsyncClient, BinanceSocketManager

async def main():
    client = await AsyncClient.create(api_key, api_secret, tld='us')
    bm = BinanceSocketManager(client)
    # start any sockets here, i.e a trade socket
    ts = bm.user_socket()
    # then start receiving messages
    async with ts as tscm:
        while True:
            res = await tscm.recv()
            print(res)
    await client.close_connection()

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

Upvotes: 1

Vindictive
Vindictive

Reputation: 321

I just figured this out myself and I was able to get mine to work so I'll try my best to guide you. I believe you're just missing this line of code after you create your WebSocket object:

ws.run_forever()

Some other reasons it might not be working; If you want to detect orders on your futures account then you need to use the futures endpoint. I think the one your using is for spot trading (Not sure).

url = 'https://fapi.binance.com'

and just in case it's not clear to you. You must replace:

<listenkeyhere>

in the socket url with your listen key, angle brackets, and all.

Upvotes: 0

Related Questions