Skip to main content

ibapi/
lib.rs

1//! [![github]](https://github.com/wboayue/rust-ibapi) [![crates-io]](https://crates.io/crates/ibapi) [![license]](https://opensource.org/licenses/MIT)
2//!
3//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
4//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust
5//! [license]: https://img.shields.io/badge/License-MIT-blue.svg?style=for-the-badge&labelColor=555555
6//!
7//! <br>
8//!
9//! A comprehensive Rust implementation of the Interactive Brokers TWS API, providing a robust and
10//! user-friendly interface for TWS and IB Gateway. Designed with simplicity in mind, it integrates smoothly into trading systems.
11//!
12//! **API Documentation:**
13//! * [TWS API Reference](https://www.interactivebrokers.com/docs/tws-api/doc/introduction) - Detailed technical documentation
14//! * [IBKR Campus](https://ibkrcampus.com/ibkr-api-page/trader-workstation-api/) - IB's official learning platform
15//!
16//! This fully featured API enables the retrieval of account information, access to real-time and historical market data, order management,
17//! market scanning, and access to news and Wall Street Horizons (WSH) event data. Future updates will focus on bug fixes,
18//! maintaining parity with the official API, and enhancing usability.
19//!
20//! # Examples
21//!
22//! Connect to TWS / IB Gateway and place a market order:
23//!
24#![cfg_attr(
25    feature = "async",
26    doc = r#"```no_run
27use ibapi::prelude::*;
28
29#[tokio::main]
30async fn main() {
31    let client = Client::connect("127.0.0.1:4002", 100)
32        .await
33        .expect("connection failed");
34
35    let contract = Contract::stock("AAPL").build();
36    let order_id = client
37        .order(&contract)
38        .buy(100)
39        .market()
40        .submit()
41        .await
42        .expect("order submission failed");
43    println!("submitted order id: {order_id}");
44}
45```"#
46)]
47#![cfg_attr(
48    not(feature = "async"),
49    doc = r#"```no_run
50use ibapi::prelude::*;
51
52fn main() {
53    let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
54
55    let contract = Contract::stock("AAPL").build();
56    let order_id = client
57        .order(&contract)
58        .buy(100)
59        .market()
60        .submit()
61        .expect("order submission failed");
62    println!("submitted order id: {order_id}");
63}
64```"#
65)]
66//!
67//! For broader usage — quick start, examples, migration from v2, full API tour — see the
68//! [README](https://github.com/wboayue/rust-ibapi/blob/main/README.md) and the
69//! [`docs/`](https://github.com/wboayue/rust-ibapi/tree/main/docs) directory.
70
71#![warn(missing_docs)]
72// Allow octal-looking escapes in string literals (used in test data)
73#![allow(clippy::octal_escapes)]
74#![allow(clippy::bool_assert_comparison)]
75#![allow(clippy::useless_format)]
76#![allow(clippy::uninlined_format_args)]
77#![allow(clippy::assertions_on_constants)]
78
79// Feature guards
80#[cfg(not(any(feature = "sync", feature = "async")))]
81compile_error!(
82    "You must enable at least one of the 'sync' or 'async' features to use this crate.\n\
83     The 'async' feature is enabled by default; if you disabled default features, be sure to\n\
84     opt back into either API:\n\
85         ibapi = { version = \"4.0\", default-features = false, features = [\"sync\"] }\n\
86         ibapi = { version = \"4.0\", default-features = false, features = [\"async\"] }\n\
87     You may also enable both to access the synchronous API under `client::blocking`."
88);
89
90// The derives emit bare `utoipa::` paths, so the selected utoipa major is
91// aliased to `utoipa` at the crate root. One major at a time: adding
92// `utoipa-<N>` takes precedence over older ones, e.g. the alias below becomes
93// `#[cfg(all(feature = "utoipa-6", not(feature = "utoipa-7")))]`, and the guard
94// `not(any(feature = "utoipa-6", feature = "utoipa-7"))`.
95#[cfg(all(feature = "utoipa", not(feature = "utoipa-6")))]
96compile_error!("the `utoipa` feature is internal; enable a `utoipa-<major>` feature such as `utoipa-6`");
97
98#[cfg(feature = "utoipa-6")]
99extern crate utoipa6 as utoipa;
100
101#[macro_use]
102mod macros;
103
104/// Describes items present in an account.
105pub mod accounts;
106
107/// TWS API Client.
108///
109/// The Client establishes the connection to TWS or the Gateway.
110/// It manages the routing of messages between TWS and the application.
111pub mod client;
112
113pub(crate) mod transport;
114
115/// Connection management
116pub(crate) mod connection;
117
118/// Typed handshake-time messages delivered to [`ClientBuilder::startup_callback`].
119///
120/// When TWS emits unsolicited `OpenOrder`, `OrderStatus`, account-update, or
121/// other frames during the handshake, the startup callback receives them as
122/// typed [`StartupMessage`] values instead of having them discarded.
123///
124/// # Examples
125///
126#[cfg_attr(
127    feature = "async",
128    doc = r#"```no_run
129use ibapi::{Client, StartupMessage};
130use std::sync::{Arc, Mutex};
131
132#[tokio::main]
133async fn main() {
134    let order_ids = Arc::new(Mutex::new(Vec::new()));
135    let order_ids_clone = order_ids.clone();
136
137    let client = Client::builder()
138        .address("127.0.0.1:4002")
139        .client_id(100)
140        .startup_callback(move |msg| if let StartupMessage::OpenOrder(o) = msg {
141            order_ids_clone.lock().unwrap().push(o.order_id);
142        })
143        .connect()
144        .await
145        .expect("connection failed");
146
147    println!("Received {} startup open-orders", order_ids.lock().unwrap().len());
148    drop(client);
149}
150```"#
151)]
152#[cfg_attr(
153    not(feature = "async"),
154    doc = r#"```no_run
155use ibapi::{Client, StartupMessage};
156use std::sync::{Arc, Mutex};
157
158fn main() {
159    let order_ids = Arc::new(Mutex::new(Vec::new()));
160    let order_ids_clone = order_ids.clone();
161
162    let client = Client::builder()
163        .address("127.0.0.1:4002")
164        .client_id(100)
165        .startup_callback(move |msg| if let StartupMessage::OpenOrder(o) = msg {
166            order_ids_clone.lock().unwrap().push(o.order_id);
167        })
168        .connect()
169        .expect("connection failed");
170
171    println!("Received {} startup open-orders", order_ids.lock().unwrap().len());
172    drop(client);
173}
174```"#
175)]
176pub use connection::StartupMessage;
177
178/// Common utilities shared across modules
179pub(crate) mod common;
180
181pub use common::timezone::register_timezone_alias;
182
183/// Display groups subscription support
184pub mod display_groups;
185
186/// Subscription types for streaming data
187pub mod subscriptions;
188
189/// APIs for reading TWS/Gateway configuration (API, precautions, orders, lock-and-exit settings).
190pub mod config;
191/// A [Contract](crate::contracts::Contract) object represents trading instruments such as a stocks, futures or options.
192///
193/// Every time a new request that requires a contract (i.e. market data, order placing, etc.) is sent to the API, the system will try to match the provided contract object with a single candidate. If there is more than one contract matching the same description, the API will return an error notifying you there is an ambiguity. In these cases the API needs further information to narrow down the list of contracts matching the provided description to a single element.
194pub mod contracts;
195// Describes primary data structures used by the model.
196pub mod errors;
197/// APIs for retrieving market data
198pub mod market_data;
199pub(crate) mod messages;
200/// APIs for retrieving news data including articles, bulletins, and providers
201pub mod news;
202/// Data types for building and placing orders.
203pub mod orders;
204/// APIs for working with the market scanner.
205pub mod scanner;
206/// APIs for working with Wall Street Horizon: Earnings Calendar & Event Data.
207pub mod wsh;
208
209/// A prelude module for convenient importing of commonly used types.
210pub mod prelude;
211
212/// Protocol version checking and constants for TWS API features.
213pub mod protocol;
214
215/// Generated protobuf message types for the TWS API wire protocol.
216pub(crate) mod proto;
217
218mod server_versions;
219
220#[doc(inline)]
221pub use errors::Error;
222
223#[doc(inline)]
224pub use client::Client;
225#[doc(inline)]
226pub use client::ClientBuilder;
227
228#[doc(inline)]
229pub use transport::rate_limiter::RateLimiter;
230
231pub(crate) use messages::{encode_option_field, ToField};
232
233#[doc(inline)]
234pub use messages::{ConnectivityStatus, IncomingMessages, Notice, NoticeCategory, OutgoingMessages};
235
236#[doc(inline)]
237pub use messages::{
238    DATA_ADVISORY_CODES, HANDSHAKE_DECODE_FAILURE_CODE, HANDSHAKE_UNKNOWN_FRAME_CODE, NOTICE_STREAM_LAG_CODE, ORDER_CANCELLED_CODE,
239    ORDER_MESSAGE_CODE, ORDER_REJECTION_CODE_RANGE, REQUEST_ERROR_CODES, SUBSCRIPTION_LAG_CODE, SYSTEM_MESSAGE_CODES, TRANSPORT_RECONNECT_CODE,
240    UNKNOWN_MESSAGE_TYPE_CODE, WARNING_CODE_RANGE,
241};
242
243#[cfg(test)]
244pub(crate) mod stubs;
245
246#[cfg(test)]
247pub(crate) mod tests;
248
249#[cfg(test)]
250#[path = "lib_tests.rs"]
251mod lib_tests;
252
253#[cfg(test)]
254pub(crate) mod testdata;