Skip to content

Listen Key Service

Igor Sazonov edited this page Mar 9, 2026 · 1 revision

The ListenKeyService is a critical component for receiving private real-time data through WebSockets. This service is responsible for managing listen keys, which are required to authenticate and subscribe to private account data streams, such as balance and order updates.

Accessing the Service

To begin managing your listen keys, you must first access the ListenKeyService through your BingXClient instance:

from bingx import BingXClient

client = BingXClient(api_key="YOUR_API_KEY", api_secret="YOUR_API_SECRET")
listen_key_service = client.listen_key()

The Listen Key Lifecycle

Managing the lifecycle of a listen key is essential for maintaining a stable WebSocket connection. The process involves three main steps:

  1. Generate: Create a new listen key.
  2. Extend: Periodically extend the validity of the listen key to keep the connection alive.
  3. Delete: Delete the listen key when it is no longer needed.

Methods

The ListenKeyService provides the following methods to manage the listen key lifecycle:

Method Description
generate() Generates a new listen key. The key is valid for 60 minutes.
extend(listen_key) Extends the validity of a listen key. It is recommended to call this method every 30 minutes.
delete(listen_key) Deletes a listen key, invalidating it for future use.

Usage Example

The following example demonstrates the complete lifecycle of a listen key when using the AccountDataStream:

from bingx.websocket import AccountDataStream

# 1. Generate a new listen key
listen_key_response = client.listen_key().generate()
listen_key = listen_key_response["listenKey"]

# 2. Initialize and connect to the AccountDataStream
account_stream = AccountDataStream(listen_key)
account_stream.connect()

# ... (your logic for handling account updates)

# 3. Periodically extend the listen key to keep the connection alive
# This should be done within a loop or a scheduled job
client.listen_key().extend(listen_key)

# 4. When you are finished, delete the listen key and disconnect
client.listen_key().delete(listen_key)
account_stream.disconnect()

Clone this wiki locally