pub struct Client { /* private fields */ }Expand description
TWS API Client. Manages the connection to TWS or Gateway. Tracks some global information such as server version and server time. Supports generation of order ids.
Implementations§
Source§impl Client
impl Client
Sourcepub fn server_time(&self) -> Result<OffsetDateTime, Error>
pub fn server_time(&self) -> Result<OffsetDateTime, Error>
TWS’s current time. TWS is synchronized with the server (not local computer) using NTP and this function will receive the current time in TWS.
§Errors
Error::Timeout if TWS sends no answer within 30 seconds, or within one_shot_timeout when set.
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let server_time = client.server_time().expect("error requesting server time");
println!("server time: {server_time:?}");Sourcepub fn server_time_millis(&self) -> Result<OffsetDateTime, Error>
pub fn server_time_millis(&self) -> Result<OffsetDateTime, Error>
Requests the current server time with millisecond precision.
§Errors
Error::Timeout if TWS sends no answer within 30 seconds, or within one_shot_timeout when set.
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let server_time = client.server_time_millis().expect("error requesting server time");
println!("server time to the millisecond: {server_time:?}");Sourcepub fn positions(&self) -> Result<Subscription<PositionUpdate>, Error>
pub fn positions(&self) -> Result<Subscription<PositionUpdate>, Error>
Subscribes to PositionUpdates for all accessible accounts. All positions sent initially, and then only updates as positions change.
§Examples
use ibapi::client::blocking::Client;
use ibapi::accounts::PositionUpdate;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let subscription = client.positions().expect("error requesting positions");
for position_response in subscription.iter_data() {
match position_response? {
PositionUpdate::Position(position) => println!("{position:?}"),
PositionUpdate::PositionEnd => println!("initial set of positions received"),
}
}Sourcepub fn positions_multi(
&self,
account: Option<&AccountId>,
model_code: Option<&ModelCode>,
) -> Result<Subscription<PositionUpdateMulti>, Error>
pub fn positions_multi( &self, account: Option<&AccountId>, model_code: Option<&ModelCode>, ) -> Result<Subscription<PositionUpdateMulti>, Error>
Subscribes to PositionUpdateMulti updates for account and/or model. Initially all positions are returned, and then updates are returned for any position changes in real time.
§Arguments
account- If an account Id is provided, only the account’s positions belonging to the specified model will be delivered.model_code- The code of the model’s positions we are interested in.
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
use ibapi::accounts::types::AccountId;
let account = AccountId("U1234567".to_string());
let subscription = client.positions_multi(Some(&account), None).expect("error requesting positions by model");
for position in subscription.iter_data() {
match position {
Ok(position) => println!("{position:?}"),
Err(e) => eprintln!("error: {e}"),
}
}Sourcepub fn pnl(
&self,
account: &AccountId,
model_code: Option<&ModelCode>,
) -> Result<Subscription<PnL>, Error>
pub fn pnl( &self, account: &AccountId, model_code: Option<&ModelCode>, ) -> Result<Subscription<PnL>, Error>
Creates subscription for real time daily PnL and unrealized PnL updates.
§Arguments
account- account for which to receive PnL updatesmodel_code- specify to request PnL updates for a specific model
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
use ibapi::accounts::types::AccountId;
let account = AccountId("account id".to_string());
let subscription = client.pnl(&account, None).expect("error requesting pnl");
for pnl in subscription.iter_data() {
match pnl {
Ok(pnl) => println!("{pnl:?}"),
Err(e) => eprintln!("error: {e}"),
}
}Sourcepub fn pnl_single(
&self,
account: &AccountId,
contract_id: ContractId,
model_code: Option<&ModelCode>,
) -> Result<Subscription<PnLSingle>, Error>
pub fn pnl_single( &self, account: &AccountId, contract_id: ContractId, model_code: Option<&ModelCode>, ) -> Result<Subscription<PnLSingle>, Error>
Requests real time updates for daily PnL of individual positions.
§Arguments
account- Account in which position existscontract_id- Contract ID of contract to receive daily PnL updates for. Note: does not return response if invalid conId is entered.model_code- Model in which position exists
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
use ibapi::accounts::types::{AccountId, ContractId};
let account = AccountId("<account id>".to_string());
let contract_id = ContractId(1001);
let subscription = client.pnl_single(&account, contract_id, None).expect("error requesting pnl");
for pnl in subscription.iter_data() {
match pnl {
Ok(pnl) => println!("{pnl:?}"),
Err(e) => eprintln!("error: {e}"),
}
}Sourcepub fn account_summary(
&self,
group: &AccountGroup,
tags: &[&str],
) -> Result<Subscription<AccountSummaryResult>, Error>
pub fn account_summary( &self, group: &AccountGroup, tags: &[&str], ) -> Result<Subscription<AccountSummaryResult>, Error>
Requests a specific account’s summary. Subscribes to the account summary as presented in the TWS’ Account Summary tab. Data received is specified by using a specific tags value.
§Subscription lifetime
The subscription stays open until it is dropped or cancelled. TWS first sends the requested
tags followed by AccountSummaryResult::End, then keeps pushing
AccountSummaryResult::Summary rows without another End: when values change, and
periodically, when a push can resend rows whose values did not change. Dropping the subscription cancels
the request.
§Arguments
group- Set to “All” to return account summary data for all accounts, or set to a specific Advisor Account Group name that has already been created in TWS Global Configuration.tags- List of the desired tags.
§Examples
use ibapi::client::blocking::Client;
use ibapi::accounts::AccountSummaryTags;
use ibapi::accounts::types::AccountGroup;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let group = AccountGroup("All".to_string());
let subscription = client.account_summary(&group, &[AccountSummaryTags::ACCOUNT_TYPE]).expect("error requesting account summary");
for summary in subscription.iter_data() {
match summary {
Ok(summary) => println!("{summary:?}"),
Err(e) => eprintln!("error: {e}"),
}
}Sourcepub fn account_summary_snapshots(
&self,
group: &AccountGroup,
tags: &[&str],
quiet: Duration,
) -> Result<AccountSummarySnapshots, Error>
pub fn account_summary_snapshots( &self, group: &AccountGroup, tags: &[&str], quiet: Duration, ) -> Result<AccountSummarySnapshots, Error>
Subscribe to account summary updates as complete snapshots.
Wraps account_summary and keeps the latest value of every row, so
each AccountSummarySnapshot holds the whole account rather than only the rows TWS pushed
last. TWS sends one End marker after the initial snapshot and none after the rows it pushes
later, so the first snapshot is emitted at the first End, even when empty, and each later
one once no row has arrived for quiet. Pushes arrive when values change and periodically
(IB documents every three minutes), and a push can resend unchanged rows. A later snapshot is
emitted only when a row changed a value since the previous one. Choose quiet longer than
the gap between the rows of one push, which arrive within milliseconds of each other.
To fold the rows with your own batching instead, use AccountSummarySnapshot::apply.
Notices that arrive on the subscription are logged at warn!. For other streams that dump
then push, batch with Subscription::next_batch.
Dropping the returned iterator cancels the subscription.
§Arguments
group- Set to “All” to return account summary data for all accounts, or set to a specific Advisor Account Group name that has already been created in TWS Global Configuration.tags- List of the desired tags.quiet- How long without a row completes a pushed update.
§Examples
use ibapi::client::blocking::Client;
use ibapi::accounts::AccountSummaryTags;
use ibapi::accounts::types::AccountGroup;
use std::time::Duration;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let group = AccountGroup("All".to_string());
let tags = &[AccountSummaryTags::NET_LIQUIDATION];
let snapshots = client
.account_summary_snapshots(&group, tags, Duration::from_secs(1))
.expect("error requesting account summary");
for snapshot in snapshots {
let snapshot = snapshot.expect("account summary error");
println!("{} rows", snapshot.len());
}Sourcepub fn account_updates(
&self,
account: &AccountId,
) -> Result<Subscription<AccountUpdate>, Error>
pub fn account_updates( &self, account: &AccountId, ) -> Result<Subscription<AccountUpdate>, Error>
Subscribes to a specific account’s information and portfolio.
All account values and positions will be returned initially, and then there will only be updates when there is a change in a position, or to an account value every 3 minutes if it has changed.
TWS streams one account at a time per connection. Subscribing to the same
account again shares the stream; another account is refused until every
subscription to the first has been cancelled or dropped. To stream several
accounts at once, use account_updates_multi.
§Arguments
account- The account id (i.e. U1234567) for which the information is requested.
§Errors
Error::AccountUpdatesInUse while another account’s updates are live.
§Examples
use ibapi::client::blocking::Client;
use ibapi::accounts::AccountUpdate;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
use ibapi::accounts::types::AccountId;
let account = AccountId("U1234567".to_string());
let subscription = client.account_updates(&account).expect("error requesting account updates");
for update in subscription.iter_data() {
let update = update?;
println!("{update:?}");
// stop after full initial update
if let AccountUpdate::End = update {
subscription.cancel();
}
}Sourcepub fn account_updates_multi(
&self,
account: Option<&AccountId>,
model_code: Option<&ModelCode>,
) -> Result<Subscription<AccountUpdateMulti>, Error>
pub fn account_updates_multi( &self, account: Option<&AccountId>, model_code: Option<&ModelCode>, ) -> Result<Subscription<AccountUpdateMulti>, Error>
Requests account updates for account and/or model.
All account values and positions will be returned initially, and then there will only be updates when there is a change in a position, or to an account value every 3 minutes if it has changed. Each subscription is routed by its own request id, so several accounts or models can stream at once.
§Arguments
account- Account values can be requested for a particular account.model_code- Account values can also be requested for a model.
§Examples
use ibapi::client::blocking::Client;
use ibapi::accounts::AccountUpdateMulti;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
use ibapi::accounts::types::AccountId;
let account = AccountId("U1234567".to_string());
let subscription = client.account_updates_multi(Some(&account), None).expect("error requesting account updates multi");
for update in subscription.iter_data() {
let update = update?;
println!("{update:?}");
// stop after full initial update
if let AccountUpdateMulti::End = update {
subscription.cancel();
}
}Sourcepub fn managed_accounts(&self) -> Result<Vec<String>, Error>
pub fn managed_accounts(&self) -> Result<Vec<String>, Error>
Fetch the list of accounts accessible to the current user.
For the list TWS sent at connect, with no round trip, see
handshake_managed_accounts.
§Errors
Error::Timeout if TWS sends no answer within 30 seconds, or within one_shot_timeout when set.
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let accounts = client.managed_accounts().expect("error requesting managed accounts");
println!("managed accounts: {accounts:?}")Sourcepub fn family_codes(&self) -> Result<Vec<FamilyCode>, Error>
pub fn family_codes(&self) -> Result<Vec<FamilyCode>, Error>
Get current FamilyCodes for all accessible accounts.
§Errors
Error::Timeout if TWS sends no answer within 30 seconds, or within one_shot_timeout when set.
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let codes = client.family_codes().expect("error requesting family codes");
println!("family codes: {codes:?}")Sourcepub fn soft_dollar_tiers(&self) -> Result<Vec<SoftDollarTier>, Error>
pub fn soft_dollar_tiers(&self) -> Result<Vec<SoftDollarTier>, Error>
Request the configured soft dollar tiers available to the account.
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let tiers = client.soft_dollar_tiers().expect("request failed");
for tier in &tiers {
println!("{}: {}", tier.name, tier.display_name);
}Sourcepub fn user_info(&self) -> Result<UserInfo, Error>
pub fn user_info(&self) -> Result<UserInfo, Error>
Request white-branding identity information for the logged-in user.
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let info = client.user_info().expect("request failed");
println!("white branding id: {}", info.white_branding_id);Sourcepub fn request_fa(&self, fa_data_type: FaDataType) -> Result<FaConfig, Error>
pub fn request_fa(&self, fa_data_type: FaDataType) -> Result<FaConfig, Error>
Request the current Financial Advisor configuration as an XML string.
§Arguments
fa_data_type- which FA dataset to fetch.
§Errors
Error::Timeout if TWS sends no answer within 30 seconds, or within one_shot_timeout when set.
§Examples
use ibapi::client::blocking::Client;
use ibapi::accounts::FaDataType;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let cfg = client.request_fa(FaDataType::Groups).expect("request failed");
println!("{}", cfg.xml);Sourcepub fn replace_fa(
&self,
fa_data_type: FaDataType,
xml: &str,
) -> Result<ReplaceFaResult, Error>
pub fn replace_fa( &self, fa_data_type: FaDataType, xml: &str, ) -> Result<ReplaceFaResult, Error>
Replace the Financial Advisor configuration on the server.
§Arguments
fa_data_type- which FA dataset to replace.xml- the replacement configuration as an XML string.
§Examples
use ibapi::client::blocking::Client;
use ibapi::accounts::FaDataType;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let result = client.replace_fa(FaDataType::Groups, "<xml/>").expect("request failed");
println!("{}", result.text);Sourcepub fn set_server_log_level(
&self,
log_level: ServerLogLevel,
) -> Result<(), Error>
pub fn set_server_log_level( &self, log_level: ServerLogLevel, ) -> Result<(), Error>
Set the verbosity level for server-side TWS API diagnostics.
§Examples
use ibapi::client::blocking::Client;
use ibapi::accounts::ServerLogLevel;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
client.set_server_log_level(ServerLogLevel::Detail).expect("request failed");Sourcepub fn verify_request(
&self,
api_name: &str,
api_version: &str,
) -> Result<VerificationChallenge, Error>
pub fn verify_request( &self, api_name: &str, api_version: &str, ) -> Result<VerificationChallenge, Error>
Initiate a TWS extension verification handshake.
Most users will not call this directly; it is part of the IB Linking flow.
§Errors
Error::Timeout if TWS sends no answer within 30 seconds, or within one_shot_timeout when set.
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let challenge = client.verify_request("MyApp", "1.0").expect("request failed");
println!("{}", challenge.api_data);Sourcepub fn verify_message(
&self,
api_data: &str,
) -> Result<VerificationResult, Error>
pub fn verify_message( &self, api_data: &str, ) -> Result<VerificationResult, Error>
Continue a TWS extension verification handshake by sending the API response data.
§Errors
Error::Timeout if TWS sends no answer within 30 seconds, or within one_shot_timeout when set.
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let result = client.verify_message("signed-challenge").expect("request failed");
if result.is_successful {
println!("verified");
} else {
eprintln!("{}", result.error_text);
}Source§impl Client
impl Client
Sourcepub fn connect(address: &str, client_id: i32) -> Result<Client, Error>
pub fn connect(address: &str, client_id: i32) -> Result<Client, Error>
Establishes a connection to TWS or Gateway with no extra configuration.
One-liner shortcut equivalent to
Client::builder().address(address).client_id(client_id).connect(). For
tcp_no_delay, startup callbacks, or a pre-bound NoticeStream, use
Client::builder instead.
§Arguments
address- address of server. e.g. 127.0.0.1:4002client_id- id of client. e.g. 100
§Errors
Error::ClientIdInUse when another connection holds client_id;
connect with a different id. Not retried here.
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
println!("server_version: {}", client.server_version());
println!("connection_time: {:?}", client.connection_time());
println!("next_order_id: {}", client.next_order_id());Sourcepub fn builder() -> ClientBuilder
pub fn builder() -> ClientBuilder
Begin a fluent connection builder.
See ClientBuilder for the configurators (address, client_id,
tcp_no_delay, startup_callback) and the two terminals
(connect, connect_with_notice_stream).
§Examples
use ibapi::client::blocking::Client;
let client = Client::builder()
.address("127.0.0.1:4002")
.client_id(100)
.tcp_no_delay(true)
.connect()
.expect("connection failed");
drop(client);Sourcepub fn next_order_id(&self) -> i32
pub fn next_order_id(&self) -> i32
Returns and increments the order ID.
The client maintains a sequence of order IDs. This function returns the next order ID in the sequence.
Sourcepub fn server_version(&self) -> i32
pub fn server_version(&self) -> i32
Returns the version of the TWS API server to which the client is connected, as negotiated in the connection handshake. Updated when the client reconnects, since the gateway may come back on a different build.
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let server_version = client.server_version();
println!("Connected to TWS server version: {server_version:?}");Sourcepub fn connection_time(&self) -> Option<OffsetDateTime>
pub fn connection_time(&self) -> Option<OffsetDateTime>
Returns the gateway’s clock reading when the client connected, or
None if the zone is unrecognized (see time_zone)
or the reading is malformed.
From the initial connection; a reconnect doesn’t update it.
Sourcepub fn time_zone(&self) -> Option<&'static Tz>
pub fn time_zone(&self) -> Option<&'static Tz>
Returns the time zone of the gateway host, from the connection handshake.
Informational: the crate does not convert any data with it. None if
the gateway sent a name that no alias or IANA zone matches (logged as a
warning at connect). Map such a name with
register_timezone_alias. See
Gateway Time Zone.
From the initial connection; a reconnect doesn’t update it.
Sourcepub fn handshake_managed_accounts(&self) -> &[String]
pub fn handshake_managed_accounts(&self) -> &[String]
Returns the accounts TWS sent when the client connected, with no round trip. Empty if TWS sent none.
From the initial connection; a reconnect doesn’t update it. For the
current list, call managed_accounts.
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
for account in client.handshake_managed_accounts() {
println!("account: {account}");
}Sourcepub fn is_connected(&self) -> bool
pub fn is_connected(&self) -> bool
Returns true if the client is currently connected to TWS/IB Gateway.
This method checks if the underlying connection to TWS or IB Gateway is active. Returns false if the connection has been lost, shut down, or reset.
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
if client.is_connected() {
println!("Client is connected to TWS/Gateway");
} else {
println!("Client is not connected");
}Sourcepub fn wait_connected(&self) -> Result<(), Error>
pub fn wait_connected(&self) -> Result<(), Error>
Blocks until the client is connected to TWS/IB Gateway again, so a
stream loop can resubscribe after Error::is_connection_lost.
Returns Ok(()) at once while connected. While the client is
reconnecting it blocks until the reconnect finishes, which with
ClientBuilder::reconnect_forever may be never.
§Errors
Error::ConnectionFailedif the reconnect gave up after its last attempt.Error::Shutdownif the client was shut down.
Both are terminal: every later request fails with the same error.
§Examples
use ibapi::client::blocking::Client;
use ibapi::prelude::*;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("AAPL").build();
loop {
let subscription = match client.realtime_bars(&contract).subscribe() {
Ok(subscription) => subscription,
Err(e) if e.is_connection_lost() => {
client.wait_connected().expect("reconnect gave up");
continue;
}
Err(e) => panic!("request failed: {e}"),
};
// ... read until a connection-lost error, wait_connected, loop
}Sourcepub fn resubscribing<T, F>(&self, open: F) -> Resubscribing<'_, T, F> ⓘ
pub fn resubscribing<T, F>(&self, open: F) -> Resubscribing<'_, T, F> ⓘ
Streams items from the subscription open returns, resubscribing after
each transport reconnect: the packaged form of the
Error::is_connection_lost → wait_connected → resubscribe loop.
Yields the same Result<SubscriptionItem<T>, Error> items as the subscription. When the
connection drops, it drops the dead subscription, waits for the reconnect, calls open
again, and yields a SubscriptionItem::Notice
with code TRANSPORT_RECONNECT_CODE before
the new subscription’s first item. Data from the outage is missing. A first open that
fails with a lost connection is retried too, without a notice.
It ends after yielding any other error, the error wait_connected returns when the
reconnect gave up, or when the subscription itself ends (a snapshot that finished).
filter_data drops notices, gap included; match the
items to see it.
T must be Resubscribable: order streams are not,
so a resubscribe can’t place or cancel again. After a resubscribe the caller sees:
| Stream | After the gap notice |
|---|---|
| market data, realtime bars, tick-by-tick, news bulletins | new data only |
| market depth | the book rebuilt from scratch: reset yours on the notice |
historical bars with keep_up_to_date | the initial bars again (duplicates) |
| account, position, PnL, account summary | the initial snapshot again |
| scanner | a fresh scan |
§Examples
use ibapi::client::blocking::Client;
use ibapi::TRANSPORT_RECONNECT_CODE;
use ibapi::prelude::*;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("AAPL").build();
for item in client.resubscribing(|| client.realtime_bars(&contract).subscribe()) {
match item {
Ok(SubscriptionItem::Data(bar)) => println!("{bar:?}"),
Ok(SubscriptionItem::Notice(n)) if n.code == TRANSPORT_RECONNECT_CODE => println!("gap: {n}"),
Ok(SubscriptionItem::Notice(n)) => println!("notice: {n}"),
Err(e) => panic!("stream ended: {e}"),
}
}Order streams don’t compile:
use ibapi::client::blocking::Client;
use ibapi::contracts::Contract;
use ibapi::orders::Order;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let (contract, order) = (Contract::stock("AAPL").build(), Order::default());
let _ = client.resubscribing(|| client.place_order(1, &contract, &order));Sourcepub fn disconnect(&self)
pub fn disconnect(&self)
Cleanly shuts down the message bus.
All outstanding Subscriptions see their channels
close and their next() calls return None. Background worker threads are joined
before this returns.
Call this before dropping the final Arc<Client> if any spawned
threads hold that Arc — otherwise Drop never runs and those
threads block forever in subscription.next().
Safe to call multiple times.
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
// ... use client, spawn threads holding Arc<Client> ...
client.disconnect();Sourcepub fn notice_stream(&self) -> Result<NoticeStream, Error>
pub fn notice_stream(&self) -> Result<NoticeStream, Error>
Subscribe to globally routed IB notices (notices with no request_id —
connectivity codes 1100/1101/1102, farm-status 2104/2105/2106/2107/2108,
and any other unrouted error/warning).
Each call returns a fresh, independent NoticeStream;
late subscribers do not see prior notices. The stream ends when the client shuts
down; one created after shutdown is already ended.
Per-subscription notices (codes carrying a real request_id) are not
delivered here — they reach their owning subscription as
SubscriptionItem::Notice
(see Subscription::next).
§Note on handshake-time notices
Notices emitted during the connection handshake — the typical
2104/2106/2158 farm-status burst that arrives before connect returns —
will not be observed by a NoticeStream created afterwards. Use
ClientBuilder::connect_with_notice_stream
to capture those (the pre-bound stream covers handshake AND post-connect
notices, and survives auto-reconnects).
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let stream = client.notice_stream().expect("notice subscription failed");
for notice in stream.iter() {
if notice.is_system_message() {
println!("connectivity: {notice}");
} else if notice.is_informational() {
println!("info: {notice}");
} else {
eprintln!("error: {notice}");
}
}Source§impl Client
impl Client
Sourcepub fn display_groups(&self) -> Result<Vec<i32>, Error>
pub fn display_groups(&self) -> Result<Vec<i32>, Error>
Returns the ids of the display groups visible in TWS, most used first.
Display Groups are a TWS-only feature (not available in IB Gateway).
Pass an id to subscribe_to_group_events.
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:7497", 100)?;
let groups = client.display_groups()?;
println!("visible display groups: {groups:?}");Sourcepub fn subscribe_to_group_events(
&self,
group_id: i32,
) -> Result<DisplayGroupSubscription, Error>
pub fn subscribe_to_group_events( &self, group_id: i32, ) -> Result<DisplayGroupSubscription, Error>
Subscribes to display group events for the specified group.
Display Groups are a TWS-only feature (not available in IB Gateway). They allow organizing contracts into color-coded groups in the TWS UI. When subscribed, you receive updates whenever the user changes the contract displayed in that group within TWS.
§Arguments
group_id- The ID of the group to subscribe to (1-9)
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:7497", 100).expect("connection failed");
let subscription = client.subscribe_to_group_events(1).expect("subscription failed");
// Update the displayed contract
subscription.update("265598@SMART").expect("update failed");
for event in subscription.iter_data() {
match event {
Ok(event) => println!("group event: {:?}", event),
Err(e) => eprintln!("error: {e}"),
}
}Source§impl Client
impl Client
Sourcepub fn config(&self) -> Result<Config, Error>
pub fn config(&self) -> Result<Config, Error>
Reads the TWS/Gateway configuration (API, precautions, orders, and lock-and-exit settings) the gateway is currently running with.
This is a read-only snapshot; fields the gateway does not report are
left as None.
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let config = client.config().expect("request config failed");
println!("{config:?}");Sourcepub fn update_config(&self) -> UpdateConfigBuilder<'_, Client>
pub fn update_config(&self) -> UpdateConfigBuilder<'_, Client>
Begins a fluent UpdateConfigBuilder to edit the TWS/Gateway
configuration. Set only the groups you want to change and terminate with
submit.
§Examples
use ibapi::client::blocking::Client;
use ibapi::config::{OrdersConfig, OrdersSmartRouting};
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let response = client
.update_config()
.orders(OrdersConfig {
smart_routing: Some(OrdersSmartRouting {
seek_price_improvement: Some(true),
..Default::default()
}),
})
.submit()
.expect("update config failed");
println!("{response:?}");Source§impl Client
impl Client
Sourcepub fn contract_details(
&self,
contract: &Contract,
) -> Result<Vec<ContractDetails>, Error>
pub fn contract_details( &self, contract: &Contract, ) -> Result<Vec<ContractDetails>, Error>
Requests contract information.
Provides all the contracts matching the contract provided. It can also be used to retrieve complete options and futures chains. Though it is now (in API version > 9.72.12) advised to use Client::option_chain for that purpose.
Collects every row before returning. To read rows as they arrive, stop reading early, or know the request id up front, use Client::contract_details_stream.
Waits for TWS’s end marker with no time bound. For a bound, use
contract_details_stream and
collect_to_end_within.
§Arguments
contract- The Contract used as sample to query the available contracts. Typically, it will contain the Contract’s symbol, currency, security_type, and exchange.
§Examples
use ibapi::client::blocking::Client;
use ibapi::contracts::Contract;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("TSLA").build();
let results = client.contract_details(&contract).expect("request failed");
for contract_detail in results {
println!("contract: {contract_detail:?}");
}Sourcepub fn contract_details_stream<'a>(
&'a self,
contract: &'a Contract,
) -> ContractDetailsBuilder<'a, Self>
pub fn contract_details_stream<'a>( &'a self, contract: &'a Contract, ) -> ContractDetailsBuilder<'a, Self>
Build a contract-details request whose subscription yields one ContractDetails per matching contract.
Use this over Client::contract_details to read rows as they arrive,
stop reading early, or know the request id before anything is sent.
Dropping the subscription before the end sends TWS’s native cancel
(server 215+); rows TWS sends after that are discarded.
collect_to_end_within
collects the whole result within a time bound.
Terminal: ContractDetailsBuilder::subscribe.
§Arguments
contract- The Contract used as sample to query the available contracts.
§Examples
use ibapi::client::blocking::Client;
use ibapi::contracts::Contract;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("AAPL").build();
let request = client.contract_details_stream(&contract);
let request_id = request.request_id(); // known before anything is sent
let subscription = request.subscribe().expect("request failed");
for details in subscription.iter_data().take(5) {
match details {
Ok(details) => println!("[{request_id}] {} on {}", details.contract.symbol, details.contract.exchange),
Err(e) => {
eprintln!("error: {e}");
break;
}
}
}Sourcepub fn cancel_contract_details(&self, request_id: i32) -> Result<(), Error>
pub fn cancel_contract_details(&self, request_id: i32) -> Result<(), Error>
Cancels an in-flight contract details request.
§Arguments
request_id- The id of the request to cancel, e.g. from ContractDetailsBuilder::request_id. Dropping a Client::contract_details_stream subscription already cancels it.
§Examples
use ibapi::client::blocking::Client;
use ibapi::contracts::Contract;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("AAPL").build();
let builder = client.contract_details_stream(&contract);
let request_id = builder.request_id();
let _subscription = builder.subscribe().expect("request failed");
// Cancelling a request that has already completed is harmless.
client.cancel_contract_details(request_id).expect("cancel failed");Sourcepub fn market_rule(&self, market_rule_id: i32) -> Result<MarketRule, Error>
pub fn market_rule(&self, market_rule_id: i32) -> Result<MarketRule, Error>
Requests details about a given market rule
The market rule for an instrument on a particular exchange provides details about how the minimum price increment changes with price.
A list of market rule ids can be obtained by invoking Self::contract_details() for a particular contract.
The returned market rule ID list will provide the market rule ID for the instrument in the correspond valid exchange list in crate::contracts::ContractDetails.
§Errors
Error::Timeout if TWS sends no answer within 30 seconds, or within one_shot_timeout when set.
§Examples
use ibapi::client::blocking::Client;
use ibapi::contracts::Contract;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
// Market rule ids come from a contract's details.
let details = client.contract_details(&Contract::stock("AAPL").build()).expect("request failed");
let rule_id: i32 = details[0]
.market_rule_ids
.first()
.and_then(|id| id.parse().ok())
.expect("contract has no market rule ids");
let rule = client.market_rule(rule_id).expect("market rule request failed");
for increment in &rule.price_increments {
println!("above {}: increment {}", increment.low_edge, increment.increment);
}Sourcepub fn smart_components(
&self,
bbo_exchange: &str,
) -> Result<Vec<SmartComponent>, Error>
pub fn smart_components( &self, bbo_exchange: &str, ) -> Result<Vec<SmartComponent>, Error>
Requests the underlying exchanges that contribute to a consolidated (BBO) feed.
Given a BBO exchange code (an opaque per-session token, e.g. "a6"),
returns the list of underlying exchanges with each entry’s bit
position, full exchange name, and single-letter abbreviation. Useful
for decoding the mdSize / mdMask bitmaps on tick-by-tick and
market-depth streams. The token is typically obtained from the
LAST_EXCHANGE market-data tick (tick type 84).
§Arguments
bbo_exchange- The BBO exchange token (e.g."a6").
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let components = client.smart_components("a6").expect("request failed");
for component in &components {
println!("bit {}: {} ({})", component.bit_number, component.exchange, component.exchange_letter);
}Sourcepub fn matching_symbols(
&self,
pattern: &str,
) -> Result<Vec<ContractDescription>, Error>
pub fn matching_symbols( &self, pattern: &str, ) -> Result<Vec<ContractDescription>, Error>
Requests matching stock symbols.
§Arguments
pattern- Either start of ticker symbol or (for larger strings) company name.
§Retries
If the connection resets mid-request, this waits for the reconnect and sends the request again with a fresh request id, up to 3 times (4 attempts in all). Other errors are not retried. A caller pacing requests against TWS limits should count each reconnect (see the notice stream) as a possible extra request.
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contracts = client.matching_symbols("IB").expect("request failed");
for contract in contracts {
println!("contract: {contract:?}");
}Sourcepub fn calculate_option_price(
&self,
contract: &Contract,
volatility: f64,
underlying_price: f64,
) -> Result<OptionComputation, Error>
pub fn calculate_option_price( &self, contract: &Contract, volatility: f64, underlying_price: f64, ) -> Result<OptionComputation, Error>
Calculates an option’s price based on the provided volatility and its underlying’s price.
§Arguments
contract- The Contract object representing the option for which the calculation is being requested.volatility- Hypothetical annualized volatility as a fraction (0.2= 20%).underlying_price- Hypothetical price of the underlying asset.
§Examples
use ibapi::client::blocking::Client;
use ibapi::contracts::{Contract, OptionRight};
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::option("AAPL", "20251219", 150.0, OptionRight::Call);
let calculation = client.calculate_option_price(&contract, 0.2, 235.0).expect("request failed");
println!("calculation: {calculation:?}");Sourcepub fn calculate_implied_volatility(
&self,
contract: &Contract,
option_price: f64,
underlying_price: f64,
) -> Result<OptionComputation, Error>
pub fn calculate_implied_volatility( &self, contract: &Contract, option_price: f64, underlying_price: f64, ) -> Result<OptionComputation, Error>
Calculates the implied volatility based on the hypothetical option price and underlying price.
§Arguments
contract- The Contract object representing the option for which the calculation is being requested.option_price- Hypothetical option price.underlying_price- Hypothetical price of the underlying asset.
§Examples
use ibapi::client::blocking::Client;
use ibapi::contracts::{Contract, OptionRight};
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::option("AAPL", "20230519", 150.0, OptionRight::Call);
let calculation = client.calculate_implied_volatility(&contract, 25.0, 235.0).expect("request failed");
println!("calculation: {calculation:?}");Sourcepub fn option_chain<'a>(
&'a self,
symbol: &'a str,
security_type: SecurityType,
contract_id: i32,
) -> OptionChainBuilder<'a, Self>
pub fn option_chain<'a>( &'a self, symbol: &'a str, security_type: SecurityType, contract_id: i32, ) -> OptionChainBuilder<'a, Self>
Build a request for an underlying’s option chain: one OptionChain per
exchange the options trade on.
Terminal: OptionChainBuilder::subscribe. Optional narrowing via OptionChainBuilder::exchange.
§Arguments
symbol- Symbol of the underlying.security_type- Security type of the underlying, e.g.SecurityType::Stock.contract_id- Contract id of the underlying. Required; TWS rejects0with code 321 “Invalid contract id”.
§Examples
use ibapi::client::blocking::Client;
use ibapi::contracts::SecurityType;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let subscription = client
.option_chain("AAPL", SecurityType::Stock, 265598)
.subscribe()
.expect("request option chain failed");
for chain in subscription.iter_data() {
let chain = chain.expect("decode error");
println!("{}: {} expirations, {} strikes", chain.exchange, chain.expirations.len(), chain.strikes.len());
}Source§impl Client
impl Client
Sourcepub fn head_timestamp(
&self,
contract: &Contract,
what_to_show: WhatToShow,
trading_hours: TradingHours,
) -> Result<OffsetDateTime, Error>
pub fn head_timestamp( &self, contract: &Contract, what_to_show: WhatToShow, trading_hours: TradingHours, ) -> Result<OffsetDateTime, Error>
Returns the timestamp of earliest available historical data for a contract and data type.
§Examples
use ibapi::client::blocking::Client;
use ibapi::contracts::Contract;
use ibapi::market_data::historical::{self, WhatToShow};
use ibapi::market_data::TradingHours;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("MSFT").build();
let what_to_show = WhatToShow::Trades;
let trading_hours = TradingHours::Regular;
let result = client.head_timestamp(&contract, what_to_show, trading_hours).expect("head timestamp failed");
print!("head_timestamp: {result:?}");Sourcepub fn historical_data<'a>(
&'a self,
contract: &'a Contract,
bar_size: BarSize,
) -> HistoricalDataBuilder<'a, Self>
pub fn historical_data<'a>( &'a self, contract: &'a Contract, bar_size: BarSize, ) -> HistoricalDataBuilder<'a, Self>
Build a request for historical bar data.
Required: a date spec via either HistoricalDataBuilder::duration
(with optional HistoricalDataBuilder::ending) or
HistoricalDataBuilder::between. Terminals:
HistoricalDataBuilder::fetch for a one-shot
HistoricalData result; HistoricalDataBuilder::stream
for a Subscription<HistoricalBarUpdate> that yields bars as they arrive.
§Arguments
contract- Contract object that is subject of querybar_size- Bar size (resolution)
§Examples
use ibapi::client::blocking::Client;
use ibapi::contracts::Contract;
use ibapi::market_data::historical::{BarSize, ToDuration, WhatToShow};
use time::macros::datetime;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("AAPL").build();
// IBKR-native: amount of data ending at a specific time (or now if `.ending` is unset)
let bars = client
.historical_data(&contract, BarSize::Hour)
.what_to_show(WhatToShow::Trades)
.duration(7.days())
.fetch()
.expect("historical data request failed");
// Convenience: explicit date range; bars outside it are dropped
let bars = client
.historical_data(&contract, BarSize::Hour)
.between(datetime!(2023-04-08 0:00 UTC), datetime!(2023-04-15 0:00 UTC))
.fetch()
.expect("historical data request failed");Sourcepub fn historical_schedules<'a>(
&'a self,
contract: &'a Contract,
duration: Duration,
) -> HistoricalScheduleBuilder<'a, Self>
pub fn historical_schedules<'a>( &'a self, contract: &'a Contract, duration: Duration, ) -> HistoricalScheduleBuilder<'a, Self>
Build a request for Schedule data over the given duration.
Defaults to anchoring at the current time. Use HistoricalScheduleBuilder::ending
to anchor at a specific end date.
§Arguments
§Examples
use time::macros::datetime;
use ibapi::client::blocking::Client;
use ibapi::contracts::Contract;
use ibapi::market_data::historical::ToDuration;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("GM").build();
// Ending now:
let schedule = client
.historical_schedules(&contract, 30.days())
.fetch()
.expect("historical schedule request failed");
// Anchored to a specific end date:
let schedule = client
.historical_schedules(&contract, 30.days())
.ending(datetime!(2023-04-15 0:00 UTC))
.fetch()
.expect("historical schedule request failed");
for session in &schedule.sessions {
println!("{session:?}");
}Sourcepub fn historical_ticks<'a>(
&'a self,
contract: &'a Contract,
number_of_ticks: i32,
) -> HistoricalTicksBuilder<'a, Self>
pub fn historical_ticks<'a>( &'a self, contract: &'a Contract, number_of_ticks: i32, ) -> HistoricalTicksBuilder<'a, Self>
Build a request for historical time & sales data (tick-by-tick).
The terminal method selects the tick type:
HistoricalTicksBuilder::trade /
.mid_point() / .bid_ask(IgnoreSize). Use
HistoricalTicksBuilder::starting /
.ending() to anchor the query (at least one is required per IBKR).
§Arguments
contract- Contract object that is subject of querynumber_of_ticks- Number of distinct data points. Max currently 1000 per request.
§Examples
use ibapi::client::blocking::Client;
use ibapi::contracts::Contract;
use ibapi::market_data::IgnoreSize;
use ibapi::market_data::TradingHours;
use time::macros::datetime;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("TSLA").build();
// Trade ticks anchored at a start date:
let trades = client
.historical_ticks(&contract, 100)
.starting(datetime!(2023-04-15 0:00 UTC))
.trading_hours(TradingHours::Regular)
.trade()
.expect("historical ticks request failed");
// Bid/ask ticks anchored at an end date, ignoring tick sizes:
let quotes = client
.historical_ticks(&contract, 100)
.ending(datetime!(2023-04-15 0:00 UTC))
.bid_ask(IgnoreSize::Yes)
.expect("historical ticks request failed");
for tick in trades {
println!("{tick:?}");
}Sourcepub fn cancel_historical_ticks(&self, request_id: i32) -> Result<(), Error>
pub fn cancel_historical_ticks(&self, request_id: i32) -> Result<(), Error>
Cancels an in-flight historical ticks request.
§Arguments
request_id- The request ID of the historical ticks subscription to cancel.
§Examples
use ibapi::client::blocking::Client;
use ibapi::contracts::Contract;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("MSFT").build();
let subscription = client.historical_ticks(&contract, 100).trade().expect("request failed");
// Holding the subscription, `subscription.cancel()` (or dropping it) does the same.
client.cancel_historical_ticks(subscription.request_id()).expect("cancel failed");Sourcepub fn histogram_data(
&self,
contract: &Contract,
trading_hours: TradingHours,
period: BarSize,
) -> Result<Vec<HistogramEntry>, Error>
pub fn histogram_data( &self, contract: &Contract, trading_hours: TradingHours, period: BarSize, ) -> Result<Vec<HistogramEntry>, Error>
Requests data histogram of specified contract.
§Arguments
contract- Contract to retrieve Histogram Entries for.trading_hours- Regular trading hours only, or include extended hours.period- The time period of each histogram bar (e.g.,BarSize::Day,BarSize::Week,BarSize::Month).
§Examples
use time::macros::datetime;
use ibapi::contracts::Contract;
use ibapi::client::blocking::Client;
use ibapi::market_data::historical::BarSize;
use ibapi::market_data::TradingHours;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("GM").build();
let histogram = client
.histogram_data(&contract, TradingHours::Regular, BarSize::Week)
.expect("histogram request failed");
for item in &histogram {
println!("{item:?}");
}Source§impl Client
impl Client
Sourcepub fn market_data<'a>(
&'a self,
contract: &'a Contract,
) -> MarketDataBuilder<'a, Self>
pub fn market_data<'a>( &'a self, contract: &'a Contract, ) -> MarketDataBuilder<'a, Self>
Returns a builder for a streaming level-1 market data subscription.
Streams by default; .snapshot() switches to a one-shot request. See
MarketDataBuilder for the chained methods.
§Examples
use ibapi::client::blocking::Client;
use ibapi::contracts::Contract;
use ibapi::market_data::realtime::TickTypes;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("AAPL").build();
// Subscribe to real-time streaming data with specific tick types
let subscription = client.market_data(&contract)
.generic_ticks(&["233", "236"]) // RTVolume and Shortable
.subscribe()
.expect("subscription failed");
for tick in subscription.iter_data() {
match tick? {
TickTypes::Price(price) => println!("Price: {price:?}"),
TickTypes::Size(size) => println!("Size: {size:?}"),
_ => {}
}
}A one-shot snapshot, driven manually. To just collect the ticks and stop, prefer
MarketDataBuilder::snapshot_once, which wraps this loop with a timeout.
use ibapi::client::blocking::Client;
use ibapi::contracts::Contract;
use ibapi::market_data::realtime::TickTypes;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("AAPL").build();
let subscription = client.market_data(&contract)
.snapshot()
.subscribe()
.expect("subscription failed");
for tick in subscription.iter_data() {
if let TickTypes::SnapshotEnd = tick? {
println!("Snapshot complete");
break;
}
}Sourcepub fn realtime_bars<'a>(
&'a self,
contract: &'a Contract,
) -> RealtimeBarsBuilder<'a, Self>
pub fn realtime_bars<'a>( &'a self, contract: &'a Contract, ) -> RealtimeBarsBuilder<'a, Self>
Returns a builder for a real-time 5-second bar subscription.
Defaults to WhatToShow::Trades and TradingHours::Regular. See
RealtimeBarsBuilder for the chained methods.
§Examples
use ibapi::client::blocking::Client;
use ibapi::contracts::Contract;
use ibapi::market_data::realtime::WhatToShow;
use ibapi::market_data::TradingHours;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("TSLA").build();
let subscription = client
.realtime_bars(&contract)
.what_to_show(WhatToShow::Trades)
.trading_hours(TradingHours::Extended)
.subscribe()
.expect("realtime bars request failed");
for (i, bar) in subscription.iter_data().enumerate().take(60) {
match bar {
Ok(bar) => println!("bar[{i}]: {bar:?}"),
Err(e) => { eprintln!("error: {e:?}"); break; }
}
}Sourcepub fn tick_by_tick<'a>(
&'a self,
contract: &'a Contract,
number_of_ticks: i32,
) -> TickByTickBuilder<'a, Self>
pub fn tick_by_tick<'a>( &'a self, contract: &'a Contract, number_of_ticks: i32, ) -> TickByTickBuilder<'a, Self>
Returns a builder for a tick-by-tick real-time subscription.
Pick the tick stream with the terminal — .last() / .all_last() /
.bid_ask(IgnoreSize) / .mid_point(). See TickByTickBuilder.
§Examples
use ibapi::client::blocking::Client;
use ibapi::contracts::Contract;
use ibapi::market_data::IgnoreSize;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("AAPL").build();
let quotes = client
.tick_by_tick(&contract, 10)
.bid_ask(IgnoreSize::No)
.expect("tick-by-tick bid/ask request failed");
for quote in quotes.iter_data().take(10) {
match quote {
Ok(quote) => println!("{quote:?}"),
Err(e) => { eprintln!("error: {e:?}"); break; }
}
}Sourcepub fn market_depth<'a>(
&'a self,
contract: &'a Contract,
number_of_rows: i32,
) -> MarketDepthBuilder<'a, Self>
pub fn market_depth<'a>( &'a self, contract: &'a Contract, number_of_rows: i32, ) -> MarketDepthBuilder<'a, Self>
Returns a builder for a level-2 market-depth (order book) subscription.
Defaults to SmartDepth::No. See MarketDepthBuilder for the chained
methods, and MarketDepths for handling a book reset (317) and halt
(316).
§Examples
use ibapi::client::blocking::Client;
use ibapi::contracts::Contract;
use ibapi::market_data::SmartDepth;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("AAPL").build();
let subscription = client
.market_depth(&contract, 5)
.smart_depth(SmartDepth::Yes)
.subscribe()
.expect("error requesting market depth");
for row in subscription.iter_data() {
match row {
Ok(row) => println!("row: {row:?}"),
Err(e) => {
eprintln!("error: {e:?}");
break;
}
}
}Sourcepub fn market_depth_exchanges(
&self,
) -> Result<Vec<DepthMarketDataDescription>, Error>
pub fn market_depth_exchanges( &self, ) -> Result<Vec<DepthMarketDataDescription>, Error>
Requests venues for which market data is returned to market_depth (those with market makers)
§Errors
Error::Timeout if TWS sends no answer within 30 seconds, or within one_shot_timeout when set.
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let exchanges = client.market_depth_exchanges().expect("error requesting market depth exchanges");
for exchange in &exchanges {
println!("{exchange:?}");
}Sourcepub fn switch_market_data_type(
&self,
market_data_type: MarketDataType,
) -> Result<(), Error>
pub fn switch_market_data_type( &self, market_data_type: MarketDataType, ) -> Result<(), Error>
Switches market data type returned from request_market_data requests to Live, Frozen, Delayed, or FrozenDelayed.
TWS does not keep the type across reconnects. The client re-sends the
last type after every automatic reconnect, before the
TRANSPORT_RECONNECT_CODE
notice, so a reconnect does not revert it to realtime.
The type is kept even when this call returns Err (say, a write
refused while the session is down) and is sent on the next reconnect.
After an Err, call again to apply it to the current session; a
repeated call is harmless.
§Arguments
market_data_type- Type of market data to retrieve.
§Examples
use ibapi::client::blocking::Client;
use ibapi::market_data::{MarketDataType};
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let market_data_type = MarketDataType::Realtime;
client.switch_market_data_type(market_data_type).expect("request failed");
println!("market data switched: {market_data_type:?}");Source§impl Client
impl Client
Sourcepub fn news_providers(&self) -> Result<Vec<NewsProvider>, Error>
pub fn news_providers(&self) -> Result<Vec<NewsProvider>, Error>
Requests news providers which the user has subscribed to.
§Errors
Error::Timeout if TWS sends no answer within 30 seconds, or within one_shot_timeout when set.
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let news_providers = client.news_providers().expect("request news providers failed");
for news_provider in &news_providers {
println!("news provider {news_provider:?}");
}Sourcepub fn news_bulletins(
&self,
all_messages: bool,
) -> Result<Subscription<NewsBulletin>, Error>
pub fn news_bulletins( &self, all_messages: bool, ) -> Result<Subscription<NewsBulletin>, Error>
Subscribes to IB’s News Bulletins.
§Arguments
all_messages- If set to true, will return all the existing bulletins for the current day, set to false to receive only the new bulletins.
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let news_bulletins = client.news_bulletins(true).expect("request news providers failed");
for news_bulletin in &news_bulletins {
println!("news bulletin {news_bulletin:?}");
}Sourcepub fn historical_news(
&self,
contract_id: i32,
provider_codes: &[&str],
start_time: OffsetDateTime,
end_time: OffsetDateTime,
total_results: u8,
) -> Result<Subscription<NewsArticle>, Error>
pub fn historical_news( &self, contract_id: i32, provider_codes: &[&str], start_time: OffsetDateTime, end_time: OffsetDateTime, total_results: u8, ) -> Result<Subscription<NewsArticle>, Error>
Requests historical news headlines.
§Arguments
contract_id- Contract ID of ticker. See contract_details for how to retrieve contract ID.provider_codes- A list of provider codes.start_time- Marks the (exclusive) start of the date range.end_time- Marks the (inclusive) end of the date range.total_results- The maximum number of headlines to fetch (1 – 300)
§Examples
use ibapi::client::blocking::Client;
use ibapi::contracts::Contract; // Or remove if conId is always known
use time::macros::datetime;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
// Example: Fetch historical news for a known contract ID (e.g., AAPL's conId)
let contract_id = 265598;
let provider_codes = &["DJNL", "BRFG"]; // Example provider codes
// Define a past date range for the news query
let start_time = datetime!(2023-01-01 0:00 UTC);
let end_time = datetime!(2023-01-02 0:00 UTC);
let total_results = 5u8; // Request a small number of articles for the example
let articles_subscription = client.historical_news(
contract_id,
provider_codes,
start_time,
end_time,
total_results,
).expect("request historical news failed");
println!("Requested historical news articles:");
for article in articles_subscription.iter_data().take(total_results as usize) {
let article = article?;
println!("- Headline: {}, ID: {}, Provider: {}, Time: {}",
article.headline, article.article_id, article.provider_code, article.time);
}Sourcepub fn news_article(
&self,
provider_code: &str,
article_id: &str,
) -> Result<NewsArticleBody, Error>
pub fn news_article( &self, provider_code: &str, article_id: &str, ) -> Result<NewsArticleBody, Error>
Requests news article body given articleId.
§Arguments
provider_code- Short code indicating news provider, e.g. FLY.article_id- ID of the specific article.
§Errors
Error::Parse if TWS reports an article type other than text (0) or binary (1).
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
// can get these using the historical_news method
let provider_code = "DJ-N";
let article_id = "DJ-N$1915168d";
let article = client.news_article(provider_code, article_id).expect("request news article failed");
println!("{article:?}");Sourcepub fn contract_news(
&self,
contract: &Contract,
provider_codes: &[&str],
) -> Result<Subscription<NewsArticle>, Error>
pub fn contract_news( &self, contract: &Contract, provider_codes: &[&str], ) -> Result<Subscription<NewsArticle>, Error>
Requests realtime contract specific news
§Arguments
contract- Contract for which news is being requested.provider_codes- Short codes indicating news providers, e.g. DJ-N.
§Examples
use ibapi::client::blocking::Client;
use ibapi::contracts::Contract;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("AAPL").build();
let provider_codes = ["DJ-N"];
let subscription = client.contract_news(&contract, &provider_codes).expect("request contract news failed");
for article in subscription.iter_data() {
match article {
Ok(article) => println!("{article:?}"),
Err(e) => eprintln!("error: {e}"),
}
}Sourcepub fn broad_tape_news(
&self,
provider_code: &str,
) -> Result<Subscription<NewsArticle>, Error>
pub fn broad_tape_news( &self, provider_code: &str, ) -> Result<Subscription<NewsArticle>, Error>
Requests realtime BroadTape News
§Arguments
provider_code- Short codes indicating news provider, e.g. DJ-N.
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let provider_code = "BRFG";
let subscription = client.broad_tape_news(provider_code).expect("request broad tape news failed");
for article in subscription.iter_data() {
match article {
Ok(article) => println!("{article:?}"),
Err(e) => eprintln!("error: {e}"),
}
}Source§impl Client
impl Client
Sourcepub fn order<'a>(
&'a self,
contract: &'a Contract,
) -> OrderBuilder<ClientBound<'a, Self>>
pub fn order<'a>( &'a self, contract: &'a Contract, ) -> OrderBuilder<ClientBound<'a, Self>>
Start building an order for the given contract
This is the primary API for creating orders, providing a fluent interface that guides you through the order creation process.
§Examples
use ibapi::client::blocking::Client;
use ibapi::contracts::Contract;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("AAPL").build();
let order_id = client.order(&contract)
.buy(100)
.limit(50.0)
.submit().expect("order submission failed");Sourcepub fn all_open_orders(&self) -> Result<Subscription<Orders>, Error>
pub fn all_open_orders(&self) -> Result<Subscription<Orders>, Error>
Requests all current open orders in associated accounts at the current moment. Open orders are returned once; this function does not initiate a subscription.
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let subscription = client.all_open_orders().expect("request failed");
for order_data in subscription.iter_data() {
match order_data {
Ok(order_data) => println!("{order_data:?}"),
Err(e) => eprintln!("error: {e}"),
}
}Sourcepub fn auto_open_orders(
&self,
auto_bind: bool,
) -> Result<Subscription<Orders>, Error>
pub fn auto_open_orders( &self, auto_bind: bool, ) -> Result<Subscription<Orders>, Error>
Requests status updates about future orders placed from TWS. Can only be used with client ID 0.
§Arguments
auto_bind- if set to true, the newly created orders will be assigned an API order ID and implicitly associated with this client. If set to false, future orders will not be.
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 0).expect("connection failed");
let subscription = client.auto_open_orders(false).expect("request failed");
for order_data in subscription.iter_data() {
match order_data {
Ok(order_data) => println!("{order_data:?}"),
Err(e) => eprintln!("error: {e}"),
}
}Sourcepub fn cancel_order(
&self,
order_id: impl Into<OrderId>,
manual_order_cancel_time: &str,
) -> Result<Subscription<CancelOrder>, Error>
pub fn cancel_order( &self, order_id: impl Into<OrderId>, manual_order_cancel_time: &str, ) -> Result<Subscription<CancelOrder>, Error>
Cancels an active crate::orders::Order placed by the same API client ID.
The confirmation (TWS code 202) arrives as a non-terminal
SubscriptionItem::Notice;
the subscription stays open until dropped, so break once cancellation
is observed.
§Arguments
order_id- ID of thecrate::orders::Orderto cancel.manual_order_cancel_time- Optional timestamp to specify the cancellation time. Use an empty string to use the current time.
§Errors
Error::OrderIdInRequestRange if order_id is at or above 1,500,000,000 (reserved for request ids).
§Examples
use ibapi::client::blocking::Client;
use ibapi::subscriptions::SubscriptionItem;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let order_id = 15;
let subscription = client.cancel_order(order_id, "").expect("request failed");
for item in &subscription {
match item {
Ok(SubscriptionItem::Data(status)) => println!("status: {status:?}"),
Ok(SubscriptionItem::Notice(n)) if n.is_cancellation() => {
println!("cancelled: {n}");
break;
}
Ok(SubscriptionItem::Notice(n)) => println!("notice: {n}"),
Err(e) => { eprintln!("cancel err: {e:?}"); break; }
}
}Sourcepub fn completed_orders(
&self,
api_only: bool,
) -> Result<Subscription<Orders>, Error>
pub fn completed_orders( &self, api_only: bool, ) -> Result<Subscription<Orders>, Error>
Requests completed crate::orders::Orders.
A completed order’s total_quantity is the quantity left unfilled, not the size
ordered: 0 for a filled order. The size ordered is total_quantity + filled_quantity.
§Arguments
api_only- request only orders placed by the API.
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let subscription = client.completed_orders(false).expect("request failed");
for order_data in subscription.iter_data() {
match order_data {
Ok(order_data) => println!("{order_data:?}"),
Err(e) => eprintln!("error: {e}"),
}
}Sourcepub fn executions(
&self,
filter: ExecutionFilter,
) -> Result<Subscription<Executions>, Error>
pub fn executions( &self, filter: ExecutionFilter, ) -> Result<Subscription<Executions>, Error>
Requests executions matching the filter.
Covers the current day (since midnight) by default; set
ExecutionFilter::last_n_days or ExecutionFilter::specific_dates
to reach earlier days.
Along with the crate::orders::ExecutionData, the crate::orders::CommissionReport will also be returned.
Join a commission to its execution by execution_id (see the
CommissionReport docs) — the commission follows its execution.
When requesting executions, a filter can be specified to receive only a subset of them
§Arguments
filter- filter criteria used to determine which execution reports are returned
§Examples
use ibapi::client::blocking::Client;
use ibapi::orders::{ExecutionFilter, ExecutionFilterSide};
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let filter = ExecutionFilter {
side: Some(ExecutionFilterSide::Buy),
..ExecutionFilter::default()
};
let subscription = client.executions(filter).expect("request failed");
for execution_data in subscription.iter_data() {
match execution_data {
Ok(execution_data) => println!("{execution_data:?}"),
Err(e) => eprintln!("error: {e}"),
}
}Sourcepub fn global_cancel(&self) -> Result<(), Error>
pub fn global_cancel(&self) -> Result<(), Error>
Cancels all open crate::orders::Orders.
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
client.global_cancel().expect("request failed");Sourcepub fn next_valid_order_id(&self) -> Result<i32, Error>
pub fn next_valid_order_id(&self) -> Result<i32, Error>
Gets the next valid order ID from the TWS server.
Unlike Self::next_order_id, this function requests the next valid order ID from the TWS server. This can be for ensuring that order IDs are unique across multiple clients.
The returned value also raises the client’s order-ID generator to at least that value — monotonically, never lowering it below locally allocated order IDs, including IDs whose order has not yet reached the server.
Use this method when coordinating order IDs across multiple client instances or when you need to synchronize with the server’s order ID sequence at the start of a session.
§Errors
Error::OrderIdInRequestRangeif TWS returns an id at or above 1,500,000,000 (reserved for request ids).Error::Timeoutif TWS sends no answer within 30 seconds, or withinone_shot_timeoutwhen set.
§Examples
use ibapi::client::blocking::Client;
// Connect to the TWS server at the given address with client ID.
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
// Request the next valid order ID from the server.
let next_valid_order_id = client.next_valid_order_id().expect("request failed");
println!("next_valid_order_id: {next_valid_order_id}");Sourcepub fn open_orders(&self) -> Result<Subscription<Orders>, Error>
pub fn open_orders(&self) -> Result<Subscription<Orders>, Error>
Requests all open orders places by this specific API client (identified by the API client id). For client ID 0, this will bind previous manual TWS orders.
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let subscription = client.open_orders().expect("request failed");
for order_data in subscription.iter_data() {
match order_data {
Ok(order_data) => println!("{order_data:?}"),
Err(e) => eprintln!("error: {e}"),
}
}Sourcepub fn place_order(
&self,
order_id: impl Into<OrderId>,
contract: &Contract,
order: &Order,
) -> Result<Subscription<PlaceOrder>, Error>
pub fn place_order( &self, order_id: impl Into<OrderId>, contract: &Contract, order: &Order, ) -> Result<Subscription<PlaceOrder>, Error>
Places or modifies an crate::orders::Order.
Submits an crate::orders::Order using Client for the given Contract.
Upon successful submission, the client will start receiving events related to the order’s activity via the subscription, including order status updates and execution reports.
§Arguments
order_id- ID forcrate::orders::Order. Get next valid ID using Client::next_order_id.contract- Contract to submit order for.order-crate::orders::Orderto submit.
§Errors
Error::OrderIdInRequestRange if order_id, or a parent_id or preset attached-order id on order, is at or above 1,500,000,000 (reserved for request ids).
§Examples
use ibapi::client::blocking::Client;
use ibapi::contracts::Contract;
use ibapi::orders::PlaceOrder;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("MSFT").build();
let order = client.order(&contract)
.buy(100)
.market()
.build_order()
.expect("failed to build order");
let order_id = client.next_order_id();
let events = client.place_order(order_id, &contract, &order).expect("request failed");
for event in events.iter_data() {
match event? {
PlaceOrder::OrderStatus(order_status) => {
println!("order status: {order_status:?}")
}
PlaceOrder::OpenOrder(open_order) => println!("open order: {open_order:?}"),
PlaceOrder::ExecutionData(execution) => println!("execution: {execution:?}"),
PlaceOrder::CommissionReport(report) => println!("commission report: {report:?}"),
}
}Sourcepub fn submit_order(
&self,
order_id: impl Into<OrderId>,
contract: &Contract,
order: &Order,
) -> Result<(), Error>
pub fn submit_order( &self, order_id: impl Into<OrderId>, contract: &Contract, order: &Order, ) -> Result<(), Error>
Submits or modifies an crate::orders::Order without returning a subscription.
This is a fire-and-forget method that submits an crate::orders::Order for the given Contract
but does not return a subscription for order updates. To receive order status updates,
fills, and commission reports, use the order_update_stream method
or use place_order instead which returns a subscription.
§Arguments
order_id- ID forcrate::orders::Order. Get next valid ID using Client::next_order_id.contract- Contract to submit order for.order-crate::orders::Orderto submit.
§Returns
Ok(())if the order was successfully sentErr(Error)if validation failed or sending failed
§Errors
Error::OrderIdInRequestRange if order_id, or a parent_id or preset attached-order id on order, is at or above 1,500,000,000 (reserved for request ids).
§Examples
use ibapi::client::blocking::Client;
use ibapi::contracts::Contract;
let client = Client::connect("127.0.0.1:4002", 100)?;
let contract = Contract::stock("MSFT").build();
let order = client.order(&contract)
.buy(100)
.market()
.build_order()?;
let order_id = client.next_order_id();
// Submit order without waiting for confirmation
client.submit_order(order_id, &contract, &order)?;
// Monitor all order updates via the order update stream
// This will receive updates for ALL orders, not just this one
use ibapi::orders::OrderUpdate;
for event in client.order_update_stream()?.iter_data() {
match event? {
OrderUpdate::OrderStatus(status) => println!("Order Status: {status:?}"),
OrderUpdate::ExecutionData(exec) => println!("Execution: {exec:?}"),
OrderUpdate::CommissionReport(report) => println!("Commission: {report:?}"),
OrderUpdate::OrderBound(binding) => println!("Order binding: {binding:?}"),
_ => {}
}
}
Sourcepub fn submit_oca_orders(
&self,
orders: Vec<(Contract, Order)>,
) -> Result<Vec<OrderId>, Error>
pub fn submit_oca_orders( &self, orders: Vec<(Contract, Order)>, ) -> Result<Vec<OrderId>, Error>
Submit multiple OCA (One-Cancels-All) orders
When one order in the group is filled, all others are automatically cancelled.
§Examples
use ibapi::client::blocking::Client;
use ibapi::contracts::Contract;
use ibapi::orders::OcaType;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract1 = Contract::stock("AAPL").build();
let contract2 = Contract::stock("MSFT").build();
let order1 = client.order(&contract1)
.buy(100)
.limit(50.0)
.oca_group("MyOCA", OcaType::CancelWithBlock)
.build_order().expect("order build failed");
let order2 = client.order(&contract2)
.buy(100)
.limit(45.0)
.oca_group("MyOCA", OcaType::CancelWithBlock)
.build_order().expect("order build failed");
let order_ids = client.submit_oca_orders(
vec![(contract1, order1), (contract2, order2)]
).expect("OCA submission failed");Sourcepub fn order_update_stream(&self) -> Result<Subscription<OrderUpdate>, Error>
pub fn order_update_stream(&self) -> Result<Subscription<OrderUpdate>, Error>
Creates a subscription stream for receiving real-time order updates.
This method establishes a stream that receives all order-related events including:
- Order status updates (e.g., submitted, filled, cancelled)
- Open order information
- Execution data for trades
- Commission reports
- Order-related messages and notices
The stream will receive updates for all orders placed through this client connection, including both new orders submitted after creating the stream and existing orders.
§Returns
Returns a Subscription<OrderUpdate> that yields OrderUpdate enum variants containing:
OrderStatus: Current status of an order (filled amount, average price, etc.)OpenOrder: Complete order details including contract and order parametersExecutionData: Details about individual trade executionsCommissionReport: Commission information for executed trades
Order-bound TWS errors and warnings (e.g. rejections, code 399 order
messages) arrive as SubscriptionItem::Notice,
not as OrderUpdate variants. They surface via iter() / next() as
below; iter_data() drops them (logging at warn! level), so match on
notices explicitly when monitoring fire-and-forget orders for rejection.
§Errors
Returns an error if the subscription cannot be created, typically due to connection issues or internal errors.
§Examples
use ibapi::client::blocking::Client;
use ibapi::orders::OrderUpdate;
use ibapi::subscriptions::SubscriptionItem;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
// Create order update stream
let updates = client.order_update_stream().expect("failed to create stream");
// `iter()` surfaces both data and notices; `iter_data()` would drop notices.
for item in updates.iter() {
match item? {
SubscriptionItem::Data(OrderUpdate::OrderStatus(status)) => {
println!("Order {} status: {} - filled: {}/{}",
status.order_id, status.status, status.filled, status.remaining);
}
SubscriptionItem::Data(update) => println!("update: {update:?}"),
SubscriptionItem::Notice(notice) if notice.is_error() => {
eprintln!("order {:?} rejected: {}", notice.request_id, notice.message);
}
SubscriptionItem::Notice(notice) => println!("notice: {}", notice.message),
}
}§Note
This stream provides updates for all orders, not just a specific order. To track a specific order, filter the updates by order ID.
To pair a CommissionReport with the
ExecutionData it belongs to, join on
execution_id — the commission follows its execution and shares that key. See
the CommissionReport docs for the idiom.
§Gaps and recovery
TWS does not replay order events, so two situations leave a gap the stream cannot fill on its own:
- Reconnect. The stream survives the client’s automatic reconnects:
the same subscription keeps delivering once the connection returns,
but updates TWS emitted during the outage are lost and no marker
appears in the stream. Watch
Self::notice_streamfor the connectivity notices (codes 1100 connectivity lost, 1101 restored with data lost, 1102 restored with data maintained, 1300 socket reset). - Error. An
Erritem ends the stream; every later call returnsNone. A frame that fails to decode is a bug in TWS or this crate, so it is surfaced rather than skipped.
Client shutdown (disconnect, drop, or a reconnect that gives up) also
ends the stream; after it, order_update_stream returns
Error::Shutdown.
After an error, drop the ended subscription and call
order_update_stream again; while the old one is held and not
cancelled, a second call returns Error::AlreadySubscribed.
After a reconnect, the existing subscription is still live. In both
cases, rebuild state from snapshots:
Self::all_open_orders: every open order and its status.Self::completed_orders(false): orders that filled or were cancelled during the gap.Self::executionswith a defaultExecutionFilter: fills and their commissions. The default covers the current day only; setlast_n_dayswhen the gap may span midnight, as the daily gateway reset does.
The snapshots cover every client’s orders, while this stream reports
only this client’s. Keep the entries whose order.client_id /
execution.client_id matches, or state will hold orders the stream
never updates.
Take the snapshots after the stream is live again, so no event falls
between the two. An event can then arrive both ways; apply updates
idempotently, keyed by perm_id for orders and execution_id for fills.
Sourcepub fn order_status_stream(
&self,
order_id: impl Into<OrderId>,
) -> Result<Subscription<OrderStatus>, Error>
pub fn order_status_stream( &self, order_id: impl Into<OrderId>, ) -> Result<Subscription<OrderStatus>, Error>
Streams one order’s status updates.
Starts with the order’s latest status, if this client has seen one
(the latest statuses of the 10,000 most recent orders are kept), then
yields each new OrderStatus as TWS sends it. A reconnect keeps only
statuses of orders that ended: TWS does not replay what happened while
disconnected, so a working order’s stream starts empty until its next
status. If TWS refuses the
order with an error before any status (e.g. 110, a price off the
minimum tick), the stream yields that error as Error::Notice and
ends; a stream opened later starts with it. Otherwise the stream does
not end on its own when the order does; stop reading, or see
wait_for_fill for the common case.
Takes nothing from order_update_stream or
a place_order subscription: all may be open at
once, as may several streams on one order. Nothing is sent to TWS.
§Errors
Error::OrderIdInRequestRange if order_id is at or above 1,500,000,000 (reserved for request ids).
§Examples
use ibapi::client::blocking::Client;
use ibapi::contracts::Contract;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("AAPL").build();
let order_id = client.order(&contract).buy(100).limit(150.0).submit().expect("order submission failed");
let statuses = client.order_status_stream(order_id).expect("stream failed");
for status in statuses.iter_data() {
let status = status.expect("stream error");
println!("{}: {}/{} filled", status.status, status.filled, status.filled + status.remaining);
if status.status.is_terminal() {
break;
}
}Sourcepub fn wait_for_fill(
&self,
order_id: impl Into<OrderId>,
timeout: Duration,
) -> Result<OrderOutcome, Error>
pub fn wait_for_fill( &self, order_id: impl Into<OrderId>, timeout: Duration, ) -> Result<OrderOutcome, Error>
Waits until an order fills or ends, or timeout elapses.
Returns OrderOutcome::Filled when the order filled completely,
OrderOutcome::Ended when it was cancelled or became inactive first,
OrderOutcome::Rejected with TWS’s error when TWS refused the order
without a status (e.g. 110, a price off the minimum tick), and
OrderOutcome::TimedOut with the last status seen when time runs
out. A timeout leaves the order working; cancel it yourself if needed.
Built on order_status_stream, so an
order that already finished before the call is reported at once, as
long as this client saw its status since connecting. When it has seen
none, the wait first looks the order up: an order this client’s open
orders (open_orders) list is still working, and
the wait goes on; otherwise one found among
completed_orders ends the wait at once,
with a status built from the completed order, whose fill prices are
None (see executions for them). Each lookup
reads its replies to the end, which can add a round trip to timeout.
With client id 0, the open-orders request also binds manual TWS orders
to this client. An order placed by another client, or one in neither
reply, waits out the timeout.
§Errors
Error::OrderIdInRequestRange if order_id is at or above 1,500,000,000
(reserved for request ids), Error::ConnectionReset if the connection is
down or drops during the wait, Error::Shutdown if the client shuts down.
§Examples
use std::time::Duration;
use ibapi::client::blocking::Client;
use ibapi::contracts::Contract;
use ibapi::orders::OrderOutcome;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("AAPL").build();
let order_id = client.order(&contract).buy(100).market().submit().expect("order submission failed");
match client.wait_for_fill(order_id, Duration::from_secs(30)).expect("wait failed") {
OrderOutcome::Filled(status) => println!("filled {} @ {:?}", status.filled, status.average_fill_price),
OrderOutcome::Ended(status) => println!("ended {:?} after {} filled", status.status, status.filled),
OrderOutcome::TimedOut(status) => println!("still working: {status:?}"),
OrderOutcome::Rejected(notice) => println!("rejected: {notice}"),
}Sourcepub fn exercise_options<'a>(
&'a self,
contract: &'a Contract,
) -> ExerciseOptionsBuilder<'a, Self>
pub fn exercise_options<'a>( &'a self, contract: &'a Contract, ) -> ExerciseOptionsBuilder<'a, Self>
Exercise or lapse an option position.
Terminal: ExerciseOptionsBuilder::submit. Pick exercise
or lapse; account,
override_natural_action and
manual_order_time are optional.
§Examples
use ibapi::client::blocking::Client;
use ibapi::contracts::{Contract, OptionRight};
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::option("AAPL", "20251219", 150.0, OptionRight::Call);
let subscription = client
.exercise_options(&contract)
.exercise(1)
.override_natural_action()
.submit()
.expect("exercise_options failed");Source§impl Client
impl Client
Sourcepub fn scanner_parameters(&self) -> Result<String, Error>
pub fn scanner_parameters(&self) -> Result<String, Error>
Requests an XML list of scanner parameters valid in TWS.
§Errors
Error::Timeout if TWS sends no answer within 30 seconds, or within one_shot_timeout when set.
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let xml = client.scanner_parameters().expect("scanner_parameters failed");
println!("scanner parameters: {} chars", xml.len());Sourcepub fn scanner_subscription(
&self,
subscription: &ScannerSubscription,
filter: &[TagValue],
) -> Result<Subscription<Vec<ScannerData>>, Error>
pub fn scanner_subscription( &self, subscription: &ScannerSubscription, filter: &[TagValue], ) -> Result<Subscription<Vec<ScannerData>>, Error>
Starts a subscription to market scan results based on the provided parameters.
§Examples
use ibapi::client::blocking::Client;
use ibapi::scanner::ScannerSubscription;
use ibapi::contracts::TagValue;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let mut sub = ScannerSubscription::default();
sub.instrument = Some("STK".to_string());
sub.location_code = Some("STK.US.MAJOR".to_string());
sub.scan_code = Some("TOP_PERC_GAIN".to_string());
// Further customize the subscription object as needed, for example:
// sub.above_price = Some(1.0);
// sub.below_price = Some(100.0);
// sub.number_of_rows = 20;
// Filter options are advanced and not always needed. Pass an empty Vec if not used.
let mut filter_options: Vec<TagValue> = Vec::new();
// Example of adding a filter:
// filter_options.push(TagValue { tag: "marketCapAbove".to_string(), value: "1000000000".to_string() });
match client.scanner_subscription(&sub, &filter_options) {
Ok(subscription) => {
// Iterate over received scanner data.
// Note: Scanner subscriptions can be continuous or return a snapshot.
// This example just takes the first batch if available.
match subscription.iter_data().next() {
Some(Ok(scanner_results_vec)) => {
println!("Scanner Results (first batch):");
for data in scanner_results_vec {
println!(" Rank: {}, Symbol: {}",
data.rank,
data.contract_details.contract.symbol);
}
}
Some(Err(e)) => eprintln!("Scanner error: {e:?}"),
None => println!("No scanner results received in the first check."),
}
// In a real application, you might continuously iterate or handle updates.
// Remember to cancel the subscription when no longer needed if it's continuous.
// subscription.cancel();
}
Err(e) => {
eprintln!("Failed to start scanner subscription: {e:?}");
}
};Source§impl Client
impl Client
Sourcepub fn wsh_metadata(&self) -> Result<WshMetadata, Error>
pub fn wsh_metadata(&self) -> Result<WshMetadata, Error>
Requests metadata from the WSH calendar.
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let metadata = client.wsh_metadata().expect("request wsh metadata failed");
println!("{metadata:?}");Sourcepub fn wsh_event_data_by_contract(
&self,
contract_id: i32,
) -> WshEventDataBuilder<'_, Self>
pub fn wsh_event_data_by_contract( &self, contract_id: i32, ) -> WshEventDataBuilder<'_, Self>
Build a request for Wall Street Horizon events on one contract.
Terminal: WshEventDataBuilder::fetch. Optional narrowing via
.starting() / .ending() / .limit() / .auto_fill().
§Arguments
contract_id- Contract identifier for the event request.
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract_id = 76792991; // TSLA
let event_data = client.wsh_event_data_by_contract(contract_id).fetch().expect("request wsh event data failed");
println!("{event_data:?}");Sourcepub fn wsh_event_data_by_filter<'a>(
&'a self,
filter: &'a str,
) -> WshEventFilterBuilder<'a, Self>
pub fn wsh_event_data_by_filter<'a>( &'a self, filter: &'a str, ) -> WshEventFilterBuilder<'a, Self>
Build a request for Wall Street Horizon events matching a JSON filter.
Terminal: WshEventFilterBuilder::subscribe.
§Arguments
filter- Json-formatted string containing all filter values.
§Examples
use ibapi::client::blocking::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let filter = "{}"; // see https://www.interactivebrokers.com/campus/ibkr-api-page/twsapi-doc/#wsheventdata-object
let subscription = client.wsh_event_data_by_filter(filter).subscribe().expect("request wsh event data failed");
for event in subscription.iter_data() {
println!("{:?}", event.expect("decode error"));
}