Skip to content

WebSockets

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

The BingX Python SDK provides a robust WebSocket interface for receiving real-time market and account data. This is essential for building high-frequency trading bots and other applications that require low-latency data feeds.

Market Data Stream

The MarketDataStream allows you to subscribe to public market data channels, such as trades, klines, and order book depth.

Usage Example

The following example demonstrates how to connect to the market data stream and subscribe to the trade channel for the BTC-USDT pair:

from bingx.websocket import MarketDataStream

# Initialize the stream
market_stream = MarketDataStream()
market_stream.connect()

# Define a message handler
def handle_message(data):
    print(f"Received data: {data}")

# Set the handler
market_stream.on_message(handle_message)

# Subscribe to the trade channel
market_stream.subscribe_trade("BTC-USDT")

# Start listening (this is a blocking call)
market_stream.listen()

Available Subscriptions

The MarketDataStream provides the following subscription methods:

Method Description
subscribe_trade(symbol) Subscribes to the trade stream for a specific symbol.
subscribe_kline(symbol, interval) Subscribes to the kline/candlestick stream for a specific symbol and interval.
subscribe_depth(symbol, limit) Subscribes to the order book depth stream.
subscribe_ticker(symbol) Subscribes to the 24-hour ticker stream.
subscribe_book_ticker(symbol) Subscribes to the best bid/ask stream.

Account Data Stream

The AccountDataStream provides access to private account data, such as balance, position, and order updates. To use this stream, you must first obtain a listenKey from the ListenKeyService.

Usage Example

The following example demonstrates how to connect to the account data stream and listen for balance, position, and order updates:

from bingx.websocket import AccountDataStream

# 1. Get a listenKey from the ListenKeyService
listen_key = client.listen_key().generate()['listenKey']

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

# 3. Define handlers for different event types
def handle_balance_update(data):
    print(f"Balance update: {data}")

def handle_position_update(data):
    print(f"Position update: {data}")

def handle_order_update(data):
    print(f"Order update: {data}")

# 4. Set the handlers
account_stream.on_balance_update(handle_balance_update)
account_stream.on_position_update(handle_position_update)
account_stream.on_order_update(handle_order_update)

# 5. Start listening
account_stream.listen()

Event Handlers

The AccountDataStream provides the following event handlers:

Method Description
on_balance_update(handler) Sets a handler for balance updates.
on_position_update(handler) Sets a handler for position updates.
on_order_update(handler) Sets a handler for order updates.

Clone this wiki locally