Please can someone tell me if there is a way to get listenkey using the WebSocket-only method, and not through using Rest API then obtaining the listenkey method.
If it is possible, then any short working code including the correct URL would be appreciated.
If you wish to listen to your own trades as they happen, I’d recommend the new feature of WebSocket API: "userDataStream.subscribe" requests.
Connect to WebSocket API on wss://ws-api.binance.com/ws-api/v3
Authenticate via "session.logon"
Subscribe via "userDataStream.subscribe"
Now you will receive user data stream events over this connection (which you can also use to send orders).
As for listen keys, currently it is not possible to request a listen key via wss://stream.binance.com connection (where you connect to listen to the stream using the listen key).
If you wish to avoid having to do HTTP calls to REST API, you can use WebSocket API to create a listen key (via "userDataStream.start" method). However, that’s still two separate WebSocket connections:
wss://ws-api.binance.com/ws-api/v3 to create a listen key
wss://stream.binance.com to listen to events using the listen key
Thank you for your response and much appreciated, I will most like stick to the REST API method to obtain a listenkey and use the websocket from there on.
Is there any chance there’s an example code showing how to do this listenKey dance? I’m new to using the websockets with binance, and every piece of the documentation assumes I know the last 15 steps already at my fingertips, so just takes me to the 16th step.
Currently, I have this:
def _start_user_data_stream(self):
"""Start user data stream for trade WebSocket."""
if not self.trade_ws_connected:
logging.error("Trade WebSocket is not connected.")
return
request_id = str(uuid.uuid4())
params = {
'apiKey': self.api_key,
'timestamp': int(datetime.now().timestamp() * 1000)
}
params['signature'] = self._generate_signature(params)
request = {
"id": request_id,
"method": "userDataStream.start",
"params": params
}
try:
self.trade_ws.send(json.dumps(request))
logging.info("User data stream started.")
except Exception as e:
logging.error(f"Failed to start user data stream: {e}")
My trade_ws looks like this:
def connect_trade_ws(self):
"""Connect to the trade WebSocket."""
if not self.api_key or not self.api_secret:
logging.error(
"API key and secret are required for trade WebSocket.")
return
url = "wss://ws-fapi.binance.com/ws-fapi/v1"
self.trade_ws = websocket.WebSocketApp(
url,
on_open=self.on_trade_open,
on_message=self.on_trade_message,
on_error=self.on_trade_error,
on_close=self.on_trade_close,
)
self.trade_ws_thread = threading.Thread(
target=self.trade_ws.run_forever)
self.trade_ws_thread.daemon = True
self.trade_ws_thread.start()
logging.info("Trade WebSocket connection initiated.")
Where does the listenKey fit in all of this? Where do I pass it?