
Branch notice: The main branch is the v3.0 release line. For v2.x maintenance and bug fixes, see the v2-stable branch.
What's new in 3.0
- Protobuf-only wire format. v3.0 drops the legacy text protocol and speaks only TWS protobuf. Requires TWS / IB Gateway server version 213 or newer. Smaller, faster, and version-gated by IB itself β see
docs/migration-3.0.md for the cutover.
- API ergonomics overhaul. Builders for multi-arg subscriptions (
market_data(&contract).subscribe(), realtime_bars(&contract).subscribe()), unified Subscription<T> shape with SubscriptionItem::{Data, Notice}, typed OrderStatusKind (was magic-string String), globally-routed Client::notice_stream() for unsolicited notices, and consistent sync/async surfaces. See the migration guide for the before/after on every breaking change.
Introduction
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. Future updates will focus on bug fixes, maintaining parity with the official API, and enhancing usability.
Sync/Async Architecture
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.
- async (default): Non-blocking client using Tokio tasks and broadcast channels. Available as
ibapi::Client.
- sync: Blocking client using crossbeam channels. Available as
ibapi::client::blocking::Client (or ibapi::Client when async is disabled).
Add to your Cargo.toml:
ibapi = "3.0"
ibapi = { version = "3.0", default-features = false, features = ["sync"] }
ibapi = { version = "3.0", default-features = false, features = ["sync", "async"] }
cargo test
cargo run --example async_connect
cargo test --no-default-features --features sync
cargo test --all-features
When both features are enabled, import the blocking types explicitly:
use ibapi::Client; use ibapi::client::blocking::Client;
π Migrating? See the v2.x β v3.0 guide for the new Subscription shape and notification handling, or the v1.x β v2.0 guide for the older transition.
If you encounter any issues or require a missing feature, please review the issues list before submitting a new one.
Available APIs
The 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.
Install
v3.0 (this branch): crates.io/crates/ibapi β see the Sync/Async Architecture section above for the Cargo.toml snippets.
v2.x (stable): earlier 2.x releases are still on crates.io/crates/ibapi. Maintenance lives on the v2-stable branch.
Examples
These examples demonstrate key features of the ibapi API.
Connecting to TWS
Sync Example
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}");
}
Async Example
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.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.
Creating Contracts
The library provides a powerful type-safe contract builder API. Here's how to create a stock contract for TSLA:
use ibapi::prelude::*;
let contract = Contract::stock("TSLA").build();
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:
let option = Contract::call("AAPL")
.strike(150.0)
.expires_on(2024, 12, 20)
.build();
let futures = Contract::futures("ES")
.front_month() .build();
let forex = Contract::forex("EUR", "USD").build();
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.
Requesting Historical Market Data
Sync Example
use time::macros::datetime;
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!");
let contract = Contract::stock("AAPL").build();
let historical_data = client
.historical_data(&contract, HistoricalBarSize::Hour)
.ending(datetime!(2023-04-11 20:00 UTC))
.duration(1.days())
.what_to_show(HistoricalWhatToShow::Trades)
.trading_hours(TradingHours::Regular)
.fetch()
.expect("historical data request failed");
println!("start: {:?}, end: {:?}", historical_data.start, historical_data.end);
for bar in &historical_data.bars {
println!("{bar:?}");
}
}
Async Example
use time::macros::datetime;
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!");
let contract = Contract::stock("AAPL").build();
let historical_data = client
.historical_data(&contract, HistoricalBarSize::Hour)
.ending(datetime!(2023-04-11 20:00 UTC))
.duration(1.days())
.what_to_show(HistoricalWhatToShow::Trades)
.trading_hours(TradingHours::Regular)
.fetch()
.await
.expect("historical data request failed");
println!("start: {:?}, end: {:?}", historical_data.start, historical_data.end);
for bar in &historical_data.bars {
println!("{bar:?}");
}
}
Requesting Realtime Market Data
These examples use iter_data() / data_stream() 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.
Sync Example
use ibapi::client::blocking::Client;
use ibapi::prelude::*;
fn main() {
let client = Client::connect("127.0.0.1:4002", 100).expect("connection to TWS failed!");
let contract = Contract::stock("AAPL").build();
let subscription = client
.realtime_bars(&contract)
.trading_hours(TradingHours::Extended)
.subscribe()
.expect("realtime bars request failed!");
for bar in subscription.iter_data() {
match bar {
Ok(bar) => println!("bar: {bar:?}"),
Err(e) => {
eprintln!("error: {e:?}");
break;
}
}
}
}
Async Example
use ibapi::prelude::*;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection to TWS failed!");
let contract = Contract::stock("AAPL").build();
let mut subscription = client
.realtime_bars(&contract)
.trading_hours(TradingHours::Extended)
.subscribe()
.await
.expect("realtime bars request failed!");
let mut data = subscription.filter_data();
while let Some(item) = data.next().await {
match item {
Ok(bar) => println!("bar: {bar:?}"),
Err(e) => { eprintln!("error: {e}"); break; }
}
}
}
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.
Non-blocking Iteration (Sync)
use std::time::Duration;
loop {
match subscription.try_iter_data().next() {
Some(Ok(bar)) => println!("bar: {bar:?}"),
Some(Err(e)) => { eprintln!("error: {e}"); break; }
None => {
std::thread::sleep(Duration::from_millis(100));
}
}
}
Explore the Subscription documentation for more details.
Since subscriptions can be converted to iterators, it is easy to iterate over multiple contracts.
use ibapi::client::blocking::Client;
use ibapi::prelude::*;
fn main() {
let client = Client::connect("127.0.0.1:4002", 100).expect("connection to TWS failed!");
let contract_aapl = Contract::stock("AAPL").build();
let contract_nvda = Contract::stock("NVDA").build();
let subscription_aapl = client
.realtime_bars(&contract_aapl)
.trading_hours(TradingHours::Extended)
.subscribe()
.expect("realtime bars request failed!");
let subscription_nvda = client
.realtime_bars(&contract_nvda)
.trading_hours(TradingHours::Extended)
.subscribe()
.expect("realtime bars request failed!");
for (bar_aapl, bar_nvda) in subscription_aapl.iter_data().zip(subscription_nvda.iter_data()) {
let (bar_aapl, bar_nvda) = match (bar_aapl, bar_nvda) {
(Ok(a), Ok(n)) => (a, n),
(Err(e), _) | (_, Err(e)) => {
eprintln!("error: {e}");
break;
}
};
println!("AAPL {}, NVDA {}", bar_aapl.close, bar_nvda.close);
}
}
Note: When using zip, the iteration will stop if either subscription ends. For independent processing, consider handling each subscription separately.
Placing Orders
For a comprehensive guide on all supported order types and their usage, see the Order Types Guide.
Sync Example
use ibapi::prelude::*;
pub fn main() {
let connection_url = "127.0.0.1:4002";
let client = Client::connect(connection_url, 100).expect("connection to TWS failed!");
let contract = Contract::stock("AAPL").build();
let order_id = client.order(&contract)
.buy(100)
.market()
.submit()
.expect("order submission failed!");
println!("Order submitted with ID: {}", order_id);
let order_id = client.order(&contract)
.sell(50)
.limit(150.00)
.good_till_cancel()
.outside_rth()
.submit()
.expect("order submission failed!");
println!("Limit order submitted with ID: {}", order_id);
}
Async Example
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!");
let contract = Contract::stock("AAPL").build();
let order_id = client.order(&contract)
.buy(100)
.market()
.submit()
.await
.expect("order submission failed!");
println!("Order submitted with ID: {}", order_id);
let bracket_ids = client.order(&contract)
.buy(100)
.bracket()
.entry_limit(150.00)
.take_profit(160.00)
.stop_loss(145.00)
.submit_all()
.await
.expect("bracket order submission failed!");
println!("Bracket order IDs - Parent: {}, TP: {}, SL: {}",
bracket_ids.parent, bracket_ids.take_profit, bracket_ids.stop_loss);
}
Monitoring Order Updates
For real-time monitoring of order status, executions, and commissions, set up an order update stream before submitting orders:
Sync Example
use ibapi::prelude::*;
use std::thread;
use std::sync::Arc;
fn main() {
let connection_url = "127.0.0.1:4002";
let client = Arc::new(Client::connect(connection_url, 100).expect("connection to TWS failed!"));
let monitor_client = client.clone();
let _monitor_handle = thread::spawn(move || {
let stream = monitor_client.order_update_stream().expect("failed to create stream");
for update in stream.iter_data() {
match update {
Ok(OrderUpdate::OrderStatus(status)) => {
println!("Order {} Status: {}", status.order_id, status.status);
println!(" Filled: {}, Remaining: {}", status.filled, status.remaining);
if status.status.is_terminal() {
break;
}
}
Ok(OrderUpdate::OpenOrder(data)) => {
println!("Open Order {}: {} {}",
data.order_id, data.order.action, data.contract.symbol);
}
Ok(OrderUpdate::ExecutionData(exec)) => {
println!("Execution: {} shares @ {}",
exec.execution.shares, exec.execution.price);
}
Ok(OrderUpdate::CommissionReport(report)) => {
println!("Commission: ${}", report.commission);
}
Err(e) => {
eprintln!("order update stream error: {e:?}");
break;
}
}
}
});
thread::sleep(std::time::Duration::from_millis(100));
let contract = Contract::stock("AAPL").build();
let order_id = client.order(&contract)
.buy(100)
.market()
.submit()
.expect("order submission failed!");
println!("Order {} submitted", order_id);
thread::sleep(std::time::Duration::from_secs(10));
}
Async Example
use ibapi::prelude::*;
use futures::StreamExt;
#[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!");
let order_stream = client.order_update_stream().await.expect("failed to create stream");
let monitor_handle = tokio::spawn(async move {
let mut order_stream = order_stream.filter_data();
while let Some(update) = order_stream.next().await {
match update {
Ok(OrderUpdate::OrderStatus(status)) => {
println!("Order {} Status: {}", status.order_id, status.status);
println!(" Filled: {}, Remaining: {}", status.filled, status.remaining);
if status.status.is_terminal() {
break;
}
}
Ok(OrderUpdate::OpenOrder(data)) => {
println!("Open Order {}: {} {}",
data.order_id, data.order.action, data.contract.symbol);
}
Ok(OrderUpdate::ExecutionData(exec)) => {
println!("Execution: {} shares @ {}",
exec.execution.shares, exec.execution.price);
}
Ok(OrderUpdate::CommissionReport(report)) => {
println!("Commission: ${}", report.commission);
}
Err(e) => {
eprintln!("Error: {:?}", e);
break;
}
}
}
});
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
let contract = Contract::stock("AAPL").build();
let order_id = client.order(&contract)
.buy(100)
.market()
.submit()
.await
.expect("order submission failed!");
println!("Order {} submitted", order_id);
tokio::time::sleep(tokio::time::Duration::from_secs(10)).await;
monitor_handle.abort();
}
The order update stream provides real-time notifications for:
- OrderStatus: Status changes typed as
OrderStatusKind (Submitted, Filled, Cancelled, β¦) with is_active() / is_terminal() helpers
- OpenOrder: Order details when opened or modified
- ExecutionData: Fill notifications with price and quantity
- CommissionReport: Commission charges for executions
Per-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.
Handling notifications
TWS emits two flavors of notification alongside subscription data:
- Per-subscription notices β warning codes 2100..=2169 and order-cancel code
202 carry a
request_id that maps back to a specific subscription. They arrive
on that subscription as SubscriptionItem::Notice(_); the stream stays open.
- Globally routed notices β connectivity codes 1100/1101/1102 and farm-status
codes (2104/2105/2106/2107/2108) have no
request_id. They are not delivered
to any subscription; subscribe via Client::notice_stream() instead.
Per-subscription notices
Subscription<T>::next() returns Option<Result<SubscriptionItem<T>, Error>>,
so a single match handles data, notices, and terminal errors:
Sync example
use ibapi::client::blocking::Client;
use ibapi::prelude::*;
fn main() {
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("AAPL").build();
let subscription = client
.realtime_bars(&contract)
.trading_hours(TradingHours::Extended)
.subscribe()
.expect("realtime bars request failed");
for item in &subscription {
match item {
Ok(SubscriptionItem::Data(bar)) => println!("bar: {bar:?}"),
Ok(SubscriptionItem::Notice(note)) => eprintln!("notice: {note}"),
Err(e) => { eprintln!("error: {e}"); break; }
}
}
}
Async example
use ibapi::prelude::*;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let contract = Contract::stock("AAPL").build();
let mut subscription = client
.realtime_bars(&contract)
.trading_hours(TradingHours::Extended)
.subscribe()
.await
.expect("realtime bars request failed");
while let Some(item) = subscription.next().await {
match item {
Ok(SubscriptionItem::Data(bar)) => println!("bar: {bar:?}"),
Ok(SubscriptionItem::Notice(note)) => eprintln!("notice: {note}"),
Err(e) => { eprintln!("error: {e}"); break; }
}
}
}
Filtering vs. observing
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.
Sync data-only example:
use ibapi::client::blocking::Client;
use ibapi::prelude::*;
fn main() {
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("AAPL").build();
let subscription = client
.realtime_bars(&contract)
.trading_hours(TradingHours::Extended)
.subscribe()
.expect("realtime bars request failed");
for bar in subscription.iter_data() {
match bar {
Ok(bar) => println!("bar: {bar:?}"),
Err(e) => {
eprintln!("error: {e:?}");
break;
}
}
}
}
Handshake-time notices
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:
use ibapi::client::blocking::Client;
fn main() {
let (client, notices) = Client::builder()
.address("127.0.0.1:4002")
.client_id(100)
.connect_with_notice_stream()
.expect("connection failed");
for n in notices.iter() {
if n.is_system_message() {
println!("connectivity: {n}");
} else {
println!("notice: {n}");
}
}
drop(client);
}
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.
Multi-Threading
The Client can be shared between threads to support concurrent operations. The following example demonstrates valid multi-threaded usage of Client.
use std::sync::Arc;
use std::thread;
use ibapi::prelude::*;
fn main() {
let connection_url = "127.0.0.1:4002";
let client = Arc::new(Client::connect(connection_url, 100).expect("connection to TWS failed!"));
let symbols = vec!["AAPL", "NVDA"];
let mut handles = vec![];
for symbol in symbols {
let client = Arc::clone(&client);
let handle = thread::spawn(move || {
let contract = Contract::stock(symbol).build();
let subscription = client
.realtime_bars(&contract)
.trading_hours(TradingHours::Extended)
.subscribe()
.expect("realtime bars request failed!");
for bar in subscription.iter_data() {
match bar {
Ok(bar) => println!("bar: {bar:?}"),
Err(e) => {
eprintln!("error: {e:?}");
break;
}
}
}
});
handles.push(handle);
}
handles.into_iter().for_each(|handle| handle.join().unwrap());
}
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 SharesChannel trait to highlight areas that the application may need to synchronize.
To 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:
use std::thread;
use ibapi::prelude::*;
fn main() {
let symbols = vec![("AAPL", 100), ("NVDA", 101)];
let mut handles = vec![];
for (symbol, client_id) in symbols {
let handle = thread::spawn(move || {
let connection_url = "127.0.0.1:4002";
let client = Client::connect(connection_url, client_id).expect("connection to TWS failed!");
let contract = Contract::stock(symbol).build();
let subscription = client
.realtime_bars(&contract)
.trading_hours(TradingHours::Extended)
.subscribe()
.expect("realtime bars request failed!");
for bar in subscription.iter_data() {
match bar {
Ok(bar) => println!("bar: {bar:?}"),
Err(e) => {
eprintln!("error: {e:?}");
break;
}
}
}
});
handles.push(handle);
}
handles.into_iter().for_each(|handle| handle.join().unwrap());
}
In this model, each client instance handles only the requests it initiates, improving the reliability of concurrent operations.
Fault Tolerance
The API will automatically attempt to reconnect to the TWS server if a disconnection is detected. The API will attempt to reconnect up to 20 times using a Fibonacci backoff strategy. In some cases, it will retry the request in progress. When receiving responses via a Subscription, the application may need to handle retries manually. In v3.0, terminal errors surface as Some(Err(_)) from Subscription::next() (no separate error() accessor); inspect the error and decide whether to resubscribe:
use ibapi::client::blocking::Client;
use ibapi::prelude::*;
fn main() {
let client = Client::connect("127.0.0.1:4002", 100).expect("connection to TWS failed!");
let contract = Contract::stock("AAPL").build();
'outer: loop {
let subscription = client
.realtime_bars(&contract)
.trading_hours(TradingHours::Extended)
.subscribe()
.expect("realtime bars request failed!");
for item in &subscription {
match item {
Ok(SubscriptionItem::Data(bar)) => println!("bar: {bar:?}"),
Ok(SubscriptionItem::Notice(note)) => eprintln!("notice: {note}"),
Err(Error::ConnectionReset) => {
eprintln!("Connection reset. Retrying stream...");
continue 'outer;
}
Err(e) => {
eprintln!("error: {e}");
break 'outer;
}
}
}
break;
}
}
Contributions
We 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.
For questions or discussions about contributions, feel free to open an issue or reach out via our GitHub discussions page.