7

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.

Cassano
  • 253
  • 5
  • 36

2 Answers2

1

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())
Bjorgum
  • 2,054
  • 2
  • 4
  • 11
  • This returns (prints) a dict, which is quite large. So where does one find a list of what the dict keys represent ? – D.L Nov 03 '22 at 14:00
  • Wondering the same thing, where are the message dict keys defined? – OpenCoderX Dec 18 '22 at 01:58
  • The dict keys are explained in Binance [documentation](https://binance-docs.github.io/apidocs/spot/en/#payload-account-update), for the different payload types – hmartos Feb 27 '23 at 17:42
0

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Vindictive
  • 311
  • 7
  • 19
  • Can you please provide me with your code? Mine doesn't work, it says:- Error Connection to remote host was lost. Error on_close() takes 1 positional argument but 3 were given – Cassano Mar 09 '22 at 13:14