### Install Pre-commit CLI Tool Source: https://github.com/unkuseni/rs_bybit/blob/master/README.md Installs the pre-commit CLI tool using Homebrew. Pre-commit is a framework for managing and maintaining multi-language pre-commit hooks. ```shell brew install pre-commit ``` -------------------------------- ### Get Position Info using Bybit API in Rust Source: https://context7.com/unkuseni/rs_bybit/llms.txt Queries the current open positions on Bybit, including P&L information. This Rust example uses the `bybit` crate and requires API keys. It constructs a `PositionRequest` and iterates through the position details, printing relevant data. ```rust use bybit::prelude::*; #[tokio::main] async fn main() -> Result<(), BybitError> { let position: PositionManager = Bybit::new( Some("your_api_key".into()), Some("your_secret_key".into()) ); let request = PositionRequest { category: Category::Linear, symbol: Some("ETHUSDT"), base_coin: None, settle_coin: None, limit: None, }; let response = position.get_info(request).await?; for pos in response.result.list { println!("Symbol: {}, Size: {}, Side: {}", pos.symbol, pos.size, pos.side); println!("Entry Price: {}, Mark Price: {}", pos.avg_price, pos.mark_price); println!("Unrealized PnL: {}", pos.unrealised_pnl); } Ok(()) } ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/unkuseni/rs_bybit/blob/master/README.md Installs the pre-commit hooks for the current repository. This ensures that code changes adhere to project standards before committing. ```shell pre-commit install ``` -------------------------------- ### PositionManager - Get Position Info Source: https://context7.com/unkuseni/rs_bybit/llms.txt Query current open positions with P&L information. ```APIDOC ## GET /api/v5/position/list ### Description Query current open positions with P&L information. ### Method GET ### Endpoint /api/v5/position/list ### Parameters #### Query Parameters - **category** (string) - Required - Order category. e.g., linear, inverse - **symbol** (string) - Optional - Trading pair - **baseCoin** (string) - Optional - Base currency - **settleCoin** (string) - Optional - Settle currency - **limit** (integer) - Optional - Page limit. Default 50, max 100 ### Response #### Success Response (200) - **list** (array) - List of open positions. - **symbol** (string) - Trading pair. - **size** (string) - Position size. - **side** (string) - Position side (e.g., Buy, Sell). - **avgPrice** (string) - Average entry price. - **markPrice** (string) - Current mark price. - **unrealisedPnl** (string) - Unrealized Profit and Loss. #### Response Example ```json { "retCode": 0, "retMsg": "OK", "result": { "list": [ { "symbol": "ETHUSDT", "size": "0.1", "side": "Buy", "avgPrice": "3000", "markPrice": "3050", "unrealisedPnl": "15" } ] } } ``` ``` -------------------------------- ### MarketData - Get Funding Rate History Source: https://context7.com/unkuseni/rs_bybit/llms.txt Retrieve historical funding rates for perpetual contracts. ```APIDOC ## GET /v5/market/funding-history ### Description Retrieve historical funding rates for perpetual contracts. ### Method GET ### Endpoint /v5/market/funding-history ### Parameters #### Query Parameters - **category** (Category) - Required - The category of the trading pair. Must be Linear or Inverse. - **symbol** (string) - Required - The trading pair symbol. - **startTime** (integer) - Optional - The start time in milliseconds. - **endTime** (integer) - Optional - The end time in milliseconds. - **limit** (integer) - Optional - The number of results per page. ### Request Example ```rust use bybit::prelude::*; #[tokio::main] async fn main() -> Result<(), BybitError> { let market: MarketData = Bybit::new(None, None); let request = FundingHistoryRequest::new( Category::Linear, "BTCUSDT", None, None, Some(10), ); let response = market.get_funding_history(request).await?; // Process response Ok(()) } ``` ### Response #### Success Response (200) - **list** (array) - List of funding rate history. - **funding_rate_timestamp** (integer) - The timestamp of the funding rate. - **funding_rate** (string) - The funding rate. #### Response Example ```json { "retCode": 0, "retMsg": "OK", "result": { "category": "Linear", "list": [ { "funding_rate_timestamp": 1678886400000, "funding_rate": "0.0001" } ] } } ``` ``` -------------------------------- ### MarketData - Get Open Interest Source: https://context7.com/unkuseni/rs_bybit/llms.txt Query aggregated open interest data over time intervals. ```APIDOC ## GET /v5/market/open-interest ### Description Query aggregated open interest data over time intervals. ### Method GET ### Endpoint /v5/market/open-interest ### Parameters #### Query Parameters - **category** (Category) - Required - The category of the trading pair. (e.g., Linear, Inverse) - **symbol** (string) - Required - The trading pair symbol. - **interval** (string) - Required - The interval for the data. (e.g., 5min, 15min, 30min, 1h, 4h, 1d) - **startTime** (integer) - Optional - The start time in milliseconds. - **endTime** (integer) - Optional - The end time in milliseconds. - **limit** (integer) - Optional - The number of results per page. ### Request Example ```rust use bybit::prelude::*; #[tokio::main] async fn main() -> Result<(), BybitError> { let market: MarketData = Bybit::new(None, None); let request = OpenInterestRequest::new( Category::Linear, "ETHUSDT", "1h", None, None, Some(24) ); let response = market.get_open_interest(request).await?; // Process response Ok(()) } ``` ### Response #### Success Response (200) - **list** (array) - List of open interest data. - **timestamp** (integer) - The timestamp of the data. - **open_interest** (string) - The open interest value. #### Response Example ```json { "retCode": 0, "retMsg": "OK", "result": { "category": "Linear", "list": [ { "timestamp": 1678886400000, "open_interest": "100000" } ] } } ``` ``` -------------------------------- ### Batch Place Orders using Bybit API in Rust Source: https://context7.com/unkuseni/rs_bybit/llms.txt Submits multiple orders in a single API call to Bybit for improved efficiency. This example uses the Bybit Rust crate and requires API keys. It constructs a `BatchPlaceRequest` with a vector of `OrderRequest` objects. ```rust use bybit::prelude::*; #[tokio::main] async fn main() -> Result<(), BybitError> { let trader: Trader = Bybit::new( Some("your_api_key".into()), Some("your_secret_key".into()) ); let orders = vec![ OrderRequest { symbol: "ETHUSDT".into(), side: Side::Buy, qty: 0.1, order_type: OrderType::Market, ..Default::default() }, OrderRequest { symbol: "BTCUSDT".into(), side: Side::Buy, qty: 0.001, order_type: OrderType::Market, ..Default::default() }, ]; let batch_request = BatchPlaceRequest::new(Category::Linear, orders); let response = trader.batch_place_order(batch_request).await?; for result in response.result.list { println!("Order placed: {}", result.order_id); } Ok(()) } ``` -------------------------------- ### MarketData - Get Instrument Info Source: https://context7.com/unkuseni/rs_bybit/llms.txt Query trading instrument specifications including lot sizes, price filters, and leverage limits. ```APIDOC ## GET /v5/market/instruments ### Description Query trading instrument specifications including lot sizes, price filters, and leverage limits. ### Method GET ### Endpoint /v5/market/instruments ### Parameters #### Query Parameters - **category** (Category) - Required - The category of the trading pair. (e.g., Linear, Inverse) - **symbol** (string) - Optional - The trading pair symbol. (e.g., ETHUSDT) - **status** (boolean) - Optional - Filter by instrument status. `true` for trading instruments. - **baseCoin** (string) - Optional - Filter by base currency. - **limit** (integer) - Optional - The number of results per page. ### Request Example ```rust use bybit::prelude::*; #[tokio::main] async fn main() -> Result<(), BybitError> { let market: MarketData = Bybit::new(None, None); let request = InstrumentRequest::new( Category::Linear, Some("ETHUSDT"), Some(true), None, None, ); let response = market.get_instrument_info(request).await?; // Process response Ok(()) } ``` ### Response #### Success Response (200) - **list** (array) - List of instrument details. - **symbol** (string) - The trading pair symbol. - **lot_size_filter** (object) - Lot size filter details. - **min_order_qty** (string) - Minimum order quantity. - **leverage_filter** (object) - Leverage filter details. - **max_leverage** (string) - Maximum leverage allowed. #### Response Example ```json { "retCode": 0, "retMsg": "OK", "result": { "category": "Linear", "list": [ { "symbol": "ETHUSDT", "lot_size_filter": { "max_order_qty": "100000", "min_order_qty": "0.001", "qty_step": "0.001", "post_only_max_order_qty": "0" }, "leverage_filter": { "min_leverage": 1, "max_leverage": 100, "leverage_step": 1 } } ] } } ``` ``` -------------------------------- ### Trader - Get Open Orders Source: https://context7.com/unkuseni/rs_bybit/llms.txt Query currently active unfilled orders. ```APIDOC ## GET /api/v5/order/open ### Description Query currently active unfilled orders. ### Method GET ### Endpoint /api/v5/order/open ### Parameters #### Query Parameters - **category** (string) - Required - Order category. e.g., linear, inverse - **symbol** (string) - Optional - Trading pair - **baseCoin** (string) - Optional - Base currency - **settleCoin** (string) - Optional - Settle currency - **orderId** (string) - Optional - Order ID - **orderLinkId** (string) - Optional - User-defined order link ID - **openOnly** (integer) - Optional - Query open orders only. 0: all, 1: only open - **orderFilter** (string) - Optional - Filter for order type. e.g., Order, StopOrder - **limit** (integer) - Optional - Page limit. Default 50, max 100 ### Response #### Success Response (200) - **list** (array) - List of open orders. - **orderId** (string) - Order ID. - **side** (string) - Order side (Buy or Sell). - **qty** (string) - Order quantity. - **price** (string) - Order price. #### Response Example ```json { "retCode": 0, "retMsg": "OK", "result": { "list": [ { "orderId": "123456789", "side": "Buy", "qty": "0.1", "price": "30000" } ] } } ``` ``` -------------------------------- ### Bybit Error Handling Example (Rust) Source: https://context7.com/unkuseni/rs_bybit/llms.txt Demonstrates robust error handling for Bybit API requests using the `BybitError` enum. It shows how to match against different error variants like `BybitError`, `Unauthorized`, and `InternalServerError` to provide specific feedback or retry logic. ```rust use bybit::prelude::*; #[tokio::main] async fn main() { let market: MarketData = Bybit::new(None, None); let request = KlineRequest::new(Some(Category::Linear), "INVALID", "60", None, None, None); match market.get_klines(request).await { Ok(response) => { println!("Klines retrieved: {}", response.result.list.len()); } Err(BybitError::BybitError(content)) => { println!("API Error Code: {}, Message: {}", content.code, content.msg); // Check typed error if let Some(typed) = content.typed() { println!("Typed error: {:?}", typed); } } Err(BybitError::Unauthorized) => { println!("Authentication failed - check API credentials"); } Err(BybitError::InternalServerError) => { println!("Server error - retry later"); } Err(e) => { println!("Other error: {}", e); } } } ``` -------------------------------- ### MarketData - Get Order Book Depth Source: https://context7.com/unkuseni/rs_bybit/llms.txt Fetch real-time order book snapshots for a given symbol and category. Allows specifying the depth of the order book to retrieve. ```APIDOC ## MarketData - Get Order Book Depth ### Description Fetch real-time order book snapshots with configurable depth levels. ### Method `market.get_depth(request)` ### Endpoint `/v5/market/orderbook` ### Parameters #### Query Parameters - **symbol** (String) - Required. Trading pair symbol (e.g., "ETHUSDT"). - **category** (Category) - Required. Market category (e.g., `Linear`, `Inverse`, `Spot`, `Option`). - **limit** (Option) - Optional. Number of data entries to return. Default is 25. Valid values: 1, 5, 10, 20, 50, 100, 200, 500, 1000. ### Request Example ```rust use bybit::prelude::*; #[tokio::main] async fn main() -> Result<(), BybitError> { let market: MarketData = Bybit::new(None, None); let request = OrderbookRequest::new( "ETHUSDT", // Symbol Category::Linear, // Category Some(25), // Depth limit (1, 25, 50, 100, 200) ); let response = market.get_depth(request).await?; let orderbook = response.result; // Access best bid/ask let best_bid = &orderbook.bids[0]; let best_ask = &orderbook.asks[0]; let mid_price = (best_bid.price + best_ask.price) / 2.0; let spread = best_ask.price - best_bid.price; println!("Best Bid: {} @ {}", best_bid.qty, best_bid.price); println!("Best Ask: {} @ {}", best_ask.qty, best_ask.price); println!("Mid Price: {:.2}, Spread: {:.4}", mid_price, spread); Ok(()) } ``` ### Response #### Success Response (200) - **bids** (Vec) - List of bid orders. - **price** (f64) - Price of the bid. - **qty** (f64) - Quantity of the bid. - **asks** (Vec) - List of ask orders. - **price** (f64) - Price of the ask. - **qty** (f64) - Quantity of the ask. - **update_id** (i64) - Update ID for the order book. #### Response Example ```json { "retCode": 0, "retMsg": "OK", "result": { "symbol": "ETHUSDT", "category": "Linear", "updateId": 123456789, "bids": [ {"price": "2310.50", "qty": "10.50"}, {"price": "2310.00", "qty": "20.00"} ], "asks": [ {"price": "2311.00", "qty": "15.20"}, {"price": "2311.50", "qty": "25.80"} ] } } ``` ``` -------------------------------- ### Trader - Get Order History Source: https://context7.com/unkuseni/rs_bybit/llms.txt Retrieve historical orders with filtering options. ```APIDOC ## GET /api/v5/order/history ### Description Retrieve historical orders with filtering options. ### Method GET ### Endpoint /api/v5/order/history ### Parameters #### Query Parameters - **category** (string) - Required - Order category. e.g., linear, inverse - **symbol** (string) - Optional - Trading pair - **baseCoin** (string) - Optional - Base currency - **settleCoin** (string) - Optional - Settle currency - **orderId** (string) - Optional - Order ID - **orderLinkId** (string) - Optional - User-defined order link ID - **orderFilter** (string) - Optional - Filter for order type. e.g., Order, StopOrder - **orderStatus** (string) - Optional - Order status - **startTime** (integer) - Optional - Start timestamp (ms) - **endTime** (integer) - Optional - End timestamp (ms) - **limit** (integer) - Optional - Page limit. Default 50, max 100 ### Response #### Success Response (200) - **list** (array) - List of historical orders. - **orderId** (string) - Order ID. - **symbol** (string) - Trading pair. - **side** (string) - Order side (Buy or Sell). - **qty** (string) - Order quantity. - **price** (string) - Order price. - **orderStatus** (string) - Order status. #### Response Example ```json { "retCode": 0, "retMsg": "OK", "result": { "list": [ { "orderId": "123456789", "symbol": "ETHUSDT", "side": "Buy", "qty": "0.1", "price": "30000", "orderStatus": "Filled" } ] } } ``` ``` -------------------------------- ### MarketData - Get Tickers Source: https://context7.com/unkuseni/rs_bybit/llms.txt Retrieve 24-hour ticker statistics for one or all symbols within a specified category. Provides information like last price, high/low prices, volume, and funding rate. ```APIDOC ## MarketData - Get Tickers ### Description Retrieve 24-hour ticker statistics for one or all symbols. ### Method `market.get_tickers(symbol, category)` ### Endpoint `/v5/market/tickers` ### Parameters #### Query Parameters - **symbol** (Option) - Optional. Trading pair symbol (e.g., "ETHUSDT"). If not provided, tickers for all symbols in the category are returned. - **category** (Category) - Required. Market category (e.g., `Linear`, `Inverse`, `Spot`, `Option`). ### Request Example ```rust use bybit::prelude::*; #[tokio::main] async fn main() -> Result<(), BybitError> { let market: MarketData = Bybit::new(None, None); // Single symbol ticker let response = market.get_tickers(Some("ETHUSDT"), Category::Linear).await?; for ticker_data in response.result.list { match ticker_data { TickerData::Futures(ticker) => { println!("Symbol: {}", ticker.symbol); println!("Last Price: {}", ticker.last_price); println!("24h High: {}, 24h Low: {}", ticker.high_price_24h, ticker.low_price_24h); println!("24h Volume: {}", ticker.volume_24h); println!("Funding Rate: {}", ticker.funding_rate); } TickerData::Spot(ticker) => { println!("Spot Symbol: {}, Price: {}", ticker.symbol, ticker.last_price); } } } Ok(()) } ``` ### Response #### Success Response (200) - **list** (Vec) - A list of ticker data objects. The structure within the list depends on the `Category`. - **TickerData::Futures**: - **symbol** (String) - Trading pair symbol. - **last_price** (String) - Last traded price. - **high_price_24h** (String) - Highest price in the last 24 hours. - **low_price_24h** (String) - Lowest price in the last 24 hours. - **volume_24h** (String) - Trading volume in the last 24 hours. - **funding_rate** (String) - Current funding rate. - **TickerData::Spot**: - **symbol** (String) - Trading pair symbol. - **last_price** (String) - Last traded price. #### Response Example ```json { "retCode": 0, "retMsg": "OK", "result": { "category": "Linear", "list": [ { "symbol": "ETHUSDT", "tickDirection": "", "priceChange": "-50.00", "priceChangePercent": "-2.13", "lastPrice": "2300.00", "highPrice24h": "2380.00", "lowPrice24h": "2250.00", "prevPrice24h": "2350.00", "volume24h": "150000.00", "turnover24h": "34500000.00", "frontTurnover24h": "34500000.00", "inAmount24h": "70000.00", "outAmount24h": "80000.00", "fundingRate": "0.0001", "averagePrice24h": "2300.00", "markPrice": "2301.00", "indexPrice": "2300.50", "premium_rate": "0.00005", "openInterest": "500000", "open24h": "2350.00", "volume30min": "1000.00", "turnover30min": "2300000.00", "delta24h": "-10000" } ] } } ``` ``` -------------------------------- ### Get Wallet Balance Source: https://context7.com/unkuseni/rs_bybit/llms.txt Retrieves wallet balances for a specified account type and currency. Supports UNIFIED, CONTRACT, and SPOT account types. Outputs coin, wallet balance, and available withdrawal amounts. ```rust use bybit::prelude::*; #[tokio::main] async fn main() -> Result<(), BybitError> { let account: AccountManager = Bybit::new( Some("your_api_key".into()), Some("your_secret_key".into()) ); // Account types: UNIFIED, CONTRACT, SPOT let response = account.get_wallet_balance("UNIFIED", Some("USDT")).await?; for wallet in response.result.list { for coin in wallet.coin { println!("Coin: {}", coin.coin); println!("Wallet Balance: {}", coin.wallet_balance); println!("Available: {}", coin.available_to_withdraw); } } Ok(()) } ``` -------------------------------- ### Get Fee Rate Source: https://context7.com/unkuseni/rs_bybit/llms.txt Queries trading fee rates for a given symbol and category. Requires API keys and returns maker and taker fee rates for the specified symbol. ```rust use bybit::prelude::*; #[tokio::main] async fn main() -> Result<(), BybitError> { let account: AccountManager = Bybit::new( Some("your_api_key".into()), Some("your_secret_key".into()) ); let response = account.get_fee_rate( Category::Linear, Some("ETHUSDT".to_string()) ).await?; for fee in response.result.list { println!("Symbol: {}", fee.symbol); println!("Maker Fee: {}", fee.maker_fee_rate); println!("Taker Fee: {}", fee.taker_fee_rate); } Ok(()) } ``` -------------------------------- ### MarketData - Get Klines Source: https://context7.com/unkuseni/rs_bybit/llms.txt Retrieve historical candlestick data (kline data) for a specified trading pair, interval, and date range. Supports various intervals and limits the number of results. ```APIDOC ## MarketData - Get Klines (Candlestick Data) ### Description Retrieve historical candlestick data for any trading pair with configurable intervals and date ranges. ### Method `market.get_klines(request)` ### Endpoint `/v5/market/kline` ### Parameters #### Query Parameters - **category** (Category) - Required. Market category (e.g., `Linear`, `Inverse`, `Spot`, `Option`). - **symbol** (String) - Required. Trading pair symbol (e.g., "ETHUSDT"). - **interval** (String) - Required. Candlestick interval (e.g., "1", "60", "D"). - **start** (Option) - Optional. Start date in DDMMYY format. - **end** (Option) - Optional. End date in DDMMYY format. - **limit** (Option) - Optional. Maximum number of results (default is 200). ### Request Example ```rust use bybit::prelude::*; #[tokio::main] async fn main() -> Result<(), BybitError> { let market: MarketData = Bybit::new(None, None); let request = KlineRequest::new( Some(Category::Linear), // Market category "ETHUSDT", // Symbol "60", // Interval: 1, 3, 5, 15, 30, 60, 120, 240, 360, 720, D, M, W Some("010124"), // Start date (DDMMYY format) Some("050224"), // End date (DDMMYY format) Some(200), // Limit (max results) ); let response = market.get_klines(request).await?; for kline in response.result.list { println!("Open: {}, High: {}, Low: {}, Close: {}, Volume: {}", kline.open, kline.high, kline.low, kline.close, kline.volume); } Ok(()) } ``` ### Response #### Success Response (200) - **list** (Vec) - A list of candlestick data objects. - **open** (String) - Opening price. - **high** (String) - Highest price. - **low** (String) - Lowest price. - **close** (String) - Closing price. - **volume** (String) - Trading volume. - **timestamp** (i64) - Timestamp of the kline. #### Response Example ```json { "retCode": 0, "retMsg": "OK", "result": { "category": "Linear", "symbol": "ETHUSDT", "list": [ { "open": "2300.00", "high": "2350.00", "low": "2280.00", "close": "2320.00", "volume": "1000.00", "turnover": "2320000.00", "timestamp": 1678886400000, "startTime": "2024-01-01T00:00:00.000Z", "endTime": "2024-01-01T00:59:59.999Z" } ] } } ``` ``` -------------------------------- ### Get Instrument Info - Rust Source: https://context7.com/unkuseni/rs_bybit/llms.txt Retrieves trading instrument specifications like lot sizes, price filters, and leverage limits for Bybit's linear and spot markets. It requires the `bybit` crate and `tokio` for async execution. The function takes an `InstrumentRequest` and returns detailed information about the instruments. ```rust use bybit::prelude::*; #[tokio::main] async fn main() -> Result<(), BybitError> { let market: MarketData = Bybit::new(None, None); let request = InstrumentRequest::new( Category::Linear, // Category Some("ETHUSDT"), // Symbol (optional, None for all) Some(true), // Status filter (trading only) None, // Base coin filter None, // Limit ); let response = market.get_instrument_info(request).await?; match response.result { InstrumentInfo::Futures(info) => { for instrument in info.list { println!("Symbol: {}", instrument.symbol); println!("Min Order Qty: {}", instrument.lot_size_filter.min_order_qty); println!("Max Leverage: {}", instrument.leverage_filter.max_leverage); } } InstrumentInfo::Spot(info) => { for instrument in info.list { println!("Spot: {}", instrument.symbol); } } } Ok(()) } ``` -------------------------------- ### Get Open Orders using Bybit API in Rust Source: https://context7.com/unkuseni/rs_bybit/llms.txt Retrieves a list of currently active, unfilled orders for a specified symbol. This function requires the Bybit Rust crate and API credentials. It accepts an `OpenOrdersRequest` and iterates through the results, printing order details. ```rust use bybit::prelude::*; #[tokio::main] async fn main() -> Result<(), BybitError> { let trader: Trader = Bybit::new( Some("your_api_key".into()), Some("your_secret_key".into()) ); let request = OpenOrdersRequest { category: Category::Linear, symbol: "ETHUSDT".into(), base_coin: None, settle_coin: None, order_id: None, order_link_id: None, open_only: Some(0), order_filter: None, limit: Some(50), }; let response = trader.get_open_orders(request).await?; for order in response.result.list { println!("Order: {} {} {} @ {}", order.order_id, order.side, order.qty, order.price); } Ok(()) } ``` -------------------------------- ### Get Funding Rate History - Rust Source: https://context7.com/unkuseni/rs_bybit/llms.txt Fetches historical funding rates for perpetual contracts on Bybit. This function requires the `bybit` crate and `tokio`. It takes a `FundingHistoryRequest` specifying the category, symbol, time range, and limit, returning a list of funding rate records. ```rust use bybit::prelude::*; #[tokio::main] async fn main() -> Result<(), BybitError> { let market: MarketData = Bybit::new(None, None); let request = FundingHistoryRequest::new( Category::Linear, // Must be Linear or Inverse "BTCUSDT", // Symbol None, // Start time (milliseconds) None, // End time (milliseconds) Some(10), // Limit ); let response = market.get_funding_history(request).await?; for rate in response.result.list { println!("Time: {}, Rate: {}", rate.funding_rate_timestamp, rate.funding_rate); } Ok(()) } ``` -------------------------------- ### Get Order History using Bybit API in Rust Source: https://context7.com/unkuseni/rs_bybit/llms.txt Retrieves historical order data from Bybit with various filtering capabilities. This Rust code snippet utilizes the `bybit` crate and requires authentication. It constructs an `OrderHistoryRequest` and processes the returned list of orders. ```rust use bybit::prelude::*; #[tokio::main] async fn main() -> Result<(), BybitError> { let trader: Trader = Bybit::new( Some("your_api_key".into()), Some("your_secret_key".into()) ); let request = OrderHistoryRequest::new( Category::Linear, Some("ETHUSDT"), // Symbol filter None, // Base coin None, // Settle coin None, // Order ID None, // Order link ID None, // Order filter None, // Order status None, // Start time None, // End time Some(50), // Limit ); let response = trader.get_order_history(request).await?; for order in response.result.list { println!("{}: {} {} {} @ {} - Status: {}", order.order_id, order.symbol, order.side, order.qty, order.price, order.order_status); } Ok(()) } ``` -------------------------------- ### Get Open Interest - Rust Source: https://context7.com/unkuseni/rs_bybit/llms.txt Queries aggregated open interest data over specified time intervals for Bybit. This function uses the `bybit` crate and `tokio`. It accepts an `OpenInterestRequest` with category, symbol, interval, time range, and limit, returning open interest data points. ```rust use bybit::prelude::*; #[tokio::main] async fn main() -> Result<(), BybitError> { let market: MarketData = Bybit::new(None, None); let request = OpenInterestRequest::new( Category::Linear, "ETHUSDT", "1h", // Interval: 5min, 15min, 30min, 1h, 4h, 1d None, // Start time None, // End time Some(24) // Limit ); let response = market.get_open_interest(request).await?; for oi in response.result.list { println!("Timestamp: {}, Open Interest: {}", oi.timestamp, oi.open_interest); } Ok(()) } ``` -------------------------------- ### Client Initialization Source: https://context7.com/unkuseni/rs_bybit/llms.txt Demonstrates how to initialize the Bybit API client for both public and authenticated endpoints, including custom configurations for testnet and receive windows. ```APIDOC ## Client Initialization ### Description Initialize the Bybit API client for public or authenticated endpoints. Supports custom configurations for testnet and receive windows. ### Method `Bybit::new()` or `Bybit::new_with_config()` ### Parameters #### Public Endpoints - **api_key** (Option) - `None` for public access. - **secret_key** (Option) - `None` for public access. #### Authenticated Endpoints - **api_key** (Option) - Your Bybit API key. - **secret_key** (Option) - Your Bybit secret key. #### Custom Configuration - **config** (Config) - Optional configuration object (e.g., `Config::testnet()`, `Config::default().set_recv_window(3000)`). ### Request Example ```rust use bybit::prelude::*; // Public endpoints let market: MarketData = Bybit::new(None, None); // Authenticated endpoints let api_key = "your_api_key".to_string(); let secret_key = "your_secret_key".to_string(); let trader: Trader = Bybit::new(Some(api_key.clone()), Some(secret_key.clone())); // Custom configuration (testnet) let config = Config::testnet(); let testnet_market: MarketData = Bybit::new_with_config(&config, None, None); // Custom receive window let custom_config = Config::default().set_recv_window(3000); let market: MarketData = Bybit::new_with_config(&custom_config, None, None); ``` ### Response Returns an initialized client instance (e.g., `MarketData`, `Trader`). ``` -------------------------------- ### Initialize Bybit API Clients Source: https://context7.com/unkuseni/rs_bybit/llms.txt Demonstrates how to initialize Bybit API clients using the Bybit trait. Supports public and authenticated endpoints, custom configurations for testnet, and custom receive windows. ```rust use bybit::prelude::*; // Public endpoints (no authentication required) let market: MarketData = Bybit::new(None, None); // Authenticated endpoints let api_key = "your_api_key".to_string(); let secret_key = "your_secret_key".to_string(); let trader: Trader = Bybit::new(Some(api_key.clone()), Some(secret_key.clone())); // Custom configuration (testnet) let config = Config::testnet(); let testnet_market: MarketData = Bybit::new_with_config(&config, None, None); // Custom receive window let custom_config = Config::default().set_recv_window(3000); let market: MarketData = Bybit::new_with_config(&custom_config, None, None); ``` -------------------------------- ### PositionManager - Set Leverage Source: https://context7.com/unkuseni/rs_bybit/llms.txt Configure leverage for a trading pair. ```APIDOC ## POST /api/v5/position/set-leverage ### Description Configure leverage for a trading pair. ### Method POST ### Endpoint /api/v5/position/set-leverage ### Parameters #### Query Parameters - **category** (string) - Required - Order category. e.g., linear, inverse ### Request Body - **symbol** (string) - Required - Trading pair - **leverage** (integer) - Required - Leverage value (e.g., 10 for 10x) ### Request Example ```json { "category": "linear", "symbol": "ETHUSDT", "leverage": 10 } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. #### Response Example ```json { "retCode": 0, "retMsg": "OK", "result": { "success": true } } ``` ``` -------------------------------- ### Trader - Batch Place Orders Source: https://context7.com/unkuseni/rs_bybit/llms.txt Submit multiple orders in a single API call for efficient execution. ```APIDOC ## POST /api/v5/order/batch-create ### Description Submit multiple orders in a single API call for efficient execution. ### Method POST ### Endpoint /api/v5/order/batch-create ### Parameters #### Query Parameters - **category** (string) - Required - Order category. e.g., linear, inverse ### Request Body - **orders** (array) - Required - List of orders to place. - **symbol** (string) - Required - Trading pair - **side** (string) - Required - Order side (Buy or Sell) - **qty** (number) - Required - Order quantity - **orderType** (string) - Required - Order type (e.g., Market, Limit) - **...other order parameters** ### Request Example ```json { "category": "linear", "orders": [ { "symbol": "ETHUSDT", "side": "Buy", "qty": 0.1, "orderType": "Market" }, { "symbol": "BTCUSDT", "side": "Buy", "qty": 0.001, "orderType": "Market" } ] } ``` ### Response #### Success Response (200) - **list** (array) - List of results for each order placed. - **orderId** (string) - The ID of the placed order. #### Response Example ```json { "retCode": 0, "retMsg": "OK", "result": { "list": [ { "orderId": "123456789" }, { "orderId": "987654321" } ] } } ``` ``` -------------------------------- ### Trader - Place Order Source: https://context7.com/unkuseni/rs_bybit/llms.txt Submit trading orders with full customization of order types, time-in-force, and TP/SL settings. ```APIDOC ## POST /v5/order/create ### Description Submit trading orders with full customization of order types, time-in-force, and TP/SL settings. ### Method POST ### Endpoint /v5/order/create ### Parameters #### Request Body - **category** (Category) - Required - The category of the trading pair. (e.g., Linear, Inverse) - **symbol** (string) - Required - The trading pair symbol. - **side** (Side) - Required - The order side. (Buy or Sell) - **orderType** (OrderType) - Required - The type of order. (e.g., Limit, Market) - **qty** (number) - Required - The quantity of the order. - **price** (number) - Optional - The price for limit orders. - **timeInForce** (string) - Optional - The time in force for the order. (e.g., GTC, IOC, FOK) - **takeProfit** (number) - Optional - The take profit price. - **stopLoss** (number) - Optional - The stop loss price. - **reduceOnly** (boolean) - Optional - Whether to reduce the position only. - **positionIdx** (integer) - Optional - The position index. (0: one-way, 1: hedge buy, 2: hedge sell) - **orderLinkId** (string) - Optional - Unique ID for the order. ### Request Example ```rust use bybit::prelude::*; use std::borrow::Cow; #[tokio::main] async fn main() -> Result<(), BybitError> { let trader: Trader = Bybit::new( Some("your_api_key".into()), Some("your_secret_key".into()) ); // Simple limit order let response = trader.place_futures_limit_order( Category::Linear, "ETHUSDT", Side::Buy, 0.1, 2500.0, 0, ).await?; println!("Order ID: {}", response.result.order_id); // Custom order with advanced options let custom_order = OrderRequest { category: Category::Linear, symbol: Cow::Borrowed("BTCUSDT"), side: Side::Buy, qty: 0.01, order_type: OrderType::Limit, price: Some(40000.0), time_in_force: Some("GTC"), take_profit: Some(45000.0), stop_loss: Some(38000.0), reduce_only: Some(false), position_idx: Some(0), ..Default::default() }; let response = trader.place_custom_order(custom_order).await?; println!("Custom Order ID: {}", response.result.order_id); Ok(()) } ``` ### Response #### Success Response (200) - **order_id** (string) - The ID of the placed order. #### Response Example ```json { "retCode": 0, "retMsg": "OK", "result": { "order_id": "1234567890" } } ``` ``` -------------------------------- ### Place Order - Rust Source: https://context7.com/unkuseni/rs_bybit/llms.txt Submits trading orders to Bybit with full customization, including order types, time-in-force, and TP/SL settings. This function requires API keys and uses the `bybit` and `tokio` crates. It supports both simple and custom order placements. ```rust use bybit::prelude::*; use std::borrow::Cow; #[tokio::main] async fn main() -> Result<(), BybitError> { let trader: Trader = Bybit::new( Some("your_api_key".into()), Some("your_secret_key".into()) ); // Simple limit order let response = trader.place_futures_limit_order( Category::Linear, "ETHUSDT", Side::Buy, 0.1, // Quantity 2500.0, // Price 0, // Position index: 0=one-way, 1=buy hedge, 2=sell hedge ).await?; println!("Order ID: {}", response.result.order_id); // Custom order with advanced options let custom_order = OrderRequest { category: Category::Linear, symbol: Cow::Borrowed("BTCUSDT"), side: Side::Buy, qty: 0.01, order_type: OrderType::Limit, price: Some(40000.0), time_in_force: Some("GTC"), take_profit: Some(45000.0), stop_loss: Some(38000.0), reduce_only: Some(false), position_idx: Some(0), ..Default::default() }; let response = trader.place_custom_order(custom_order).await?; println!("Custom Order ID: {}", response.result.order_id); Ok(()) } ``` -------------------------------- ### WebSocket Subscribe to Order Book Source: https://context7.com/unkuseni/rs_bybit/llms.txt Subscribes to real-time order book updates for specified symbols and depths via WebSocket. Uses `tokio::sync::mpsc` for receiving updates and supports different depth levels. ```rust use bybit::prelude::*; use tokio::sync::mpsc; #[tokio::main] async fn main() -> Result<(), BybitError> { let ws: Stream = Bybit::new(None, None); let (tx, mut rx) = mpsc::unbounded_channel(); // (depth, symbol) pairs - depth: 1, 50, 200, 500 let subscriptions = vec![(50, "ETHUSDT"), (50, "BTCUSDT")]; tokio::spawn(async move { ws.ws_orderbook(subscriptions, Category::Linear, tx).await.unwrap(); }); while let Some(update) = rx.recv().await { println!("Order Book Update - Type: {}", update.update_type); println!("Best Bid: {:?}", update.data.bids.first()); println!("Best Ask: {:?}", update.data.asks.first()); } Ok(()) } ```