Search code examples
pythonbinancebinance-api-client

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.


Solution

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