binance-futures-connector-python

repository·main·Indexed 22 days ago

https://github.com/binance/binance-futures-connector-python

A lightweight Python connector for the Binance Futures public API, supporting USDT-M and COIN-M futures via RESTful APIs and WebSockets. It features HMAC and RSA authentication, proxy support, and WebSocket stream clients. Note: This repository is deprecated; users are advised to use binance-connector-python.

Tokens
1.4K
Snippets
4
Records
7
Agent score
29%

What's inside binance-futures-connector-python

  1. Use exact parameter names for API methods

    main
    Unlike standard Python PEP8 conventions, this connector requires that optional parameters in method calls match the exact casing and naming used in the Binance API documentation. Using lowercase or underscores where the API expects CamelCase will result in the parameter being unrecognized.
  2. Authenticate with HMAC or RSA

    main

    The connector supports two authentication methods:

    1. HMAC Authentication: Pass key and secret to the client constructor.
    2. RSA Authentication: Pass the key (public key string), private_key (content of your .pem file), and an optional private_key_passphrase (if the key is encrypted).
    # HMAC Authentication
    client = Client(api_key, api_secret)
    print(client.account())
    
    # RSA Authentication
    key = ""
    with open("/Users/john/private_key.pem", "r") as f: # Location of private key file
        private_key = f.read()
    private_key_passphrase = "" # Optional: only used for encrypted RSA key
    
    client = Client(key=key, private_key=private_key, private_key_passphrase=private_key_passphrase)
    print(client.account())
  3. Use WebSocket Stream Client

    main

    Establish WebSocket connections for market or user data streams. You must provide an on_message callback function to handle incoming messages.

    Key Features:

    • Request ID: You can optionally pass an id to each request; otherwise, the library generates a random UUID.
    • Combined Streams: Set is_combined=True to append /stream/ to the baseURL instead of the default /ws/.
    • Proxy Support: Pass a proxies dictionary (e.g., {'http': 'http://user:pass@host:port'}) during initialization.
    • Heartbeat: The library automatically handles pong responses to server pings.
    import time
    from binance.websocket.um_futures.websocket_client import UMFuturesWebsocketClient
    
    def message_handler(_, message):
        print(message)
    
    # Initialize with proxy
    proxies = {'http': 'http://1.2.3.4:8080'}
    my_client = UMFuturesWebsocketClient(on_message=message_handler, proxies=proxies)
    
    # Subscribe with a custom request ID
    my_client.agg_trade(symbol="bnbusdt", id="my_request_id")
    
    time.sleep(5)
    my_client.stop()
  4. Use RESTful APIs for COIN-M Futures

    main

    Use the CMFutures class to interact with COIN-M Delivery APIs. You can perform public actions like getting server time or private actions like accessing account information and placing orders by providing your API credentials.

    Common methods include:

    • time(): Get server time.
    • account(): Get account information.
    • new_order(**params): Post a new order.
    from binance.cm_futures import CMFutures
    
    # Public API usage
    cm_futures_client = CMFutures()
    print(cm_futures_client.time())
    
    # Private API usage
    cm_futures_client = CMFutures(key='<api_key>', secret='<api_secret>')
    
    # Get account information
    print(cm_futures_client.account())
    
    # Post a new order
    params = {
        'symbol': 'BTCUSDT',
        'side': 'SELL',
        'type': 'LIMIT',
        'timeInForce': 'GTC',
        'quantity': 0.002,
        'price': 59808
    }
    
    response = cm_futures_client.new_order(**params)
    print(response)
  5. Configure Client parameters: timeout, proxy, and base_url

    main

    When initializing a client, you can customize several connection parameters:

    • base_url: The API endpoint. Defaults to fapi.binance.com for USDT-M and dapi.binance.com for COIN-M. It is recommended to provide this explicitly.
    • timeout: Number of seconds to wait for a server response. Defaults to None (no timeout).
    • proxies: A dictionary for proxy settings (e.g., {'https': 'http://1.2.3.4:8080'}).
    • show_limit_usage: Set to True to include weight usage in response metadata.