pub struct Client { /* private fields */ }Expand description
Asynchronous TWS API Client
Implementations§
Source§impl Client
impl Client
Sourcepub async fn connect(address: &str, client_id: i32) -> Result<Client, Error>
pub async fn connect(address: &str, client_id: i32) -> Result<Client, Error>
Establishes async connection to TWS or Gateway
Connects to server using the given connection string
§Arguments
address- address of server. e.g. 127.0.0.1:4002client_id- id of client. e.g. 100
§Examples
use ibapi::Client;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.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 server_version(&self) -> i32
pub fn server_version(&self) -> i32
Returns the server version
Sourcepub fn connection_time(&self) -> Option<OffsetDateTime>
pub fn connection_time(&self) -> Option<OffsetDateTime>
Returns the connection time
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;
#[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");
}
}Sourcepub fn next_order_id(&self) -> i32
pub fn next_order_id(&self) -> i32
Returns the next order ID
Sourcepub fn next_request_id(&self) -> i32
pub fn next_request_id(&self) -> i32
Returns the next request ID
Sourcepub fn order<'a>(&'a self, contract: &'a Contract) -> OrderBuilder<'a, Self>
pub fn order<'a>(&'a self, contract: &'a Contract) -> OrderBuilder<'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.
§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");
}Sourcepub 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
Sourcepub async fn server_time(&self) -> Result<OffsetDateTime, Error>
pub async fn server_time(&self) -> Result<OffsetDateTime, Error>
Requests the current server time.
§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:?}");
}Sourcepub async fn positions(&self) -> Result<Subscription<PositionUpdate>, Error>
pub async fn positions(&self) -> Result<Subscription<PositionUpdate>, Error>
Subscribes to position updates for all accessible accounts. All positions sent initially, and then only updates as positions change.
§Examples
use ibapi::Client;
use ibapi::accounts::PositionUpdate;
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(position_response) = subscription.next().await {
match position_response {
Ok(PositionUpdate::Position(position)) => println!("{position:?}"),
Ok(PositionUpdate::PositionEnd) => println!("initial set of positions received"),
Err(e) => eprintln!("Error: {e}"),
}
}
}Sourcepub 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>
Subscribes to position 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;
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:?}")
}
}Sourcepub 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>
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;
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:?}")
}
}Sourcepub 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>
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;
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:?}")
}
}Sourcepub 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>
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.
§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;
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:?}")
}
}Sourcepub async fn account_updates(
&self,
account: &AccountId,
) -> Result<Subscription<AccountUpdate>, Error>
pub async 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. Only one account can be subscribed at a time.
§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 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(update_result) = subscription.next().await {
match update_result {
Ok(update) => {
println!("{update:?}");
// stop after full initial update
if let AccountUpdate::End = update {
break;
}
}
Err(e) => eprintln!("Error: {e}"),
}
}
}Sourcepub 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>
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. Only one account can be subscribed at a time.
§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 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(update_result) = subscription.next().await {
match update_result {
Ok(update) => {
println!("{update:?}");
// stop after full initial update
if let AccountUpdateMulti::End = update {
break;
}
}
Err(e) => eprintln!("Error: {e}"),
}
}
}Sourcepub async fn managed_accounts(&self) -> Result<Vec<String>, Error>
pub async fn managed_accounts(&self) -> Result<Vec<String>, Error>
Requests the accounts to which the logged user has access to.
§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:?}")
}Sourcepub async fn family_codes(&self) -> Result<Vec<FamilyCode>, Error>
pub async fn family_codes(&self) -> Result<Vec<FamilyCode>, Error>
Get current family codes for all accessible accounts.
§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:?}")
}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>
Creates a market data subscription builder with a fluent interface.
This is the preferred way to subscribe to market data, providing a more intuitive and discoverable API than the raw method.
§Arguments
contract- The contract to receive market data for
§Examples
use ibapi::prelude::*;
use ibapi::client::r#async::Client;
#[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();
// Subscribe to real-time streaming data with specific tick types
let mut subscription = client.market_data(&contract)
.generic_ticks(&["233", "236"]) // RTVolume and Shortable
.subscribe()
.await
.expect("subscription failed");
while let Some(tick) = subscription.next().await {
match tick {
Ok(TickTypes::Price(price)) => println!("Price: {price:?}"),
Ok(TickTypes::Size(size)) => println!("Size: {size:?}"),
Ok(TickTypes::SnapshotEnd) => break,
Err(e) => eprintln!("Error: {e:?}"),
_ => {}
}
}
}Sourcepub async fn realtime_bars(
&self,
contract: &Contract,
bar_size: BarSize,
what_to_show: WhatToShow,
trading_hours: TradingHours,
) -> Result<Subscription<Bar>, Error>
pub async fn realtime_bars( &self, contract: &Contract, bar_size: BarSize, what_to_show: WhatToShow, trading_hours: TradingHours, ) -> Result<Subscription<Bar>, Error>
Requests real time bars Currently, only 5 seconds bars are provided.
§Arguments
contract- The Contract for which the depth is being requestedbar_size- Currently being ignoredwhat_to_show- The nature of the data being retrieved (TRADES, MIDPOINT, BID, ASK)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::realtime::{BarSize, WhatToShow};
use ibapi::market_data::TradingHours;
use futures::StreamExt;
#[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, BarSize::Sec5, WhatToShow::Trades, TradingHours::Extended)
.await
.expect("request failed");
while let Some(bar_result) = subscription.next().await {
match bar_result {
Ok(bar) => println!("{bar:?}"),
Err(e) => eprintln!("Error: {e:?}"),
}
}
}Sourcepub async fn tick_by_tick_all_last(
&self,
contract: &Contract,
number_of_ticks: i32,
ignore_size: bool,
) -> Result<Subscription<Trade>, Error>
pub async fn tick_by_tick_all_last( &self, contract: &Contract, number_of_ticks: i32, ignore_size: bool, ) -> Result<Subscription<Trade>, Error>
Requests tick by tick AllLast ticks.
§Arguments
contract- The Contract for which tick-by-tick data is requested.number_of_ticks- Number of historical ticks to return from the TWS’s historical database. Max value is 1000.ignore_size- Ignore size flag.
§Examples
use ibapi::Client;
use ibapi::contracts::Contract;
use futures::StreamExt;
#[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
.tick_by_tick_all_last(&contract, 0, false)
.await
.expect("request failed");
while let Some(trade_result) = subscription.next().await {
match trade_result {
Ok(trade) => println!("Trade: {} - ${} x {} on {}",
trade.time, trade.price, trade.size, trade.exchange),
Err(e) => eprintln!("Error: {e:?}"),
}
}
}Sourcepub async fn tick_by_tick_last(
&self,
contract: &Contract,
number_of_ticks: i32,
ignore_size: bool,
) -> Result<Subscription<Trade>, Error>
pub async fn tick_by_tick_last( &self, contract: &Contract, number_of_ticks: i32, ignore_size: bool, ) -> Result<Subscription<Trade>, Error>
Requests tick by tick Last ticks.
§Arguments
contract- The Contract for which tick-by-tick data is requested.number_of_ticks- Number of historical ticks to return from the TWS’s historical database. Max value is 1000.ignore_size- Ignore size flag.
Sourcepub async fn tick_by_tick_bid_ask(
&self,
contract: &Contract,
number_of_ticks: i32,
ignore_size: bool,
) -> Result<Subscription<BidAsk>, Error>
pub async fn tick_by_tick_bid_ask( &self, contract: &Contract, number_of_ticks: i32, ignore_size: bool, ) -> Result<Subscription<BidAsk>, Error>
Requests tick by tick BidAsk ticks.
§Arguments
contract- The Contract for which tick-by-tick data is requested.number_of_ticks- Number of historical ticks to return from the TWS’s historical database. Max value is 1000.ignore_size- Ignore size flag.
§Examples
use ibapi::Client;
use ibapi::contracts::Contract;
use futures::StreamExt;
#[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
.tick_by_tick_bid_ask(&contract, 0, false)
.await
.expect("request failed");
while let Some(quote_result) = subscription.next().await {
match quote_result {
Ok(quote) => println!("Quote: {} - Bid: ${} x {} | Ask: ${} x {}",
quote.time, quote.bid_price, quote.bid_size,
quote.ask_price, quote.ask_size),
Err(e) => eprintln!("Error: {e:?}"),
}
}
}Sourcepub async fn tick_by_tick_midpoint(
&self,
contract: &Contract,
number_of_ticks: i32,
ignore_size: bool,
) -> Result<Subscription<MidPoint>, Error>
pub async fn tick_by_tick_midpoint( &self, contract: &Contract, number_of_ticks: i32, ignore_size: bool, ) -> Result<Subscription<MidPoint>, Error>
Requests tick by tick MidPoint ticks.
§Arguments
contract- The Contract for which tick-by-tick data is requested.number_of_ticks- Number of historical ticks to return from the TWS’s historical database. Max value is 1000.ignore_size- Ignore size flag.
Sourcepub async fn market_depth(
&self,
contract: &Contract,
number_of_rows: i32,
is_smart_depth: bool,
) -> Result<Subscription<MarketDepths>, Error>
pub async fn market_depth( &self, contract: &Contract, number_of_rows: i32, is_smart_depth: bool, ) -> Result<Subscription<MarketDepths>, Error>
Requests the contract’s market depth (order book).
This request returns the full available market depth and updates whenever there’s a change in the order book. Market depth data is not available for all instruments. Check the TWS Contract Details under “Market Data Availability” - “Deep Book” field before requesting market depth.
§Arguments
contract- The Contract for which the depth is being requestednumber_of_rows- The number of rows on each side of the order book (max 50)is_smart_depth- Flag indicates that this is smart depth request
§Examples
use ibapi::Client;
use ibapi::contracts::Contract;
use ibapi::market_data::realtime::MarketDepths;
use futures::StreamExt;
#[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, false)
.await
.expect("request failed");
while let Some(depth_result) = subscription.next().await {
match depth_result {
Ok(MarketDepths::MarketDepth(depth)) => {
let side = if depth.side == 1 { "Bid" } else { "Ask" };
let operation = match depth.operation {
0 => "Insert",
1 => "Update",
2 => "Delete",
_ => "Unknown",
};
println!("{} {} at position {} - Price: ${}, Size: {}",
operation, side, depth.position, depth.price, depth.size);
}
Ok(MarketDepths::Notice(notice)) => println!("Notice: {}", notice.message),
_ => {}
}
}
}Sourcepub 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::Client;
#[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("request failed");
for exchange in exchanges {
println!("{} - {} ({})",
exchange.exchange_name, exchange.security_type, exchange.service_data_type);
}
}Sourcepub 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 market data request.
§Arguments
market_data_type- Type of market data to retrieve.
§Examples
use ibapi::Client;
use ibapi::market_data::{MarketDataType};
#[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:?}");
}Sourcepub 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.
§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 what_to_show = WhatToShow::Trades;
let trading_hours = TradingHours::Regular;
let timestamp = client
.head_timestamp(&contract, what_to_show, trading_hours)
.await
.expect("error requesting head timestamp");
println!("Earliest data available: {timestamp:?}");
}Sourcepub async fn historical_data(
&self,
contract: &Contract,
end_date: Option<OffsetDateTime>,
duration: Duration,
bar_size: BarSize,
what_to_show: Option<WhatToShow>,
trading_hours: TradingHours,
) -> Result<HistoricalData, Error>
pub async fn historical_data( &self, contract: &Contract, end_date: Option<OffsetDateTime>, duration: Duration, bar_size: BarSize, what_to_show: Option<WhatToShow>, trading_hours: TradingHours, ) -> Result<HistoricalData, Error>
Requests historical bars data.
When requesting historical data, a finishing time and date is required along with a duration string. For example, having: end_date = 20130701 23:59:59 GMT and duration = 3 D will return three days of data counting backwards from July 1st 2013 at 23:59:59 GMT resulting in all the available bars of the last three days until the date and time specified.
§Arguments
contract- The contract for which we want to retrieve the data.end_date- Request’s ending time. If None, current time is used.duration- The amount of time for which the data needs to be retrieved.bar_size- The bar size.what_to_show- The kind of information being retrieved.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 time::macros::datetime;
use ibapi::contracts::Contract;
use ibapi::Client;
use ibapi::market_data::historical::{BarSize, ToDuration, 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("TSLA").build();
let interval_end = Some(datetime!(2023-04-11 20:00 UTC));
let duration = 5.days();
let bar_size = BarSize::Hour;
let what_to_show = Some(WhatToShow::Trades);
let trading_hours = TradingHours::Regular;
let historical_data = client
.historical_data(&contract, interval_end, duration, bar_size, what_to_show, trading_hours)
.await
.expect("historical bars request failed");
println!("start: {}, end: {}", historical_data.start, historical_data.end);
for bar in &historical_data.bars {
println!("{bar:?}")
}
}Sourcepub async fn historical_schedule(
&self,
contract: &Contract,
end_date: Option<OffsetDateTime>,
duration: Duration,
) -> Result<Schedule, Error>
pub async fn historical_schedule( &self, contract: &Contract, end_date: Option<OffsetDateTime>, duration: Duration, ) -> Result<Schedule, Error>
Requests historical schedule.
§Arguments
contract- Contract object for which trading schedule is requested.end_date- Request’s ending date. If None, current time is used.duration- The amount of time for which the data needs to be retrieved.
§Examples
use time::macros::datetime;
use ibapi::contracts::Contract;
use ibapi::Client;
use ibapi::market_data::historical::ToDuration;
#[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 end_date = Some(datetime!(2022-11-21 00:00 UTC));
let duration = 30.days();
let schedule = client
.historical_schedule(&contract, end_date, duration)
.await
.expect("error requesting historical schedule");
println!("Trading schedule from {} to {}", schedule.start, schedule.end);
for session in &schedule.sessions {
println!(" {} - Trading: {} to {}",
session.reference, session.start, session.end);
}
}Sourcepub async fn historical_ticks_bid_ask(
&self,
contract: &Contract,
start: Option<OffsetDateTime>,
end: Option<OffsetDateTime>,
number_of_ticks: i32,
trading_hours: TradingHours,
ignore_size: bool,
) -> Result<TickSubscription<TickBidAsk>, Error>
pub async fn historical_ticks_bid_ask( &self, contract: &Contract, start: Option<OffsetDateTime>, end: Option<OffsetDateTime>, number_of_ticks: i32, trading_hours: TradingHours, ignore_size: bool, ) -> Result<TickSubscription<TickBidAsk>, Error>
Requests historical bid/ask tick data.
§Arguments
contract- Contract object that is subject of querystart- Start timestamp. Either start or end must be specified.end- End timestamp. Either start or end must be specified.number_of_ticks- Number of ticks to retrievetrading_hours- Regular trading hours only, or include extended hoursignore_size- Ignore size flag
§Examples
use time::macros::datetime;
use ibapi::contracts::Contract;
use ibapi::Client;
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 start = Some(datetime!(2022-11-07 16:00 UTC));
let end = Some(datetime!(2022-11-07 17:00 UTC));
let number_of_ticks = 1000;
let trading_hours = TradingHours::Regular;
let ignore_size = false;
let mut subscription = client
.historical_ticks_bid_ask(&contract, start, end, number_of_ticks, trading_hours, ignore_size)
.await
.expect("error requesting historical ticks");
while let Some(tick) = subscription.next().await {
println!("Bid/Ask tick: {} - Bid: ${} x {} | Ask: ${} x {}",
tick.timestamp, tick.price_bid, tick.size_bid,
tick.price_ask, tick.size_ask);
}
}Sourcepub async fn historical_ticks_mid_point(
&self,
contract: &Contract,
start: Option<OffsetDateTime>,
end: Option<OffsetDateTime>,
number_of_ticks: i32,
trading_hours: TradingHours,
) -> Result<TickSubscription<TickMidpoint>, Error>
pub async fn historical_ticks_mid_point( &self, contract: &Contract, start: Option<OffsetDateTime>, end: Option<OffsetDateTime>, number_of_ticks: i32, trading_hours: TradingHours, ) -> Result<TickSubscription<TickMidpoint>, Error>
Requests historical midpoint tick data.
§Arguments
contract- Contract object that is subject of querystart- Start timestamp. Either start or end must be specified.end- End timestamp. Either start or end must be specified.number_of_ticks- Number of ticks to retrievetrading_hours- Regular trading hours only, or include extended hours
Sourcepub async fn historical_ticks_trade(
&self,
contract: &Contract,
start: Option<OffsetDateTime>,
end: Option<OffsetDateTime>,
number_of_ticks: i32,
trading_hours: TradingHours,
) -> Result<TickSubscription<TickLast>, Error>
pub async fn historical_ticks_trade( &self, contract: &Contract, start: Option<OffsetDateTime>, end: Option<OffsetDateTime>, number_of_ticks: i32, trading_hours: TradingHours, ) -> Result<TickSubscription<TickLast>, Error>
Requests historical trade tick data.
§Arguments
contract- Contract object that is subject of querystart- Start timestamp. Either start or end must be specified.end- End timestamp. Either start or end must be specified.number_of_ticks- Number of ticks to retrievetrading_hours- Regular trading hours only, or include extended hours
Sourcepub 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>
Returns histogram of market data for a contract.
§Arguments
contract- Contract object for which histogram is being requestedtrading_hours- Regular trading hours only, or include extended hoursperiod- Period of which data is being requested
§Examples
use time::macros::datetime;
use ibapi::contracts::Contract;
use ibapi::Client;
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 trading_hours = TradingHours::Regular;
let period = BarSize::Week;
let histogram = client
.histogram_data(&contract, trading_hours, period)
.await
.expect("error requesting histogram");
for entry in &histogram {
println!("Price: ${} - Count: {}", entry.price, entry.size);
}
}Sourcepub async fn wsh_metadata(&self) -> Result<WshMetadata, Error>
pub async fn wsh_metadata(&self) -> Result<WshMetadata, Error>
Requests Wall Street Horizon metadata information.
§Examples
use ibapi::Client;
#[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("error requesting wsh metadata");
println!("wsh metadata: {metadata:?}")
}Sourcepub 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>
Requests event data for a specified contract from the Wall Street Horizons (WSH) calendar.
§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- Number of events to return.auto_fill- Autofill configuration for watchlist, portfolio, and position.
§Examples
use ibapi::Client;
use time::macros::date;
use ibapi::wsh::AutoFill;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let contract_id = 12345;
let start_date = Some(date!(2024-01-01));
let end_date = Some(date!(2024-12-31));
let limit = Some(100);
let auto_fill = Some(AutoFill {
competitors: true,
portfolio: false,
watchlist: false,
});
let event_data = client
.wsh_event_data_by_contract(contract_id, start_date, end_date, limit, auto_fill)
.await
.expect("error requesting wsh event data");
println!("wsh event data: {event_data:?}")
}Sourcepub 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>
Requests event data using a filter from the Wall Street Horizons (WSH) calendar.
§Arguments
filter- Filter for the event request (e.g. JSON-encoded string).limit- Number of events to return.auto_fill- Autofill configuration for watchlist, portfolio, and position.
§Examples
use ibapi::Client;
use ibapi::wsh::AutoFill;
use futures::StreamExt;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let filter = r#"{"country": "US"}"#;
let limit = Some(100);
let auto_fill = Some(AutoFill {
competitors: true,
portfolio: false,
watchlist: false,
});
let mut event_data_subscription = client
.wsh_event_data_by_filter(filter, limit, auto_fill)
.await
.expect("error requesting wsh event data");
while let Some(event_data) = event_data_subscription.next().await {
println!("{event_data:?}")
}
}Sourcepub async fn contract_details(
&self,
contract: &Contract,
) -> Result<Vec<ContractDetails>, Error>
pub async fn contract_details( &self, contract: &Contract, ) -> Result<Vec<ContractDetails>, Error>
Requests detailed contract information for matching contracts.
This function returns all contracts that match the provided contract sample. It can be used to retrieve complete options and futures chains.
§Arguments
contract- The Contract used as a sample to query 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);
}
}Sourcepub async fn matching_symbols(
&self,
pattern: &str,
) -> Result<Vec<ContractDescription>, Error>
pub async fn matching_symbols( &self, pattern: &str, ) -> Result<Vec<ContractDescription>, Error>
Searches for stock contracts matching the provided pattern.
§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);
}
}Sourcepub 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>
Retrieves market rule details for a specific market rule ID.
Market rules define how minimum price increments change with price. Rule IDs can be obtained from contract details.
§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);
}
}Sourcepub 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 option price based on volatility and underlying price.
§Arguments
contract- The option contractvolatility- Hypothetical volatilityunderlying_price- Hypothetical underlying price
§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 option = Contract::option("AAPL", "20240119", 150.0, "C");
let computation = client.calculate_option_price(&option, 0.3, 145.0).await
.expect("calculation failed");
if let Some(price) = computation.option_price {
println!("Option price: ${:.2}", price);
}
}Sourcepub 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 implied volatility based on option and underlying prices.
§Arguments
contract- The option contractoption_price- Hypothetical option priceunderlying_price- Hypothetical underlying price
§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 option = Contract::option("AAPL", "20240119", 150.0, "C");
let computation = client.calculate_implied_volatility(&option, 7.5, 148.0).await
.expect("calculation failed");
if let Some(iv) = computation.implied_volatility {
println!("Implied volatility: {:.2}%", iv * 100.0);
}
}Sourcepub 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.
Returns option expiration dates and strikes available for the specified underlying.
§Arguments
symbol- The underlying symbolexchange- The exchangesecurity_type- The underlying security typecontract_id- The underlying contract ID
§Examples
use ibapi::Client;
use ibapi::contracts::SecurityType;
use futures::StreamExt;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let mut chain = client.option_chain("AAPL", "SMART", SecurityType::Stock, 265598).await
.expect("request failed");
while let Some(result) = chain.next().await {
match result {
Ok(data) => {
println!("Expirations: {:?}", data.expirations);
println!("Strikes: {:?}", data.strikes);
}
Err(e) => eprintln!("Error: {e:?}"),
}
}
}Sourcepub 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.
This function returns a subscription that will receive updates of activity for all orders placed by the client. Use this when you need a global view of all order activity, especially with submit_order().
§Examples
use futures::StreamExt;
use ibapi::Client;
use ibapi::orders::OrderUpdate;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let mut stream = client.order_update_stream().await.expect("failed to create stream");
while let Some(update) = stream.next().await {
match update {
Ok(OrderUpdate::OrderStatus(status)) => {
println!("Order {} status: {}", status.order_id, status.status);
}
Ok(OrderUpdate::ExecutionData(exec)) => {
println!("Execution: {} shares @ {}", exec.execution.shares, exec.execution.price);
}
_ => {}
}
}
}Sourcepub 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).
After the order is submitted correctly, events will be returned through the order_update_stream(). This is a fire-and-forget method that does not wait for confirmation or return a subscription.
§Arguments
order_id- Unique order identifiercontract- Contract to submit order fororder- Order details
§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 order = client.order(&contract)
.buy(100)
.limit(150.0)
.build_order()
.expect("failed to build order");
let order_id = client.next_order_id();
client.submit_order(order_id, &contract, &order).await.expect("failed to submit order");
}Sourcepub 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.
After the order is submitted correctly, events will be returned concerning the order’s activity through the returned subscription.
§Arguments
order_id- Unique order identifiercontract- Contract to submit order fororder- Order details
§Examples
use futures::StreamExt;
use ibapi::Client;
use ibapi::contracts::Contract;
use ibapi::orders::PlaceOrder;
#[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)
.limit(150.0)
.build_order()
.expect("failed to build order");
let order_id = client.next_order_id();
let mut subscription = client.place_order(order_id, &contract, &order).await
.expect("failed to place order");
while let Some(update) = subscription.next().await {
match update {
Ok(PlaceOrder::OrderStatus(status)) => {
println!("Status: {}", status.status);
if status.status == "Filled" { break; }
}
_ => {}
}
}
}Sourcepub 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.
§Arguments
order_id- Order ID to cancelmanual_order_cancel_time- Time of manual order cancellation (empty string for API cancellations)
Sourcepub async fn global_cancel(&self) -> Result<(), Error>
pub async fn global_cancel(&self) -> Result<(), Error>
Cancels all open Orders.
Sourcepub 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.
Sourcepub 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 Orders.
§Arguments
api_only- If true, only orders placed through the API are returned
Sourcepub 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 (identified by the API client id). For client ID 0, this will bind previous manual TWS orders.
Sourcepub 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 at the current moment. Open orders are returned once; this function does not initiate a subscription.
Sourcepub 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. Can only be used with client ID 0.
§Arguments
auto_bind- If true, newly submitted orders will be implicitly associated with this client
Sourcepub 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 (since midnight) executions matching the filter.
Only the current day’s executions can be retrieved. Along with the ExecutionData, the CommissionReport will also be returned.
§Arguments
filter- Filter criteria used to determine which execution reports are returned
Sourcepub 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>
Exercises an options contract.
§Arguments
contract- Option contract to exerciseexercise_action- Whether to exercise (1) or lapse (2)exercise_quantity- Number of contracts to exerciseaccount- Account for which to exerciseovrd- Override default handling actionmanual_order_time- Time of manual order entry
Sourcepub async fn news_providers(&self) -> Result<Vec<NewsProvider>, Error>
pub async fn news_providers(&self) -> Result<Vec<NewsProvider>, Error>
Requests available news providers.
Returns a list of news providers that the user has subscribed to.
§Examples
use ibapi::Client;
#[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("request failed");
for provider in providers {
println!("{} - {}", provider.code, provider.name);
}
}Sourcepub 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 News Bulletins.
§Arguments
all_messages- If true, returns all messages including exchange availability
§Examples
use ibapi::Client;
use futures::StreamExt;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let mut bulletins = client.news_bulletins(true).await.expect("request failed");
while let Some(result) = bulletins.next().await {
match result {
Ok(bulletin) => println!("{}: {}", bulletin.exchange, bulletin.message),
Err(e) => eprintln!("Error: {e:?}"),
}
}
}Sourcepub 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>
Requests historical news headlines.
§Arguments
contract_id- Contract ID to get news forprovider_codes- List of provider codes to filter bystart_time- Start of the time periodend_time- End of the time periodtotal_results- Maximum number of headlines to return
§Examples
use ibapi::Client;
use futures::StreamExt;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let contract_id = 265598; // AAPL
let providers = &["BRFG", "DJNL"];
let end_time = time::OffsetDateTime::now_utc();
let start_time = end_time - time::Duration::days(7);
let mut news = client
.historical_news(contract_id, providers, start_time, end_time, 100)
.await
.expect("request failed");
while let Some(result) = news.next().await {
match result {
Ok(article) => println!("{}: {}", article.time, article.headline),
Err(e) => eprintln!("Error: {e:?}"),
}
}
}Sourcepub 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 the body of a news article.
§Arguments
provider_code- The news provider codearticle_id- The article ID
§Examples
use ibapi::Client;
#[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$12345").await.expect("request failed");
println!("Article type: {:?}", article.article_type);
println!("Content: {}", article.article_text);
}Sourcepub 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>
Subscribes to real-time news for a specific contract.
§Arguments
contract- The contract to monitorprovider_codes- List of provider codes to subscribe to
§Examples
use ibapi::Client;
use ibapi::contracts::Contract;
use futures::StreamExt;
#[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 providers = &["BRFG", "DJNL"];
let mut news = client.contract_news(&contract, providers).await.expect("request failed");
while let Some(result) = news.next().await {
match result {
Ok(article) => println!("{}: {}", article.time, article.headline),
Err(e) => eprintln!("Error: {e:?}"),
}
}
}Sourcepub 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>
Subscribes to broad tape news from a specific provider.
§Arguments
provider_code- The news provider code
§Examples
use ibapi::Client;
use futures::StreamExt;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let mut news = client.broad_tape_news("BRFG").await.expect("request failed");
while let Some(result) = news.next().await {
match result {
Ok(article) => println!("{}: {}", article.time, article.headline),
Err(e) => eprintln!("Error: {e:?}"),
}
}
}Sourcepub async fn scanner_parameters(&self) -> Result<String, Error>
pub async fn scanner_parameters(&self) -> Result<String, Error>
Requests scanner parameters available in TWS.
Returns an XML string containing all available scanner parameters including scan types, locations, instruments, and filters.
§Examples
use ibapi::Client;
#[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("request failed");
println!("Scanner parameters XML: {} bytes", xml.len());
}Sourcepub async fn scanner_subscription(
&self,
subscription: &ScannerSubscription,
filter: &Vec<TagValue>,
) -> Result<Subscription<Vec<ScannerData>>, Error>
pub async fn scanner_subscription( &self, subscription: &ScannerSubscription, filter: &Vec<TagValue>, ) -> Result<Subscription<Vec<ScannerData>>, Error>
Starts a subscription to market scanner results.
Scans the market based on the specified criteria and returns matching contracts.
§Arguments
subscription- Scanner subscription parameters defining the scan criteriafilter- Additional filters to apply to the scan
§Examples
use ibapi::Client;
use ibapi::scanner::ScannerSubscription;
use futures::StreamExt;
#[tokio::main]
async fn main() {
let client = Client::connect("127.0.0.1:4002", 100).await.expect("connection failed");
let subscription = ScannerSubscription {
number_of_rows: 10,
instrument: Some("STK".to_string()),
location_code: Some("STK.US.MAJOR".to_string()),
scan_code: Some("TOP_PERC_GAIN".to_string()),
above_price: Some(5.0),
..Default::default()
};
let mut scanner = client.scanner_subscription(&subscription, &vec![]).await
.expect("request failed");
while let Some(result) = scanner.next().await {
match result {
Ok(data_list) => {
for data in data_list {
println!("Rank {}: {}", data.rank,
data.contract_details.contract.symbol);
}
}
Err(e) => eprintln!("Error: {e:?}"),
}
}
}Source§impl Client
Extension trait for submitting multiple OCA orders
impl Client
Extension trait for submitting multiple OCA orders
Sourcepub 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");
}