ibapi 2.2.2

A Rust implementation of the Interactive Brokers TWS API, providing a reliable and user friendly interface for TWS and IB Gateway. Designed with a focus on simplicity and performance.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
[![Build](https://github.com/wboayue/rust-ibapi/workflows/ci/badge.svg)](https://github.com/wboayue/rust-ibapi/actions/workflows/ci.yml)
[![License:MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
[![crates.io](https://img.shields.io/crates/v/ibapi.svg)](https://crates.io/crates/ibapi)
[![Documentation](https://img.shields.io/badge/Documentation-green.svg)](https://docs.rs/ibapi/latest/ibapi/)
[![Coverage Status](https://coveralls.io/repos/github/wboayue/rust-ibapi/badge.png?branch=main)](https://coveralls.io/github/wboayue/rust-ibapi?branch=main)

## Introduction

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

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

```toml
# Async only (default features)
ibapi = "2.1"

# Blocking only
ibapi = { version = "2.1", default-features = false, features = ["sync"] }

# Async + blocking together
ibapi = { version = "2.1", 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
```

> **📚 Migrating from v1.x?** See the [Migration Guide](MIGRATION.md) for step-by-step upgrade instructions.

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

## Available APIs

The [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.

## Install

Check [crates.io/crates/ibapi](https://crates.io/crates/ibapi) for the latest available version and installation instructions.

## 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](docs/contract-builder.md) for comprehensive documentation on all contract types.

For lower-level control, you can also create contracts directly using the type wrappers:

```rust
use ibapi::prelude::*;

// Create a contract directly using the struct and type wrappers
let contract = Contract {
    symbol: Symbol::from("TSLA"),
    security_type: SecurityType::Stock,
    currency: Currency::from("USD"),
    exchange: Exchange::from("SMART"),
    ..Default::default()
};
```

For a complete list of contract attributes, explore the [Contract documentation](https://docs.rs/ibapi/latest/ibapi/contracts/struct.Contract.html).

### Requesting Historical Market Data

#### Sync Example

```rust
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,
            Some(datetime!(2023-04-11 20:00 UTC)),
            1.days(),
            HistoricalBarSize::Hour,
            Some(HistoricalWhatToShow::Trades),
            TradingHours::Regular,
        )
        .expect("historical data request failed");

    println!("start: {:?}, end: {:?}", historical_data.start, historical_data.end);

    for bar in &historical_data.bars {
        println!("{bar:?}");
    }
}
```

#### Async Example

```rust
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,
            Some(datetime!(2023-04-11 20:00 UTC)),
            1.days(),
            HistoricalBarSize::Hour,
            Some(HistoricalWhatToShow::Trades),
            TradingHours::Regular,
        )
        .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

#### Sync Example

```rust
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!");

    // Request real-time bars data for AAPL with 5-second intervals
    let contract = Contract::stock("AAPL").build();
    let subscription = client
        .realtime_bars(&contract, RealtimeBarSize::Sec5, RealtimeWhatToShow::Trades, TradingHours::Extended)
        .expect("realtime bars request failed!");

    for bar in subscription {
        // Process each bar here (e.g., print or use in calculations)
        println!("bar: {bar:?}");
    }
}
```

#### Async Example

```rust
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!");

    // Request real-time bars data for AAPL with 5-second intervals
    let contract = Contract::stock("AAPL").build();
    let mut subscription = client
        .realtime_bars(&contract, RealtimeBarSize::Sec5, RealtimeWhatToShow::Trades, TradingHours::Extended)
        .await
        .expect("realtime bars request failed!");

    while let Some(bar) = subscription.next().await {
        // Process each bar here (e.g., print or use in calculations)
        println!("bar: {bar:?}");
    }
}
```

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

#### Non-blocking Iteration (Sync)

```rust
use std::time::Duration;

// Example of non-blocking iteration in sync mode
loop {
    match subscription.try_next() {
        Some(bar) => println!("bar: {bar:?}"),
        None => {
            // No new data yet; perform other tasks or sleep
            std::thread::sleep(Duration::from_millis(100));
        }
    }
}
```

Explore the [Subscription documentation](https://docs.rs/ibapi/latest/ibapi/struct.Subscription.html) for more details.

Since subscriptions can be converted to iterators, it is easy to iterate over multiple contracts.

```rust
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!");

    // Request real-time bars data for AAPL with 5-second intervals
    let contract_aapl = Contract::stock("AAPL").build();
    let contract_nvda = Contract::stock("NVDA").build();

    let subscription_aapl = client
        .realtime_bars(&contract_aapl, RealtimeBarSize::Sec5, RealtimeWhatToShow::Trades, TradingHours::Extended)
        .expect("realtime bars request failed!");
    let subscription_nvda = client
        .realtime_bars(&contract_nvda, RealtimeBarSize::Sec5, RealtimeWhatToShow::Trades, TradingHours::Extended)
        .expect("realtime bars request failed!");

    for (bar_aapl, bar_nvda) in subscription_aapl.iter().zip(subscription_nvda.iter()) {
        // Process each bar here (e.g., print or use in calculations)
        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](docs/order-types.md).

#### Sync Example

```rust
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();

    // Create and submit a market order to purchase 100 shares using the fluent API
    let order_id = client.order(&contract)
        .buy(100)
        .market()
        .submit()
        .expect("order submission failed!");

    println!("Order submitted with ID: {}", order_id);

    // Example of a more complex order: limit order with time in force
    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

```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!");

    let contract = Contract::stock("AAPL").build();

    // Create and submit a market order to purchase 100 shares using the fluent API
    let order_id = client.order(&contract)
        .buy(100)
        .market()
        .submit()
        .await
        .expect("order submission failed!");

    println!("Order submitted with ID: {}", order_id);

    // Example of a bracket order: entry with take profit and stop loss
    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

```rust
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!"));

    // Start background thread to monitor order updates
    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 {
            match update {
                OrderUpdate::OrderStatus(status) => {
                    println!("Order {} Status: {}", status.order_id, status.status);
                    println!("  Filled: {}, Remaining: {}", status.filled, status.remaining);
                }
                OrderUpdate::OpenOrder(data) => {
                    println!("Open Order {}: {} {}",
                             data.order_id, data.order.action, data.contract.symbol);
                }
                OrderUpdate::ExecutionData(exec) => {
                    println!("Execution: {} shares @ {}",
                             exec.execution.shares, exec.execution.price);
                }
                OrderUpdate::CommissionReport(report) => {
                    println!("Commission: ${}", report.commission);
                }
                OrderUpdate::Message(msg) => {
                    println!("Message: {}", msg.message);
                }
            }
        }
    });

    // Give monitor time to start
    thread::sleep(std::time::Duration::from_millis(100));

    // Now submit orders - updates will be received by the monitoring thread
    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);

    // Keep main thread alive to receive updates
    thread::sleep(std::time::Duration::from_secs(10));
}
```

##### Async Example

```rust
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!");

    // Create order update stream before submitting orders
    let mut order_stream = client.order_update_stream().await.expect("failed to create stream");

    // Spawn task to monitor updates
    let monitor_handle = tokio::spawn(async move {
        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);
                }
                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);
                }
                Ok(OrderUpdate::Message(msg)) => {
                    println!("Message: {}", msg.message);
                }
                Err(e) => {
                    eprintln!("Error: {:?}", e);
                    break;
                }
            }
        }
    });

    // Give monitor time to start
    tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

    // Now submit orders - updates will be received by the monitoring task
    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);

    // Wait for updates
    tokio::time::sleep(tokio::time::Duration::from_secs(10)).await;

    // Clean up
    monitor_handle.abort();
}
```

The order update stream provides real-time notifications for:
- **OrderStatus**: Status changes (Submitted, Filled, Cancelled, etc.)
- **OpenOrder**: Order details when opened or modified
- **ExecutionData**: Fill notifications with price and quantity
- **CommissionReport**: Commission charges for executions
- **Message**: System messages and notifications

## Multi-Threading

The [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).

```rust
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, RealtimeBarSize::Sec5, RealtimeWhatToShow::Trades, TradingHours::Extended)
                .expect("realtime bars request failed!");

            for bar in subscription {
                // Process each bar here (e.g., print or use in calculations)
                println!("bar: {bar:?}");
            }
        });
        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](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.

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:

```rust
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, RealtimeBarSize::Sec5, RealtimeWhatToShow::Trades, TradingHours::Extended)
                .expect("realtime bars request failed!");

            for bar in subscription {
                // Process each bar here (e.g., print or use in calculations)
                println!("bar: {bar:?}");
            }
        });
        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 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.

```rust
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();

    loop {
        // Request real-time bars data with 5-second intervals
        let subscription = client
            .realtime_bars(&contract, RealtimeBarSize::Sec5, RealtimeWhatToShow::Trades, TradingHours::Extended)
            .expect("realtime bars request failed!");

        for bar in &subscription {
            // Process each bar here (e.g., print or use in calculations)
            println!("bar: {bar:?}");
        }

        if let Some(Error::ConnectionReset) = subscription.error() {
            eprintln!("Connection reset. Retrying stream...");
            continue;
        }

        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](https://github.com/wboayue/rust-ibapi/blob/main/CONTRIBUTING.md).

For 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).