binance-rs Documentation

repository·master·Indexed 21 days ago

https://github.com/ccxt/binance-rs

An unofficial Rust library providing programmatic access to the Binance Spot and Futures APIs. It includes functionality for fetching public market data, managing private account data and orders, and handling real-time data streaming via WebSockets for both user data and market streams. Version 0.21.2.

Tokens
16K
Snippets
55
Records
72
Agent score
75%

What's inside binance-rs

  1. Subscribe to Market Data Streams (Trades and Klines)

    master

    You can subscribe to public market data streams using the WebSockets struct.

    Supported stream types include:

    • Trades: Use stream names like !ticker@arr for all symbols or specific symbol tickers.
    • Klines (Candlesticks): Use the format {symbol}@kline_{interval} (e.g., ethbtc@kline_1m).
    • Depth: Use the format {symbol}@depth@{interval} (e.g., ethbtc@depth@100ms).

    To listen to multiple streams simultaneously, use web_socket.connect_multiple_streams(&endpoints) where endpoints is a slice of formatted stream strings.

    // Example: Multiple Streams (Depth)
    let endpoints = ["ETHBTC", "BNBETH"]
        .map(|symbol| format!("{}@depth@100ms", symbol.to_lowercase()));
    
    let mut web_socket = WebSockets::new(|event: WebsocketEvent| {
        if let WebsocketEvent::DepthOrderBook(depth_order_book) = event {
            println!("{:?}", depth_order_book);
        }
        Ok(())
    });
    
    web_socket.connect_multiple_streams(&endpoints).unwrap();
  2. Install binance-rs via Cargo

    master

    To use binance-rs in your Rust project, add the following dependency to your Cargo.toml file. This pulls the crate directly from the GitHub repository:

    [dependencies]
    binance = { git = "https://github.com/ccxt/binance-rs.git" }
  3. Manage User Data Streams via WebSockets

    master

    The UserStream struct allows you to listen to private user data (like account updates and order trades) via WebSockets.

    Workflow:

    1. Initialize UserStream with your API key.
    2. Call .start() to receive a listen_key.
    3. Use WebSockets::new with a callback to handle WebsocketEvent (e.g., AccountUpdate, OrderTrade).
    4. Call web_socket.connect(&listen_key) to begin the stream.
    5. Run the event_loop to process incoming events.
    6. Use .keep_alive(&listen_key) periodically to prevent the stream from expiring.
    7. Call .close(&listen_key) to end the stream.
    use binance::api::Binance;
    use binance::userstream::UserStream;
    use binance::websockets::WebSockets;
    use binance::websockets::WebsocketEvent;
    use std::sync::atomic::AtomicBool;
    
    fn main() {
        let api_key_user = Some("YOUR_KEY".into());
        let keep_running = AtomicBool::new(true);
        let user_stream: UserStream = Binance::new(api_key_user, None);
    
        if let Ok(answer) = user_stream.start() {
            let listen_key = answer.listen_key;
    
            let mut web_socket = WebSockets::new(|event: WebsocketEvent| {
                match event {
                    WebsocketEvent::AccountUpdate(account_update) => {
                        for balance in &account_update.balance {
                            println!("Asset: {}, free: {}, locked: {}", balance.asset, balance.free, balance.locked);
                        }
                    },
                    WebsocketEvent::OrderTrade(trade) => {
                        println!("Symbol: {}, Side: {}, Price: {}, Execution Type: {}", trade.symbol, trade.side, trade.price, trade.execution_type);
                    },
                    _ => (),
                };
                Ok(())
            });
    
            web_socket.connect(&listen_key).unwrap();
            if let Err(e) = web_socket.event_loop(&keep_running) {
                println!("Error: {:?}", e);
            }
        }
    }
  4. Handle Binance API Errors

    master

    The client returns a Result<T>. Errors can arise from several sources:

    • Network/HTTP Errors: Standard reqwest errors.
    • Server Errors: Internal Server Error (500), Service Unavailable (503), or Unauthorized (401).
    • Binance API Errors: If the server returns a 400 Bad Request, the client attempts to parse the response into a BinanceContentError. This is wrapped in ErrorKind::BinanceError.
  5. Order configuration types

    master

    When interacting with orders, you will use the following enums to define order behavior:

    OrderType

    • Limit: An order to buy/sell at a specific price or better.
    • Market: An order to buy/sell immediately at the best available price.
    • StopLossLimit: A stop order that, when triggered, becomes a limit order.

    OrderSide

    • Buy: Buying an asset.
    • Sell: Selling an asset.

    TimeInForce

    • GTC (Good Till Cancel): The order remains active until filled or canceled.
    • IOC (Immediate Or Cancel): The order must be filled immediately; any part that cannot be filled is canceled.
    • FOK (Fill Or Kill): The order must be filled entirely or canceled completely.
  6. Understand Exchange Information and Symbol Filters

    master

    The ExchangeInformation struct provides metadata about the exchange, including timezone, server time, rate limits, and a list of available Symbols. Each Symbol contains critical trading constraints via a filters field.

    Common filters include:

    • PRICE_FILTER: Defines min_price, max_price, and tick_size.
    • LOT_SIZE: Defines min_qty, max_qty, and step_size.
    • MIN_NOTIONAL: Defines minimum order value requirements.
    • PERCENT_PRICE: Constraints based on a multiplier of the average price.
    • MARKET_LOT_SIZE: Similar to LOT_SIZE but specifically for market orders.

    Use these filters to validate order parameters (price and quantity) before sending them to the API to avoid rejection.

    // Example of the structure of ExchangeInformation
    // (Conceptual representation of the data returned)
    ExchangeInformation {
        timezone: "UTC",
        server_time: 1626118018407,
        rate_limits: [...],
        symbols: [
            Symbol {
                symbol: "BTCUSDT",
                status: "TRADING",
                base_asset: "BTC",
                quote_asset: "USDT",
                filters: [
                    Filters::PriceFilter { min_price: "0.01", max_price: "100000.00", tick_size: "0.01" },
                    Filters::LotSize { min_qty: "0.00001", max_qty: "100.0", step_size: "0.00001" }
                ],
                ..
            }
        ],
    }
  7. Switch between Binance Mainnet and Testnet

    master

    The set_testnet(bool) method on any Binance trait implementation adjusts the underlying host endpoint. The behavior varies depending on the client type:

    • Spot Clients (Market, Account, Savings, General, UserStream): Switches between SPOT_MAINNET and SPOT_TESTNET for REST, or SPOT_WS_MAINNET and SPOT_WS_TESTNET for WebSocket-based UserStream.
    • Futures Clients (FuturesMarket, FuturesAccount, FuturesGeneral, FuturesUserStream): Switches between FUTURES_MAINNET and FUTURES_TESTNET for REST, or FUTURES_WS_MAINNET and FUTURES_WS_TESTNET for WebSocket-based FuturesUserStream.
  8. Process WebSocket Stream Events

    master

    The library includes models for various Binance WebSocket streams. Key event types include:

    • AggrTradesEvent: Aggregated trade information (<symbol>@aggTrade).
    • TradeEvent: Raw trade information (<symbol>@trade).
    • BookTickerEvent: Best bid/ask prices and quantities (<symbol>@bookTicker).
    • KlineEvent: Candlestick/Kline data (<symbol>@kline).
    • LiquidationEvent: Liquidation order details (<symbol>@liquidation).
    • AccountUpdateEvent: Real-time updates to account balances and positions.
    • MarkPriceEvent: Mark price and funding rate updates for futures.
  9. Configure Testnet and API Clusters

    master

    By default, the library connects to the main Binance API. You can override the default endpoints to use the Binance Testnet or specific API clusters using the Config struct and Binance::new_with_config.

    This is useful for testing orders without risking real funds or for improving performance by selecting specific clusters.

    let general: General = if use_testnet {
        let config = Config::default().set_rest_api_endpoint("https://testnet.binance.vision");
        Binance::new_with_config(None, None, &config)
    } else {
        Binance::new(None, None)
    };
  10. Use the FuturesWebSockets event loop

    master

    To process incoming messages from a WebSocket connection, you must run the event_loop method. This method continuously reads messages from the socket, handles Pings/Pongs to keep the connection alive, and passes incoming data to your registered handler.

    The loop runs as long as the provided AtomicBool is set to true. To stop the loop, set the boolean to false from another thread.

    Error Handling

    • If the connection is closed by the server, event_loop will return an error.
    • If the handler returns an error, the loop will terminate with a bail! error.
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::Arc;
    
    let running = Arc::new(AtomicBool::new(true));
    let r = running.clone();
    
    // Run the event loop in a separate thread
    std::thread::spawn(move || {
        ws.event_loop(&r).expect("Event loop failed");
    });
    
    // Later, to stop the loop:
    running.store(false, Ordering::Relaxed);
  11. Connect to Binance Futures WebSockets

    master

    The FuturesWebSockets struct provides several methods to establish connections to different Binance Futures markets. You must provide a callback function (handler) during initialization that processes incoming FuturesWebsocketEvent objects.

    Connection Methods

    • connect(market, subscription): Connects to a single stream using the default API pattern.
    • connect_with_config(market, subscription, config): Connects using a custom WebSocket endpoint defined in the provided Config object.
    • connect_multiple_streams(market, endpoints): Connects to multiple streams simultaneously using the MultiStream API pattern.

    Supported Markets (FuturesMarket)

    • USDM: USD-M Futures
    • COINM: Coin-M Futures
    • Vanilla: Vanilla Futures
    • USDMTestnet, COINMTestnet, VanillaTestnet: Testnet versions of the above markets.
    // Example: Initializing and connecting to a USD-M stream
    let mut ws = FuturesWebSockets::new(|event| {
        match event {
            FuturesWebsocketEvent::Trade(trade) => println!("Trade: {:?}", trade),
            _ => {}
        }
        Ok(())
    });
    
    ws.connect(&FuturesMarket::USDM, "btcusdt@trade")?;