ib-flex
Type-safe Rust parser for Interactive Brokers FLEX XML statements with comprehensive coverage and financial precision.
Features
- Complete attribute coverage - Maps the full set of IB FLEX attributes (modeled against the mature ibflex reference), so you don't silently lose data
- Robust on real data - Tolerates IB's real-world quirks: thousands separators,
-/--/N/Asentinels,MULTIdates,Yes/Nobooleans, legacy date/time separators - Financial precision -
rust_decimalfor all monetary values (no floating-point error) - Type-safe - 19 enums covering asset classes, trade/cash/corporate-action types, transfer types, and more
- Comprehensive sections - Trades, positions, cash, corporate actions, transfers, performance summaries, accruals, and 40+ FLEX sections in total
- Edge cases covered - Warrants, T-Bills, CFDs, crypto, fractional shares, cancelled/corrected trades, cost-basis lots
- Optional API client - Fetch FLEX statements programmatically from IB (
api-clientfeature)
Installation
Add this to your Cargo.toml:
[]
= "0.2"
Quick Start
Every field that maps an IB attribute is an Option<T> (real statements may omit
any attribute), so access them with as_deref() / unwrap_or_default() as needed.
use ;
Upgrading from 0.1.x? 0.2.0 makes all attribute-derived fields
Option<T>so a statement that omits any attribute no longer fails to parse. Update call sites accordingly (e.g.statement.account_idโstatement.account_id.as_deref()). See the CHANGELOG.
FLEX Query Setup
Interactive Brokers FLEX queries must be configured in the IB Client Portal:
- Navigate to: Reports โ Flex Queries โ Create Activity Flex Query
- Select required sections (Trades, Positions, Cash Transactions, etc.)
- Choose date format: ISO-8601 (
yyyy-MM-dd) or compact (yyyyMMdd) - Set output format to XML
- Save query and note the Query ID
Important: European date formats (dd/MM/yyyy) are NOT supported by the IB FLEX API.
๐ For comprehensive setup instructions, see FLEX_SETUP.md which covers all 21 recommended sections, field selections, and configuration options.
FLEX Web Service API Client (Optional)
The api-client feature provides programmatic access to fetch FLEX statements directly from Interactive Brokers without manual downloads.
Installation with API Client
[]
= { = "0.2", = ["api-client"] }
API Setup
- Log in to IB Account Management
- Navigate to: Reports โ Settings โ FlexWeb Service
- Generate a FLEX Web Service token (keep it secure!)
- Note your FLEX Query ID from the Flex Queries page
Usage Example
use FlexApiClient;
use Duration;
async
API Examples
Run the API examples (requires IB credentials):
Supported FLEX Sections
Activity FLEX - Core Types
- โ Trades - Executions with 90+ fields including P&L, commissions, dates, IDs, security details
- โ
Trade sub-rows -
<Lot>cost-basis detail and<Order>/<SymbolSummary>/<AssetSummary>roll-ups captured from inside<Trades> - โ Open Positions - Current holdings
- โ Cash Transactions - Deposits, withdrawals, interest, fees, dividends
- โ Corporate Actions - Splits, mergers, spinoffs, dividends
- โ Securities Info - Reference data for all traded instruments
- โ FX Conversion Rates - Currency conversion rates for multi-currency accounts
Extended FLEX Sections
- โ Account Information, Change in NAV, Equity Summary, Cash Report
- โ Trade Confirmations - Real-time trade execution confirmations
- โ Option EAE - Option exercises, assignments, and expirations
- โ FX Transactions & FX Lots - Foreign exchange conversions and lots
- โ Dividend Accruals (open + change) and Interest Accruals (incl. tier detail)
- โ Transfers - Transfers, trade transfers, unsettled transfers (ACATS, ATON, FOP, internal, OTC, ...)
- โ Performance summaries - MTM, FIFO, and MTD/YTD
- โ Securities lending - SLB activity, fees, hard-to-borrow, and open contracts
- โ Fees & commissions - Client fees, unbundled commission detail, transaction taxes, sales tax
- โ Other - Net stock positions, prior-period positions, statement of funds, change-in-position value, debit-card activity, CFD charges, stock-grant activity
Asset Classes Supported
- โ Stocks (STK) - Including fractional shares
- โ Options (OPT) - Calls, puts, assignments, expirations
- โ Futures (FUT) - All major contracts (ES, NQ, CL, GC, etc.)
- โ Forex (CASH) - FX trades and positions
- โ Bonds (BOND) - Treasuries, corporate, municipal
- โ Treasury Bills (BILL) - With maturity handling
- โ Warrants (WAR) - Equity warrants
- โ CFDs (CFD / FXCFD) - Contract for difference
- โ Crypto (CRYPTO) - Cryptocurrency
- โ Funds, Commodities, and more - 22 asset categories total
Trade Confirmation FLEX
- โ Trade Confirmations - Real-time trade execution data
- โ All trade fields - Full support for all trade attributes
- โ Automatic detection - Detect statement type from XML
Performance
Benchmarked on M1 MacBook Pro:
| Statement Type | Transactions | Parse Time |
|---|---|---|
| Minimal | 1 trade | ~6.5 ยตs |
| Options | 4 trades | ~65 ยตs |
| Cash | 15 transactions | ~71 ยตs |
The full multi-statement test corpus (142 statements, ~2,600 trades) parses in a few milliseconds.
Type Safety
All financial values use rust_decimal::Decimal for exact arithmetic without floating-point error. The public enums include:
- AssetCategory (22 variants) - STK, OPT, FUT, FOP, CASH, BOND, BILL, CFD, FXCFD, WAR, FUND, CMDTY, CRYPTO, FSFOP, FSOPT, ...
- BuySell, OpenClose, PutCall, LongShort - trade direction and option basics
- TradeType - ExchTrade, BookTrade, TradeCancel, TradeCorrect, FracShare, ...
- OrderType - market, limit, stop, stop-limit, trailing, ...
- CashTransactionType - dividends, interest, fees, deposits/withdrawals, ...
- SecurityIdType - CUSIP, ISIN, FIGI, SEDOL
- SubCategory - ETF, ADR, REIT, Preferred, Common, ...
- LevelOfDetail - Summary, Detail, Execution, Lot
- DerivativeInfo - consolidated option/future/warrant metadata via
Trade::derivative()
Examples
The repository includes several complete example programs:
Parsing Examples
- parse_activity_statement.rs - Basic Activity FLEX parsing and display
- filter_trades.rs - Filter by asset class, side, symbol, quantity, P&L, date range
- calculate_commissions.rs - Analyze commission costs by category
- parse_trade_confirmation.rs - Trade Confirmation FLEX parsing
Run parsing examples:
Historical Backfill Example
- backfill_summary.rs - Parse multi-statement FLEX XML and display comprehensive summary
To use this example:
- Create a FLEX query with Period: Last 180 Calendar Days (or similar) in IBKR Client Portal - see FLEX_SETUP.md
- Download the XML file manually or via API
- Run the summary:
Output includes:
- NAV over time with returns, high/low, drawdown
- Trading activity by symbol with P&L attribution
- Cash transaction breakdown (dividends, interest, fees)
- Current positions from latest statement
- Monthly returns table
API Client Examples (requires api-client feature)
- fetch_flex_statement.rs - Complete API workflow with detailed output
- api_simple_usage.rs - Minimal API client usage
- api_with_retry.rs - API client with automatic retry logic
Run API examples:
Development
Build
Test
Benchmark
Format
Lint
Testing
The library has comprehensive test coverage including:
- Integration tests covering all asset classes and edge cases
- Extended types tests for FLEX sections
- Error tests for malformed XML and invalid data
- Unit tests for custom deserializers
- Doc tests in inline documentation
- XML fixtures including extended types, warrants, T-Bills, CFDs, fractional shares, cancelled trades
Reliability Testing
The library includes comprehensive reliability tests using:
- Property-based testing with proptest for random inputs
- Stress tests for large XML files
- Concurrency tests for thread safety
- Memory efficiency tests for repeated parsing
- Edge case fuzzing for malformed inputs
Run tests with:
Contributing
Contributions welcome! This is an open-source project designed to benefit the Rust trading community.
Before submitting a PR:
- Ensure all tests pass:
cargo test - Run clippy:
cargo clippy --all-targets -- -D warnings - Format code:
cargo fmt - Add tests for new features
- Update CHANGELOG.md
Bug reports and feature requests are appreciated. When reporting bugs, please include:
- Anonymized XML sample demonstrating the issue
- Expected vs actual behavior
- Rust version and platform
Documentation
- API Documentation
- FLEX Query Setup Guide - How to configure your IBKR FLEX query
- Changelog - Release history
- Project Guide for Claude Code - Development guide
Resources
License
Licensed under the MIT License.
Acknowledgments
- Inspired by csingley/ibflex (Python) - Comprehensive enum research
- Built with quick-xml - Fast XML parsing with serde
- rust_decimal - Financial precision
- chrono - Date/time handling