### Time Format Example (Unix Seconds) Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-history-plant.md Illustrates the use of Unix seconds (i32) for time parameters like start, end, and since. ```rust // January 1, 2024 00:00:00 UTC let start = 1704067200i32; // January 2, 2024 00:00:00 UTC let end = 1704153600i32; ``` -------------------------------- ### Complete Rithmic RS Setup and Connection Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/configuration.md This snippet demonstrates how to load configuration from environment variables or build it programmatically. It then connects to the Rithmic ticker plant, logs in, and subscribes to a symbol. Use this for a full-fledged application setup. ```rust use rithmic_rs::{RithmicConfig, RithmicAccount, RithmicEnv, ConnectStrategy, RithmicTickerPlant}; #[tokio::main] async fn main() -> Result<(), Box> { // Option 1: Load from environment variables let config = RithmicConfig::from_env(RithmicEnv::Demo)?; let account = RithmicAccount::from_env(RithmicEnv::Demo)?; // Option 2: Build programmatically /* let config = RithmicConfig::builder(RithmicEnv::Demo) .user("my_user".to_string()) .password("my_password".to_string()) .url("wss://demo.rithmic.com:443".to_string()) .beta_url("wss://demo-alt.rithmic.com:443".to_string()) .app_name("my_app".to_string()) .app_version("1".to_string()) .build()?; let account = RithmicAccount::new("my_fcm", "my_ib", "my_account"); */ // Connect to ticker plant let ticker_plant = RithmicTickerPlant::connect(&config, ConnectStrategy::Retry).await?; let mut handle = ticker_plant.get_handle(); handle.login().await?; handle.subscribe("ESM6", "CME").await?; // ... use the handle handle.disconnect().await?; Ok(()) } ``` -------------------------------- ### TrailingStop Examples Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-response.md Illustrates how to create `TrailingStop` instances for dollar/tick and percentage-based trailing stops. ```rust use rithmic_rs::TrailingStop; // Trail by $5 let trailing = TrailingStop { amount: 5.0, is_percent: false, }; // Trail by 0.5% let trailing_pct = TrailingStop { amount: 0.5, is_percent: true, }; ``` -------------------------------- ### Example Usage of BarType Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-history-plant.md Demonstrates how to specify the BarType when loading time bars. ```rust use rithmic_rs::util::BarType; let bars = handle.load_time_bars("ESM6", "CME", BarType::MinuteBar, 5, start, end).await?; ``` -------------------------------- ### Complete Order Placement Example Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-response.md Demonstrates placing a limit order and a bracket order using the Rithmic API. Ensure RithmicConfig and RithmicAccount are properly configured from environment variables. ```rust use rithmic_rs::{ RithmicOrder, RithmicBracketOrder, RithmicModifyOrder, NewOrderTransactionType, NewOrderPriceType, NewOrderDuration, BracketTransactionType, BracketPriceType, }; #[tokio::main] async fn main() -> Result<(), Box> { let config = RithmicConfig::from_env(RithmicEnv::Demo)?; let account = RithmicAccount::from_env(RithmicEnv::Demo)?; let order_plant = RithmicOrderPlant::connect(&config, ConnectStrategy::Retry).await?; let handle = order_plant.get_handle(&account); handle.login().await?; // Place a limit order let order = RithmicOrder { symbol: "ESM6".to_string(), exchange: "CME".to_string(), quantity: 2, price: 5000.0, transaction_type: NewOrderTransactionType::Buy, price_type: NewOrderPriceType::Limit, user_tag: "entry_order".to_string(), order_duration: Some(NewOrderDuration::Day), ..Default::default() }; let resp = handle.place_order(order).await?; if let Some(err) = &resp.error { eprintln!("Order rejected: {}", err); } else { println!("Order placed successfully"); } // Place a bracket order let bracket = RithmicBracketOrder { symbol: "ESM6".to_string(), exchange: "CME".to_string(), quantity: 1, transaction_type: BracketTransactionType::Buy, price_type: BracketPriceType::Limit, price: 5001.0, profit_target_price: 5011.0, stop_price: 4991.0, user_tag: "bracket_entry".to_string(), ..Default::default() }; handle.place_bracket_order(bracket).await?; handle.disconnect().await?; Ok(()) } ``` -------------------------------- ### Placing a Limit Buy Order Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-response.md Example of creating and placing a Limit Buy order with specified symbol, quantity, price, and duration. ```rust use rithmic_rs::{RithmicOrder, NewOrderTransactionType, NewOrderPriceType, NewOrderDuration}; let order = RithmicOrder { symbol: "ESM6".to_string(), exchange: "CME".to_string(), quantity: 2, price: 5000.0, transaction_type: NewOrderTransactionType::Buy, price_type: NewOrderPriceType::Limit, user_tag: "scalp_001".to_string(), order_duration: Some(NewOrderDuration::Day), stop_price: None, ..Default::default() }; handle.place_order(order).await?; ``` -------------------------------- ### Complete Rithmic PnL Plant Usage Example Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-pnl-plant.md Demonstrates connecting to the PnL plant, logging in, fetching a P&L snapshot, subscribing to real-time updates, processing updates, and disconnecting. ```rust use rithmic_rs::{ RithmicConfig, RithmicEnv, ConnectStrategy, RithmicPnlPlant, RithmicAccount, rti::messages::RithmicMessage, }; #[tokio::main] async fn main() -> Result<(), Box> { // Load configuration and account let config = RithmicConfig::from_env(RithmicEnv::Demo)?; let account = RithmicAccount::from_env(RithmicEnv::Demo)?; // Connect to PnL plant let pnl_plant = RithmicPnlPlant::connect(&config, ConnectStrategy::Retry).await?; let mut handle = pnl_plant.get_handle(&account); // Login handle.login().await?; println!("Logged in to PnL plant"); // Get current P&L snapshot let snapshot = handle.pnl_position_snapshots().await?; println!("Current positions: {:?}", snapshot); // Subscribe to real-time updates handle.subscribe_pnl_updates().await?; println!("Subscribed to P&L updates"); // Process 10 updates for i in 0..10 { match handle.subscription_receiver.recv().await { Ok(update) => { if let Some(err) = &update.error { eprintln!("Error: {}", err); break; } match update.message { RithmicMessage::AccountPnLPositionUpdate(acct_pnl) => { println!("[{}] Account PnL - Unrealized: {:?}", i, acct_pnl.unrealized_pnl); } RithmicMessage::InstrumentPnLPositionUpdate(instr_pnl) => { println!("[{}] {} PnL - Unrealized: {:?}", i, instr_pnl.symbol, instr_pnl.unrealized_pnl); } _ => {} } } Err(e) => { eprintln!("Channel error: {}", e); break; } } } // Unsubscribe and disconnect handle.unsubscribe_pnl_updates().await?; handle.disconnect().await?; println!("Disconnected"); Ok(()) } ``` -------------------------------- ### TimeInForce Enum Usage Example Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/types.md Shows an example of using the TimeInForce enum, including printing its display value and parsing from a string. ```rust use rithmic_rs::TimeInForce; let gtc = TimeInForce::Gtc; println!("{}", gtc); // "GTC" let day_order = "DAY".parse::()?; assert_eq!(day_order, TimeInForce::Day); ``` -------------------------------- ### Place a Rithmic Bracket Order Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-response.md Example of creating and placing a standard Rithmic bracket order. Ensure necessary enums like BracketTransactionType and BracketPriceType are imported. ```rust use rithmic_rs::{RithmicBracketOrder, BracketTransactionType, BracketPriceType}; let bracket = RithmicBracketOrder { symbol: "ESM6".to_string(), exchange: "CME".to_string(), quantity: 1, transaction_type: BracketTransactionType::Buy, price_type: BracketPriceType::Limit, price: 5000.0, // Entry profit_target_price: 5010.0, // TP stop_price: 4990.0, // SL user_tag: "bracket_001".to_string(), ..Default::default() }; handle.place_bracket_order(bracket).await?; ``` -------------------------------- ### Serde Serialization and Deserialization Example Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/types.md Demonstrates serializing an OrderSide enum to JSON and deserializing it back, highlighting the lowercase string format used by default. ```rust use rithmic_rs::OrderSide; use serde_json; let side = OrderSide::Buy; let json = serde_json::to_string(&side)?; println!("{}", json); // "Buy" let side_from_json: OrderSide = serde_json::from_str(""Buy"")?; assert_eq!(side_from_json, OrderSide::Buy); ``` -------------------------------- ### OrderType Enum Usage Example Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/types.md Provides an example of using the OrderType enum, demonstrating its display output and parsing from a string alias. ```rust use rithmic_rs::OrderType; let market = OrderType::Market; println!("{}", market); // "MARKET" let limit = "LMT".parse::()?; assert_eq!(limit, OrderType::Limit); ``` -------------------------------- ### Get Easy-to-Borrow List Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-order-plant.md Request a list of securities that are considered easy to borrow, which is essential for short selling. Requires specific request parameters. ```rust pub async fn get_easy_to_borrow_list( &self, req: EasyToBorrowRequest, ) -> Result, RithmicError> ``` ```rust let etb = handle.get_easy_to_borrow_list(etb_request).await?; ``` -------------------------------- ### Get System Gateway Info Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-ticker-plant.md Requests gateway information for a Rithmic system, optionally filtered by system name. Use this to get details about system connectivity. ```rust pub async fn get_system_gateway_info( &self, system_name: Option<&str>, ) -> Result let gateway_info = handle.get_system_gateway_info(None).await?; ``` -------------------------------- ### Get Volume at Price Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-ticker-plant.md Requests volume profile data at each price level for a given symbol and exchange. Use this to analyze trading volume distribution. ```rust pub async fn get_volume_at_price( &self, symbol: &str, exchange: &str, ) -> Result let volume = handle.get_volume_at_price("ESM6", "CME").await?; ``` -------------------------------- ### RithmicEnv Parsing Example Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/configuration.md Demonstrates how to set the Rithmic environment using either the enum variant or by parsing a string representation. Requires the `FromStr` trait to be implemented for `RithmicEnv`. ```rust use rithmic_rs::RithmicEnv; let env = RithmicEnv::Demo; // or let env: RithmicEnv = "demo".parse()?; // FromStr support ``` -------------------------------- ### Get Product Codes Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-ticker-plant.md Requests a list of product codes, optionally filtered by exchange and whether to include only TOI products. Useful for discovering available trading instruments. ```rust pub async fn get_product_codes( &self, exchange: Option<&str>, give_toi_products_only: Option, ) -> Result let products = handle.get_product_codes(Some("CME"), None).await?; ``` -------------------------------- ### Get Login Information Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-order-plant.md Retrieve information about the current login session, including account details and connection status. This is useful for verifying session validity. ```rust pub async fn get_login_info(&self) -> Result ``` ```rust let login_info = handle.get_login_info().await?; ``` -------------------------------- ### OrderSide Enum Usage Example Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/types.md Illustrates how to use the OrderSide enum, including printing its display value and parsing from a string. ```rust use rithmic_rs::OrderSide; let buy = OrderSide::Buy; println!("{}", buy); // "BUY" let side = "SELL".parse::()?; assert_eq!(side, OrderSide::Sell); ``` -------------------------------- ### Place a Rithmic OCO Order Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-response.md Example of creating and placing one leg of an OCO order. The `handle.place_oco_order` function likely takes two such legs to form the OCO pair. ```rust use rithmic_rs::RithmicOcoOrderLeg; let oco = RithmicOcoOrderLeg { symbol: "ESM6".to_string(), exchange: "CME".to_string(), quantity: 1, transaction_type: OcoTransactionType::Sell, price_type: OcoPriceType::Limit, price: 4950.0, ..Default::default() }; handle.place_oco_order(oco).await?; ``` -------------------------------- ### Get Product Risk Management System Info Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-order-plant.md Retrieve product-level risk management system information, such as overnight and day margins. Use this to understand margin requirements for specific products. ```rust pub async fn get_product_rms_info(&self) -> Result, RithmicError> ``` ```rust let product_rms = handle.get_product_rms_info().await?; ``` -------------------------------- ### Get Order Session Configuration Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-order-plant.md Retrieve the order session configuration, which includes trading hours and other session-related settings. This helps in understanding the active trading periods. ```rust pub async fn get_order_session_config(&self) -> Result ``` ```rust let config = handle.get_order_session_config().await?; ``` -------------------------------- ### Spawn Task with Rithmic Handle Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/overview.md Rithmic handles can be cloned and sent across threads. This example demonstrates spawning a new tokio task to subscribe to market data using a cloned handle. ```rust let handle = plant.get_handle(); let handle_copy = handle.clone(); tokio::spawn(async move { handle_copy.subscribe("ESM6", "CME").await; }); ``` -------------------------------- ### Get List of Trading Accounts Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-order-plant.md Retrieve a list of all trading accounts accessible to the authenticated user. This is useful for multi-account setups. ```rust pub async fn get_account_list(&self) -> Result, RithmicError> ``` ```rust let accounts = handle.get_account_list().await?; ``` -------------------------------- ### Typical Usage of rithmic-rs Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/README.md Demonstrates the typical workflow for using the rithmic-rs library, including loading configuration, connecting a plant, obtaining a handle, logging in, and subscribing to updates. This pattern is common for interacting with real-time market data. ```rust let config = RithmicConfig::from_env(RithmicEnv::Demo)?; let account = RithmicAccount::from_env(RithmicEnv::Demo)?; let ticker_plant = RithmicTickerPlant::connect(&config, ConnectStrategy::Retry).await?; let handle = ticker_plant.get_handle(); handle.login().await?; handle.subscribe("ESM6", "CME").await?; while let Ok(update) = handle.subscription_receiver.recv().await { match update.message { RithmicMessage::LastTrade(trade) => println!("Trade: {:?}", trade), _ => {} } } ``` -------------------------------- ### Place a Rithmic Advanced Bracket Order with Trailing Stop Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-response.md Example of creating and placing an advanced bracket order with a trailing stop. The `TrailingStop` struct specifies the amount and whether it's a percentage or tick-based trail. ```rust use rithmic_rs::{RithmicAdvancedBracketOrder, TrailingStop}; let advanced = RithmicAdvancedBracketOrder { symbol: "ESM6".to_string(), exchange: "CME".to_string(), quantity: 1, // ... basic fields ... trailing_stop: Some(TrailingStop { amount: 10.0, // Trail by $10 is_percent: false, }), ..Default::default() }; handle.place_advanced_bracket_order(advanced).await?; ``` -------------------------------- ### Place a Simple Order Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-response.md Demonstrates how to construct and send a `RithmicOrder` to place a simple buy or sell order with specified parameters like symbol, quantity, price, and order type. ```APIDOC ## Place a Simple Order ### `place_order()` #### Description This method is used to place a simple, non-bracket order. It requires essential details such as the trading symbol, exchange, quantity, price, transaction type (Buy/Sell), and price type (Market/Limit/StopMarket/StopLimit). ### Parameters #### Request Body (`RithmicOrder`) - **symbol** (String) - Required - The trading symbol (e.g., "ESM6"). - **exchange** (String) - Required - The exchange code (e.g., "CME"). - **quantity** (i32) - Required - The number of contracts to trade. - **price** (f64) - Required - The order price, applicable for Limit and StopLimit orders. - **transaction_type** (NewOrderTransactionType) - Required - Specifies whether the order is a `Buy` or `Sell`. - **price_type** (NewOrderPriceType) - Required - Defines the order type, such as `Market`, `Limit`, `StopMarket`, or `StopLimit`. - **user_tag** (String) - Optional - An application-defined tag for order identification. Defaults to an empty string. - **order_duration** (Option) - Optional - Specifies the order's validity period (e.g., `Day`, `Gtc`, `Ioc`, `Fok`). Defaults to `None`. - **stop_price** (Option) - Optional - The stop price, required for `StopMarket` and `StopLimit` orders. Defaults to `None`. ### Example Usage ```rust use rithmic_rs::{RithmicOrder, NewOrderTransactionType, NewOrderPriceType, NewOrderDuration}; // Constructing a Limit Buy order let order = RithmicOrder { symbol: "ESM6".to_string(), exchange: "CME".to_string(), quantity: 2, price: 5000.0, transaction_type: NewOrderTransactionType::Buy, price_type: NewOrderPriceType::Limit, user_tag: "scalp_001".to_string(), order_duration: Some(NewOrderDuration::Day), stop_price: None, ..Default::default() // Fills other optional fields with defaults }; // Assuming 'handle' is an initialized Rithmic client handle handle.place_order(order).await?; ``` ``` -------------------------------- ### RithmicOrderPlantHandle::list_system_info Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-order-plant.md Returns system infrastructure details. ```APIDOC ## RithmicOrderPlantHandle::list_system_info ### Description Returns system infrastructure details. ### Method `async fn list_system_info(&self) -> Result` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Request Example * None provided in source. ### Response #### Success Response `Result` #### Response Example * None provided in source. ``` -------------------------------- ### Handle ParseOrderSideError Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/types.md Example of catching and handling a ParseOrderSideError when attempting to parse an invalid string into an OrderSide. ```rust use std::str::FromStr; use rithmic_rs::{OrderSide, ParseOrderSideError}; match "invalid".parse::() { Err(ParseOrderSideError(_)) => println!("Invalid side"), _ => {} } ``` -------------------------------- ### Get Front Month Contract Source: https://github.com/pbeets/rithmic-rs/blob/main/README.md Retrieve the front-month contract details for a given symbol and exchange. ```rust let front_month = handle.get_front_month_contract("ES", "CME", false).await?; ``` -------------------------------- ### RithmicPnlPlantHandle::login_with_config Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-pnl-plant.md Logs into the Rithmic system with custom configuration options. ```APIDOC ## RithmicPnlPlantHandle::login_with_config ### Description Logs in with custom options. ### Method `pub async fn login_with_config(&self, config: LoginConfig) -> Result` ### Parameters #### Request Body - **config** (LoginConfig) - Required - Custom login configuration options. ### Response - `Result` - Confirmation of login or an error. ### Example ```rust let config = LoginConfig { aggregated_quotes: Some(true), ..Default::default() }; handle.login_with_config(config).await?; ``` ``` -------------------------------- ### Get Instrument by Underlying Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-ticker-plant.md List all instruments for an underlying symbol on a specific exchange. Can be filtered by expiration date. ```rust let instruments = handle.get_instrument_by_underlying("ES", "CME", None).await?; ``` -------------------------------- ### Create Handles for Different Accounts Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-pnl-plant.md Demonstrates how to create separate handles for different accounts, ensuring that each handle's subscription receiver only processes updates for its bound account. ```rust let account1 = RithmicAccount::new("fcm1", "ib1", "acct1"); let account2 = RithmicAccount::new("fcm1", "ib1", "acct2"); let handle1 = pnl_plant.get_handle(&account1); let handle2 = pnl_plant.get_handle(&account2); // handle1.subscription_receiver receives only account1 updates // handle2.subscription_receiver receives only account2 updates ``` -------------------------------- ### RithmicOrderPlantHandle::login_with_config Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-order-plant.md Logs in with custom options. ```APIDOC ## RithmicOrderPlantHandle::login_with_config ### Description Logs in with custom options. ### Method `async fn login_with_config( &self, config: LoginConfig, ) -> Result ` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Request Example ```rust let config = LoginConfig { aggregated_quotes: Some(true), ..Default::default() }; handle.login_with_config(config).await?; ``` ### Response #### Success Response `Result` #### Response Example * None provided in source. ``` -------------------------------- ### get_front_month_contract Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-ticker-plant.md Get the front-month contract for a given underlying symbol and exchange. Optionally subscribe to updates as contracts roll. ```APIDOC ## get_front_month_contract ### Description Get the front-month contract for a given underlying symbol. ### Method (Not specified, likely part of a client library) ### Parameters #### Path Parameters - **symbol** (string) - Required - Underlying symbol (e.g., "ES"). - **exchange** (string) - Required - Exchange code (e.g., "CME"). - **need_updates** (boolean) - Required - Whether to subscribe to updates as contracts roll. ### Request Example ```rust let front_month = handle.get_front_month_contract("ES", "CME", false).await?; ``` ### Response (Not specified) ``` -------------------------------- ### Place and Manage Orders Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/overview.md Connect to the Rithmic order plant, log in, place an order, and subscribe to execution reports for fills. ```rust let config = RithmicConfig::from_env(RithmicEnv::Demo)?; let account = RithmicAccount::from_env(RithmicEnv::Demo)?; let order_plant = RithmicOrderPlant::connect(&config, ConnectStrategy::Retry).await?; let handle = order_plant.get_handle(&account); handle.login().await?; // Place order let order = RithmicOrder { /* ... */ }; let resp = handle.place_order(order).await?; // Subscribe to updates handle.subscribe_order_updates().await?; while let Ok(update) = handle.subscription_receiver.recv().await { if let RithmicMessage::ExecutionReport(exec) = update.message { println!("Fill: {:?}", exec); } } ``` -------------------------------- ### Get RithmicTickerPlant Handle Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-ticker-plant.md Returns a handle to interact with the RithmicTickerPlant. Multiple handles can be created, all sharing the same underlying connection. ```rust pub fn get_handle(&self) -> RithmicTickerPlantHandle ``` ```rust let mut handle = ticker_plant.get_handle(); handle.login().await?; handle.subscribe("ESM6", "CME").await?; ``` -------------------------------- ### Modify an Existing Order Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-response.md Example of creating and sending a modify order request. Specify the `order_id`, new `quantity`, and `price`. ```rust use rithmic_rs::RithmicModifyOrder; let modify = RithmicModifyOrder { order_id: "order_123".to_string(), quantity: 3, price: 5005.0, price_type: None, ..Default::default() }; handle.modify_order(modify).await?; ``` -------------------------------- ### RithmicPnlPlantHandle::list_system_info Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-pnl-plant.md Retrieves system infrastructure details. ```APIDOC ## RithmicPnlPlantHandle::list_system_info ### Description Returns system infrastructure details. ### Method `pub async fn list_system_info(&self) -> Result` ### Parameters None ### Response - `Result` - System information or an error. ``` -------------------------------- ### Get Handle for RithmicHistoryPlant Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-history-plant.md Retrieves a handle to query historical data from an established RithmicHistoryPlant connection. Multiple handles can be created. ```rust let mut handle = history_plant.get_handle(); handle.login().await?; ``` -------------------------------- ### List System Information Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-ticker-plant.md Retrieves system infrastructure details, including gateway information, system name, and available services. Use this to understand the Rithmic environment. ```rust pub async fn list_system_info(&self) -> Result ``` ```rust let sys_info = handle.list_system_info().await?; ``` -------------------------------- ### Connect and Login to Order Plant Source: https://github.com/pbeets/rithmic-rs/blob/main/README.md Establish a connection to the Rithmic Order Plant and log in using configuration and account details loaded from environment variables. ```rust use rithmic_rs::{ ConnectStrategy, NewOrderPriceType, NewOrderTransactionType, RithmicAccount, RithmicConfig, RithmicEnv, RithmicOrder, RithmicOrderPlant, }; let config = RithmicConfig::from_env(RithmicEnv::Demo)?; let account = RithmicAccount::from_env(RithmicEnv::Demo)?; let plant = RithmicOrderPlant::connect(&config, ConnectStrategy::Retry).await?; let mut handle = plant.get_handle(&account); handle.login().await?; ``` -------------------------------- ### Get Auxiliary Reference Data Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-ticker-plant.md Requests auxiliary reference data for a specified symbol and exchange. This provides additional contract-related information. ```rust pub async fn get_auxilliary_reference_data( &self, symbol: &str, exchange: &str, ) -> Result let aux_refdata = handle.get_auxilliary_reference_data("ESM6", "CME").await?; ``` -------------------------------- ### Cancel an Existing Order Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-response.md Example of cancelling an order using its ID. This is a direct function call without needing to construct a specific struct. ```rust handle.cancel_order("order_123").await?; ``` -------------------------------- ### Rithmic Demo Environment Variables Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/README.md Sets up the necessary environment variables for connecting to the Rithmic demo environment. Ensure these are exported in your shell before running the application. ```sh # Credentials export RITHMIC_DEMO_USER=your_username export RITHMIC_DEMO_PW=your_password # Connection URLs export RITHMIC_DEMO_URL=wss://demo.rithmic.com:443 export RITHMIC_DEMO_ALT_URL=wss://demo-alt.rithmic.com:443 # Account identity (for order/PnL operations) export RITHMIC_DEMO_ACCOUNT_ID=your_account_id export RITHMIC_DEMO_FCM_ID=your_fcm_id export RITHMIC_DEMO_IB_ID=your_ib_id # App identity export RITHMIC_APP_NAME=your_app_name export RITHMIC_APP_VERSION=1 ``` -------------------------------- ### Configuring Login for Tick-by-Tick Quotes Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-response.md Demonstrates how to create a LoginConfig to receive tick-by-tick (individual) quote updates. ```rust use rithmic_rs::LoginConfig; // Tick-by-tick (individual ticks) let config = LoginConfig { aggregated_quotes: Some(false), ..Default::default() }; handle.login_with_config(config).await?; ``` -------------------------------- ### Get Trade Routes Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-order-plant.md Retrieve available trade routes for a specific symbol and exchange. This is useful for understanding routing options before placing an order. ```rust pub async fn get_trade_routes( &self, symbol: &str, exchange: &str, ) -> Result, RithmicError> ``` ```rust let routes = handle.get_trade_routes("ESM6", "CME").await?; ``` -------------------------------- ### RithmicPnlPlant Methods Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/README.md Methods available for interacting with the RithmicPnlPlant for profit/loss tracking. ```APIDOC ## RithmicPnlPlant ### Description Tracks profit and loss and provides snapshots of positions. ### Methods - `subscribe_pnl_updates()`: Subscribes to real-time profit/loss updates. - `pnl_position_snapshots()`: Retrieves snapshots of current positions. ``` -------------------------------- ### Connect and Use Rithmic Plant Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/overview.md Demonstrates the typical usage pattern for connecting to a Rithmic plant, obtaining a handle, logging in, subscribing to data, receiving updates, and disconnecting. Ensure RithmicConfig is set up from environment variables. ```rust let config = RithmicConfig::from_env(RithmicEnv::Demo)?; let ticker_plant = RithmicTickerPlant::connect(&config, ConnectStrategy::Retry).await?; let mut handle = ticker_plant.get_handle(); handle.login().await?; handle.subscribe("ESM6", "CME").await?; while let Ok(update) = handle.subscription_receiver.recv().await { // Process RithmicMessage and RithmicError } handle.disconnect().await?; ``` -------------------------------- ### Get Front Month Contract Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-ticker-plant.md Retrieve the front-month contract for a given underlying symbol and exchange. Can optionally subscribe to updates as contracts roll. ```rust let front_month = handle.get_front_month_contract("ES", "CME", false).await?; ``` -------------------------------- ### RithmicOrderPlantHandle::login Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-order-plant.md Logs in with default settings. ```APIDOC ## RithmicOrderPlantHandle::login ### Description Logs in with default settings. ### Method `async fn login(&self) -> Result` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Request Example ```rust handle.login().await?; ``` ### Response #### Success Response `Result` #### Response Example * None provided in source. ``` -------------------------------- ### Demo Environment Configuration Variables Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/overview.md These environment variables are required for configuring a connection to the Rithmic demo environment using the `from_env()` methods. Ensure all necessary credentials and URLs are provided. ```dotenv RITHMIC_DEMO_USER=your_username RITHMIC_DEMO_PW=your_password RITHMIC_DEMO_URL=wss://demo.rithmic.com:443 RITHMIC_DEMO_ALT_URL=wss://demo-alt.rithmic.com:443 RITHMIC_DEMO_ACCOUNT_ID=your_account_id RITHMIC_DEMO_FCM_ID=your_fcm_id RITHMIC_DEMO_IB_ID=your_ib_id RITHMIC_APP_NAME=your_app_name RITHMIC_APP_VERSION=1 ``` -------------------------------- ### Configuring Login for Aggregated Quotes Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-response.md Demonstrates how to create a LoginConfig to enable aggregated quotes (batched updates) for a login session. ```rust use rithmic_rs::LoginConfig; // Aggregated quotes (batched updates) let config = LoginConfig { aggregated_quotes: Some(true), ..Default::default() }; handle.login_with_config(config).await?; ``` -------------------------------- ### Request PnL Position Snapshot Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-pnl-plant.md Call this method to get a complete snapshot of all current position P&L data for the account. This is a one-time query. ```rust pub async fn pnl_position_snapshots(&self) -> Result ``` ```rust let snapshot = handle.pnl_position_snapshots().await?; // snapshot.message contains all positions and their P&L ``` -------------------------------- ### Rithmic Connection Strategy: AlternateWithRetry Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/overview.md Alternates between primary and beta URLs, with exponential backoff on each. Suitable for high availability scenarios where both URLs are expected to be available. ```rust let plant = RithmicTickerPlant::connect(&config, ConnectStrategy::AlternateWithRetry).await?; ``` -------------------------------- ### RithmicHistoryPlant::connect Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-history-plant.md Establishes a WebSocket connection to the Rithmic History Plant. This function initializes the connection and starts the background actor loop for handling data. ```APIDOC ## RithmicHistoryPlant::connect ### Description Establishes a WebSocket connection to the Rithmic History Plant and spawns the background actor loop. ### Method `connect` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters - **config** (`&RithmicConfig`) - Required - Connection configuration with credentials and server URLs - **strategy** (`ConnectStrategy`) - Required - Connection retry strategy ### Returns `Result` - The connected plant instance. ### Example ```rust use rithmic_rs::{RithmicConfig, RithmicEnv, ConnectStrategy, RithmicHistoryPlant>; let config = RithmicConfig::from_env(RithmicEnv::Demo)?; let history_plant = RithmicHistoryPlant::connect(&config, ConnectStrategy::Retry).await?; ``` ``` -------------------------------- ### Login with Default Settings Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-pnl-plant.md Logs into the Rithmic system using default authentication settings. This is a prerequisite for many handle operations. ```rust handle.login().await?; ``` -------------------------------- ### RithmicPnlPlantHandle::login Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-pnl-plant.md Logs into the Rithmic system with default settings using the provided handle. ```APIDOC ## RithmicPnlPlantHandle::login ### Description Logs in with default settings. ### Method `pub async fn login(&self) -> Result` ### Parameters None ### Response - `Result` - Confirmation of login or an error. ### Example ```rust handle.login().await?; ``` ``` -------------------------------- ### RithmicTickerPlantHandle::login_with_config Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-ticker-plant.md Logs in with custom options, allowing configuration of aggregated quotes, heartbeat settings, and more. ```APIDOC ## RithmicTickerPlantHandle::login_with_config ### Description Logs in with custom options (aggregated quotes, heartbeat settings, etc.). ### Method `pub async fn login_with_config( &self, config: LoginConfig, ) -> Result ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | config | `LoginConfig` | Yes | — | Custom login configuration (see [`LoginConfig`](rithmic-response.md#loginconfig)) | ### Returns `Result` - Login response with session info, or error. ### Example ```rust let login_config = LoginConfig { aggregated_quotes: Some(true), ..Default::default() }; handle.login_with_config(login_config).await?; ``` ``` -------------------------------- ### Get Tick Size Type Table Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-ticker-plant.md Requests the tick size table for a specified tick size type. Use this to retrieve pricing granularity information. ```rust pub async fn get_tick_size_type_table( &self, tick_size_type: &str, ) -> Result let tick_table = handle.get_tick_size_type_table("ES").await?; ``` -------------------------------- ### Connect to RithmicTickerPlant with AlternateWithRetry Strategy Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/configuration.md Connects to the RithmicTickerPlant using the AlternateWithRetry strategy, which attempts connections to both primary and beta URLs with retries. This strategy is useful when a beta URL is available. ```rust use rithmic_rs::ConnectStrategy; let config = RithmicConfig::from_env(RithmicEnv::Demo)?; // Or use AlternateWithRetry if beta URL is available let ticker_plant = RithmicTickerPlant::connect(&config, ConnectStrategy::AlternateWithRetry).await?; ``` -------------------------------- ### RithmicTickerPlantHandle::list_system_info Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-ticker-plant.md Retrieves system infrastructure details, including gateway information, system name, and available services. ```APIDOC ## RithmicTickerPlantHandle::list_system_info ### Description Returns system infrastructure details (gateway info, system name, available services). ### Method `pub async fn list_system_info(&self) -> Result` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Returns `Result` ### Example ```rust let sys_info = handle.list_system_info().await?; ``` ``` -------------------------------- ### Handle Real-time Updates Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-ticker-plant.md Clones a broadcast receiver to subscribe to real-time updates like market data and connection events. All cloned receivers get the same stream of updates. ```rust pub subscription_receiver: broadcast::Receiver let mut rx = handle.subscription_receiver.clone(); while let Ok(update) = rx.recv().await { println!("Update: {:?}", update.message); } ``` -------------------------------- ### Login with Custom Configuration Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-pnl-plant.md Logs into the Rithmic system with custom authentication options, such as enabling aggregated quotes. Use this for non-default login behaviors. ```rust let config = LoginConfig { aggregated_quotes: Some(true), ..Default::default() }; handle.login_with_config(config).await?; ``` -------------------------------- ### RithmicPnlPlant::connect Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-pnl-plant.md Establishes a WebSocket connection to the Rithmic PnL Plant and spawns the background actor loop. Requires connection configuration and a retry strategy. ```APIDOC ## RithmicPnlPlant::connect ### Description Establishes a WebSocket connection to the Rithmic PnL Plant and spawns the background actor loop. ### Method `async fn connect( config: &RithmicConfig, strategy: ConnectStrategy, ) -> Result` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | config | `&RithmicConfig` | Yes | — | Connection configuration with credentials and server URLs | | strategy | `ConnectStrategy` | Yes | — | Connection retry strategy | ### Response #### Success Response - `RithmicPnlPlant` - The connected plant instance. #### Error Response - `RithmicError` - If connection fails. ### Example ```rust use rithmic_rs::{RithmicConfig, RithmicEnv, ConnectStrategy, RithmicPnlPlant, RithmicAccount}; let config = RithmicConfig::from_env(RithmicEnv::Demo)?; let pnl_plant = RithmicPnlPlant::connect(&config, ConnectStrategy::Retry).await?; ``` ``` -------------------------------- ### Get Reference Data Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-ticker-plant.md Requests static reference data such as contract specifications, tick size, and multiplier for a given symbol and exchange. Useful for understanding contract details. ```rust pub async fn get_reference_data( &self, symbol: &str, exchange: &str, ) -> Result let refdata = handle.get_reference_data("ESM6", "CME").await?; ``` -------------------------------- ### Load Historical Ticks Source: https://github.com/pbeets/rithmic-rs/blob/main/README.md Load historical tick data for a symbol and exchange within a specified time range. Requires start and end times as Unix timestamps. ```rust let ticks = handle.load_ticks("ESM6", "CME", start, end).await?; ``` -------------------------------- ### RithmicOrderPlant::connect Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-order-plant.md Establishes a WebSocket connection to the Rithmic Order Plant and spawns the background actor loop. ```APIDOC ## RithmicOrderPlant::connect ### Description Establishes a WebSocket connection to the Rithmic Order Plant and spawns the background actor loop. ### Method `async fn connect( config: &RithmicConfig, strategy: ConnectStrategy, ) -> Result ` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Request Example ```rust use rithmic_rs::{RithmicConfig, RithmicEnv, ConnectStrategy, RithmicOrderPlant, RithmicAccount}; let config = RithmicConfig::from_env(RithmicEnv::Demo)?; let order_plant = RithmicOrderPlant::connect(&config, ConnectStrategy::Retry).await?; ``` ### Response #### Success Response `Result` - The connected plant instance. #### Response Example * None provided in source. ``` -------------------------------- ### Run Cargo Tests Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/overview.md Execute all unit tests included within the library's source files using the cargo test command. ```bash cargo test ``` -------------------------------- ### Get RithmicOrderPlant Handle Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-order-plant.md Obtains a handle bound to a specific trading account. Create one handle per account for managing its own request queue. Requires an account object. ```rust let account = RithmicAccount::from_env(RithmicEnv::Demo)?; let mut handle = order_plant.get_handle(&account); handle.login().await?; ``` -------------------------------- ### Get RithmicPnlPlant Handle for an Account Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/api-reference/rithmic-pnl-plant.md Obtains a handle bound to a specific trading account for P&L tracking. Each handle filters updates to the associated account's positions. ```rust let account = RithmicAccount::from_env(RithmicEnv::Demo)?; let mut handle = pnl_plant.get_handle(&account); handle.login().await?; ``` -------------------------------- ### Rithmic Connection Strategy: Simple Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/overview.md Establishes a single connection attempt. Fails immediately if unsuccessful. Use for integration tests or when immediate feedback is critical. ```rust let plant = RithmicTickerPlant::connect(&config, ConnectStrategy::Simple).await?; ``` -------------------------------- ### Connect to PnL Plant and Subscribe to Updates Source: https://github.com/pbeets/rithmic-rs/blob/main/README.md Establishes a connection to the Rithmic PnL Plant using a retry strategy, logs in, and subscribes to PnL updates. Retrieves initial position snapshots. ```rust use rithmic_rs::{ ConnectStrategy, RithmicAccount, RithmicConfig, RithmicEnv, RithmicPnlPlant, }; let config = RithmicConfig::from_env(RithmicEnv::Demo)?; let account = RithmicAccount::from_env(RithmicEnv::Demo)?; let plant = RithmicPnlPlant::connect(&config, ConnectStrategy::Retry).await?; let mut handle = plant.get_handle(&account); handle.login().await?; // Monitor P&L handle.subscribe_pnl_updates().await?; let snapshot = handle.pnl_position_snapshots().await?; ``` -------------------------------- ### Displaying RithmicError with std::fmt::Display Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/errors.md Shows how `RithmicError` implements `std::fmt::Display` for human-readable error messages. This example constructs a `RequestRejected` error and prints its formatted output. ```rust use rithmic_rs::{RithmicError, RithmicRequestError}; let err = RithmicError::RequestRejected(RithmicRequestError { rp_code: vec!["1039".to_string(), "FCM Id field is not received.".to_string()], code: Some("1039".to_string()), message: Some("FCM Id field is not received.".to_string()), }); println!("{}", err); // "request rejected: [1039] FCM Id field is not received." ``` -------------------------------- ### Handle ConfigError During Configuration Loading Source: https://github.com/pbeets/rithmic-rs/blob/main/_autodocs/configuration.md Demonstrates how to match and handle different ConfigError variants when loading Rithmic configuration from the environment. ```rust use rithmic_rs::{RithmicConfig, RithmicEnv, ConfigError}; match RithmicConfig::from_env(RithmicEnv::Demo) { Ok(config) => { /* use config */ } Err(ConfigError::MissingEnvVar(var)) => { eprintln!("Please set environment variable: {}", var); } Err(e) => eprintln!("Config error: {}", e), } ```