### Run Parsing Examples Source: https://github.com/clifton/ib-flex/blob/main/README.md Execute various parsing examples for IB FLEX statements. Ensure you have the necessary Rust environment set up. ```bash cargo run --example parse_activity_statement ``` ```bash cargo run --example parse_trade_confirmation ``` ```bash cargo run --example filter_trades ``` ```bash cargo run --example calculate_commissions ``` -------------------------------- ### Run API Client Examples Source: https://github.com/clifton/ib-flex/blob/main/README.md Execute examples demonstrating API client usage for fetching FLEX statements. Requires setting environment variables for IB_FLEX_TOKEN and IB_FLEX_QUERY_ID, and enabling the 'api-client' feature. ```bash export IB_FLEX_TOKEN="your_token" export IB_FLEX_QUERY_ID="your_query_id" cargo run --example fetch_flex_statement --features api-client ``` -------------------------------- ### Run API Client Examples Source: https://github.com/clifton/ib-flex/blob/main/README.md Execute the provided example commands to test the API client functionality. Ensure your IB FLEX token and Query ID are set as environment variables. ```bash export IB_FLEX_TOKEN="your_token" export IB_FLEX_QUERY_ID="your_query_id" cargo run --example fetch_flex_statement --features api-client cargo run --example api_simple_usage --features api-client cargo run --example api_with_retry --features api-client ``` -------------------------------- ### Backfill Summary Example Source: https://github.com/clifton/ib-flex/blob/main/FLEX_SETUP.md Use this command to process an XML file containing historical data for backfill analysis. Ensure the XML file is correctly formatted. ```bash cargo run --example backfill_summary -- your_file.xml ``` -------------------------------- ### Run Historical Backfill Example Source: https://github.com/clifton/ib-flex/blob/main/README.md Parse multi-statement FLEX XML and display a comprehensive summary. Requires a FLEX query created in IBKR Client Portal and the path to the downloaded XML file. ```bash cargo run --example backfill_summary -- path/to/your/backfill.xml ``` -------------------------------- ### Install ib-flex with API Client Feature Source: https://github.com/clifton/ib-flex/blob/main/README.md Add the `ib-flex` crate with the `api-client` feature to your project's dependencies to enable programmatic fetching of FLEX statements. ```toml [dependencies] ib-flex = { version = "0.2", features = ["api-client"] } ``` -------------------------------- ### Run Documentation Tests Source: https://github.com/clifton/ib-flex/blob/main/README.md Execute only the documentation tests to ensure examples within the documentation are correct. ```bash cargo test --doc ``` -------------------------------- ### Parse Activity FLEX Statement and Print Trades Source: https://github.com/clifton/ib-flex/blob/main/README.md Parses a single Activity FLEX statement and iterates through its trades, printing the symbol, quantity, and price. This example demonstrates how to handle optional fields by using `as_deref().unwrap_or()` or `unwrap_or_default()`. ```rust use ib_flex::{detect_statement_type, parse_activity_flex, StatementType}; fn main() -> Result<(), Box> { let xml = std::fs::read_to_string("flex_statement.xml")?; if let StatementType::Activity = detect_statement_type(&xml)? { let statement = parse_activity_flex(&xml)?; for trade in &statement.trades.items { println!( "{} {} @ {}", trade.symbol.as_deref().unwrap_or("?"), trade.quantity.unwrap_or_default(), trade.price.unwrap_or_default(), ); } } Ok(()) } ``` -------------------------------- ### Build and Test Commands Source: https://github.com/clifton/ib-flex/blob/main/CLAUDE.md Commands for building the library, running tests (including doctests), and benchmarks. The `api-client` feature enables the HTTP client. ```bash cargo build # library (add --features api-client for the HTTP client) ``` ```bash cargo test # unit + integration + doctests ``` ```bash cargo test --doc # doctests only ``` ```bash cargo bench # benchmarks ``` -------------------------------- ### Build Project with Cargo Source: https://github.com/clifton/ib-flex/blob/main/README.md Use this command to compile the project. ```bash cargo build ``` -------------------------------- ### Run All Tests Source: https://github.com/clifton/ib-flex/blob/main/CONTRIBUTING.md Execute the entire test suite for the project. Ensure all tests pass before submitting changes. ```bash cargo test ``` -------------------------------- ### Run Benchmarks Source: https://github.com/clifton/ib-flex/blob/main/CONTRIBUTING.md Execute the project's benchmarks to measure performance. Use this to identify performance regressions. ```bash cargo bench ``` -------------------------------- ### Fetch and Parse Daily Data with Rust Source: https://github.com/clifton/ib-flex/blob/main/FLEX_SETUP.md This script automates the daily retrieval and parsing of financial data from Interactive Brokers' Flex Web Service. It requires environment variables IB_FLEX_TOKEN and IB_FLEX_QUERY_ID to be set. The script fetches statement data, retries if necessary, parses the XML response, logs a summary, and saves the raw XML to a file. ```rust use ib_flex::api::FlexApiClient; use ib_flex::parse_activity_flex; use std::time::Duration; use chrono::Local; fn daily_data_fetch() -> Result<(), Box> { let token = std::env::var("IB_FLEX_TOKEN")?; let query_id = std::env::var("IB_FLEX_QUERY_ID")?; let client = FlexApiClient::new(&token); // Fetch statement let reference = client.send_request(&query_id)?; let xml = client.get_statement_with_retry( &reference, 15, // More retries for reliability Duration::from_secs(3), )?; // Parse let statement = parse_activity_flex(&xml)?; // Log summary let now = Local::now(); println!("[{}] Daily fetch completed", now.format("%Y-%m-%d %H:%M:%S")); println!(" Account: {}", statement.account_id); println!(" Period: {} to {}", statement.from_date, statement.to_date); println!(" Trades: {}", statement.trades.items.len()); println!(" Positions: {}", statement.positions.items.len()); println!(" Cash Transactions: {}", statement.cash_transactions.items.len()); println!(" Corporate Actions: {}", statement.corporate_actions.items.len()); // Save to file (or database) let filename = format!("flex_{}_{}.xml", statement.account_id, statement.to_date); std::fs::write(&filename, &xml)?; println!(" Saved to: {}", filename); Ok(()) } ``` -------------------------------- ### Format and Lint Code Source: https://github.com/clifton/ib-flex/blob/main/CLAUDE.md Run `cargo fmt` for formatting and `cargo clippy` for linting with warnings treated as errors. Both must pass before committing. ```bash cargo fmt && cargo clippy --all-targets -- -D warnings ``` -------------------------------- ### Run Tests with Output Source: https://github.com/clifton/ib-flex/blob/main/CONTRIBUTING.md Execute tests and display their output. Helpful for diagnosing test failures. ```bash cargo test -- --nocapture ``` -------------------------------- ### Basic Flex API Usage with ib-flex Source: https://github.com/clifton/ib-flex/blob/main/FLEX_SETUP.md This Rust code demonstrates how to initialize the `FlexApiClient`, request a Flex statement, and retrieve it with retries. It then parses the XML response and prints summary information about the account and data. ```rust use ib_flex::api::FlexApiClient; use std::time::Duration; fn main() -> Result<(), Box> { // Load credentials from environment let token = std::env::var("IB_FLEX_TOKEN")?; let query_id = std::env::var("IB_FLEX_QUERY_ID")?; // Create API client let client = FlexApiClient::new(&token); // Step 1: Send request to generate statement println!("Requesting Flex statement..."); let reference_code = client.send_request(&query_id)?; println!("Reference code: {}", reference_code); // Step 2: Retrieve statement with retry // (IB may take a few seconds to generate the report) println!("Fetching statement..."); let xml = client.get_statement_with_retry( &reference_code, 10, // max retries Duration::from_secs(2), // delay between retries )?; // Step 3: Parse the XML let statement = ib_flex::parse_activity_flex(&xml)?; // Access the data println!("Account: {}", statement.account_id); println!("Period: {} to {}", statement.from_date, statement.to_date); println!("Trades: {}", statement.trades.items.len()); println!("Positions: {}", statement.positions.items.len()); println!("Cash Transactions: {}", statement.cash_transactions.items.len()); Ok(()) } ``` -------------------------------- ### Format Code with Cargo Source: https://github.com/clifton/ib-flex/blob/main/README.md Apply standard code formatting to the project. This should be run before committing changes. ```bash cargo fmt ``` -------------------------------- ### Set Environment Variables for Credentials Source: https://github.com/clifton/ib-flex/blob/main/FLEX_SETUP.md Configure your API token and Query ID as environment variables before running the application. This is a security best practice to avoid hardcoding sensitive information. ```bash export IB_FLEX_TOKEN="your_token_here" export IB_FLEX_QUERY_ID="123456" ``` -------------------------------- ### Add ib-flex to Cargo.toml Source: https://github.com/clifton/ib-flex/blob/main/README.md Add this to your Cargo.toml to include the ib-flex crate as a dependency. ```toml [dependencies] ib-flex = "0.2" ``` -------------------------------- ### Parse NAV Time Series and Calculate Sharpe Ratio Source: https://github.com/clifton/ib-flex/blob/main/README.md Parses a multi-period Activity FLEX export to extract NAV over time and compute an annualized Sharpe ratio. Requires the `rust_decimal` crate for precise monetary value handling. NAV points are filtered for report date and total value, then sorted by date to calculate daily returns. ```rust use ib_flex::parse_activity_flex_all; use rust_decimal::prelude::ToPrimitive; // for Decimal::to_f64 fn main() -> Result<(), Box> { let xml = std::fs::read_to_string("flex_statement.xml")?; // NAV over time: the `total` of each daily equity-summary row, across all // statements, sorted by date. Every attribute is `Option`, so `?`-filter. let mut nav: Vec<(chrono::NaiveDate, f64)> = parse_activity_flex_all(&xml)? .iter() .flat_map(|stmt| stmt.equity_summary.items.iter()) .filter_map(|e| Some((e.report_date?, e.total?.to_f64()?))) .collect(); nav.sort_by_key(|(date, _)| *date); // Daily returns -> annualized Sharpe (risk-free = 0, ~252 trading days). let returns: Vec = nav.windows(2).map(|w| w[1].1 / w[0].1 - 1.0).collect(); let mean = returns.iter().sum::() / returns.len() as f64; let variance = returns.iter().map(|r| (r - mean).powi(2)).sum::() / returns.len() as f64; let sharpe = mean / variance.sqrt() * 252f64.sqrt(); println!("{} NAV points, annualized Sharpe: {sharpe:.2}", nav.len()); Ok(()) } ``` -------------------------------- ### Run Clippy and Format Code Source: https://github.com/clifton/ib-flex/blob/main/CONTRIBUTING.md Enforce code style and linting rules using Clippy, and format the code automatically. Fix all warnings reported by Clippy. ```bash cargo clippy -- -D warnings ``` ```bash cargo fmt ``` -------------------------------- ### Add ib-flex Dependency to Cargo.toml Source: https://github.com/clifton/ib-flex/blob/main/FLEX_SETUP.md Add the `ib-flex` crate with the `api-client` feature to your project's dependencies in `Cargo.toml`. ```toml [dependencies] ib-flex = { version = "0.1", features = ["api-client"] } ``` -------------------------------- ### Lint Project with Cargo Clippy Source: https://github.com/clifton/ib-flex/blob/main/README.md Check the code for common mistakes and style issues using Clippy. Warnings are treated as errors. ```bash cargo clippy --all-targets -- -D warnings ``` -------------------------------- ### Parse and Analyze Portfolio Positions Source: https://github.com/clifton/ib-flex/blob/main/FLEX_SETUP.md Parses an IB Flex API XML string to analyze and print details of current positions, including symbol, quantity, mark price, position value, and unrealized P&L. Aggregates total portfolio value and unrealized P&L. ```rust use ib_flex::parse_activity_flex; use rust_decimal::Decimal; fn analyze_positions(xml: &str) -> Result<(), Box> { let statement = parse_activity_flex(xml)?; let mut total_value = Decimal::ZERO; let mut total_unrealized_pnl = Decimal::ZERO; for position in &statement.positions.items { total_value += position.position_value; if let Some(pnl) = position.fifo_pnl_unrealized { total_unrealized_pnl += pnl; } println!( "{}: {} @ {} = {} (P&L: {:?})", position.symbol, position.quantity, position.mark_price, position.position_value, position.fifo_pnl_unrealized ); } println!("\nPortfolio Summary:"); println!(" Total Value: {}", total_value); println!(" Unrealized P&L: {}", total_unrealized_pnl); Ok(()) } ``` -------------------------------- ### Run Specific Test Source: https://github.com/clifton/ib-flex/blob/main/CONTRIBUTING.md Execute a single, named test case. Useful for debugging specific issues. ```bash cargo test test_parse_trade ``` -------------------------------- ### Fetch and Parse FLEX Statement with API Client Source: https://github.com/clifton/ib-flex/blob/main/README.md This Rust code demonstrates how to use the `FlexApiClient` to send a request for a FLEX statement, retrieve it with automatic retries, and parse the XML response. Ensure you have your IB FLEX Web Service token and Query ID configured. ```rust use ib_flex::api::FlexApiClient; use std::time::Duration; #[tokio::main] async fn main() -> Result<(), Box> { // Create client with your token let client = FlexApiClient::new("YOUR_TOKEN"); // Step 1: Send request with your query ID let reference_code = client.send_request("123456").await?; // Step 2: Get statement with automatic retry let xml = client.get_statement_with_retry( &reference_code, 10, // max retries Duration::from_secs(2) // delay between retries ).await?; // Step 3: Parse the statement let statement = ib_flex::parse_activity_flex(&xml)?; println!("Trades: {}", statement.trades.items.len()); Ok(()) } ``` -------------------------------- ### Optional Real Data Smoke Test Source: https://github.com/clifton/ib-flex/blob/main/CLAUDE.md Perform a smoke test against a real XML statement by setting the `IB_FLEX_REAL_XML` environment variable. This test is skipped if the variable is unset. ```bash # Optional smoke test against a real (private) statement; skipped if the env var is unset: IB_FLEX_REAL_XML=path/to/statement.xml cargo test --test real_data_smoke -- --nocapture ``` -------------------------------- ### Deserialize Optional String Helper Source: https://github.com/clifton/ib-flex/blob/main/CLAUDE.md Custom deserializer for `Option` that converts empty strings and specific sentinels to `None`. ```rust Option → deserialize_optional_string (`""` and sentinels → `None`) ``` -------------------------------- ### Parse and Analyze Extended Financial Data Source: https://github.com/clifton/ib-flex/blob/main/FLEX_SETUP.md Parses an IB Flex API XML string to extract and print extended financial data, including NAV changes, equity summaries, dividend accruals, and option events. Requires the `ib_flex` crate. ```rust use ib_flex::parse_activity_flex; fn analyze_extended_data(xml: &str) -> Result<(), Box> { let statement = parse_activity_flex(xml)?; // NAV Changes for nav in &statement.change_in_nav.items { println!( "NAV: {} -> {} (P&L: {:?})", nav.starting_value, nav.ending_value, nav.realized_pnl ); } // Equity Summary for equity in &statement.equity_summary.items { println!( "Equity on {}: Cash={:?}, Stock={:?}, Options={:?}, Total={}", equity.report_date, equity.cash, equity.stock, equity.options, equity.total ); } // Dividend Accruals for div in &statement.open_dividend_accruals.items { println!( "Expected dividend: {} - {} shares @ {} (ex: {}, pay: {:?})", div.symbol, div.quantity, div.gross_rate, div.ex_date, div.pay_date ); } // Option Events for option in &statement.option_eae.items { println!( "Option {}: {} {} @ {:?}", option.action_type, option.symbol, option.quantity, option.strike ); } Ok(()) } ``` -------------------------------- ### Deserialize Optional Decimal Helper Source: https://github.com/clifton/ib-flex/blob/main/CLAUDE.md Custom deserializer for `Option` that handles thousands separators and converts specific string values ('-', '--', 'N/A', '') to `None`. ```rust Option → deserialize_optional_decimal (strips thousands separators; `-`/`--`/`N/A`/`""` → `None`) ``` -------------------------------- ### Retry Statement Retrieval with Delay Source: https://github.com/clifton/ib-flex/blob/main/FLEX_SETUP.md Use `get_statement_with_retry` to handle cases where IB needs time to generate statements. Increase the number of retries and the delay duration for robustness. ```rust let xml = client.get_statement_with_retry( &reference, 15, // Increase retries Duration::from_secs(5), // Increase delay )?; ``` -------------------------------- ### Deserialize Optional Date Helper Source: https://github.com/clifton/ib-flex/blob/main/CLAUDE.md Custom deserializer for `Option` that accepts `yyyy-MM-dd`, `yyyyMMdd`, the `MULTI` sentinel, and optional trailing time components. ```rust Option → deserialize_optional_date (accepts `yyyy-MM-dd` / `yyyyMMdd`, the `MULTI` sentinel, and a trailing time component) ``` -------------------------------- ### Deserialize Enum with Default Source: https://github.com/clifton/ib-flex/blob/main/CLAUDE.md Use `#[serde(rename = "@x", default)]` for enums, ensuring each enum variant has an `#[serde(other)] Unknown` catch-all for unhandled values. ```rust enums → `#[serde(rename = "@x", default)]` (each enum has an `#[serde(other)] Unknown` catch-all) ``` -------------------------------- ### Deserialize Optional Boolean Helper Source: https://github.com/clifton/ib-flex/blob/main/CLAUDE.md Custom deserializer for `Option` that maps 'Y'/'N' and 'Yes'/'No' to boolean values. ```rust Option → deserialize_optional_bool (`Y`/`N`/`Yes`/`No`) ``` -------------------------------- ### Analyze Trade Data from Flex Statement XML Source: https://github.com/clifton/ib-flex/blob/main/FLEX_SETUP.md This Rust function parses Flex statement XML, iterates through trades, and extracts details such as symbol, quantity, price, and commission. It also demonstrates handling different asset categories like options and futures. ```rust use ib_flex::{parse_activity_flex, AssetCategory, BuySell}; use rust_decimal::Decimal; fn analyze_trades(xml: &str) -> Result<(), Box> { let statement = parse_activity_flex(xml)?; let mut total_commission = Decimal::ZERO; let mut total_realized_pnl = Decimal::ZERO; for trade in &statement.trades.items { // Basic trade info println!( "{} {} {} @ {}", trade.symbol, trade.buy_sell.as_ref().map(|b| format!("{:?}", b)).unwrap_or_default(), trade.quantity.unwrap_or_default(), trade.price.unwrap_or_default() ); // Accumulate commissions (for TCA) total_commission += trade.commission; // Accumulate realized P&L if let Some(pnl) = trade.fifo_pnl_realized { total_realized_pnl += pnl; } // Handle different asset types match trade.asset_category { AssetCategory::Option => { println!( " Option: {} {} @ {} exp {}", trade.underlying_symbol.as_ref().unwrap_or(&""..to_string()), trade.put_call.as_ref().map(|p| format!("{:?}", p)).unwrap_or_default(), trade.strike.unwrap_or_default(), trade.expiry.map(|d| d.to_string()).unwrap_or_default() ); } AssetCategory::Future => { println!( " Future: exp {}", trade.expiry.map(|d| d.to_string()).unwrap_or_default() ); } _ => {} } } println!("\nSummary:"); println!(" Total Commission: {}", total_commission); println!(" Total Realized P&L: {}", total_realized_pnl); Ok(()) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.