unicorn-binance-websocket-api

repository·master·Indexed 20 days ago

https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api

A Python SDK (v2.15.1) for interacting with Binance WebSocket APIs, including Spot, Futures, Margin, and Portfolio Margin. It supports various environments such as com, testnet, us, tr, and dex/chain. The library provides features for managing user data streams, filtering USDⓈ-M Futures events, and integrating market data with external systems like Apache Kafka or SQLite databases.

Tokens
29.3K
Snippets
94
Records
143
Agent score
69%

What's inside unicorn-binance-websocket-api

  1. Overview of UNICORN Binance WebSocket API

    master

    The UNICORN Binance WebSocket API is a high-performance Python package designed to interface with various Binance WebSocket endpoints. It provides a fully managed connection with 100% auto-reconnect capabilities and handles maintenance windows automatically.

    Key features include:

    • Broad Exchange Support: Supports Binance (com, US, TR), Binance Testnet, Margin, Isolated Margin, Futures (USD-M and COIN-M), European Options, and Portfolio Margin.
    • High Performance: Delivered as a compiled C extension (part of the UBS stack) for maximum speed and no memory leaks across Python versions 3.9 to 3.14.
    • Versatile Data Handling: Supports public streams (trade, kline, ticker, depth, etc.) and private !userData streams using api_key and api_secret.
    • Concurrency: Streams are processed using asyncio in separate threads, allowing you to consume data via callbacks or await without needing to manage complex asyncio logic yourself.
    • Request Support: Enables sending requests like create_order and cancel_open_orders directly over the WebSocket API.
  2. Explore the unicorn_binance_websocket_api package structure

    master

    The unicorn_binance_websocket_api package is organized into several submodules that handle different aspects of interacting with the Binance WebSocket and REST APIs:

    • manager: The core module for managing WebSocket connections and streams (e.g., BinanceWebSocketApiManager).
    • api: Contains API definitions, further divided into:
      • spot: For Spot market API interactions.
      • futures: For Futures market API interactions.
    • restclient: Handles REST API requests.
    • sockets: Manages low-level socket connections.
    • connection: Handles connection-related logic.
    • exceptions: Defines custom exception classes for error handling.
  3. Operational details for the Binance to Kafka example

    master

    When running the Binance to Kafka integration script, keep the following operational behaviors in mind:

    • Graceful Shutdown: The script is designed to handle KeyboardInterrupt (e.g., via Ctrl+C) or unexpected exceptions to ensure a clean exit.
    • Logging: The script uses logging to track operations and assist in troubleshooting. Logs are automatically saved to a file named after the script with a .log extension.
  4. Avoid mixing Futures WebSocket categories

    master

    As of 2026-04-23, Binance routes USDT-M Futures via three distinct base paths. You cannot mix these categories in a single create_stream call. If you attempt to do so, UBWA will raise a ValueError.

    The three categories are:

    • public: e.g., bookTicker, depth (top-levels and diff).
    • market: e.g., aggTrade, kline, ticker, miniTicker, forceOrder, markPrice.
    • private: userData via listenKey.

    Action: Open one create_stream() call per category.

  5. Subscribe to USDT-M Futures UserData events

    master

    When streaming USDT-M Futures !userData streams, you can filter which event types Binance pushes by using the events parameter. This accepts a single event name, an iterable of names, or None (which defaults to all documented events).

    Known event types (as of 2026-05):

    • ORDER_TRADE_UPDATE
    • ACCOUNT_UPDATE
    • MARGIN_CALL
    • TRADE_LITE
    • ACCOUNT_CONFIG_UPDATE
    • STRATEGY_UPDATE
    • GRID_UPDATE
    • CONDITIONAL_ORDER_TRIGGER_REJECT
    • ALGO_ORDER_UPDATE
    • listenKeyExpired

    Note: UBWA does not validate these names against an allow-list; typos will result in a stream with no matching events.

  6. Filter Binance USDⓈ-M Futures User Data Events

    master

    Binance introduced a new URL form (/private/ws?listenKey=...&events=...) that allows users to subscribe to specific event types. In unicorn-binance-websocket-api, you can use the events parameter when creating a stream to filter the incoming data.

    Key Considerations:

    • Default Behavior: If you do not provide an events argument, the library subscribes to all available event types (e.g., ORDER_TRADE_UPDATE, ACCOUNT_UPDATE, MARGIN_CALL, etc.), preserving the legacy behavior.
    • Filtered Streams: You can pass a list of specific event strings to the events parameter to receive only those types. This is useful for reducing bandwidth and processing load for execution bots.
    • Critical Event: Always include listenKeyExpired in your filtered event list. The library's internal reconnection logic depends on this event to manage the lifecycle of the stream.
    • Extensibility: Event names are not validated against a local allow-list, meaning any new event types introduced by Binance will be passed through by the library immediately.
  7. Use the Portfolio Margin exchange (`binance.com-portfolio_margin`)

    master

    The binance.com-portfolio_margin exchange is a specialized exchange entry in the library. It is currently limited in scope compared to standard futures exchanges.

    Supported Features

    • User-Data Streams only: You can use it to listen to user-data via the lifecycle of a listenKey (wss://fstream.binance.com/pm/ws/<listenKey>).
    • ListenKey Management: You can acquire, keep alive, and close listen keys using the library's PAPI (Python API) methods.

    Unsupported Features

    • No Market-Data: There are no public market-data endpoints available for this exchange.
    • No WS API: There is no websocket_api_base_uri support, meaning you cannot place orders or send requests via the WebSocket API for this exchange.

    Implementation Note

    This exchange is kept separate from BINANCE_FUTURES_EXCHANGES because it uses the legacy /ws/<listenKey> URL format, whereas standard futures exchanges use the newer /private/ws?listenKey=...&events=... format. Keeping it as a distinct exchange entry ensures routing remains a simple lookup rather than requiring complex conditional logic.

  8. Monitor stream state with stream_signals

    master

    The stream_signals feature allows you to monitor the real-time lifecycle and health of your WebSocket streams. This is critical for detecting when your system is "blind" (disconnected) so you can take defensive actions like closing positions or reloading data via REST.

    To use signals, pass a callback function to the BinanceWebSocketApiManager constructor using the process_stream_signals parameter. This callback will be triggered for various events including:

    • Stream connected
    • Received first data record
    • Disconnected and stopped
    • Stream cannot be restored

    The callback receives signal_type, stream_id, data_record, and error_msg.

    from unicorn_binance_websocket_api import BinanceWebSocketApiManager
    import time
    
    def process_stream_signals(signal_type=None, stream_id=None, data_record=None, error_msg=None):
        print(f"Received stream_signal for stream '{ubwa.get_stream_label(stream_id=stream_id)}': "
              f"{signal_type} - {stream_id} - {data_record} - {error_msg}")
    
    with BinanceWebSocketApiManager(process_stream_signals=process_stream_signals) as ubwa:
        ubwa.create_stream(channels="trade", markets="btcusdt", stream_label="TRADES")
        print(f"Waiting a few seconds and then stopping the stream ...")
        time.sleep(7)
  9. Understand and use `stream_signals` for stream monitoring

    master

    The stream_signals feature in the UNICORN Binance WebSocket API allows you to monitor the lifecycle of a WebSocket stream in real time. This is critical for detecting when your system is "blind" (disconnected) so you can take defensive actions like closing positions or reloading missing data via REST.

    stream_signals provide notifications for the following events:

    • Connected: The stream has successfully established a connection.
    • First Data Received: The stream has received its first actual data record.
    • Disconnected/Stopped: The stream has been disconnected or stopped.
    • Unrestorable: The stream cannot be automatically restored.

    In a typical implementation, you would pass a callback function to the stream creation method to handle these signals as they occur.

  10. Handle graceful shutdowns and logging in WebSocket scripts

    master

    When implementing WebSocket connections following these best practices:

    • Graceful Shutdown: Ensure your script is designed to handle KeyboardInterrupt (e.g., via Ctrl+C) or unexpected exceptions to close connections cleanly.
    • Logging: Use the logging module to track operations and troubleshoot issues. The example script automatically saves logs to a file named after the script with a .log extension.
  11. Create a multiplex websocket connection with a stream buffer

    master

    You can create a multiplexed connection to Binance and retrieve data by polling a stream_buffer. This method is useful if you want to manage the data retrieval loop manually. Use create_stream to initialize the connection and pop_stream_data_from_stream_buffer() to retrieve the oldest available data.

    from unicorn_binance_websocket_api import BinanceWebSocketApiManager
    
    ubwa = BinanceWebSocketApiManager(exchange="binance.com")
    ubwa.create_stream(channels=['trade', 'kline_1m'], markets=['btcusdt', 'bnbbtc', 'ethbtc'])
    
    while True:
        oldest_data_from_stream_buffer = ubwa.pop_stream_data_from_stream_buffer()
        if oldest_data_from_stream_buffer:
            print(oldest_data_from_stream_buffer)