Binance Python Connector

repository·master·Indexed 25 days ago

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

A collection of auto-generated Python SDKs for various Binance APIs, including Spot, Futures, and Margin trading. It provides modular, service-specific packages such as binance-sdk-algo, binance-sdk-alpha, binance-sdk-c2c, binance-sdk-convert, binance-sdk-copy-trading, and binance-sdk-crypto-loan. These SDKs require Python 3.10 or later and utilize binance-common for shared types and utilities.

Tokens
176.4K
Snippets
353
Records
512
Agent score
84%

What's inside binance-connector-python

  1. Overview of Binance Python SPOT SDK features

    master

    The Binance Python SPOT SDK allows developers to interact programmatically with the Binance SPOT trading platform. It provides access to three main interaction methods:

    • REST API: For standard request-response interactions via /api/* endpoints.
    • Websocket API: For real-time data streaming and request-response communication.
    • Websocket Streams: For continuous real-time data feeds.

    The library includes test cases and examples to assist with onboarding.

  2. Overview of Binance USDS-M Futures SDK capabilities

    master

    The Binance Python Derivatives Trading (USDS-M Futures) SDK provides programmatic access to Binance's USDS-M Futures API through three primary interfaces:

    1. REST API: For standard request-response interactions using /fapi/* endpoints.
    2. WebSocket API: For real-time data streaming and request-response communication over WebSockets.
    3. WebSocket Streams: For subscribing to real-time market data streams.

    The SDK includes test cases and examples to assist with onboarding.

  3. List of available Binance Python SDKs

    master

    The Binance Python Connectors repository provides modular SDKs for various Binance services. Each is available as a separate PyPI package:

    • binance-sdk-algo: Algo Trading
    • binance-sdk-alpha: Alpha
    • binance-sdk-c2c: C2C
    • binance-sdk-convert: Convert
    • binance-sdk-copy-trading: Copy Trading
    • binance-sdk-crypto-loan: Crypto Loan
    • binance-sdk-derivatives-trading-coin-futures: Coin Futures Trading
    • binance-sdk-derivatives-trading-options: Options Trading
    • binance-sdk-derivatives-trading-portfolio-margin: Portfolio Margin Futures Trading
    • binance-sdk-derivatives-trading-portfolio-margin-pro: Portfolio Margin Pro Trading
    • binance-sdk-derivatives-trading-usds-futures: USDs Futures Trading
    • binance-sdk-dual-investment: Dual Investment
    • binance-sdk-fiat: Fiat
    • binance-sdk-gift-card: Gift Card
    • binance-sdk-margin-trading: Margin Trading
    • binance-sdk-mining: Mining
    • binance-sdk-pay: Pay
    • binance-sdk-rebate: Rebate
    • binance-sdk-simple-earn: Simple Earn
    • binance-sdk-spot: Spot Trading
    • binance-sdk-staking: Staking
    • binance-sdk-sub-account: Sub Account
    • binance-sdk-vip-loan: VIP Loan
    • binance-sdk-wallet: Wallet
    • binance-sdk-w3w-prediction: W3W Prediction

    Note: binance-sdk-nft is deprecated.

    For detailed API specifications, refer to the Binance API Documentation.

  4. Compare Monolithic vs Modular Connector Structures

    master

    When deciding whether to migrate, note the following structural differences:

    FeatureMonolithic ConnectorModular Connector
    Package Namebinance-connectorbinance-sdk-<product>
    API CoverageAll Binance APIsIndividual APIs (Spot, Wallet, Algo Trading, etc.)
    ImportsSingle package importSeparate package per product
    Code StructureOne large clientSmaller, focused clients

    Note on Backward Compatibility:

    • If a modular connector is not yet available for your specific product, continue using the monolithic binance-connector.
    • The monolithic connector will receive critical bug fixes, but new features will be focused on the modular connectors.
  5. Configure retries for SubAccount REST API requests

    master

    When initializing the ConfigurationRestAPI object, you can specify the number of retries for failed requests using the retries parameter. This configuration is then passed to the SubAccount client to manage automatic retry logic for REST API calls.

    from binance_common.configuration import ConfigurationRestAPI
    from binance_sdk_sub_account.sub_account import SubAccount
    from binance_sdk_sub_account.rest_api.models import GetSummaryOfSubAccountsMarginAccountResponse
    
    configuration = ConfigurationRestAPI(
        api_key="your-api-key",
        api_secret="your-api-secret",
        retries=2
    )
    client = SubAccount(config_rest_api=configuration)
    
    try:
        response = client.rest_api.get_summary_of_sub_accounts_margin_account()
        data: GetSummaryOfSubAccountsMarginAccountResponse = response.data()
        print(data)
    except Exception as e:
        print(e)
  6. Authenticate WebSocket API using Key Pair Authentication

    master

    To use the WebSocket API with Key Pair authentication in the binance-sdk-derivatives-trading-coin-futures SDK, you must initialize a ConfigurationWebSocketAPI object with your api_key, private_key, and private_key_passphrase. This configuration is then passed to the DerivativesTradingCoinFutures client via the config_ws_api parameter. Once authenticated, you can establish a connection using client.websocket_api.create_connection() and perform authenticated requests like position_information().

    import asyncio
    import logging
    
    from binance_common.configuration import ConfigurationWebSocketAPI
    from binance_sdk_derivatives_trading_coin_futures.derivatives_trading_coin_futures import DerivativesTradingCoinFutures
    from binance_sdk_derivatives_trading_coin_futures.websocket_api.models import PositionInformationResponse
    
    logging.basicConfig(level=logging.INFO)
    
    # Initialize configuration with Key Pair credentials
    configuration_ws_api = ConfigurationWebSocketAPI(
        api_key="your-api-key",
        private_key=private_key,
        private_key_passphrase=private_key_passphrase,
    )
    
    # Initialize the client with the WebSocket configuration
    client = DerivativesTradingCoinFutures(config_ws_api=configuration_ws_api)
    
    async def position_information():
        connection = None
        try:
            # Establish the WebSocket connection
            connection = await client.websocket_api.create_connection()
    
            # Perform an authenticated request
            response = await client.websocket_api.position_information()
    
            data = response.data()
            logging.info(f"position_information() response: {data}")
        except Exception as e:
            logging.error(f"position_information() error: {e}")
        finally:
            if connection:
                # Close the connection and the session
                await connection.close_connection(close_session=True)
    
    if __name__ == "__main__":
        asyncio.run(position_information())
  7. Configure API compression for Dual Investment

    master

    When initializing the ConfigurationRestAPI object for the Dual Investment SDK, you can enable or disable HTTP compression by setting the compression parameter. Setting compression=True (default behavior depends on implementation, but explicitly set here) allows the client to use compressed responses to reduce bandwidth usage. Set compression=False to disable it.

    from binance_common.configuration import ConfigurationRestAPI
    from binance_sdk_dual_investment.dual_investment import DualInvestment
    
    configuration = ConfigurationRestAPI(
        api_key="your-api-key",
        api_secret="your-api-secret",
        compression=False
    )
    client = DualInvestment(config_rest_api=configuration)
  8. Migrate from binance-connector to binance-sdk-rebate

    master
    The Binance Connector has transitioned from a monolithic binance-connector package to a modularized structure. To use Rebate features, you must migrate to the binance-sdk-rebate library. This involves uninstalling the old package, installing the new one, updating import paths, and adjusting how the client is initialized using ConfigurationRestAPI.
  9. Configure a proxy for Fiat REST API requests

    master

    When using the Fiat client, you can route your REST API requests through a proxy by providing a proxy dictionary to the ConfigurationRestAPI object. The proxy configuration requires a host, port, and protocol ('http' or 'https'). If your proxy requires authentication, include an auth dictionary containing username and password keys.

    from binance_common.configuration import ConfigurationRestAPI
    from binance_sdk_fiat.fiat import Fiat
    
    configuration = ConfigurationRestAPI(
        api_key="your-api-key",
        api_secret="your-api-secret",
        proxy = {
            "host": "127.0.0.1",
            "port": 8080,
            "protocol": "http", # or 'https'
            "auth": {
                "username": "proxy-user",
                "password": "proxy-password",
            },
        }
    )
    client = Fiat(config_rest_api=configuration)
  10. Migrate from binance-connector to binance-sdk-sub-account

    master

    The Binance Connector has transitioned from a monolithic binance-connector package to a modularized structure. To use Sub Account features, you must migrate to the binance-sdk-sub-account library.

    Migration Steps

    1. Uninstall the old package:

      pip uninstall binance-connector
    2. Install the new package:

      pip install binance-sdk-sub-account
    3. Update Imports: Replace from binance.spot import Spot as Client with:

      from binance_sdk_sub_account.sub_account import SubAccount
    4. Update Client Initialization: The new structure requires initializing a ConfigurationRestAPI object first, then passing it to the SubAccount client.

    5. Update Method Calls: API calls are now accessed through the rest_api attribute of the client instance (e.g., client.rest_api.query_sub_account_list()).

    from binance_sdk_sub_account.sub_account import SubAccount, ConfigurationRestAPI
    
    configuration = ConfigurationRestAPI(
        api_key="your-key",
        api_secret="your-secret"
    )
    client = SubAccount(config_rest_api=configuration)
          
    response = client.rest_api.query_sub_account_list()
  11. Configure API compression for Derivatives Trading Portfolio Margin Pro

    master

    When initializing the ConfigurationRestAPI for the DerivativesTradingPortfolioMarginPro client, you can enable or disable response compression using the compression parameter. Setting compression=True enables compressed responses to reduce data transfer size, while compression=False (default) uses uncompressed responses.

    from binance_common.configuration import ConfigurationRestAPI
    from binance_sdk_derivatives_trading_portfolio_margin_pro.derivatives_trading_portfolio_margin_pro import DerivativesTradingPortfolioMarginPro
    from binance_sdk_derivatives_trading_portfolio_margin_pro.rest_api.models import GetPortfolioMarginProAccountInfoResponse
    
    configuration = ConfigurationRestAPI(
        api_key="your-api-key",
        api_secret="your-api-secret",
        compression=False
    )
    client = DerivativesTradingPortfolioMarginPro(config_rest_api=configuration)
    
    try:
        response = client.rest_api.get_portfolio_margin_pro_account_info()
        data: GetPortfolioMarginProAccountInfoResponse = response.data()
        print(data)
    except Exception as e:
        print(e)