python-binance

repository·master·Indexed 19 days ago

https://github.com/binance-exchange/python-binance

A Python library for interacting with the Binance exchange. It provides functionality to retrieve exchange information, fetch real-time and historical market data (including klines and aggregate trades), manage account balances, and create or cancel limit and market orders. Note: This library is being discontinued; developers are encouraged to migrate to the officially supported binance-connector-python library.

Tokens
12.6K
Snippets
58
Records
75
Agent score
65%

What's inside python-binance

  1. How BinanceSocketManager works

    master

    The BinanceSocketManager handles all websocket connections. You initialize it by passing an existing API client.

    Key behaviors:

    • Multiple Connections: You can open multiple socket connections through one manager.
    • Singleton Socket Types: Only one instance of a specific socket type per symbol is allowed (e.g., you cannot have two BNBBTC Depth sockets, but you can have one BNBBTC Depth and one BNBBTC Trade socket simultaneously).
    • Callbacks: Every socket requires a callback function that is executed whenever a message is received. Messages are provided as dictionary objects.
    • Automatic Reconnection: Websockets are configured to attempt reconnection with a maximum of 5 retries.
    • Lifecycle: You must start individual sockets before calling bm.start() to begin the manager's execution loop.
    from binance.websockets import BinanceSocketManager
    
    # Initialize manager with client
    bm = BinanceSocketManager(client)
    
    # 1. Define callback
    def process_message(msg):
        print(msg)
    
    # 2. Start specific sockets
    conn_key = bm.start_trade_socket('BNBBTC', process_message)
    
    # 3. Start the manager
    bm.start()
  2. Understand Binance API rate limits

    master

    Binance enforces rate limits on API endpoints. While limits can change, you should check the get_exchange_info() call for the most up-to-date information.

    Typical limits include:

    • 1200 requests per minute
    • 10 orders per second
    • 100,000 orders per 24hrs

    Note that some calls have a higher weight than others (e.g., calls returning information for all symbols).

  3. Handle Websocket errors and reconnections

    master

    If a websocket disconnects and fails to reconnect after the maximum number of retries, the manager sends an error message to your callback function.

    To prevent your application from crashing or processing invalid data, check for the 'e': 'error' key in the message dictionary.

    def process_message(msg):
        if msg['e'] == 'error':
            # Handle error (e.g., close and restart the socket)
            print(f"Error: {msg['m']}")
        else:
            # Process message normally
            print(f"Message type: {msg['e']}")
  4. Use DepthCacheManager to follow depth updates

    master

    Use the DepthCacheManager to track real-time order book updates for a specific symbol. You must provide an API client, the symbol name (e.g., 'BNBBTC'), and an optional callback function.

    The callback function receives a DepthCache object. This object provides access to pre-sorted lists of bids and asks. If you are using the same callback for multiple managers, you can identify the symbol by accessing the symbol attribute on the DepthCache object.

    from binance.depthcache import DepthCacheManager
    
    # Initialize the manager with a client, symbol, and callback
    dcm = DepthCacheManager(client, 'BNBBTC', callback=process_depth)
  5. Format numbers for Binance precision requirements

    master

    Binance enforces strict rules regarding minimum price, quantity, and total order value for symbol pairs. To avoid validation errors, you should format your numeric values to the required precision using a formatting snippet like the one below.

    amount = 0.000234234
    precision = 5
    amt_str = "{:0.0{}f}".format(amount, precision)
  6. Iterate over Aggregate Trades

    master

    The aggregate_trade_iter method provides a way to stream or iterate through aggregate trade data from a specific point in time until the present.

    Usage Patterns:

    • Initial Cache Sync: Pass start_str (a UTC date string or millisecond timestamp) to fetch all trades from that time forward.
    • Real-time Updates: Pass last_id (the AGG_ID from the last received trade) to fetch only new trades occurring after that ID.

    Note: You cannot specify both start_str and last_id simultaneously.

    Data Format: Each yielded object follows the structure of Client.aggregate_trades(), containing keys like a (aggId), p (price), q (quantity), T (timestamp), etc.

    # Example: Iterating from a specific time
    for trade in client.aggregate_trade_iter(symbol='ETHBTC', start_str='1 hour ago UTC'):
        print(f"Price: {trade['p']}, Qty: {trade['q']}")
  7. Configure DepthCacheManager refresh intervals

    master

    By default, the DepthCacheManager performs a full order book fetch via a REST request every 30 minutes to refresh the cache. You can customize this behavior using the refresh_interval parameter:

    • Custom interval: Pass the number of seconds (e.g., 60*60 for 1 hour).
    • Disable refreshing: Pass 0 or None to prevent periodic REST refreshes. The websocket connection will remain open to receive updates, but no full order book re-sync will occur.
    # 1 hour interval refresh
    dcm = DepthCacheManager(client, 'BNBBTC', callback=process_depth, refresh_interval=60*60)
    
    # disable refreshing
    dcm = DepthCacheManager(client, 'BNBBTC', callback=process_depth, refresh_interval=0)