### Manage Binance User Data Streams (Rust) Source: https://github.com/ccxt/binance-rs/blob/master/README.md This example shows how to start, keep alive, and close a user data stream using the Binance API. It initializes the `UserStream` client with an API key, retrieves a listen key, and then demonstrates how to maintain the stream's activity and properly close it. Requires API keys and the Binance Rust library. ```rust use binance::api::*; use binance::userstream::*; fn main() { let api_key_user = Some("YOUR_API_KEY".into()); let user_stream: UserStream = Binance::new(api_key_user.clone(), None); if let Ok(answer) = user_stream.start() { println!("Data Stream Started ..."); let listen_key = answer.listen_key; match user_stream.keep_alive(&listen_key) { Ok(msg) => println!("Keepalive user data stream: {:?}", msg), Err(e) => println!("Error: {:?}", e), } match user_stream.close(&listen_key) { Ok(msg) => println!("Close user data stream: {:?}", msg), Err(e) => println!("Error: {:?}", e), } } else { println!("Not able to start an User Stream (Check your API_KEY)"); } } ``` -------------------------------- ### Install Rust Stable Toolchain Source: https://github.com/ccxt/binance-rs/blob/master/README.md This command installs the stable version of the Rust toolchain using rustup, which is a prerequisite for using the binance-rs library as indicated by the project. ```bash rustup install stable ``` -------------------------------- ### Get Current Prices Source: https://context7.com/ccxt/binance-rs/llms.txt Fetches the latest trading prices for a single symbol or all available symbols. Also provides functionality to get the average price for a symbol. ```APIDOC ## Get Current Prices ### Description Fetch the latest trading prices for one or all symbols. ### Method GET (Implied by library usage) ### Endpoint N/A (Method calls on Market client) ### Parameters #### Query Parameters - **symbol** (string) - Required (for `get_price` and `get_average_price`) - The trading pair (e.g., "BTCUSDT"). ### Request Example ```rust use binance::api::*; use binance::market::*; fn main() { let market: Market = Binance::new(None, None); // Single symbol price match market.get_price("BTCUSDT") { Ok(answer) => println!("BTC/USDT: {}", answer.price), Err(e) => println!("Error: {}", e), } // All symbols prices match market.get_all_prices() { Ok(prices) => { for price in prices { println!("{}: {}", price.symbol, price.price); } }, Err(e) => println!("Error: {}", e), } // Average price match market.get_average_price("ETHBTC") { Ok(avg) => println!("Average price: {}", avg.price), Err(e) => println!("Error: {}", e), } } ``` ### Response #### Success Response (200) - **symbol** (string) - The trading pair. - **price** (string) - The latest trading price. #### Response Example ```json { "symbol": "BTCUSDT", "price": "45000.12345" } ``` ``` -------------------------------- ### Handle Binance API Errors with Detailed Information (Rust) Source: https://github.com/ccxt/binance-rs/blob/master/README.md This example demonstrates how to handle errors returned by the Binance API client. It specifically shows how to inspect the error kind and extract detailed information, such as Binance-specific error codes and messages, for more granular error reporting. This requires the Binance Rust library and knowledge of Binance error codes. ```rust use binance::errors::ErrorKind as BinanceLibErrorKind; // ... elsewhere in your code ... Err(err) => { println!("Can't put an order!"); match err.0 { BinanceLibErrorKind::BinanceError(response) => match response.code { -1013_i16 => println!("Filter failure: LOT_SIZE!"), -2010_i16 => println!("Funds insufficient! {}", response.msg), _ => println!("Non-catched code {}: {}", response.code, response.msg), }, BinanceLibErrorKind::Msg(msg) => { println!("Binancelib error msg: {}", msg) } _ => println!("Other errors: {}.", err.0), }; } ``` -------------------------------- ### General API Functions Source: https://context7.com/ccxt/binance-rs/llms.txt Access general server information and status, including pinging the server, getting the current server time, and retrieving exchange trading rules. ```APIDOC ## General API Endpoints ### Ping #### Description Tests the connectivity to the Binance API. Should return 'pong'. #### Method GET #### Endpoint `/api/v1/ping` #### Response ##### Success Response (200) - **response** (string) - Should be "pong". ### Get Server Time #### Description Retrieves the current server time from Binance. #### Method GET #### Endpoint `/api/v1/time` #### Response ##### Success Response (200) - **serverTime** (integer) - Current server time in milliseconds. ### Exchange Information #### Description Retrieves general exchange information including trading rules, symbol information, and rate limits. #### Method GET #### Endpoint `/api/v1/exchangeInfo` #### Response ##### Success Response (200) - **timezone** (string) - The exchange timezone. - **serverTime** (integer) - Current server time in milliseconds. - **rateLimits** (array) - List of rate limits. - **symbols** (array) - List of trading symbols with their details (filters, order types, etc.). #### Symbol Information Example (within `symbols` array) - **symbol** (string) - Trading symbol. - **status** (string) - Trading status. - **baseAsset** (string) - Base asset. - **quoteAsset** (string) - Quote asset. ### Get Symbol Information #### Description Retrieves specific information for a given trading symbol. #### Method GET #### Endpoint `/api/v1/exchangeInfo` (filtered by symbol) #### Parameters ##### Query Parameters - **symbol** (string) - Required - The trading symbol (e.g., "BTCUSDT"). #### Response ##### Success Response (200) (Similar structure to a single symbol object from `exchangeInfo`) - **symbol** (string) - Trading symbol. - **status** (string) - Trading status. - **baseAsset** (string) - Base asset. - **quoteAsset** (string) - Quote asset. ### Request Example (for Get Symbol Info) ```json { "symbol": "BTCUSDT" } ``` ### Response Example (for Get Symbol Info) ```json { "symbol": "BTCUSDT", "status": "TRADING", "baseAsset": "BTC", "quoteAsset": "USDT" } ``` ``` -------------------------------- ### Get Current Prices (Rust) Source: https://context7.com/ccxt/binance-rs/llms.txt Fetches the latest trading prices for a single symbol or all symbols on Binance. It also provides functionality to retrieve the average price for a given trading pair. ```rust use binance::api::* use binance::market::* fn main() { let market: Market = Binance::new(None, None); // Single symbol price match market.get_price("BTCUSDT") { Ok(answer) => println!("BTC/USDT: {}", answer.price), Err(e) => println!("Error: {}", e), } // All symbols prices match market.get_all_prices() { Ok(prices) => { for price in prices { println!("{}: {}", price.symbol, price.price); } }, Err(e) => println!("Error: {}", e), } // Average price match market.get_average_price("ETHBTC") { Ok(avg) => println!("Average price: {}", avg.price), Err(e) => println!("Error: {}", e), } } ``` -------------------------------- ### Fetch Binance Account Data and Manage Orders (Rust) Source: https://github.com/ccxt/binance-rs/blob/master/README.md This snippet shows how to initialize the Binance API client with API keys, retrieve account balances, fetch open orders, and execute various order types (limit buy/sell, market buy/sell, custom orders). It also includes examples for checking order status, canceling orders, and retrieving trade history. Requires API keys and the Binance Rust library. ```rust use binance::api::*; use binance::account::*; fn main() { let api_key = Some("YOUR_API_KEY".into()); let secret_key = Some("YOUR_SECRET_KEY".into()); let account: Account = Binance::new(api_key, secret_key); match account.get_account() { Ok(answer) => println!("{:?}", answer.balances), Err(e) => println!("Error: {:?}", e), } match account.get_open_orders("WTCETH") { Ok(answer) => println!("{:?}", answer), Err(e) => println!("Error: {:?}", e), } match account.limit_buy("WTCETH", 10, 0.014000) { Ok(answer) => println!("{:?}", answer), Err(e) => println!("Error: {:?}", e), } match account.market_buy("WTCETH", 5) { Ok(answer) => println!("{:?}", answer), Err(e) => println!("Error: {:?}", e), } match account.limit_sell("WTCETH", 10, 0.035000) { Ok(answer) => println!("{:?}", answer), Err(e) => println!("Error: {:?}", e), } match account.market_sell("WTCETH", 5) { Ok(answer) => println!("{:?}", answer), Err(e) => println!("Error: {:?}", e), } match account.custom_order("WTCETH", 9999, 0.0123, "SELL", "LIMIT", "IOC") { Ok(answer) => println!("{:?}", answer), Err(e) => println!("Error: {:?}", e), } let order_id = 1_957_528; match account.order_status("WTCETH", order_id) { Ok(answer) => println!("{:?}", answer), Err(e) => println!("Error: {:?}", e), } match account.cancel_order("WTCETH", order_id) { Ok(answer) => println!("{:?}", answer), Err(e) => println!("Error: {:?}", e), } match account.cancel_all_open_orders("WTCETH") { Ok(answer) => println!("{:?}", answer), Err(e) => println!("Error: {:?}", e), } match account.get_balance("KNC") { Ok(answer) => println!("{:?}", answer), Err(e) => println!("Error: {:?}", e), } match account.trade_history("WTCETH") { Ok(answer) => println!("{:?}", answer), Err(e) => println!("Error: {:?}", e), } } ``` -------------------------------- ### Get Candlestick Data (Klines) Source: https://context7.com/ccxt/binance-rs/llms.txt Fetches historical candlestick or kline data for technical analysis. Supports specifying interval, limit, start time, and end time. ```APIDOC ## Get Candlestick Data (Klines) ### Description Fetch historical candlestick/kline data for technical analysis. ### Method GET (Implied by library usage) ### Endpoint N/A (Method calls on Market client) ### Parameters #### Query Parameters - **symbol** (string) - Required - The trading pair (e.g., "BNBETH"). - **interval** (string) - Required - The candlestick interval (e.g., "1m", "5m", "1h", "1d"). - **limit** (integer) - Optional - The number of data points to retrieve. Defaults to 500. Maximum is 1000. - **start_time** (integer) - Optional - The start time in milliseconds (Unix timestamp). - **end_time** (integer) - Optional - The end time in milliseconds (Unix timestamp). ### Request Example ```rust use binance::api::*; use binance::market::*; use binance::model::KlineSummary; fn main() { let market: Market = Binance::new(None, None); // Get last 10 5-minute klines match market.get_klines("BNBETH", "5m", 10, None, None) { Ok(klines) => { match klines { binance::model::KlineSummaries::AllKlineSummaries(klines) => { for kline in klines { println!( "Time: {}, Open: {}, High: {}, Low: {}, Close: {}, Volume: {}", kline.open_time, kline.open, kline.high, kline.low, kline.close, kline.volume ); } } } }, Err(e) => println!("Error: {}", e), } // With time range let start_time: u64 = 1609459200000; // Unix timestamp in ms let end_time: u64 = 1609545600000; match market.get_klines("BTCUSDT", "1h", 100, Some(start_time), Some(end_time)) { Ok(klines) => println!("Retrieved klines in time range"), Err(e) => println!("Error: {}", e), } } ``` ### Response #### Success Response (200) - **open_time** (integer) - Kline opening time. - **open** (string) - Open price. - **high** (string) - High price. - **low** (string) - Low price. - **close** (string) - Close price. - **volume** (string) - Volume. - **close_time** (integer) - Kline closing time. - **quote_asset_volume** (string) - Quote asset volume. - **number_of_trades** (integer) - Number of trades. - **taker_buy_base_asset_volume** (string) - Taker buy base asset volume. - **taker_buy_quote_asset_volume** (string) - Taker buy quote asset volume. #### Response Example ```json { "open_time": 1609459200000, "open": "29000.00", "high": "29500.00", "low": "28800.00", "close": "29200.00", "volume": "500.00", "close_time": 1609462800000, "quote_asset_volume": "14600000.00", "number_of_trades": 1000, "taker_buy_base_asset_volume": "250.00", "taker_buy_quote_asset_volume": "7300000.00" } ``` ``` -------------------------------- ### General API Functions using Binance Rust API Source: https://context7.com/ccxt/binance-rs/llms.txt Access general Binance API functionalities like checking server status, retrieving server time, and getting exchange information. These functions do not require API credentials. ```rust use binance::api::*; use binance::general::*; fn main() { let general: General = Binance::new(None, None); // Test connectivity match general.ping() { Ok(response) => println!("API Response: {}", response), // prints "pong" Err(e) => println!("Error: {}", e), } // Get server time match general.get_server_time() { Ok(time) => println!("Server time: {}", time.server_time), Err(e) => println!("Error: {}", e), } // Get exchange information (trading rules, symbol info) match general.exchange_info() { Ok(info) => { println!("Timezone: {}", info.timezone); println!("Available symbols: {}", info.symbols.len()); for symbol in info.symbols.iter().take(5) { println!( " {}: {}/{}", symbol.symbol, symbol.base_asset, symbol.quote_asset ); } }, Err(e) => println!("Error: {}", e), } // Get specific symbol information match general.get_symbol_info("BTCUSDT") { Ok(symbol) => println!( "Symbol: {}, Status: {}, Base: {}, Quote: {}", symbol.symbol, symbol.status, symbol.base_asset, symbol.quote_asset ), Err(e) => println!("Error: {}", e), } } ``` -------------------------------- ### User Data Stream Management using Binance Rust API Source: https://context7.com/ccxt/binance-rs/llms.txt Manage real-time user data streams on Binance for account updates. This involves starting a stream, keeping it alive, and closing it when no longer needed. Requires an API key. ```rust use binance::api::*; use binance::userstream::*; fn main() { let api_key = Some("your_api_key".into()); let user_stream: UserStream = Binance::new(api_key, None); // Start user data stream if let Ok(answer) = user_stream.start() { println!("Data stream started"); let listen_key = answer.listen_key; println!("Listen key: {}", listen_key); // Keep stream alive (call every 30-60 minutes) match user_stream.keep_alive(&listen_key) { Ok(_) => println!("Stream keepalive sent"), Err(e) => println!("Error: {}", e), } // Close stream when done match user_stream.close(&listen_key) { Ok(_) => println!("Stream closed"), Err(e) => println!("Error: {}", e), } } else { println!("Failed to start user stream - check API key"); } } ``` -------------------------------- ### Get 24-Hour Price Statistics Source: https://context7.com/ccxt/binance-rs/llms.txt Retrieves comprehensive price change statistics over the last 24 hours for a specific symbol or all symbols. ```APIDOC ## Get 24-Hour Price Statistics ### Description Retrieve comprehensive price change statistics over the last 24 hours. ### Method GET (Implied by library usage) ### Endpoint N/A (Method calls on Market client) ### Parameters #### Query Parameters - **symbol** (string) - Required (for `get_24h_price_stats`) - The trading pair (e.g., "BNBETH"). ### Request Example ```rust use binance::api::*; use binance::market::*; fn main() { let market: Market = Binance::new(None, None); match market.get_24h_price_stats("BNBETH") { Ok(stats) => println!( "Open: {}, High: {}, Low: {}, Close: {}, Volume: {}", stats.open_price, stats.high_price, stats.low_price, stats.last_price, stats.volume ), Err(e) => println!("Error: {}", e), } // All symbols 24h stats match market.get_all_24h_price_stats() { Ok(all_stats) => { for stats in all_stats { println!("{}: Volume {}", stats.symbol, stats.volume); } }, Err(e) => println!("Error: {}", e), } } ``` ### Response #### Success Response (200) - **symbol** (string) - The trading pair. - **priceChange** (string) - The price change over 24 hours. - **priceChangePercent** (string) - The percentage price change over 24 hours. - **weightedAvgPrice** (string) - The weighted average price over 24 hours. - **prevClosePrice** (string) - The price of the previous close. - **lastPrice** (string) - The last price. - **lastQty** (string) - The quantity of the last trade. - **bidPrice** (string) - The best bid price. - **bidQty** (string) - The best bid quantity. - **askPrice** (string) - The best ask price. - **askQty** (string) - The best ask quantity. - **openPrice** (string) - The opening price over 24 hours. - **highPrice** (string) - The highest price over 24 hours. - **lowPrice** (string) - The lowest price over 24 hours. - **volume** (string) - The total trading volume over 24 hours. - **quoteVolume** (string) - The total quote volume over 24 hours. - **openTime** (integer) - The open time of the 24-hour period. - **closeTime** (integer) - The close time of the 24-hour period. - **firstId** (integer) - The first trade ID. - **lastId** (integer) - The last trade ID. - **count** (integer) - The number of trades. #### Response Example ```json { "symbol": "BNBETH", "priceChange": "0.10000000", "priceChangePercent": "5.00", "weightedAvgPrice": "2.10000000", "prevClosePrice": "2.00000000", "lastPrice": "2.10000000", "lastQty": "10.00000000", "bidPrice": "2.10000000", "bidQty": "10.00000000", "askPrice": "2.10000100", "askQty": "5.00000000", "openPrice": "2.00000000", "highPrice": "2.20000000", "lowPrice": "1.90000000", "volume": "10000.00000000", "quoteVolume": "21000.00000000", "openTime": 1609459200000, "closeTime": 1609545600000, "firstId": 1, "lastId": 100, "count": 100 } ``` ``` -------------------------------- ### Get 24-Hour Price Statistics (Rust) Source: https://context7.com/ccxt/binance-rs/llms.txt Retrieves comprehensive price change statistics over the last 24 hours for a specific symbol or all symbols on Binance. This includes open, high, low, close prices, and volume. ```rust use binance::api::* use binance::market::* fn main() { let market: Market = Binance::new(None, None); match market.get_24h_price_stats("BNBETH") { Ok(stats) => println!( "Open: {}, High: {}, Low: {}, Close: {}, Volume: {}", stats.open_price, stats.high_price, stats.low_price, stats.last_price, stats.volume ), Err(e) => println!("Error: {}", e), } // All symbols 24h stats match market.get_all_24h_price_stats() { Ok(all_stats) => { for stats in all_stats { println!("{}: Volume {}", stats.symbol, stats.volume); } }, Err(e) => println!("Error: {}", e), } } ``` -------------------------------- ### Get Trade History Source: https://context7.com/ccxt/binance-rs/llms.txt Retrieve historical trades for a symbol, either all trades or those within a specified time range. ```APIDOC ## GET /api/v1/historicalTrades (Conceptual) ### Description Retrieves historical trades for a specified trading symbol. This function can fetch all trades for a symbol, trades starting from a specific timestamp, or trades within a given time range. ### Method GET ### Endpoint `/api/v1/historicalTrades` (conceptual, actual endpoint may vary by library implementation) ### Parameters #### Query Parameters - **symbol** (string) - Required - The trading symbol (e.g., "BTCUSDT"). - **limit** (integer) - Optional - The number of trades to retrieve (default: 500). - **fromId** (integer) - Optional - Trades with ID greater than this value. - **startTime** (integer) - Optional - Retrieves trades starting from this timestamp (milliseconds). - **endTime** (integer) - Optional - Retrieves trades ending at this timestamp (milliseconds). ### Request Example ```json { "symbol": "BTCUSDT" } ``` ### Response #### Success Response (200) - **List of Trades**: An array of trade objects, each containing: - **id** (integer) - Trade ID. - **price** (string) - Trade price. - **qty** (string) - Trade quantity. - **commission** (string) - Commission amount. - **commissionAsset** (string) - Asset used for commission. - **time** (integer) - Timestamp of the trade. #### Response Example ```json [ { "id": 123456789, "price": "45000.50", "qty": "0.001", "commission": "0.0000001", "commissionAsset": "BTC", "time": 1609459200000 } ] ``` ``` -------------------------------- ### Get Order Book Depth (Rust) Source: https://context7.com/ccxt/binance-rs/llms.txt Retrieves the order book, including bids and asks, for a specified trading pair on Binance. Supports fetching the default depth (100) or a custom depth up to 5000. ```rust use binance::api::* use binance::market::* fn main() { let market: Market = Binance::new(None, None); // Default depth (100) match market.get_depth("BNBETH") { Ok(order_book) => { println!("Bids: {:?}", order_book.bids); println!("Asks: {:?}", order_book.asks); }, Err(e) => println!("Error: {}", e), } // Custom depth (5, 10, 20, 50, 100, 500, 1000, 5000) match market.get_custom_depth("BNBETH", 500) { Ok(order_book) => println!("Deep order book: {:?}", order_book), Err(e) => println!("Error: {}", e), } } ``` -------------------------------- ### Get Candlestick Data (Klines) (Rust) Source: https://context7.com/ccxt/binance-rs/llms.txt Fetches historical candlestick (kline) data for technical analysis on Binance. Supports specifying the symbol, interval, limit, and optional start/end times. ```rust use binance::api::* use binance::market::* use binance::model::KlineSummary; fn main() { let market: Market = Binance::new(None, None); // Get last 10 5-minute klines match market.get_klines("BNBETH", "5m", 10, None, None) { Ok(klines) => { match klines { binance::model::KlineSummaries::AllKlineSummaries(klines) => { for kline in klines { println!( "Time: {}, Open: {}, High: {}, Low: {}, Close: {}, Volume: {}", kline.open_time, kline.open, kline.high, kline.low, kline.close, kline.volume ); } } } }, Err(e) => println!("Error: {}", e), } // With time range let start_time: u64 = 1609459200000; // Unix timestamp in ms let end_time: u64 = 1609545600000; match market.get_klines("BTCUSDT", "1h", 100, Some(start_time), Some(end_time)) { Ok(klines) => println!("Retrieved klines in time range"), Err(e) => println!("Error: {}", e), } } ``` -------------------------------- ### Get Order Book Depth Source: https://context7.com/ccxt/binance-rs/llms.txt Retrieves the order book, including bids and asks, for a specified trading pair. Supports fetching default depth or a custom number of bids/asks. ```APIDOC ## Get Order Book Depth ### Description Retrieve the order book with bids and asks for a trading pair. ### Method GET (Implied by library usage) ### Endpoint N/A (Method call on Market client) ### Parameters #### Query Parameters - **symbol** (string) - Required - The trading pair (e.g., "BNBETH"). - **depth** (integer) - Optional - The number of bids/asks to retrieve. Defaults to 100. Accepted values: 5, 10, 20, 50, 100, 500, 1000, 5000. ### Request Example ```rust use binance::api::*; use binance::market::*; fn main() { let market: Market = Binance::new(None, None); // Default depth (100) match market.get_depth("BNBETH") { Ok(order_book) => { println!("Bids: {:?}", order_book.bids); println!("Asks: {:?}", order_book.asks); }, Err(e) => println!("Error: {}", e), } // Custom depth (5, 10, 20, 50, 100, 500, 1000, 5000) match market.get_custom_depth("BNBETH", 500) { Ok(order_book) => println!("Deep order book: {:?}", order_book), Err(e) => println!("Error: {}", e), } } ``` ### Response #### Success Response (200) - **lastUpdateId** (integer) - Last update ID. - **bids** (array of arrays) - Array of bid price/quantity pairs. - **asks** (array of arrays) - Array of ask price/quantity pairs. #### Response Example ```json { "lastUpdateId": 1027024, "bids": [ [ "4.00000000", "431.00000000" ], [ "3.99990000", "100.00000000" ] ], "asks": [ [ "4.00000100", "12.00000000" ], [ "4.00000200", "7.00000000" ] ] } ``` ``` -------------------------------- ### Get Aggregated Trades (Rust) Source: https://context7.com/ccxt/binance-rs/llms.txt Retrieves aggregated trade data for a given symbol. Supports filtering by time range and limiting the number of trades returned. Requires the 'binance' crate. ```rust use binance::api::*; use binance::market::*; fn main() { let market: Market = Binance::new(None, None); // Last 10 aggregated trades match market.get_agg_trades("BNBETH", None, None, None, Some(10)) { Ok(trades) => { for trade in trades { println!( "{} - Price: {}, Qty: {}, Time:જી {}", if trade.maker { "SELL" } else { "BUY" }, trade.price, trade.qty, trade.timestamp ); } }, Err(e) => println!("Error: {}", e), } // Trades within time range let start_time: u64 = 1609459200000; let end_time: u64 = 1609545600000; match market.get_agg_trades("BTCUSDT", None, Some(start_time), Some(end_time), Some(500)) { Ok(trades) => println!("Retrieved {} trades", trades.len()), Err(e) => println!("Error: {}", e), } } ``` -------------------------------- ### Binance Trades Stream Subscription in Rust Source: https://github.com/ccxt/binance-rs/blob/master/README.md This Rust code snippet shows how to subscribe to the aggregated trade data stream for all symbols on Binance. It uses the `binance-rs` crate and WebSockets to receive real-time trade events. The example specifically filters for BTCUSDT trades and prints its average price and closing price. ```rust use binance::websockets::* use std::sync::atomic::{AtomicBool}; fn main() { let keep_running = AtomicBool::new(true); // Used to control the event loop let agg_trade = format!("!ticker@arr"); // All Symbols let mut web_socket = WebSockets::new(|event: WebsocketEvent| { match event { // 24hr rolling window ticker statistics for all symbols that changed in an array. WebsocketEvent::DayTickerAll(ticker_events) => { for tick_event in ticker_events { if tick_event.symbol == "BTCUSDT" { let btcusdt: f32 = tick_event.average_price.parse().unwrap(); let btcusdt_close: f32 = tick_event.current_close.parse().unwrap(); println!("{} - {}", btcusdt, btcusdt_close); } } }, _ => (), }; Ok(()) }); web_socket.connect(&agg_trade).unwrap(); // check error if let Err(e) = web_socket.event_loop(&keep_running) { match e { err => { println!("Error: {:?}", err); } } } } ``` -------------------------------- ### Binance Multiple Streams Subscription in Rust Source: https://github.com/ccxt/binance-rs/blob/master/README.md This Rust code snippet shows how to subscribe to multiple Binance WebSocket streams simultaneously using the `binance-rs` crate. It defines an array of symbols and their desired stream types (e.g., depth order book at 100ms intervals). The example connects to these multiple streams and prints the received depth order book data. ```rust use binance::websockets::* use std::sync::atomic::{AtomicBool}; fn main() { let endpoints = ["ETHBTC", "BNBETH"] .map(|symbol| format!("{}@depth@100ms", symbol.to_lowercase())); let keep_running = AtomicBool::new(true); 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(); // check error if let Err(e) = web_socket.event_loop(&keep_running) { println!("Error: {:?}", e); } web_socket.disconnect().unwrap(); } ``` -------------------------------- ### Get Specific Account Balance (Rust) Source: https://context7.com/ccxt/binance-rs/llms.txt Retrieves the balance for a specific cryptocurrency asset from your Binance account. Requires an authenticated client. This function is useful for checking the available and locked amounts of a particular coin. Requires the 'binance' crate. ```rust use binance::api::*; use binance::account::*; fn main() { let api_key = Some("your_api_key".into()); let secret_key = Some("your_secret_key".into()); let account: Account = Binance::new(api_key, secret_key); match account.get_balance("BTC") { Ok(balance) => println!( "BTC Balance - Free: {}, Locked:જી {}", balance.free, balance.locked ), Err(e) => println!("Error: {}", e), } } ``` -------------------------------- ### Binance Kline Stream Subscription in Rust Source: https://github.com/ccxt/binance-rs/blob/master/README.md This Rust code snippet demonstrates how to subscribe to the kline (candlestick) data stream for a specific symbol on Binance. It uses the `binance-rs` crate and WebSockets to receive kline events, such as high and low prices. The example connects to the 'ethbtc@kline_1m' stream and prints relevant kline data. ```rust use binance::websockets::* use std::sync::atomic::{AtomicBool}; fn main() { let keep_running = AtomicBool::new(true); // Used to control the event loop let kline = format!("{}", "ethbtc@kline_1m"); let mut web_socket = WebSockets::new(|event: WebsocketEvent| { match event { WebsocketEvent::Kline(kline_event) => { println!("Symbol: {}, high: {}, low: {}", kline_event.kline.symbol, kline_event.kline.low, kline_event.kline.high); }, _ => (), }; Ok(()) }); web_socket.connect(&kline).unwrap(); // check error if let Err(e) = web_socket.event_loop(&keep_running) { match e { err => { println!("Error: {:?}", err); } } } web_socket.disconnect().unwrap(); } ``` -------------------------------- ### Get Trade History using Binance Rust API Source: https://context7.com/ccxt/binance-rs/llms.txt Retrieve historical trades for a specific symbol on Binance. This function allows fetching all trades, trades from a specific timestamp, or trades within a defined time range. Requires API credentials. ```rust use binance::api::*; use binance::account::*; fn main() { let api_key = Some("your_api_key".into()); let secret_key = Some("your_secret_key".into()); let account: Account = Binance::new(api_key, secret_key); // All trades for a symbol match account.trade_history("BTCUSDT") { Ok(trades) => { for trade in trades { println!( "Trade ID: {}, Price: {}, Qty: {}, Commission: {} {}", trade.id, trade.price, trade.qty, trade.commission, trade.commission_asset ); } }, Err(e) => println!("Error: {}", e), } // Trades from specific time let start_time: u64 = 1609459200000; match account.trade_history_from("ETHUSDT", start_time) { Ok(trades) => println!("Retrieved {} trades since timestamp", trades.len()), Err(e) => println!("Error: {}", e), } // Trades within time range let end_time: u64 = 1609545600000; match account.trade_history_from_to("BNBBTC", start_time, end_time) { Ok(trades) => println!("Retrieved {} trades in range", trades.len()), Err(e) => println!("Error: {}", e), } } ``` -------------------------------- ### Initialize Market Data Client (Rust) Source: https://context7.com/ccxt/binance-rs/llms.txt Initializes a market data client for accessing public Binance market data without requiring authentication. It takes optional API keys and secrets, and returns a Market client instance. ```rust use binance::api::* use binance::market::* fn main() { let market: Market = Binance::new(None, None); match market.get_price("BTCUSDT") { Ok(price) => println!("BTC Price: {}", price.price), Err(e) => println!("Error: {}", e), } } ``` -------------------------------- ### Initialize Market Data Client Source: https://context7.com/ccxt/binance-rs/llms.txt Creates a client for accessing public market data without requiring authentication. This client can then be used to fetch various market-related information. ```APIDOC ## Initialize Market Data Client ### Description Create a client for accessing public market data without authentication. ### Method GET (Implied by library usage) ### Endpoint N/A (Client Initialization) ### Parameters None for initialization. ### Request Example ```rust use binance::api::*; use binance::market::*; fn main() { let market: Market = Binance::new(None, None); match market.get_price("BTCUSDT") { Ok(price) => println!("BTC Price: {}", price.price), Err(e) => println!("Error: {}", e), } } ``` ### Response #### Success Response (200) - **price** (string) - The current trading price of the symbol. #### Response Example ```json { "symbol": "BTCUSDT", "price": "45000.12345" } ``` ``` -------------------------------- ### Initialize Authenticated Account Client (Rust) Source: https://context7.com/ccxt/binance-rs/llms.txt Initializes an authenticated Binance client using API key and secret key. This client is used for account-specific operations like retrieving balances and placing orders. Requires the 'binance' crate. ```rust use binance::api::*; use binance::account::*; fn main() { let api_key = Some("your_api_key".into()); let secret_key = Some("your_secret_key".into()); let account: Account = Binance::new(api_key, secret_key); match account.get_account() { Ok(info) => { println!("Account balances:"); for balance in info.balances { if balance.free.parse::().unwrap() > 0.0 { println!("{}: Free={}, Locked={}", balance.asset, balance.free, balance.locked); } } }, Err(e) => println!("Error: {}", e), } } ``` -------------------------------- ### Place Custom Orders with Parameters in Rust Source: https://context7.com/ccxt/binance-rs/llms.txt Allows placing orders with fine-grained control over all parameters, including custom options like `icebergQty`. This function requires API keys, secret keys, and a `BTreeMap` for additional parameters. It returns a transaction confirmation with a client order ID or an error. ```rust use binance::api::*; use binance::account::*; use std::collections::BTreeMap; fn main() { let api_key = Some("your_api_key".into()); let secret_key = Some("your_secret_key".into()); let account: Account = Binance::new(api_key, secret_key); // Custom order with additional parameters let mut extra_params = BTreeMap::new(); extra_params.insert("icebergQty".to_string(), "100".to_string()); match account.custom_order_with_params( "BTCUSDT", 0.01, // quantity 50000.0, // price None, // stop_price OrderSide::Buy, OrderType::Limit, TimeInForce::IOC, // Immediate or Cancel Some("my_order_123".into()), // custom client order ID extra_params ) { Ok(transaction) => println!( "Custom order placed - Client Order ID: {}", transaction.client_order_id ), Err(e) => println!("Error: {}", e), } } ``` -------------------------------- ### Place Market Orders (Rust) Source: https://context7.com/ccxt/binance-rs/llms.txt Executes market orders on Binance for buying or selling assets immediately at the best available price. Supports specifying quantity or quote quantity (e.g., spend a specific amount of USDT). Requires an authenticated client. Requires the 'binance' crate. ```rust use binance::api::*; use binance::account::*; fn main() { let api_key = Some("your_api_key".into()); let secret_key = Some("your_secret_key".into()); let account: Account = Binance::new(api_key, secret_key); // Market buy with quantity match account.market_buy("BTCUSDT", 0.001) { Ok(transaction) => println!( "Market buy executed - Price: {}, Qty: {}", transaction.price, transaction.executed_qty ), Err(e) => println!("Error: {}", e), } // Market buy with quote quantity (spend exact USDT amount) match account.market_buy_using_quote_quantity("BTCUSDT", 100.0) { Ok(transaction) => println!( "Bought with $100 - Received: {} BTC", transaction.executed_qty ), Err(e) => println!("Error: {}", e), } // Market sell match account.market_sell("ETHUSDT", 0.5) { Ok(transaction) => println!("Sold 0.5 ETH"), Err(e) => println!("Error: {}", e), } } ``` -------------------------------- ### Place Limit Orders (Rust) Source: https://context7.com/ccxt/binance-rs/llms.txt Places limit buy and sell orders on Binance. You specify the symbol, quantity, and price. The order will only be executed at the specified price or better. Requires an authenticated client. Requires the 'binance' crate. ```rust use binance::api::*; use binance::account::*; fn main() { let api_key = Some("your_api_key".into()); let secret_key = Some("your_secret_key".into()); let account: Account = Binance::new(api_key, secret_key); // Limit buy order match account.limit_buy("ETHBTC", 1.0, 0.05) { Ok(transaction) => println!( "Buy order placed - Order ID: {}, Status: {}", transaction.order_id, transaction.status ), Err(e) => println!("Error: {}", e), } // Limit sell order match account.limit_sell("ETHBTC", 1.0, 0.06) { Ok(transaction) => println!( "Sell order placed - Order ID: {}, Executed Qty: {}", transaction.order_id, transaction.executed_qty ), Err(e) => println!("Error: {}", e), } } ``` -------------------------------- ### Rust: Receive Real-time Account Updates via WebSocket Source: https://context7.com/ccxt/binance-rs/llms.txt This snippet demonstrates how to establish a WebSocket connection to receive real-time account updates from Binance. It handles events such as account balance changes and order fills. Requires API key for authentication. ```rust use binance::api::*; use binance::userstream::*; use binance::websockets::*; use std::sync::atomic::AtomicBool; fn main() { let api_key = Some("your_api_key".into()); let keep_running = AtomicBool::new(true); let user_stream: UserStream = Binance::new(api_key, 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(update) => { println!("Account Update - Event Time: {}", update.event_time); for balance in &update.data.balances { println!( " {}: Free={}, Locked={}", balance.asset, balance.wallet_balance, balance.cross_wallet_balance ); } }, WebsocketEvent::OrderTrade(trade) => { println!( "Order Update - Symbol: {}, Side: {}, Type: {}, Status: {}", trade.symbol, trade.side, trade.order_type, trade.execution_type ); println!(" Price: {}, Qty: {}", trade.price, trade.qty); }, WebsocketEvent::BalanceUpdate(balance_update) => { println!( "Balance Update - Asset: {}, Delta: {}", balance_update.asset, balance_update.balance_delta ); }, _ => () } Ok(()) }); web_socket.connect(&listen_key).unwrap(); if let Err(e) = web_socket.event_loop(&keep_running) { println!("Error: {}", e); } user_stream.close(&listen_key).unwrap(); web_socket.disconnect().unwrap(); } else { println!("Failed to start user stream"); } } ```