Binance Rust Connector

repository·main·Indexed 43 days ago

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

An official collection of auto-generated Rust SDK modules for accessing Binance public APIs. Provided as the binance-sdk crate, it offers a modular approach to interact with services including Spot, USDS-M Futures, COIN-M Futures, and Alpha via REST and WebSocket APIs. Supports both OpenSSL and Rustls TLS backends.

Tokens
102.8K
Snippets
224
Records
253
Agent score
52%

What's inside Binance Rust Connector

  1. Overview of Binance Rust SPOT Connector features

    main

    The Binance Rust SPOT Connector provides programmatic access to Binance's SPOT trading platform through three primary interfaces:

    • REST API: Access to /api/* endpoints for market data and order management.
    • Websocket API: Real-time request-response communication.
    • Websocket Streams: Real-time data streaming.

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

  2. Overview of USDS-M Futures Connector capabilities

    main

    The derivatives_trading_usds_futures module provides an official Rust client for interacting with Binance's USDS-M Futures API. It supports three primary interaction patterns:

    1. REST API: Access to /fapi/* endpoints for request-response operations.
    2. Websocket API: Real-time request-response communication.
    3. Websocket Streams: Real-time data streaming.

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

  3. Overview of Binance COIN-M Futures Connector capabilities

    main

    The derivatives_trading_coin_futures module provides an official Rust client for interacting with Binance's COIN-M Futures API. It supports three primary interaction patterns:

    1. REST API: Access to /dapi/* endpoints for request-response operations.
    2. Websocket API: Real-time data streaming and request-response communication via WebSockets.
    3. Websocket Streams: Continuous real-time data feeds.

    The module includes built-in test cases and examples to assist with onboarding.

  4. Use Key Pair Based Authentication for Sub-Account REST API

    main

    To authenticate requests to the Sub-Account REST API using a private key, configure a ConfigurationRestApi using the builder pattern. You must provide an api_key and a private_key. If your private key file is encrypted, you must also provide the private_key_passphrase.

    Once configured, pass the configuration to sub_account::SubAccountRestApi::production(configuration) to initialize the client.

    use binance_sdk::sub_account;
    use binance_sdk::config;
    
    let configuration = config::ConfigurationRestApi::builder()
        .api_key("your-api-key")
        .private_key(config::PrivateKey::File("your-private-key-file-path".to_string())) // Provide the private key file path
        .private_key_passphrase("your-passphrase".to_string()) // Optional: Required if the private key is encrypted
        .build()?;
    
    let client = sub_account::SubAccountRestApi::production(configuration);
    let params = sub_account::rest_api::GetSummaryOfSubAccountsMarginAccountParams::default();
    let response = client.get_summary_of_sub_accounts_margin_account(params).await?;
  5. Configure a proxy for the Pay REST API

    main

    To route your Pay REST API requests through a proxy, create a config::ProxyConfig instance and pass it to the config::ConfigurationRestApi builder. You can specify the host, port, protocol (e.g., "http"), and optional authentication credentials using config::ProxyAuth.

    use binance_sdk::pay;
    use binance_sdk::config;
    
    let proxy_config = config::ProxyConfig {
        host: "127.0.0.1".to_string(),
        port: 8080,
        protocol: Some("http".to_string()),
        auth: Some(config::ProxyAuth {
            username: "proxy-user".to_string(),
            password: "proxy-password".to_string(),
        }),
    };
    
    let configuration = config::ConfigurationRestApi::builder()
        .api_key("your-api-key")
        .api_secret("your-api-secret")
        .proxy(proxy_config)
        .build()?;
    
    let client = pay::PayRestApi::production(configuration);
    let params = pay::rest_api::GetPayTradeHistoryParams::default();
    let response = client.get_pay_trade_history(params).await?;
  6. Handle errors in Simple Earn REST API calls

    main

    When using the SimpleEarnRestApi, errors are returned as a generic error type that can be inspected using downcast_ref to access specific errors::ConnectorError variants. This allows you to distinguish between client-side issues (like invalid parameters), authentication issues, rate limits, and server-side errors.

    To handle errors effectively, you should:

    1. Match on the result of your API call.
    2. Attempt to downcast the error to errors::ConnectorError.
    3. Match on the specific ConnectorError variants to implement custom logic (e.g., retrying on TooManyRequestsError or logging a warning for UnauthorizedError).
    use binance_sdk::simple_earn;
    use binance_sdk::config;
    use binance_sdk::errors;
    
    let configuration = config::ConfigurationRestApi::builder()
        .api_key("your-api-key")
        .api_secret("your-api-secret")
        .build()?;
    
    let client = simple_earn::SimpleEarnRestApi::production(configuration);
    let params = simple_earn::rest_api::GetSimpleEarnFlexibleProductListParams::default();
    
    match client.get_simple_earn_flexible_product_list(params).await {
        Ok(response) => response,
        Err(e) => {
            if let Some(conn_err) = e.downcast_ref::<errors::ConnectorError>() {
                match conn_err {
                    errors::ConnectorError::ConnectorClientError { msg, code } => {
                        eprintln!("Client error: Check your request parameters. {}", msg);
                    }
                    errors::ConnectorError::UnauthorizedError { msg, code } => {
                        eprintln!("Unauthorized: Invalid API credentials. {}", msg);
                    }
                    errors::ConnectorError::ForbiddenError { msg, code } => {
                        eprintln!("Forbidden: Check your API key permissions. {}", msg);
                    }
                    errors::ConnectorError::TooManyRequestsError { msg, code } => {
                        eprintln!("Rate limit exceeded. Please wait and try again. {}", msg);
                    }
                    errors::ConnectorError::RateLimitBanError { msg, code } => {
                        eprintln!("IP address banned due to excessive rate limits. {}", msg);
                    }
                    errors::ConnectorError::ServerError { msg, status_code } => {
                        eprintln!("Server error: {} (status code: {:?})", msg, status_code);
                    }
                    errors::ConnectorError::NetworkError { msg, code } => {
                        eprintln!("Network error: Check your internet connection. {}", msg);
                    }
                    errors::ConnectorError::NotFoundError { msg, code } => {
                        eprintln!("Resource not found. {}", msg);
                    }
                    errors::ConnectorError::BadRequestError { msg, code } => {
                        eprintln!("Bad request: Verify your input parameters. {}", msg);
                    }
                    other => {
                        eprintln!("Unexpected ConnectorError variant: {:?}", other);
                    }
                }
            } else {
                eprintln!("An unexpected error occurred: {:#}", e);
            }
    
            return Err(e);
        }
    };
  7. Configure Keep-Alive for the Crypto Loan REST API

    main

    When building a ConfigurationRestApi for the crypto_loan module, you can control the HTTP Keep-Alive behavior. By default, Keep-Alive is enabled (true). If you need to disable it, use the .keep_alive(false) method on the configuration builder. This is useful for managing connection persistence in specific network environments.

    use binance_sdk::crypto_loan;
    use binance_sdk::config;
    
    let configuration = config::ConfigurationRestApi::builder()
        .api_key("your-api-key")
        .api_secret("your-api-secret")
        .keep_alive(false) // default is true
        .build()?;
    
    let client = crypto_loan::CryptoLoanRestApi::production(configuration);
    let params = crypto_loan::rest_api::GetFlexibleLoanBorrowHistoryParams::default();
    let response = client.get_flexible_loan_borrow_history(params).await?;
  8. Handle API errors using ConnectorError

    main

    When using the SpotRestApi, errors returned from API calls can be downcast to errors::ConnectorError to identify specific failure modes. This allows you to distinguish between client-side issues (like invalid parameters), authentication issues (invalid API keys), rate limiting, and server-side errors.

    To handle these errors, use e.downcast_ref::<errors::ConnectorError>() on the error returned by the API call.

    Common ConnectorError variants include:

    • ConnectorClientError: Check request parameters.
    • UnauthorizedError: Invalid API credentials.
    • ForbiddenError: Check API key permissions.
    • TooManyRequestsError: Rate limit exceeded.
    • RateLimitBanError: IP address banned due to excessive rate limits.
    • ServerError: Binance server-side error (includes status_code).
    • NetworkError: Connectivity issues.
    • NotFoundError: The requested resource does not exist.
    • BadRequestError: Verify input parameters.
    use binance_sdk::spot;
    use binance_sdk::config;
    use binance_sdk::errors;
    
    let configuration = config::ConfigurationRestApi::builder()
        .api_key("your-api-key")
        .api_secret("your-api-secret")
        .build()?;
    
    let client = spot::SpotRestApi::production(configuration);
    let params = spot::rest_api::ExchangeInfoParams::default();
    
    match client.exchange_info(params).await {
        Ok(response) => response,
        Err(e) => {
            if let Some(conn_err) = e.downcast_ref::<errors::ConnectorError>() {
                match conn_err {
                    errors::ConnectorError::ConnectorClientError { msg, code } => {
                        eprintln!("Client error: Check your request parameters. {}", msg);
                    }
                    errors::ConnectorError::UnauthorizedError { msg, code } => {
                        eprintln!("Unauthorized: Invalid API credentials. {}", msg);
                    }
                    errors::ConnectorError::ForbiddenError { msg, code } => {
                        eprintln!("Forbidden: Check your API key permissions. {}", msg);
                    }
                    errors::ConnectorError::TooManyRequestsError { msg, code } => {
                        eprintln!("Rate limit exceeded. Please wait and try again. {}", msg);
                    }
                    errors::ConnectorError::RateLimitBanError { msg, code } => {
                        eprintln!("IP address banned due to excessive rate limits. {}", msg);
                    }
                    errors::ConnectorError::ServerError { msg, status_code } => {
                        eprintln!("Server error: {} (status code: {:?})", msg, status_code);
                    }
                    errors::ConnectorError::NetworkError { msg, code } => {
                        eprintln!("Network error: Check your internet connection. {}", msg);
                    }
                    errors::ConnectorError::NotFoundError { msg, code } => {
                        eprintln!("Resource not found. {}", msg);
                    }
                    errors::ConnectorError::BadRequestError { msg, code } => {
                        eprintln!("Bad request: Verify your input parameters. {}", msg);
                    }
                    other => {
                        eprintln!("Unexpected ConnectorError variant: {:?}", other);
                    }
                }
            } else {
                eprintln!("An unexpected error occurred: {:#}", e);
            }
    
            return Err(e);
        }
    };
  9. Configure a proxy for Derivatives Trading Portfolio Margin Pro

    main

    To route your requests through a proxy when using the derivatives_trading_portfolio_margin_pro module, you must create a config::ProxyConfig instance and pass it to the config::ConfigurationRestApi builder.

    ProxyConfig supports:

    • host: The proxy server address.
    • port: The port number.
    • protocol: An optional protocol string (e.g., Some("http".to_string())).
    • auth: An optional config::ProxyAuth object containing username and password.
    use binance_sdk::derivatives_trading_portfolio_margin_pro;
    use binance_sdk::config;
    
    let proxy_config = config::ProxyConfig {
        host: "127.0.0.1".to_string(),
        port: 8080,
        protocol: Some("http".to_string()),
        auth: Some(config::ProxyAuth {
            username: "proxy-user".to_string(),
            password: "proxy-password".to_string(),
        }),
    };
    
    let configuration = config::ConfigurationRestApi::builder()
        .api_key("your-api-key")
        .api_secret("your-api-secret")
        .proxy(proxy_config)
        .build()?;
    
    let client = derivatives_trading_portfolio_margin_pro::DerivativesTradingPortfolioMarginProRestApi::production(configuration);
    let params = derivatives_trading_portfolio_margin_pro::rest_api::GetPortfolioMarginProAccountInfoParams::default();
    let response = client.get_portfolio_margin_pro_account_info(params).await?;
  10. Implement Certificate Pinning for Wallet API

    main

    To enhance security, you can implement certificate pinning by providing a custom HttpAgent to the ConfigurationRestApi. This involves loading a .pem certificate and using reqwest::ClientBuilder::add_root_certificate to inject it into the client.

    1. Load your certificate file from disk.
    2. Create a reqwest::Certificate from the PEM data.
    3. Wrap the certificate injection logic in a config::HttpAgent using an Arc closure.
    4. Pass this agent to the ConfigurationRestApi builder via .agent().
    5. Initialize the wallet::WalletRestApi with the resulting configuration.
    use std;
    use reqwest;
    
    use binance_sdk::wallet;
    use binance_sdk::config;
    
    let pem = std::fs::read("/path/to/pinned_cert.pem");
    let cert = reqwest::Certificate::from_pem(&pem);
    
    let custom_agent = config::HttpAgent(std::sync::Arc::new(|builder: reqwest::ClientBuilder| {
        builder.add_root_certificate(cert.clone())
    }));
    
    let configuration = config::ConfigurationRestApi::builder()
        .api_key("your-api-key")
        .api_secret("your-api-secret")
        .agent(custom_agent)
        .build()?;
    
    let client = wallet::WalletRestApi::production(configuration);
    let params = wallet::rest_api::AccountInfoParams::default();
    let response = client.account_info(params).await?;
  11. Configure retries for the Rebate REST API

    main

    When initializing a ConfigurationRestApi for the Rebate REST API, you can specify retry logic to handle transient network errors or rate limits. Use the .retries(n) method to set the maximum number of retry attempts and .backoff(ms) to set the duration (in milliseconds) to wait between each attempt.

    To apply this configuration, pass the resulting ConfigurationRestApi instance to the rebate::RebateRestApi::production() constructor.

    use binance_sdk::rebate;
    use binance_sdk::config;
    
    let configuration = config::ConfigurationRestApi::builder()
        .api_key("your-api-key")
        .api_secret("your-api-secret")
        .retries(5) // Retry up to 5 times
        .backoff(2000) // 2 seconds between retries
        .build()?;
    
    let client = rebate::RebateRestApi::production(configuration);
    let params = rebate::rest_api::GetSpotRebateHistoryRecordsParams::default();
    let response = client.get_spot_rebate_history_records(params).await?;