pub struct SharedClientHandle { /* private fields */ }Expand description
Handle to a shared IB client; when dropped, ref count is decremented and the connection is removed from the registry when the count reaches zero.
Implementations§
Methods from Deref<Target = Client>§
pub async fn positions(&self) -> Result<Subscription<PositionUpdate>, Error>
pub async fn positions(&self) -> Result<Subscription<PositionUpdate>, Error>
Subscribe to streaming position updates for all accessible accounts.
The stream first replays the full position list and then sends incremental updates.
§Examples
use ibapi::Client;
use ibapi::accounts::PositionUpdate;
use ibapi::subscriptions::SubscriptionItem;
use futures::StreamExt;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let mut subscription = client.positions().await.expect("error requesting positions");
while let Some(item) = subscription.next().await {
match item {
Ok(SubscriptionItem::Data(PositionUpdate::Position(position))) => println!("{position:?}"),
Ok(SubscriptionItem::Data(PositionUpdate::PositionEnd)) => println!("initial set of positions received"),
Ok(SubscriptionItem::Notice(n)) => eprintln!("notice: {n}"),
Err(e) => eprintln!("Error: {e}"),
}
}
}pub async fn positions_multi(
&self,
account: Option<&AccountId>,
model_code: Option<&ModelCode>,
) -> Result<Subscription<PositionUpdateMulti>, Error>
pub async fn positions_multi( &self, account: Option<&AccountId>, model_code: Option<&ModelCode>, ) -> Result<Subscription<PositionUpdateMulti>, Error>
Subscribe to streaming position updates scoped by account and model code.
Requires [Features::MODELS_SUPPORT] to be available on the connected gateway.
§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;
use ibapi::accounts::types::AccountId;
use futures::StreamExt;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let account = AccountId("U1234567".to_string());
let mut subscription = client.positions_multi(Some(&account), None).await.expect("error requesting positions by model");
while let Some(position) = subscription.next().await {
println!("{position:?}")
}
}pub async fn family_codes(&self) -> Result<Vec<FamilyCode>, Error>
pub async fn family_codes(&self) -> Result<Vec<FamilyCode>, Error>
Fetch the account family codes registered with the broker.
§Examples
use ibapi::Client;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let codes = client.family_codes().await.expect("error requesting family codes");
println!("family codes: {codes:?}")
}pub async fn pnl(
&self,
account: &AccountId,
model_code: Option<&ModelCode>,
) -> Result<Subscription<PnL>, Error>
pub async fn pnl( &self, account: &AccountId, model_code: Option<&ModelCode>, ) -> Result<Subscription<PnL>, Error>
Subscribe to real-time daily and unrealized PnL updates for an account.
Optionally filter by model code to scope the updates.
§Arguments
account- account for which to receive PnL updatesmodel_code- specify to request PnL updates for a specific model
§Examples
use ibapi::Client;
use ibapi::accounts::types::AccountId;
use futures::StreamExt;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let account = AccountId("account id".to_string());
let mut subscription = client.pnl(&account, None).await.expect("error requesting pnl");
while let Some(pnl) = subscription.next().await {
println!("{pnl:?}")
}
}pub async fn pnl_single(
&self,
account: &AccountId,
contract_id: ContractId,
model_code: Option<&ModelCode>,
) -> Result<Subscription<PnLSingle>, Error>
pub async fn pnl_single( &self, account: &AccountId, contract_id: ContractId, model_code: Option<&ModelCode>, ) -> Result<Subscription<PnLSingle>, Error>
Subscribe to real-time daily PnL updates for a single contract.
The stream includes realized and unrealized PnL information for the requested position.
§Arguments
account- Account in which position existscontract_id- Contract ID of contract to receive daily PnL updates for.model_code- Model in which position exists
§Examples
use ibapi::Client;
use ibapi::accounts::types::{AccountId, ContractId};
use futures::StreamExt;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let account = AccountId("<account id>".to_string());
let contract_id = ContractId(1001);
let mut subscription = client.pnl_single(&account, contract_id, None).await.expect("error requesting pnl");
while let Some(pnl) = subscription.next().await {
println!("{pnl:?}")
}
}pub async fn account_summary(
&self,
group: &AccountGroup,
tags: &[&str],
) -> Result<Subscription<AccountSummaryResult>, Error>
pub async fn account_summary( &self, group: &AccountGroup, tags: &[&str], ) -> Result<Subscription<AccountSummaryResult>, Error>
Subscribe to account summary updates for a group of accounts.
§Arguments
group- Set to “All” to return account summary data for all accounts, or set to a specific Advisor Account Group name.tags- List of the desired tags.
§Examples
use ibapi::Client;
use ibapi::accounts::AccountSummaryTags;
use ibapi::accounts::types::AccountGroup;
use futures::StreamExt;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let group = AccountGroup("All".to_string());
let mut subscription = client.account_summary(&group, AccountSummaryTags::ALL).await.expect("error requesting account summary");
while let Some(summary) = subscription.next().await {
println!("{summary:?}")
}
}pub async fn account_updates(
&self,
account: &AccountId,
) -> Result<Subscription<AccountUpdate>, Error>
pub async fn account_updates( &self, account: &AccountId, ) -> Result<Subscription<AccountUpdate>, Error>
Subscribe to detailed account updates for a specific account.
§Arguments
account- The account id (i.e. U1234567) for which the information is requested.
§Examples
use ibapi::Client;
use ibapi::accounts::AccountUpdate;
use ibapi::accounts::types::AccountId;
use ibapi::subscriptions::SubscriptionItem;
use futures::StreamExt;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let account = AccountId("U1234567".to_string());
let mut subscription = client.account_updates(&account).await.expect("error requesting account updates");
while let Some(item) = subscription.next().await {
match item {
Ok(SubscriptionItem::Data(update)) => {
println!("{update:?}");
if let AccountUpdate::End = update {
break;
}
}
Ok(SubscriptionItem::Notice(n)) => eprintln!("notice: {n}"),
Err(e) => eprintln!("Error: {e}"),
}
}
}pub async fn account_updates_multi(
&self,
account: Option<&AccountId>,
model_code: Option<&ModelCode>,
) -> Result<Subscription<AccountUpdateMulti>, Error>
pub async fn account_updates_multi( &self, account: Option<&AccountId>, model_code: Option<&ModelCode>, ) -> Result<Subscription<AccountUpdateMulti>, Error>
Subscribe to account updates scoped by account and model code.
Requires [Features::MODELS_SUPPORT] to be available on the connected gateway.
§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;
use ibapi::accounts::AccountUpdateMulti;
use ibapi::accounts::types::AccountId;
use ibapi::subscriptions::SubscriptionItem;
use futures::StreamExt;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let account = AccountId("U1234567".to_string());
let mut subscription = client.account_updates_multi(Some(&account), None).await.expect("error requesting account updates multi");
while let Some(item) = subscription.next().await {
match item {
Ok(SubscriptionItem::Data(update)) => {
println!("{update:?}");
if let AccountUpdateMulti::End = update {
break;
}
}
Ok(SubscriptionItem::Notice(n)) => eprintln!("notice: {n}"),
Err(e) => eprintln!("Error: {e}"),
}
}
}pub async fn managed_accounts(&self) -> Result<Vec<String>, Error>
pub async fn managed_accounts(&self) -> Result<Vec<String>, Error>
Fetch the list of accounts accessible to the current user.
§Examples
use ibapi::Client;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let accounts = client.managed_accounts().await.expect("error requesting managed accounts");
println!("managed accounts: {accounts:?}")
}pub async fn server_time(&self) -> Result<OffsetDateTime, Error>
pub async fn server_time(&self) -> Result<OffsetDateTime, Error>
Query the current server time reported by TWS or IB Gateway.
§Examples
use ibapi::Client;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let server_time = client.server_time().await.expect("error requesting server time");
println!("server time: {server_time:?}");
}pub async fn server_time_millis(&self) -> Result<OffsetDateTime, Error>
pub async fn server_time_millis(&self) -> Result<OffsetDateTime, Error>
Query the current server time in milliseconds reported by TWS or IB Gateway.
pub async fn soft_dollar_tiers(&self) -> Result<Vec<SoftDollarTier>, Error>
pub async fn soft_dollar_tiers(&self) -> Result<Vec<SoftDollarTier>, Error>
Request the configured soft dollar tiers available to the account.
§Examples
use ibapi::Client;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let tiers = client.soft_dollar_tiers().await.expect("request failed");
for tier in &tiers {
println!("{}: {}", tier.name, tier.display_name);
}
}pub async fn user_info(&self) -> Result<UserInfo, Error>
pub async fn user_info(&self) -> Result<UserInfo, Error>
Request white-branding identity information for the logged-in user.
§Examples
use ibapi::Client;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let info = client.user_info().await.expect("request failed");
println!("white branding id: {}", info.white_branding_id);
}pub async fn request_fa(
&self,
fa_data_type: FaDataType,
) -> Result<FaConfig, Error>
pub async 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.
§Examples
use ibapi::Client;
use ibapi::accounts::FaDataType;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let cfg = client.request_fa(FaDataType::Groups).await.expect("request failed");
println!("{}", cfg.xml);
}pub async fn replace_fa(
&self,
fa_data_type: FaDataType,
xml: &str,
) -> Result<ReplaceFaResult, Error>
pub async 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;
use ibapi::accounts::FaDataType;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let result = client.replace_fa(FaDataType::Groups, "<xml/>").await.expect("request failed");
println!("{}", result.text);
}pub async fn set_server_log_level(
&self,
log_level: ServerLogLevel,
) -> Result<(), Error>
pub async 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;
use ibapi::accounts::ServerLogLevel;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
client.set_server_log_level(ServerLogLevel::Detail).await.expect("request failed");
}pub async fn verify_request(
&self,
api_name: &str,
api_version: &str,
) -> Result<VerificationChallenge, Error>
pub async 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.
§Examples
use ibapi::Client;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let challenge = client.verify_request("MyApp", "1.0").await.expect("request failed");
println!("{}", challenge.api_data);
}pub async fn verify_message(
&self,
api_data: &str,
) -> Result<VerificationResult, Error>
pub async fn verify_message( &self, api_data: &str, ) -> Result<VerificationResult, Error>
Continue a TWS extension verification handshake by sending the API response data.
§Examples
use ibapi::Client;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let result = client.verify_message("signed-challenge").await.expect("request failed");
if result.is_successful {
println!("verified");
} else {
eprintln!("{}", result.error_text);
}
}pub fn server_version(&self) -> i32
pub fn server_version(&self) -> i32
Returns the server version
pub fn connection_time(&self) -> Option<OffsetDateTime>
pub fn connection_time(&self) -> Option<OffsetDateTime>
Returns the connection time
pub 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;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
if client.is_connected() {
println!("Client is connected to TWS/Gateway");
} else {
println!("Client is not connected");
}
}pub async fn disconnect(&self)
pub async fn disconnect(&self)
Cleanly shuts down the message bus.
All outstanding Subscriptions see their channels
close and their next() calls return None. The background dispatch task is awaited
to completion before this returns.
Call this before dropping the final Arc<Client> if any spawned
tasks hold that Arc. Otherwise the tokio runtime will hang on
shutdown — Drop cannot perform the full async shutdown because it
is not async.
Safe to call multiple times.
§Examples
use ibapi::Client;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
// ... use client, spawn tasks holding Arc<Client> ...
client.disconnect().await;
}pub 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 disconnects.
Per-subscription notices (codes carrying a real request_id) are not
delivered here — they reach their owning subscription as
SubscriptionItem::Notice
(via [futures::StreamExt::next] on the Subscription stream).
§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;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let mut stream = client.notice_stream().expect("notice subscription failed");
while let Some(notice) = stream.next().await {
if notice.is_system_message() {
println!("connectivity: {notice}");
} else if notice.is_warning() {
println!("warning: {notice}");
} else {
eprintln!("error: {notice}");
}
}
}pub fn next_order_id(&self) -> i32
pub fn next_order_id(&self) -> i32
Returns the next order ID
pub fn next_request_id(&self) -> i32
pub fn next_request_id(&self) -> i32
Returns the next request ID
pub fn order<'a>(&'a self, contract: &'a Contract) -> OrderBuilder<'a, Client>
pub fn order<'a>(&'a self, contract: &'a Contract) -> OrderBuilder<'a, Client>
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.
§Example
use ibapi::Client;
use ibapi::contracts::Contract;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let contract = Contract::stock("AAPL").build();
let order_id = client.order(&contract)
.buy(100)
.limit(50.0)
.submit().await.expect("order submission failed");
}pub fn market_data<'a>(
&'a self,
contract: &'a Contract,
) -> MarketDataBuilder<'a, Client>
pub fn market_data<'a>( &'a self, contract: &'a Contract, ) -> MarketDataBuilder<'a, Client>
Creates a market data subscription builder with a fluent interface.
pub fn check_server_version(
&self,
required_version: i32,
feature: &str,
) -> Result<(), Error>
pub fn check_server_version( &self, required_version: i32, feature: &str, ) -> Result<(), Error>
Check server version requirement
pub async fn subscribe_to_group_events(
&self,
group_id: i32,
) -> Result<DisplayGroupSubscription, Error>
pub async 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::prelude::*;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:7497", 100).await.expect("connection failed");
let mut subscription = client.subscribe_to_group_events(1).await.expect("subscription failed");
// Update the displayed contract
subscription.update("265598@SMART").await.expect("update failed");
// Consume the subscription so display-group events surface.
while let Some(event) = subscription.next().await {
println!("group event: {event:?}");
}
}pub async fn contract_details(
&self,
contract: &Contract,
) -> Result<Vec<ContractDetails>, Error>
pub async 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.
§Arguments
contract- The [Contract] used as sample to query the available contracts.
§Examples
use ibapi::Client;
use ibapi::contracts::Contract;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let contract = Contract::stock("AAPL").build();
let details = client.contract_details(&contract).await.expect("request failed");
for detail in details {
println!("Contract: {} - Exchange: {}", detail.contract.symbol, detail.contract.exchange);
}
}pub async fn matching_symbols(
&self,
pattern: &str,
) -> Result<Vec<ContractDescription>, Error>
pub async 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.
§Examples
use ibapi::Client;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let symbols = client.matching_symbols("AAP").await.expect("request failed");
for symbol in symbols {
println!("{} - {} ({})", symbol.contract.symbol,
symbol.contract.primary_exchange, symbol.contract.currency);
}
}pub async fn market_rule(
&self,
market_rule_id: i32,
) -> Result<MarketRule, Error>
pub async 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.
§Arguments
market_rule_id- The market rule ID to query
§Examples
use ibapi::Client;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let rule = client.market_rule(26).await.expect("request failed");
for increment in rule.price_increments {
println!("Above ${}: increment ${}", increment.low_edge, increment.increment);
}
}pub async fn smart_components(
&self,
bbo_exchange: &str,
) -> Result<Vec<SmartComponent>, Error>
pub async 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;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let components = client.smart_components("a6").await.expect("request failed");
for component in &components {
println!("bit {}: {} ({})", component.bit_number, component.exchange, component.exchange_letter);
}
}pub async fn calculate_option_price(
&self,
contract: &Contract,
volatility: f64,
underlying_price: f64,
) -> Result<OptionComputation, Error>
pub async 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 for which the depth is being requested.volatility- Hypothetical volatility.underlying_price- Hypothetical option’s underlying price.
§Examples
use ibapi::prelude::*;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let contract = Contract::option("AAPL", "20251219", 150.0, OptionRight::Call);
let calculation = client
.calculate_option_price(&contract, 100.0, 235.0)
.await
.expect("request failed");
println!("calculation: {calculation:?}");
}pub async fn calculate_implied_volatility(
&self,
contract: &Contract,
option_price: f64,
underlying_price: f64,
) -> Result<OptionComputation, Error>
pub async fn calculate_implied_volatility( &self, contract: &Contract, option_price: f64, underlying_price: f64, ) -> Result<OptionComputation, Error>
Calculates the implied volatility based on hypothetical option and its underlying prices.
§Arguments
contract- The [Contract] object for which the depth is being requested.option_price- Hypothetical option price.underlying_price- Hypothetical option’s underlying price.
§Examples
use ibapi::prelude::*;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let contract = Contract::option("AAPL", "20230519", 150.0, OptionRight::Call);
let calculation = client
.calculate_implied_volatility(&contract, 25.0, 235.0)
.await
.expect("request failed");
println!("calculation: {calculation:?}");
}pub async fn cancel_contract_details(
&self,
request_id: i32,
) -> Result<(), Error>
pub async fn cancel_contract_details( &self, request_id: i32, ) -> Result<(), Error>
Cancels an in-flight contract details request.
§Examples
use ibapi::prelude::*;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
// `request_id` is the id used to launch the original contract_details request.
client.cancel_contract_details(42).await.expect("cancel failed");
}pub async fn option_chain(
&self,
symbol: &str,
exchange: &str,
security_type: SecurityType,
contract_id: i32,
) -> Result<Subscription<OptionChain>, Error>
pub async fn option_chain( &self, symbol: &str, exchange: &str, security_type: SecurityType, contract_id: i32, ) -> Result<Subscription<OptionChain>, Error>
Requests option chain data for an underlying instrument.
§Arguments
symbol- The underlying symbolexchange- The exchangesecurity_type- The underlying security typecontract_id- The underlying contract ID
§Examples
use ibapi::prelude::*;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let subscription = client
.option_chain("AAPL", "", SecurityType::Stock, 265598)
.await
.expect("option_chain failed");
let mut chains = subscription.filter_data();
while let Some(chain) = chains.next().await {
println!("{chain:?}");
}
}pub async fn fundamental_data(
&self,
contract: &Contract,
report_type: FundamentalReportType,
) -> Result<FundamentalData, Error>
pub async fn fundamental_data( &self, contract: &Contract, report_type: FundamentalReportType, ) -> Result<FundamentalData, Error>
Requests a fundamental data report for the given contract.
The response is a single XML payload (schema varies by report type); this crate does not parse it. The request is one-shot — if you need to retrieve a different report, call this method again.
§Examples
use ibapi::contracts::Contract;
use ibapi::fundamental::FundamentalReportType;
use ibapi::Client;
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let contract = Contract::stock("AAPL").build();
let report = client
.fundamental_data(&contract, FundamentalReportType::ReportSnapshot)
.await
.expect("fundamental data request failed");
println!("{}", report.data);pub async fn head_timestamp(
&self,
contract: &Contract,
what_to_show: WhatToShow,
trading_hours: TradingHours,
) -> Result<OffsetDateTime, Error>
pub async 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.
§Arguments
contract- [Contract] to retrieve the head timestamp for.what_to_show- requested bar type: [WhatToShow].trading_hours- Use [TradingHours::Regular] for data generated only during regular trading hours, or [TradingHours::Extended] to include data from outside regular trading hours.
§Examples
use ibapi::Client;
use ibapi::contracts::Contract;
use ibapi::market_data::historical::WhatToShow;
use ibapi::market_data::TradingHours;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let contract = Contract::stock("MSFT").build();
let result = client
.head_timestamp(&contract, WhatToShow::Trades, TradingHours::Regular)
.await
.expect("head timestamp failed");
println!("head_timestamp: {result:?}");
}pub fn historical_data<'a>(
&'a self,
contract: &'a Contract,
bar_size: BarSize,
) -> HistoricalDataBuilder<'a, Client>
pub fn historical_data<'a>( &'a self, contract: &'a Contract, bar_size: BarSize, ) -> HistoricalDataBuilder<'a, Client>
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::prelude::*;
use time::macros::datetime;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let contract = Contract::stock("AAPL").build();
// IBKR-native: amount of data ending at a specific time (or now)
let bars = client
.historical_data(&contract, HistoricalBarSize::Hour)
.what_to_show(HistoricalWhatToShow::Trades)
.duration(7.days())
.fetch()
.await
.expect("historical data request failed");
// Convenience: explicit date range (computes duration internally)
let bars = client
.historical_data(&contract, HistoricalBarSize::Hour)
.between(datetime!(2023-04-08 0:00 UTC), datetime!(2023-04-15 0:00 UTC))
.fetch()
.await
.expect("historical data request failed");
let _ = bars;
}pub fn historical_schedules<'a>(
&'a self,
contract: &'a Contract,
duration: Duration,
) -> HistoricalScheduleBuilder<'a, Client>
pub fn historical_schedules<'a>( &'a self, contract: &'a Contract, duration: Duration, ) -> HistoricalScheduleBuilder<'a, Client>
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
contract- [Contract] to retrieve [Schedule] for.duration- [Duration] of the interval to retrieve.
§Examples
use ibapi::prelude::*;
use time::macros::datetime;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let contract = Contract::stock("GM").build();
// Ending now:
let schedule = client
.historical_schedules(&contract, 30.days())
.fetch()
.await
.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()
.await
.expect("historical schedule request failed");
for session in &schedule.sessions {
println!("{session:?}");
}
}pub fn historical_ticks<'a>(
&'a self,
contract: &'a Contract,
number_of_ticks: i32,
) -> HistoricalTicksBuilder<'a, Client>
pub fn historical_ticks<'a>( &'a self, contract: &'a Contract, number_of_ticks: i32, ) -> HistoricalTicksBuilder<'a, Client>
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::prelude::*;
use ibapi::market_data::IgnoreSize;
use time::macros::datetime;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let contract = Contract::stock("TSLA").build();
// Trade ticks anchored at a start date:
let mut trades = client
.historical_ticks(&contract, 100)
.starting(datetime!(2023-04-15 0:00 UTC))
.trade()
.await
.expect("historical ticks request failed");
while let Some(tick) = trades.next().await {
println!("{tick:?}");
}
// 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)
.await
.expect("historical ticks request failed");
}pub async fn cancel_historical_ticks(
&self,
request_id: i32,
) -> Result<(), Error>
pub async 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.
pub async fn histogram_data(
&self,
contract: &Contract,
trading_hours: TradingHours,
period: BarSize,
) -> Result<Vec<HistogramEntry>, Error>
pub async 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 [HistogramEntry] data 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 ibapi::Client;
use ibapi::contracts::Contract;
use ibapi::market_data::historical::BarSize;
use ibapi::market_data::TradingHours;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let contract = Contract::stock("GM").build();
let histogram = client
.histogram_data(&contract, TradingHours::Regular, BarSize::Week)
.await
.expect("histogram request failed");
for item in &histogram {
println!("{item:?}");
}
}pub async fn switch_market_data_type(
&self,
market_data_type: MarketDataType,
) -> Result<(), Error>
pub async 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.
§Arguments
market_data_type- Type of market data to retrieve.
§Examples
use ibapi::prelude::*;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let market_data_type = MarketDataType::Realtime;
client.switch_market_data_type(market_data_type).await.expect("request failed");
println!("market data switched: {market_data_type:?}");
}pub fn realtime_bars<'a>(
&'a self,
contract: &'a Contract,
) -> RealtimeBarsBuilder<'a, Client>
pub fn realtime_bars<'a>( &'a self, contract: &'a Contract, ) -> RealtimeBarsBuilder<'a, Client>
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::prelude::*;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let contract = Contract::stock("TSLA").build();
let mut subscription = client
.realtime_bars(&contract)
.what_to_show(RealtimeWhatToShow::Trades)
.trading_hours(TradingHours::Extended)
.subscribe()
.await
.expect("realtime bars request failed");
while let Some(item) = subscription.next().await {
match item {
Ok(SubscriptionItem::Data(bar)) => println!("{bar:?}"),
Ok(SubscriptionItem::Notice(n)) => eprintln!("notice: {n}"),
Err(e) => { eprintln!("error: {e}"); break; }
}
}
}pub fn tick_by_tick<'a>(
&'a self,
contract: &'a Contract,
number_of_ticks: i32,
) -> TickByTickBuilder<'a, Client>
pub fn tick_by_tick<'a>( &'a self, contract: &'a Contract, number_of_ticks: i32, ) -> TickByTickBuilder<'a, Client>
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::prelude::*;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let contract = Contract::stock("AAPL").build();
let mut quotes = client
.tick_by_tick(&contract, 10)
.bid_ask(IgnoreSize::No)
.await
.expect("tick-by-tick bid/ask request failed");
while let Some(item) = quotes.next().await {
match item {
Ok(SubscriptionItem::Data(q)) => println!("{q:?}"),
Ok(SubscriptionItem::Notice(n)) => eprintln!("notice: {n}"),
Err(e) => { eprintln!("error: {e}"); break; }
}
}
}pub fn market_depth<'a>(
&'a self,
contract: &'a Contract,
number_of_rows: i32,
) -> MarketDepthBuilder<'a, Client>
pub fn market_depth<'a>( &'a self, contract: &'a Contract, number_of_rows: i32, ) -> MarketDepthBuilder<'a, Client>
Returns a builder for a level-2 market-depth (order book) subscription.
Defaults to SmartDepth::No. See [MarketDepthBuilder] for the chained
methods.
§Examples
use ibapi::prelude::*;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let contract = Contract::stock("AAPL").build();
let mut subscription = client
.market_depth(&contract, 5)
.smart_depth(SmartDepth::Yes)
.subscribe()
.await
.expect("market depth request failed");
while let Some(item) = subscription.next().await {
match item {
Ok(SubscriptionItem::Data(row)) => println!("{row:?}"),
Ok(SubscriptionItem::Notice(n)) => eprintln!("notice: {n}"),
Err(e) => { eprintln!("error: {e}"); break; }
}
}
}pub async fn market_depth_exchanges(
&self,
) -> Result<Vec<DepthMarketDataDescription>, Error>
pub async fn market_depth_exchanges( &self, ) -> Result<Vec<DepthMarketDataDescription>, Error>
Requests venues for which market data is returned to market_depth (those with market makers)
§Examples
use ibapi::prelude::*;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let exchanges = client.market_depth_exchanges().await.expect("error requesting market depth exchanges");
for exchange in &exchanges {
println!("{exchange:?}");
}
}pub async fn news_providers(&self) -> Result<Vec<NewsProvider>, Error>
pub async fn news_providers(&self) -> Result<Vec<NewsProvider>, Error>
Requests news providers which the user has subscribed to.
§Examples
use ibapi::prelude::*;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let providers = client.news_providers().await.expect("news_providers failed");
for provider in providers {
println!("{provider:?}");
}
}pub async fn news_bulletins(
&self,
all_messages: bool,
) -> Result<Subscription<NewsBulletin>, Error>
pub async fn news_bulletins( &self, all_messages: bool, ) -> Result<Subscription<NewsBulletin>, Error>
Subscribes to IB’s News Bulletins.
§Examples
use ibapi::prelude::*;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let subscription = client.news_bulletins(true).await.expect("news_bulletins failed");
let mut bulletins = subscription.filter_data();
while let Some(bulletin) = bulletins.next().await {
println!("{bulletin:?}");
}
}pub async fn historical_news(
&self,
contract_id: i32,
provider_codes: &[&str],
start_time: OffsetDateTime,
end_time: OffsetDateTime,
total_results: u8,
) -> Result<Subscription<NewsArticle>, Error>
pub async fn historical_news( &self, contract_id: i32, provider_codes: &[&str], start_time: OffsetDateTime, end_time: OffsetDateTime, total_results: u8, ) -> Result<Subscription<NewsArticle>, Error>
Historical News Headlines
§Examples
use ibapi::prelude::*;
use time::macros::datetime;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let subscription = client
.historical_news(
8314, // IBM
&["BRFG"],
datetime!(2025-01-01 0:00 UTC),
datetime!(2025-01-31 23:59 UTC),
10,
)
.await
.expect("historical_news failed");
let mut articles = subscription.filter_data();
while let Some(article) = articles.next().await {
println!("{article:?}");
}
}pub async fn news_article(
&self,
provider_code: &str,
article_id: &str,
) -> Result<NewsArticleBody, Error>
pub async fn news_article( &self, provider_code: &str, article_id: &str, ) -> Result<NewsArticleBody, Error>
Requests news article body
§Examples
use ibapi::prelude::*;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let article = client
.news_article("BRFG", "BRFG$0a3e3f54")
.await
.expect("news_article failed");
println!("{article:?}");
}pub async fn contract_news(
&self,
contract: &Contract,
provider_codes: &[&str],
) -> Result<Subscription<NewsArticle>, Error>
pub async fn contract_news( &self, contract: &Contract, provider_codes: &[&str], ) -> Result<Subscription<NewsArticle>, Error>
Subscribe to news for a specific contract
§Examples
use ibapi::prelude::*;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let contract = Contract::stock("AAPL").build();
let subscription = client.contract_news(&contract, &["BRFG"]).await.expect("contract_news failed");
let mut articles = subscription.filter_data();
while let Some(article) = articles.next().await {
println!("{article:?}");
}
}pub async fn broad_tape_news(
&self,
provider_code: &str,
) -> Result<Subscription<NewsArticle>, Error>
pub async fn broad_tape_news( &self, provider_code: &str, ) -> Result<Subscription<NewsArticle>, Error>
Subscribe to broad tape news
§Examples
use ibapi::prelude::*;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let subscription = client.broad_tape_news("BRFG").await.expect("broad_tape_news failed");
let mut articles = subscription.filter_data();
while let Some(article) = articles.next().await {
println!("{article:?}");
}
}pub async fn submit_oca_orders(
&self,
orders: Vec<(Contract, Order)>,
) -> Result<Vec<OrderId>, Error>
pub async 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.
§Example
use ibapi::Client;
use ibapi::contracts::Contract;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.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", 1)
.build_order().expect("order build failed");
let order2 = client.order(&contract2)
.buy(100)
.limit(45.0)
.oca_group("MyOCA", 1)
.build_order().expect("order build failed");
let order_ids = client.submit_oca_orders(
vec![(contract1, order1), (contract2, order2)]
).await.expect("OCA submission failed");
}pub async fn order_update_stream(
&self,
) -> Result<Subscription<OrderUpdate>, Error>
pub async fn order_update_stream( &self, ) -> Result<Subscription<OrderUpdate>, Error>
Subscribes to order update events. Only one subscription can be active at a time.
§Examples
use ibapi::prelude::*;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let stream = client.order_update_stream().await.expect("failed to create stream");
let mut updates = stream.filter_data();
while let Some(update) = updates.next().await {
match update {
Ok(OrderUpdate::OrderStatus(s)) => println!("status: {s:?}"),
Ok(OrderUpdate::OpenOrder(o)) => println!("open: {o:?}"),
Ok(OrderUpdate::ExecutionData(e)) => println!("exec: {e:?}"),
Ok(OrderUpdate::CommissionReport(r)) => println!("commission: {r:?}"),
Err(e) => { eprintln!("err: {e:?}"); break; }
}
}
}pub async fn submit_order(
&self,
order_id: i32,
contract: &Contract,
order: &Order,
) -> Result<(), Error>
pub async fn submit_order( &self, order_id: i32, contract: &Contract, order: &Order, ) -> Result<(), Error>
Submits an Order (fire-and-forget).
§Examples
use ibapi::prelude::*;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let contract = Contract::stock("AAPL").build();
let order = client
.order(&contract)
.buy(100)
.market()
.build()
.expect("order build");
let order_id = client.next_valid_order_id().await.expect("next id");
client.submit_order(order_id, &contract, &order).await.expect("submit failed");
}pub async fn place_order(
&self,
order_id: i32,
contract: &Contract,
order: &Order,
) -> Result<Subscription<PlaceOrder>, Error>
pub async fn place_order( &self, order_id: i32, contract: &Contract, order: &Order, ) -> Result<Subscription<PlaceOrder>, Error>
Submits an Order with a subscription for updates.
§Examples
use ibapi::prelude::*;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let contract = Contract::stock("AAPL").build();
let order = client
.order(&contract)
.buy(100)
.market()
.build()
.expect("order build");
let order_id = client.next_valid_order_id().await.expect("next id");
let subscription = client.place_order(order_id, &contract, &order).await.expect("place");
let mut updates = subscription.filter_data();
while let Some(update) = updates.next().await {
println!("{update:?}");
}
}pub async fn cancel_order(
&self,
order_id: i32,
manual_order_cancel_time: &str,
) -> Result<Subscription<CancelOrder>, Error>
pub async fn cancel_order( &self, order_id: i32, manual_order_cancel_time: &str, ) -> Result<Subscription<CancelOrder>, Error>
Cancels an open [Order].
§Examples
use ibapi::prelude::*;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
// `""` selects immediate cancel (no manual order time).
let subscription = client.cancel_order(42, "").await.expect("cancel failed");
// Consume the subscription so cancel confirmations and errors surface.
let mut updates = subscription.filter_data();
while let Some(update) = updates.next().await {
match update {
Ok(event) => println!("cancel event: {event:?}"),
Err(e) => { eprintln!("cancel err: {e:?}"); break; }
}
}
}pub async fn global_cancel(&self) -> Result<(), Error>
pub async fn global_cancel(&self) -> Result<(), Error>
Cancels all open [Order]s.
§Examples
use ibapi::prelude::*;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
client.global_cancel().await.expect("global_cancel failed");
}pub async fn next_valid_order_id(&self) -> Result<i32, Error>
pub async fn next_valid_order_id(&self) -> Result<i32, Error>
Gets next valid order id
§Examples
use ibapi::prelude::*;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let next = client.next_valid_order_id().await.expect("next id failed");
println!("next_valid_order_id: {next}");
}pub async fn completed_orders(
&self,
api_only: bool,
) -> Result<Subscription<Orders>, Error>
pub async fn completed_orders( &self, api_only: bool, ) -> Result<Subscription<Orders>, Error>
Requests completed [Order]s.
§Examples
use ibapi::prelude::*;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let subscription = client.completed_orders(true).await.expect("completed_orders failed");
let mut orders = subscription.filter_data();
while let Some(order) = orders.next().await {
println!("{order:?}");
}
}pub async fn open_orders(&self) -> Result<Subscription<Orders>, Error>
pub async fn open_orders(&self) -> Result<Subscription<Orders>, Error>
Requests all open orders placed by this specific API client.
§Examples
use ibapi::prelude::*;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let subscription = client.open_orders().await.expect("open_orders failed");
let mut orders = subscription.filter_data();
while let Some(order) = orders.next().await {
println!("{order:?}");
}
}pub async fn all_open_orders(&self) -> Result<Subscription<Orders>, Error>
pub async fn all_open_orders(&self) -> Result<Subscription<Orders>, Error>
Requests all current open orders in associated accounts.
§Examples
use ibapi::prelude::*;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let subscription = client.all_open_orders().await.expect("all_open_orders failed");
let mut orders = subscription.filter_data();
while let Some(order) = orders.next().await {
println!("{order:?}");
}
}pub async fn auto_open_orders(
&self,
auto_bind: bool,
) -> Result<Subscription<Orders>, Error>
pub async fn auto_open_orders( &self, auto_bind: bool, ) -> Result<Subscription<Orders>, Error>
Requests status updates about future orders placed from TWS.
§Examples
use ibapi::prelude::*;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let subscription = client.auto_open_orders(true).await.expect("auto_open_orders failed");
let mut orders = subscription.filter_data();
while let Some(order) = orders.next().await {
println!("{order:?}");
}
}pub async fn executions(
&self,
filter: ExecutionFilter,
) -> Result<Subscription<Executions>, Error>
pub async fn executions( &self, filter: ExecutionFilter, ) -> Result<Subscription<Executions>, Error>
Requests current day’s executions matching the filter.
§Examples
use ibapi::Client;
use ibapi::orders::{ExecutionFilter, ExecutionFilterSide};
use ibapi::subscriptions::SubscriptionItem;
use futures::StreamExt;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let filter = ExecutionFilter {
side: Some(ExecutionFilterSide::Buy),
..ExecutionFilter::default()
};
let mut subscription = client.executions(filter).await.expect("request failed");
while let Some(item) = subscription.next().await {
match item {
Ok(SubscriptionItem::Data(ex)) => println!("{ex:?}"),
Ok(SubscriptionItem::Notice(n)) => eprintln!("notice: {n}"),
Err(e) => eprintln!("Error: {e}"),
}
}
}pub async fn exercise_options(
&self,
contract: &Contract,
exercise_action: ExerciseAction,
exercise_quantity: i32,
account: &str,
ovrd: bool,
manual_order_time: Option<OffsetDateTime>,
) -> Result<Subscription<ExerciseOptions>, Error>
pub async fn exercise_options( &self, contract: &Contract, exercise_action: ExerciseAction, exercise_quantity: i32, account: &str, ovrd: bool, manual_order_time: Option<OffsetDateTime>, ) -> Result<Subscription<ExerciseOptions>, Error>
Exercise an option contract.
§Examples
use ibapi::prelude::*;
use ibapi::orders::ExerciseAction;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let contract = Contract::option("AAPL", "20251219", 150.0, OptionRight::Call);
let subscription = client
.exercise_options(&contract, ExerciseAction::Exercise, 1, "DU000001", false, None)
.await
.expect("exercise_options failed");
// Consume the subscription so execution updates and commission reports surface.
let mut events = subscription.filter_data();
while let Some(event) = events.next().await {
match event {
Ok(item) => println!("exercise event: {item:?}"),
Err(e) => { eprintln!("exercise err: {e:?}"); break; }
}
}
}pub async fn scanner_parameters(&self) -> Result<String, Error>
pub async fn scanner_parameters(&self) -> Result<String, Error>
Requests an XML list of scanner parameters valid in TWS.
§Examples
use ibapi::prelude::*;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let xml = client.scanner_parameters().await.expect("scanner_parameters failed");
println!("scanner parameters: {} chars", xml.len());
}pub async fn scanner_subscription(
&self,
subscription: &ScannerSubscription,
filter: &[TagValue],
) -> Result<Subscription<Vec<ScannerData>>, Error>
pub async 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::prelude::*;
use ibapi::scanner::ScannerSubscription;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.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());
let filter: Vec<ibapi::contracts::TagValue> = Vec::new();
let subscription = client
.scanner_subscription(&sub, &filter)
.await
.expect("scanner_subscription failed");
// Take the first batch of results, if any.
let mut data = subscription.filter_data();
if let Some(batch) = data.next().await {
match batch {
Ok(rows) => {
for row in rows {
println!(
"rank: {}, symbol: {}",
row.rank, row.contract_details.contract.symbol
);
}
}
Err(e) => eprintln!("scanner error: {e:?}"),
}
}
}pub async fn wsh_metadata(&self) -> Result<WshMetadata, Error>
pub async fn wsh_metadata(&self) -> Result<WshMetadata, Error>
Fetch Wall Street Horizon metadata table with retry semantics.
§Examples
use ibapi::prelude::*;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let metadata = client.wsh_metadata().await.expect("request wsh metadata failed");
println!("{metadata:?}");
}pub async fn wsh_event_data_by_contract(
&self,
contract_id: i32,
start_date: Option<Date>,
end_date: Option<Date>,
limit: Option<i32>,
auto_fill: Option<AutoFill>,
) -> Result<WshEventData, Error>
pub async fn wsh_event_data_by_contract( &self, contract_id: i32, start_date: Option<Date>, end_date: Option<Date>, limit: Option<i32>, auto_fill: Option<AutoFill>, ) -> Result<WshEventData, Error>
Fetch WSH event data filtered by contract identifier.
§Arguments
contract_id- Contract identifier for the event request.start_date- Start date of the event request.end_date- End date of the event request.limit- Maximum number of events to return. Maximum of 100.auto_fill- Fields to automatically fill in. See [AutoFill] for more information.
§Examples
use ibapi::prelude::*;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let contract_id = 76792991; // TSLA
let event_data = client
.wsh_event_data_by_contract(contract_id, None, None, None, None)
.await
.expect("request wsh event data failed");
println!("{event_data:?}");
}pub async fn wsh_event_data_by_filter(
&self,
filter: &str,
limit: Option<i32>,
auto_fill: Option<AutoFill>,
) -> Result<Subscription<WshEventData>, Error>
pub async fn wsh_event_data_by_filter( &self, filter: &str, limit: Option<i32>, auto_fill: Option<AutoFill>, ) -> Result<Subscription<WshEventData>, Error>
Subscribe to WSH event data using a filter expression.
§Arguments
filter- JSON-formatted string containing all filter values.limit- Maximum number of events to return. Maximum of 100.auto_fill- Fields to automatically fill in. See [AutoFill] for more information.
§Examples
use ibapi::prelude::*;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.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, None, None)
.await
.expect("request wsh event data failed");
let mut data = subscription.filter_data();
while let Some(result) = data.next().await {
println!("{result:?}");
}
}Trait Implementations§
Auto Trait Implementations§
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more