An implementation of the Interactive Brokers API for Rust
An implementation of the Interactive Brokers API for Rust
This library provides a comprehensive Rust implementation of the Interactive Brokers TWS API, 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.
With 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.
** Migrating?** See the v3.x → v4.0 guide for the latest breaking changes, the v2.x → v3.0 guide for the
Subscriptionshape and notification handling, or the v1.x → v2.0 guide for the older transition.
rust-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.
ibapi::Client.ibapi::client::blocking::Client (or ibapi::Client when async is disabled).Add to your Cargo.toml:
# Async only (default features)
ibapi = "4.0"
# Blocking only
ibapi = { version = "4.0", default-features = false, features = ["sync"] }
# Async + blocking together
ibapi = { version = "4.0", default-features = false, features = ["sync", "async"] }# Async client (default configuration)
cargo test
cargo run --example async_connect
# Blocking client only
cargo test --no-default-features --features sync
# Validate both clients together
cargo test --all-featuresWhen both features are enabled, import the blocking types explicitly:
use ibapi::Client; // async client
use ibapi::client::blocking::Client; // blocking clientThe Client documentation provides comprehensive details on all currently available APIs, including trading, account management, and market data features, along with examples to help you get started.
These examples demonstrate key features of the ibapi API.
use ibapi::client::blocking::Client;
use ibapi::prelude::*;
fn main() {
let connection_url = "127.0.0.1:4002";
let client = Client::connect(connection_url, 100).expect("connection to TWS failed!");
println!("Successfully connected to TWS at {connection_url}");
}use ibapi::prelude::*;
#[tokio::main]
async fn main() {
let connection_url = "127.0.0.1:4002";
let client = Client::connect(connection_url, 100).await.expect("connection to TWS failed!");
println!("Successfully connected to TWS at {connection_url}");
}Note: Use
127.0.0.1instead oflocalhostfor the connection. On some systems,localhostresolves to an IPv6 address, which TWS may block. TWS only allows specifying IPv4 addresses in the allowed IP addresses list.
The library provides a powerful type-safe contract builder API. Here's how to create a stock contract for TSLA:
use ibapi::prelude::*;
// Simple stock contract with defaults (USD, SMART routing)
let contract = Contract::stock("TSLA").build();
// Stock with customization - accepts string literals directly
let contract = Contract::stock("7203")
.on_exchange("TSEJ")
.in_currency("JPY")
.build();The builder API provides type-safe construction for all contract types with compile-time validation:
// Options - required fields enforced at compile time
let option = Contract::call("AAPL")
.strike(150.0)
.expires_on(2024, 12, 20)
.build();
// Futures with convenience methods
let futures = Contract::futures("ES")
.front_month() // Next expiring contract
.build();
// Forex pairs
let forex = Contract::forex("EUR", "USD").build();
// Bonds - simplified API for CUSIP and ISIN
let treasury = Contract::bond_cusip("912810RN0");
let euro_bond = Contract::bond_isin("DE0001102309");See the Contract Builder Guide for comprehensive documentation on all contract types.
For a complete list of contract attributes, explore the Contract documentation.
……These examples use iter_data() (sync) / filter_data() (async) to focus on bars; per-subscription notices are filtered (and logged at warn!). See Handling notifications for the pattern when you also want to observe Notice items.
……In both examples, the request for realtime bars returns a Subscription that can be used as an iterator (sync) or stream (async). The subscription is automatically cancelled when it goes out of scope.
Continuing from the sync example above, try_iter_data() polls without blocking:
use std::time::Duration;
// Example of non-blocking iteration in sync mode
loop {
match subscription.try_iter_data().next() {
Some(Ok(bar)) => println!("bar: {bar:?}"),
Some(Err(e)) => { eprintln!("error: {e}"); break; }
None => {
// No new data yet; perform other tasks or sleep
std::thread::sleep(Duration::from_millis(100));
}
}
}Explore the Subscription documentation for more details.
For a single snapshot rather than a streaming subscription, snapshot_once(timeout) requests snapshot mode, collects the ticks until the snapshot completes (or the timeout elapses), and returns them as a Vec — no hand-written collect loop. The same collect_for / collect_until terminals are available on any Subscription.
use ibapi::client::blocking::Client;
use ibapi::prelude::*;
use std::time::Duration;
fn main() {
let client = Client::connect("127.0.0.1:4002", 100).expect("connection to TWS failed!");
let contract = Contract::stock("AAPL").build();
let ticks = client
.market_data(&contract)
.snapshot_once(Duration::from_secs(5))
.expect("snapshot request failed!");
for tick in ticks {
println!("tick: {tick:?}");
}
}Since subscriptions can be converted to iterators, it is easy to iterate over multiple contracts.
…Note: When using
zip, the iteration will stop if either subscription ends. For independent processing, consider handling each subscription separately.
For a comprehensive guide on all supported order types and their usage, see the Order Types Guide.
……For real-time monitoring of order status, executions, and commissions, set up an order update stream before submitting orders:
……The order update stream provides real-time notifications for:
OrderStatusKind (Submitted, Filled, Cancelled, …) with is_active() / is_terminal() helpersPer-order TWS warnings (e.g. quote-throttling 2100 codes scoped to an order) flow through SubscriptionItem::Notice on the per-order subscription returned by place_order, not through OrderUpdate. See Handling notifications.
TWS emits two flavors of notification alongside subscription data:
request_id that maps back to a specific subscription. They arrive
on that subscription as SubscriptionItem::Notice(_); the stream stays open.request_id. They are not delivered
to any subscription; subscribe via Client::notice_stream() instead.Subscription::next() returns Option, Error>>,
so a single match handles data, notices, and terminal errors:
……Pick the iterator/stream shape based on whether the call site cares about notices:
| Want | Sync | Async |
|---|---|---|
| Data only (notices logged at warn) | subscription.iter_data() / next_data() |
subscription.filter_data() (then .next().await) |
| Data + notices (full visibility) | subscription.iter() / next() |
subscription.next().await (matches on SubscriptionItem) |
Most call sites (downstream business logic, indicators, paper-trading loops)
want iter_data() / filter_data() — notices are observability concerns and
already log at warn!. UI status indicators, custom logging, and audit pipelines
match on SubscriptionItem::Data vs SubscriptionItem::Notice directly.
For a complete data-only example, see the sync example under
Requesting Realtime Market Data above — its
iter_data() loop is exactly this shape.
Farm-status codes (2104/2106/2158, etc.) typically arrive before
Client::connect returns, so a notice_stream registered afterwards will not
see that initial burst. To capture handshake-time notices — useful for
connection-state UIs and startup telemetry — use the builder's
connect_with_notice_stream terminal instead of connect:
…The pre-bound stream survives auto-reconnects (the broadcaster lives on
Connection, not on the bus), so a single subscription covers both paths.
For runtime-only unrouted notices once the client is up, you can also call
Client::notice_stream
post-connect — both subscribe to the same broadcaster.
The Client can be shared between threads to support concurrent operations. The following example demonstrates valid multi-threaded usage of Client.
…Some 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 using shared channels are tagged with the blocking client's SharesChannel trait to highlight areas that the application may need to synchronize.
To avoid this issue, y
No open issues yet, or sync has not completed.