[Python] How to connect to User Data Stream Binance?

Discussão em 'Python' iniciado por Stack, Maio 30, 2025.

  1. Stack

    Stack Membro Participativo

    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.

    Continue reading...

Compartilhe esta Página