百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
R

rust-ibapi

> 编程语言
开源

用于 Rust 的 Interactive Brokers API 的实现

361 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

用于 Rust 的 Interactive Brokers API 的实现

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.

** Migrating?** See the v3.x → v4.0 guide for the latest breaking changes, the v2.x → v3.0 guide for the Subscription shape and notification handling, or the v1.x → v2.0 guide for the older transition.

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:

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"] }
bash
# 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-features

When both features are enabled, import the blocking types explicitly:

rust
use ibapi::Client;                    // async client
use ibapi::client::blocking::Client;  // blocking client

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.

Examples

These examples demonstrate key features of the ibapi API.

Connecting to TWS

Sync Example

rust
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

rust
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:

rust
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:

rust
// 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.

Requesting Historical Market Data

Sync Example

…

Async Example

…

Requesting Realtime Market Data

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.

Sync Example

…

Async Example

…

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)

Continuing from the sync example above, try_iter_data() polls without blocking:

rust
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.

One-Shot Snapshot

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.

rust
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.

Placing Orders

For a comprehensive guide on all supported order types and their usage, see the Order Types Guide.

Sync Example

…

Async Example

…

Monitoring Order Updates

For real-time monitoring of order status, executions, and commissions, set up an order update stream before submitting orders:

Sync Example
…
Async Example
…

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..=2199 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::next() returns Option, Error>>, so a single match handles data, notices, and terminal errors:

Sync example

…

Async example

…

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.

For a complete data-only example, see the sync example under Requesting Realtime Market Data above — its iter_data() loop is exactly this shape.

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:

…

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.

…

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

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Rustibapiinteractive-brokerstrading-api

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言