{"id":35370182,"url":"https://github.com/wboayue/rust-ibapi","last_synced_at":"2026-03-08T02:08:50.081Z","repository":{"id":152003373,"uuid":"562678345","full_name":"wboayue/rust-ibapi","owner":"wboayue","description":"An implementation of the Interactive Brokers API for Rust","archived":false,"fork":false,"pushed_at":"2026-02-09T07:22:03.000Z","size":2157,"stargazers_count":264,"open_issues_count":0,"forks_count":60,"subscribers_count":18,"default_branch":"main","last_synced_at":"2026-02-09T10:52:41.732Z","etag":null,"topics":["ibapi","interactive-brokers","trading-api"],"latest_commit_sha":null,"homepage":"","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/wboayue.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":"AGENTS.md","dco":null,"cla":null}},"created_at":"2022-11-07T02:36:46.000Z","updated_at":"2026-02-09T09:12:19.000Z","dependencies_parsed_at":"2024-02-09T23:29:17.547Z","dependency_job_id":"7657e429-ff39-4d19-9f8f-3c181a08b94c","html_url":"https://github.com/wboayue/rust-ibapi","commit_stats":null,"previous_names":[],"tags_count":49,"template":false,"template_full_name":null,"purl":"pkg:github/wboayue/rust-ibapi","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wboayue%2Frust-ibapi","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wboayue%2Frust-ibapi/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wboayue%2Frust-ibapi/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wboayue%2Frust-ibapi/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/wboayue","download_url":"https://codeload.github.com/wboayue/rust-ibapi/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wboayue%2Frust-ibapi/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29362205,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-12T08:51:36.827Z","status":"ssl_error","status_checked_at":"2026-02-12T08:51:26.849Z","response_time":55,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ibapi","interactive-brokers","trading-api"],"created_at":"2026-01-02T02:53:23.031Z","updated_at":"2026-03-08T02:08:50.058Z","avatar_url":"https://github.com/wboayue.png","language":"Rust","readme":"[![Build](https://github.com/wboayue/rust-ibapi/workflows/ci/badge.svg)](https://github.com/wboayue/rust-ibapi/actions/workflows/ci.yml)\n[![License:MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)\n[![crates.io](https://img.shields.io/crates/v/ibapi.svg)](https://crates.io/crates/ibapi)\n[![Documentation](https://img.shields.io/badge/Documentation-green.svg)](https://docs.rs/ibapi/latest/ibapi/)\n[![Coverage Status](https://coveralls.io/repos/github/wboayue/rust-ibapi/badge.png?branch=main)](https://coveralls.io/github/wboayue/rust-ibapi?branch=main)\n\n## Introduction\n\nThis library provides a comprehensive Rust implementation of the Interactive Brokers [TWS API](https://ibkrcampus.com/campus/ibkr-api-page/twsapi-doc/), offering a robust and user-friendly interface for TWS and IB Gateway. Designed with performance and simplicity in mind, `ibapi` is a good fit for automated trading systems, market analysis, real-time data collection and portfolio management tools.\n\nWith this fully featured API, you can retrieve account information, access real-time and historical market data, manage orders, perform market scans, and access news and Wall Street Horizons (WSH) event data. Future updates will focus on bug fixes, maintaining parity with the official API, and enhancing usability.\n\n## Sync/Async Architecture\n\nrust-ibapi ships both asynchronous (Tokio) and blocking (threaded) clients. The async client is enabled by default; opt into the blocking client with the `sync` feature and use both together when you need to mix execution models.\n\n- **async** *(default)*: Non-blocking client using Tokio tasks and broadcast channels. Available as `ibapi::Client`.\n- **sync**: Blocking client using crossbeam channels. Available as `ibapi::client::blocking::Client` (or `ibapi::Client` when `async` is disabled).\n\n```toml\n# Async only (default features)\nibapi = \"2.9\"\n\n# Blocking only\nibapi = { version = \"2.9\", default-features = false, features = [\"sync\"] }\n\n# Async + blocking together\nibapi = { version = \"2.9\", default-features = false, features = [\"sync\", \"async\"] }\n```\n\n```bash\n# Async client (default configuration)\ncargo test\ncargo run --example async_connect\n\n# Blocking client only\ncargo test --no-default-features --features sync\n\n# Validate both clients together\ncargo test --all-features\n```\n\nWhen both features are enabled, import the blocking types explicitly:\n\n```rust\nuse ibapi::Client;                    // async client\nuse ibapi::client::blocking::Client;  // blocking client\n```\n\n\u003e **📚 Migrating from v1.x?** See the [Migration Guide](MIGRATION.md) for step-by-step upgrade instructions.\n\nIf you encounter any issues or require a missing feature, please review the [issues list](https://github.com/wboayue/rust-ibapi/issues) before submitting a new one.\n\n## Available APIs\n\nThe [Client documentation](https://docs.rs/ibapi/latest/ibapi/struct.Client.html) provides comprehensive details on all currently available APIs, including trading, account management, and market data features, along with examples to help you get started.\n\n## Install\n\nCheck [crates.io/crates/ibapi](https://crates.io/crates/ibapi) for the latest available version and installation instructions.\n\n## Examples\n\nThese examples demonstrate key features of the `ibapi` API.\n\n### Connecting to TWS\n\n#### Sync Example\n\n```rust\nuse ibapi::client::blocking::Client;\nuse ibapi::prelude::*;\n\nfn main() {\n    let connection_url = \"127.0.0.1:4002\";\n\n    let client = Client::connect(connection_url, 100).expect(\"connection to TWS failed!\");\n    println!(\"Successfully connected to TWS at {connection_url}\");\n}\n```\n\n#### Async Example\n\n```rust\nuse ibapi::prelude::*;\n\n#[tokio::main]\nasync fn main() {\n    let connection_url = \"127.0.0.1:4002\";\n\n    let client = Client::connect(connection_url, 100).await.expect(\"connection to TWS failed!\");\n    println!(\"Successfully connected to TWS at {connection_url}\");\n}\n```\n\u003e **Note**: Use `127.0.0.1` instead of `localhost` for the connection. On some systems, `localhost` resolves to an IPv6 address, which TWS may block. TWS only allows specifying IPv4 addresses in the allowed IP addresses list.\n\n### Creating Contracts\n\nThe library provides a powerful type-safe contract builder API. Here's how to create a stock contract for TSLA:\n\n```rust\nuse ibapi::prelude::*;\n\n// Simple stock contract with defaults (USD, SMART routing)\nlet contract = Contract::stock(\"TSLA\").build();\n\n// Stock with customization - accepts string literals directly\nlet contract = Contract::stock(\"7203\")\n    .on_exchange(\"TSEJ\")\n    .in_currency(\"JPY\")\n    .build();\n```\n\nThe builder API provides type-safe construction for all contract types with compile-time validation:\n\n```rust\n// Options - required fields enforced at compile time\nlet option = Contract::call(\"AAPL\")\n    .strike(150.0)\n    .expires_on(2024, 12, 20)\n    .build();\n\n// Futures with convenience methods\nlet futures = Contract::futures(\"ES\")\n    .front_month()  // Next expiring contract\n    .build();\n\n// Forex pairs\nlet forex = Contract::forex(\"EUR\", \"USD\").build();\n\n// Bonds - simplified API for CUSIP and ISIN\nlet treasury = Contract::bond_cusip(\"912810RN0\");\nlet euro_bond = Contract::bond_isin(\"DE0001102309\");\n```\n\nSee the [Contract Builder Guide](docs/contract-builder.md) for comprehensive documentation on all contract types.\n\nFor lower-level control, you can also create contracts directly using the type wrappers:\n\n```rust\nuse ibapi::prelude::*;\n\n// Create a contract directly using the struct and type wrappers\nlet contract = Contract {\n    symbol: Symbol::from(\"TSLA\"),\n    security_type: SecurityType::Stock,\n    currency: Currency::from(\"USD\"),\n    exchange: Exchange::from(\"SMART\"),\n    ..Default::default()\n};\n```\n\nFor a complete list of contract attributes, explore the [Contract documentation](https://docs.rs/ibapi/latest/ibapi/contracts/struct.Contract.html).\n\n### Requesting Historical Market Data\n\n#### Sync Example\n\n```rust\nuse time::macros::datetime;\nuse ibapi::prelude::*;\n\nfn main() {\n    let connection_url = \"127.0.0.1:4002\";\n    let client = Client::connect(connection_url, 100).expect(\"connection to TWS failed!\");\n\n    let contract = Contract::stock(\"AAPL\").build();\n\n    let historical_data = client\n        .historical_data(\n            \u0026contract,\n            Some(datetime!(2023-04-11 20:00 UTC)),\n            1.days(),\n            HistoricalBarSize::Hour,\n            Some(HistoricalWhatToShow::Trades),\n            TradingHours::Regular,\n        )\n        .expect(\"historical data request failed\");\n\n    println!(\"start: {:?}, end: {:?}\", historical_data.start, historical_data.end);\n\n    for bar in \u0026historical_data.bars {\n        println!(\"{bar:?}\");\n    }\n}\n```\n\n#### Async Example\n\n```rust\nuse time::macros::datetime;\nuse ibapi::prelude::*;\n\n#[tokio::main]\nasync fn main() {\n    let connection_url = \"127.0.0.1:4002\";\n    let client = Client::connect(connection_url, 100).await.expect(\"connection to TWS failed!\");\n\n    let contract = Contract::stock(\"AAPL\").build();\n\n    let historical_data = client\n        .historical_data(\n            \u0026contract,\n            Some(datetime!(2023-04-11 20:00 UTC)),\n            1.days(),\n            HistoricalBarSize::Hour,\n            Some(HistoricalWhatToShow::Trades),\n            TradingHours::Regular,\n        )\n        .await\n        .expect(\"historical data request failed\");\n\n    println!(\"start: {:?}, end: {:?}\", historical_data.start, historical_data.end);\n\n    for bar in \u0026historical_data.bars {\n        println!(\"{bar:?}\");\n    }\n}\n```\n\n### Requesting Realtime Market Data\n\n#### Sync Example\n\n```rust\nuse ibapi::prelude::*;\n\nfn main() {\n    let connection_url = \"127.0.0.1:4002\";\n    let client = Client::connect(connection_url, 100).expect(\"connection to TWS failed!\");\n\n    // Request real-time bars data for AAPL with 5-second intervals\n    let contract = Contract::stock(\"AAPL\").build();\n    let subscription = client\n        .realtime_bars(\u0026contract, RealtimeBarSize::Sec5, RealtimeWhatToShow::Trades, TradingHours::Extended)\n        .expect(\"realtime bars request failed!\");\n\n    for bar in subscription {\n        // Process each bar here (e.g., print or use in calculations)\n        println!(\"bar: {bar:?}\");\n    }\n}\n```\n\n#### Async Example\n\n```rust\nuse ibapi::prelude::*;\nuse futures::StreamExt;\n\n#[tokio::main]\nasync fn main() {\n    let connection_url = \"127.0.0.1:4002\";\n    let client = Client::connect(connection_url, 100).await.expect(\"connection to TWS failed!\");\n\n    // Request real-time bars data for AAPL with 5-second intervals\n    let contract = Contract::stock(\"AAPL\").build();\n    let mut subscription = client\n        .realtime_bars(\u0026contract, RealtimeBarSize::Sec5, RealtimeWhatToShow::Trades, TradingHours::Extended)\n        .await\n        .expect(\"realtime bars request failed!\");\n\n    while let Some(bar) = subscription.next().await {\n        // Process each bar here (e.g., print or use in calculations)\n        println!(\"bar: {bar:?}\");\n    }\n}\n```\n\nIn both examples, the request for realtime bars returns a [Subscription](https://docs.rs/ibapi/latest/ibapi/struct.Subscription.html) that can be used as an iterator (sync) or stream (async). The subscription is automatically cancelled when it goes out of scope.\n\n#### Non-blocking Iteration (Sync)\n\n```rust\nuse std::time::Duration;\n\n// Example of non-blocking iteration in sync mode\nloop {\n    match subscription.try_next() {\n        Some(bar) =\u003e println!(\"bar: {bar:?}\"),\n        None =\u003e {\n            // No new data yet; perform other tasks or sleep\n            std::thread::sleep(Duration::from_millis(100));\n        }\n    }\n}\n```\n\nExplore the [Subscription documentation](https://docs.rs/ibapi/latest/ibapi/struct.Subscription.html) for more details.\n\nSince subscriptions can be converted to iterators, it is easy to iterate over multiple contracts.\n\n```rust\nuse ibapi::prelude::*;\n\nfn main() {\n    let connection_url = \"127.0.0.1:4002\";\n    let client = Client::connect(connection_url, 100).expect(\"connection to TWS failed!\");\n\n    // Request real-time bars data for AAPL with 5-second intervals\n    let contract_aapl = Contract::stock(\"AAPL\").build();\n    let contract_nvda = Contract::stock(\"NVDA\").build();\n\n    let subscription_aapl = client\n        .realtime_bars(\u0026contract_aapl, RealtimeBarSize::Sec5, RealtimeWhatToShow::Trades, TradingHours::Extended)\n        .expect(\"realtime bars request failed!\");\n    let subscription_nvda = client\n        .realtime_bars(\u0026contract_nvda, RealtimeBarSize::Sec5, RealtimeWhatToShow::Trades, TradingHours::Extended)\n        .expect(\"realtime bars request failed!\");\n\n    for (bar_aapl, bar_nvda) in subscription_aapl.iter().zip(subscription_nvda.iter()) {\n        // Process each bar here (e.g., print or use in calculations)\n        println!(\"AAPL {}, NVDA {}\", bar_aapl.close, bar_nvda.close);\n    }\n}\n```\n\u003e **Note:** When using `zip`, the iteration will stop if either subscription ends. For independent processing, consider handling each subscription separately.\n\n### Placing Orders\n\nFor a comprehensive guide on all supported order types and their usage, see the [Order Types Guide](docs/order-types.md).\n\n#### Sync Example\n\n```rust\nuse ibapi::prelude::*;\n\npub fn main() {\n    let connection_url = \"127.0.0.1:4002\";\n    let client = Client::connect(connection_url, 100).expect(\"connection to TWS failed!\");\n\n    let contract = Contract::stock(\"AAPL\").build();\n\n    // Create and submit a market order to purchase 100 shares using the fluent API\n    let order_id = client.order(\u0026contract)\n        .buy(100)\n        .market()\n        .submit()\n        .expect(\"order submission failed!\");\n\n    println!(\"Order submitted with ID: {}\", order_id);\n\n    // Example of a more complex order: limit order with time in force\n    let order_id = client.order(\u0026contract)\n        .sell(50)\n        .limit(150.00)\n        .good_till_cancel()\n        .outside_rth()\n        .submit()\n        .expect(\"order submission failed!\");\n\n    println!(\"Limit order submitted with ID: {}\", order_id);\n}\n```\n\n#### Async Example\n\n```rust\nuse ibapi::prelude::*;\n\n#[tokio::main]\nasync fn main() {\n    let connection_url = \"127.0.0.1:4002\";\n    let client = Client::connect(connection_url, 100).await.expect(\"connection to TWS failed!\");\n\n    let contract = Contract::stock(\"AAPL\").build();\n\n    // Create and submit a market order to purchase 100 shares using the fluent API\n    let order_id = client.order(\u0026contract)\n        .buy(100)\n        .market()\n        .submit()\n        .await\n        .expect(\"order submission failed!\");\n\n    println!(\"Order submitted with ID: {}\", order_id);\n\n    // Example of a bracket order: entry with take profit and stop loss\n    let bracket_ids = client.order(\u0026contract)\n        .buy(100)\n        .bracket()\n        .entry_limit(150.00)\n        .take_profit(160.00)\n        .stop_loss(145.00)\n        .submit_all()\n        .await\n        .expect(\"bracket order submission failed!\");\n\n    println!(\"Bracket order IDs - Parent: {}, TP: {}, SL: {}\",\n             bracket_ids.parent, bracket_ids.take_profit, bracket_ids.stop_loss);\n}\n```\n\n#### Monitoring Order Updates\n\nFor real-time monitoring of order status, executions, and commissions, set up an order update stream before submitting orders:\n\n##### Sync Example\n\n```rust\nuse ibapi::prelude::*;\nuse std::thread;\nuse std::sync::Arc;\n\nfn main() {\n    let connection_url = \"127.0.0.1:4002\";\n    let client = Arc::new(Client::connect(connection_url, 100).expect(\"connection to TWS failed!\"));\n\n    // Start background thread to monitor order updates\n    let monitor_client = client.clone();\n    let _monitor_handle = thread::spawn(move || {\n        let stream = monitor_client.order_update_stream().expect(\"failed to create stream\");\n\n        for update in stream {\n            match update {\n                OrderUpdate::OrderStatus(status) =\u003e {\n                    println!(\"Order {} Status: {}\", status.order_id, status.status);\n                    println!(\"  Filled: {}, Remaining: {}\", status.filled, status.remaining);\n                }\n                OrderUpdate::OpenOrder(data) =\u003e {\n                    println!(\"Open Order {}: {} {}\",\n                             data.order_id, data.order.action, data.contract.symbol);\n                }\n                OrderUpdate::ExecutionData(exec) =\u003e {\n                    println!(\"Execution: {} shares @ {}\",\n                             exec.execution.shares, exec.execution.price);\n                }\n                OrderUpdate::CommissionReport(report) =\u003e {\n                    println!(\"Commission: ${}\", report.commission);\n                }\n                OrderUpdate::Message(msg) =\u003e {\n                    println!(\"Message: {}\", msg.message);\n                }\n            }\n        }\n    });\n\n    // Give monitor time to start\n    thread::sleep(std::time::Duration::from_millis(100));\n\n    // Now submit orders - updates will be received by the monitoring thread\n    let contract = Contract::stock(\"AAPL\").build();\n    let order_id = client.order(\u0026contract)\n        .buy(100)\n        .market()\n        .submit()\n        .expect(\"order submission failed!\");\n\n    println!(\"Order {} submitted\", order_id);\n\n    // Keep main thread alive to receive updates\n    thread::sleep(std::time::Duration::from_secs(10));\n}\n```\n\n##### Async Example\n\n```rust\nuse ibapi::prelude::*;\nuse futures::StreamExt;\n\n#[tokio::main]\nasync fn main() {\n    let connection_url = \"127.0.0.1:4002\";\n    let client = Client::connect(connection_url, 100).await.expect(\"connection to TWS failed!\");\n\n    // Create order update stream before submitting orders\n    let mut order_stream = client.order_update_stream().await.expect(\"failed to create stream\");\n\n    // Spawn task to monitor updates\n    let monitor_handle = tokio::spawn(async move {\n        while let Some(update) = order_stream.next().await {\n            match update {\n                Ok(OrderUpdate::OrderStatus(status)) =\u003e {\n                    println!(\"Order {} Status: {}\", status.order_id, status.status);\n                    println!(\"  Filled: {}, Remaining: {}\", status.filled, status.remaining);\n                }\n                Ok(OrderUpdate::OpenOrder(data)) =\u003e {\n                    println!(\"Open Order {}: {} {}\",\n                             data.order_id, data.order.action, data.contract.symbol);\n                }\n                Ok(OrderUpdate::ExecutionData(exec)) =\u003e {\n                    println!(\"Execution: {} shares @ {}\",\n                             exec.execution.shares, exec.execution.price);\n                }\n                Ok(OrderUpdate::CommissionReport(report)) =\u003e {\n                    println!(\"Commission: ${}\", report.commission);\n                }\n                Ok(OrderUpdate::Message(msg)) =\u003e {\n                    println!(\"Message: {}\", msg.message);\n                }\n                Err(e) =\u003e {\n                    eprintln!(\"Error: {:?}\", e);\n                    break;\n                }\n            }\n        }\n    });\n\n    // Give monitor time to start\n    tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;\n\n    // Now submit orders - updates will be received by the monitoring task\n    let contract = Contract::stock(\"AAPL\").build();\n    let order_id = client.order(\u0026contract)\n        .buy(100)\n        .market()\n        .submit()\n        .await\n        .expect(\"order submission failed!\");\n\n    println!(\"Order {} submitted\", order_id);\n\n    // Wait for updates\n    tokio::time::sleep(tokio::time::Duration::from_secs(10)).await;\n\n    // Clean up\n    monitor_handle.abort();\n}\n```\n\nThe order update stream provides real-time notifications for:\n- **OrderStatus**: Status changes (Submitted, Filled, Cancelled, etc.)\n- **OpenOrder**: Order details when opened or modified\n- **ExecutionData**: Fill notifications with price and quantity\n- **CommissionReport**: Commission charges for executions\n- **Message**: System messages and notifications\n\n## Multi-Threading\n\nThe [Client](https://docs.rs/ibapi/latest/ibapi/struct.Client.html) can be shared between threads to support concurrent operations. The following example demonstrates valid multi-threaded usage of [Client](https://docs.rs/ibapi/latest/ibapi/struct.Client.html).\n\n```rust\nuse std::sync::Arc;\nuse std::thread;\nuse ibapi::prelude::*;\n\nfn main() {\n    let connection_url = \"127.0.0.1:4002\";\n    let client = Arc::new(Client::connect(connection_url, 100).expect(\"connection to TWS failed!\"));\n\n    let symbols = vec![\"AAPL\", \"NVDA\"];\n    let mut handles = vec![];\n\n    for symbol in symbols {\n        let client = Arc::clone(\u0026client);\n        let handle = thread::spawn(move || {\n            let contract = Contract::stock(symbol).build();\n            let subscription = client\n                .realtime_bars(\u0026contract, RealtimeBarSize::Sec5, RealtimeWhatToShow::Trades, TradingHours::Extended)\n                .expect(\"realtime bars request failed!\");\n\n            for bar in subscription {\n                // Process each bar here (e.g., print or use in calculations)\n                println!(\"bar: {bar:?}\");\n            }\n        });\n        handles.push(handle);\n    }\n\n    handles.into_iter().for_each(|handle| handle.join().unwrap());\n}\n```\n\nSome TWS API calls do not have a unique request ID and are mapped back to the initiating request by message type instead. Since the message type is not unique, concurrent requests of the same message type (if not synchronized by the application) may receive responses for other requests of the same message type. [Subscriptions](https://docs.rs/ibapi/latest/ibapi/client/struct.Subscription.html) using shared channels are tagged with the [SharesChannel](https://docs.rs/ibapi/latest/ibapi/client/trait.SharesChannel.html) trait to highlight areas that the application may need to synchronize.\n\nTo avoid this issue, you can use a model of one client per thread. This ensures that each client instance handles only its own messages, reducing potential conflicts:\n\n```rust\nuse std::thread;\nuse ibapi::prelude::*;\n\nfn main() {\n    let symbols = vec![(\"AAPL\", 100), (\"NVDA\", 101)];\n    let mut handles = vec![];\n\n    for (symbol, client_id) in symbols {\n        let handle = thread::spawn(move || {\n            let connection_url = \"127.0.0.1:4002\";\n            let client = Client::connect(connection_url, client_id).expect(\"connection to TWS failed!\");\n\n            let contract = Contract::stock(symbol).build();\n            let subscription = client\n                .realtime_bars(\u0026contract, RealtimeBarSize::Sec5, RealtimeWhatToShow::Trades, TradingHours::Extended)\n                .expect(\"realtime bars request failed!\");\n\n            for bar in subscription {\n                // Process each bar here (e.g., print or use in calculations)\n                println!(\"bar: {bar:?}\");\n            }\n        });\n        handles.push(handle);\n    }\n\n    handles.into_iter().for_each(|handle| handle.join().unwrap());\n}\n```\n\nIn this model, each client instance handles only the requests it initiates, improving the reliability of concurrent operations.\n\n# Fault Tolerance\n\nThe API will automatically attempt to reconnect to the TWS server if a disconnection is detected. The API will attempt to reconnect up to 30 times using a Fibonacci backoff strategy. In some cases, it will retry the request in progress. When receiving responses via a [Subscription](https://docs.rs/ibapi/latest/ibapi/client/struct.Subscription.html), the application may need to handle retries manually, as shown below.\n\n```rust\nuse ibapi::prelude::*;\n\nfn main() {\n    let connection_url = \"127.0.0.1:4002\";\n    let client = Client::connect(connection_url, 100).expect(\"connection to TWS failed!\");\n\n    let contract = Contract::stock(\"AAPL\").build();\n\n    loop {\n        // Request real-time bars data with 5-second intervals\n        let subscription = client\n            .realtime_bars(\u0026contract, RealtimeBarSize::Sec5, RealtimeWhatToShow::Trades, TradingHours::Extended)\n            .expect(\"realtime bars request failed!\");\n\n        for bar in \u0026subscription {\n            // Process each bar here (e.g., print or use in calculations)\n            println!(\"bar: {bar:?}\");\n        }\n\n        if let Some(Error::ConnectionReset) = subscription.error() {\n            eprintln!(\"Connection reset. Retrying stream...\");\n            continue;\n        }\n\n        break;\n    }\n}\n```\n\n## Contributions\n\nWe welcome contributions of all kinds. Feel free to propose new ideas, share bug fixes, or enhance the documentation. If you'd like to contribute, please start by reviewing our [contributor documentation](https://github.com/wboayue/rust-ibapi/blob/main/CONTRIBUTING.md).\n\nFor questions or discussions about contributions, feel free to open an issue or reach out via our [GitHub discussions page](https://github.com/wboayue/rust-ibapi/discussions).\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwboayue%2Frust-ibapi","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwboayue%2Frust-ibapi","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwboayue%2Frust-ibapi/lists"}