pub struct Client { /* private fields */ }Expand description
TWS API Client. Manages the connection to TWS or Gateway. Tracks some global information such as server version and server time. Supports generation of order ids
Implementations§
source§impl Client
impl Client
sourcepub fn connect(address: &str, client_id: i32) -> Result<Client, Error>
pub fn connect(address: &str, client_id: i32) -> Result<Client, Error>
Establishes 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;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
println!("server_version: {}", client.server_version());
println!("connection_time: {}", client.connection_time());
println!("managed_accounts: {}", client.managed_accounts());
println!("next_order_id: {}", client.next_order_id());sourcepub fn next_request_id(&self) -> i32
pub fn next_request_id(&self) -> i32
Returns the next request ID.
sourcepub fn next_order_id(&self) -> i32
pub fn next_order_id(&self) -> i32
Returns and increments the order ID.
pub fn server_version(&self) -> i32
sourcepub fn connection_time(&self) -> &OffsetDateTime
pub fn connection_time(&self) -> &OffsetDateTime
The time of the server when the client connected
sourcepub fn managed_accounts(&self) -> String
pub fn managed_accounts(&self) -> String
Returns the managed accounts.
sourcepub fn positions<'a>(
&'a self
) -> Result<impl Iterator<Item = Position> + 'a, Error>
pub fn positions<'a>( &'a self ) -> Result<impl Iterator<Item = Position> + 'a, Error>
Get current Positions for all accessible accounts.
sourcepub fn contract_details(
&self,
contract: &Contract
) -> Result<impl Iterator<Item = ContractDetails>, Error>
pub fn contract_details( &self, contract: &Contract ) -> Result<impl Iterator<Item = ContractDetails>, Error>
Requests contract information.
Provides all the contracts matching the contract provided. It can also be used to retrieve complete options and futures chains. Though it is now (in API version > 9.72.12) advised to use reqSecDefOptParams for that purpose.
Arguments
contract- The Contract used as sample to query the available contracts. Typically, it will contain the Contract’s symbol, currency, security_type, and exchange.
Examples
use ibapi::Client;
use ibapi::contracts::Contract;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("TSLA");
let results = client.contract_details(&contract).expect("request failed");
for contract_detail in results {
println!("contract: {:?}", contract_detail);
}sourcepub fn market_rule(&self, market_rule_id: i32) -> Result<MarketRule, Error>
pub fn market_rule(&self, market_rule_id: i32) -> Result<MarketRule, Error>
Requests details about a given market rule
The market rule for an instrument on a particular exchange provides details about how the minimum price increment changes with price. A list of market rule ids can be obtained by invoking Self::contract_details() for a particular contract. The returned market rule ID list will provide the market rule ID for the instrument in the correspond valid exchange list in contracts::ContractDetails.
sourcepub fn matching_symbols(
&self,
pattern: &str
) -> Result<impl Iterator<Item = ContractDescription>, Error>
pub fn matching_symbols( &self, pattern: &str ) -> Result<impl Iterator<Item = ContractDescription>, Error>
Requests matching stock symbols.
Arguments
pattern- Either start of ticker symbol or (for larger strings) company name.
Examples
use ibapi::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contracts = client.matching_symbols("IB").expect("request failed");
for contract in contracts {
println!("contract: {:?}", contract);
}sourcepub fn all_open_orders(
&self
) -> Result<impl Iterator<Item = OrderDataResult>, Error>
pub fn all_open_orders( &self ) -> Result<impl Iterator<Item = OrderDataResult>, Error>
Requests all current open orders in associated accounts at the current moment. Open orders are returned once; this function does not initiate a subscription.
Examples
use ibapi::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let results = client.all_open_orders().expect("request failed");
for order_data in results {
println!("{order_data:?}")
}sourcepub fn auto_open_orders(
&self,
auto_bind: bool
) -> Result<impl Iterator<Item = OrderDataResult>, Error>
pub fn auto_open_orders( &self, auto_bind: bool ) -> Result<impl Iterator<Item = OrderDataResult>, Error>
Requests status updates about future orders placed from TWS. Can only be used with client ID 0.
Arguments
auto_bind- if set to true, the newly created orders will be assigned an API order ID and implicitly associated with this client. If set to false, future orders will not be.
Examples
use ibapi::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let results = client.auto_open_orders(false).expect("request failed");
for order_data in results {
println!("{order_data:?}")
}sourcepub fn cancel_order(
&self,
order_id: i32,
manual_order_cancel_time: &str
) -> Result<impl Iterator<Item = CancelOrderResult>, Error>
pub fn cancel_order( &self, order_id: i32, manual_order_cancel_time: &str ) -> Result<impl Iterator<Item = CancelOrderResult>, Error>
Cancels an open Order.
Arguments
order_id- ID of Order to cancel.manual_order_cancel_time- can’t find documentation. leave blank.
Examples
use ibapi::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let order_id = 15;
let results = client.cancel_order(order_id, "").expect("request failed");
for result in results {
println!("{result:?}");
}sourcepub fn completed_orders(
&self,
api_only: bool
) -> Result<impl Iterator<Item = OrderDataResult>, Error>
pub fn completed_orders( &self, api_only: bool ) -> Result<impl Iterator<Item = OrderDataResult>, Error>
Requests completed Orders.
Arguments
api_only- request only orders placed by the API.
Examples
use ibapi::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let results = client.completed_orders(false).expect("request failed");
for order_data in results {
println!("{order_data:?}")
}sourcepub fn executions(
&self,
filter: ExecutionFilter
) -> Result<impl Iterator<Item = ExecutionDataResult>, Error>
pub fn executions( &self, filter: ExecutionFilter ) -> Result<impl Iterator<Item = ExecutionDataResult>, Error>
Requests current day’s (since midnight) executions matching the filter.
Only the current day’s executions can be retrieved. Along with the orders::ExecutionData, the orders::CommissionReport will also be returned. When requesting executions, a filter can be specified to receive only a subset of them
Arguments
filter- filter criteria used to determine which execution reports are returned
Examples
use ibapi::Client;
use ibapi::orders::ExecutionFilter;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let filter = ExecutionFilter{
side: "BUY".to_owned(),
..ExecutionFilter::default()
};
let executions = client.executions(filter).expect("request failed");
for execution_data in executions {
println!("{execution_data:?}")
}sourcepub fn global_cancel(&self) -> Result<(), Error>
pub fn global_cancel(&self) -> Result<(), Error>
sourcepub fn next_valid_order_id(&self) -> Result<i32, Error>
pub fn next_valid_order_id(&self) -> Result<i32, Error>
sourcepub fn open_orders(
&self
) -> Result<impl Iterator<Item = OrderDataResult>, Error>
pub fn open_orders( &self ) -> Result<impl Iterator<Item = OrderDataResult>, Error>
Requests all open orders places by this specific API client (identified by the API client id). For client ID 0, this will bind previous manual TWS orders.
Examples
use ibapi::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let results = client.open_orders().expect("request failed");
for order_data in results {
println!("{order_data:?}")
}sourcepub fn place_order(
&self,
order_id: i32,
contract: &Contract,
order: &Order
) -> Result<impl Iterator<Item = OrderNotification>, Error>
pub fn place_order( &self, order_id: i32, contract: &Contract, order: &Order ) -> Result<impl Iterator<Item = OrderNotification>, Error>
Submits an Order.
Submits an Order using Client for the given Contract. Immediately after the order was submitted correctly, the TWS will start sending events concerning the order’s activity via IBApi.EWrapper.openOrder and IBApi.EWrapper.orderStatus
Arguments
order_id- ID for Order. Get next valid ID using Client::next_order_id.contract- Contract to submit order for.order- Order to submit.
Examples
use ibapi::Client;
use ibapi::contracts::Contract;
use ibapi::orders::{order_builder, Action, OrderNotification};
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("MSFT");
let order = order_builder::market_order(Action::Buy, 100.0);
let order_id = client.next_order_id();
let notifications = client.place_order(order_id, &contract, &order).expect("request failed");
for notification in notifications {
match notification {
OrderNotification::OrderStatus(order_status) => {
println!("order status: {order_status:?}")
}
OrderNotification::OpenOrder(open_order) => println!("open order: {open_order:?}"),
OrderNotification::ExecutionData(execution) => println!("execution: {execution:?}"),
OrderNotification::CommissionReport(report) => println!("commission report: {report:?}"),
OrderNotification::Message(message) => println!("message: {message:?}"),
}
}sourcepub fn head_timestamp(
&self,
contract: &Contract,
what_to_show: WhatToShow,
use_rth: bool
) -> Result<OffsetDateTime, Error>
pub fn head_timestamp( &self, contract: &Contract, what_to_show: WhatToShow, use_rth: bool ) -> Result<OffsetDateTime, Error>
Returns the timestamp of earliest available historical data for a contract and data type.
use ibapi::Client;
use ibapi::contracts::Contract;
use ibapi::market_data::historical::{self, WhatToShow};
let mut client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("MSFT");
let what_to_show = WhatToShow::Trades;
let use_rth = true;
let result = client.head_timestamp(&contract, what_to_show, use_rth).expect("head timestamp failed");
print!("head_timestamp: {result:?}");sourcepub fn historical_data(
&self,
contract: &Contract,
interval_end: OffsetDateTime,
duration: Duration,
bar_size: BarSize,
what_to_show: WhatToShow,
use_rth: bool
) -> Result<HistoricalData, Error>
pub fn historical_data( &self, contract: &Contract, interval_end: OffsetDateTime, duration: Duration, bar_size: BarSize, what_to_show: WhatToShow, use_rth: bool ) -> Result<HistoricalData, Error>
Requests interval of historical data ending at specified time for Contract.
Arguments
contract- Contract to retrieve historical::HistoricalData for.interval_end- end date of interval to retrieve historical::HistoricalData for.duration- duration of interval to retrieve historical::HistoricalData for.bar_size- historical::BarSize to return.what_to_show- requested bar type: historical::WhatToShow.use_rth- use regular trading hours.
Examples
use time::macros::datetime;
use ibapi::contracts::Contract;
use ibapi::Client;
use ibapi::market_data::historical::{BarSize, ToDuration, WhatToShow};
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("TSLA");
let historical_data = client
.historical_data(&contract, datetime!(2023-04-15 0:00 UTC), 7.days(), BarSize::Day, WhatToShow::Trades, true)
.expect("historical data request failed");
println!("start_date: {}, end_date: {}", historical_data.start, historical_data.end);
for bar in &historical_data.bars {
println!("{bar:?}");
}sourcepub fn historical_data_ending_now(
&self,
contract: &Contract,
duration: Duration,
bar_size: BarSize,
what_to_show: WhatToShow,
use_rth: bool
) -> Result<HistoricalData, Error>
pub fn historical_data_ending_now( &self, contract: &Contract, duration: Duration, bar_size: BarSize, what_to_show: WhatToShow, use_rth: bool ) -> Result<HistoricalData, Error>
Requests interval of historical data end now for Contract.
Arguments
contract- Contract to retrieve historical::HistoricalData for.duration- duration of interval to retrieve historical::HistoricalData for.bar_size- historical::BarSize to return.what_to_show- requested bar type: historical::WhatToShow.use_rth- use regular trading hours.
Examples
use ibapi::contracts::Contract;
use ibapi::Client;
use ibapi::market_data::historical::{BarSize, ToDuration, WhatToShow};
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("TSLA");
let historical_data = client
.historical_data_ending_now(&contract, 7.days(), BarSize::Day, WhatToShow::Trades, true)
.expect("historical data request failed");
println!("start_date: {}, end_date: {}", historical_data.start, historical_data.end);
for bar in &historical_data.bars {
println!("{bar:?}");
}sourcepub fn historical_schedules(
&self,
contract: &Contract,
interval_end: OffsetDateTime,
duration: Duration
) -> Result<Schedule, Error>
pub fn historical_schedules( &self, contract: &Contract, interval_end: OffsetDateTime, duration: Duration ) -> Result<Schedule, Error>
Requests [historical::HistoricalSchedule] for an interval of given duration ending at specified date.
Arguments
contract- Contract to retrieve [historical::HistoricalSchedule] for.interval_end- end date of interval to retrieve [historical::HistoricalSchedule] for.duration- duration of interval to retrieve [historical::HistoricalSchedule] for.
Examples
use time::macros::datetime;
use ibapi::contracts::Contract;
use ibapi::Client;
use ibapi::market_data::historical::ToDuration;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("GM");
let historical_data = client
.historical_schedules(&contract, datetime!(2023-04-15 0:00 UTC), 30.days())
.expect("historical schedule request failed");
println!("start: {:?}, end: {:?}", historical_data.start, historical_data.end);
for session in &historical_data.sessions {
println!("{session:?}");
}sourcepub fn historical_schedules_ending_now(
&self,
contract: &Contract,
duration: Duration
) -> Result<Schedule, Error>
pub fn historical_schedules_ending_now( &self, contract: &Contract, duration: Duration ) -> Result<Schedule, Error>
Requests historical::Schedule for interval ending at current time.
Arguments
contract- Contract to retrieve historical::Schedule for.duration- historical::Duration for interval to retrieve historical::Schedule for.
Examples
use ibapi::contracts::Contract;
use ibapi::Client;
use ibapi::market_data::historical::ToDuration;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("GM");
let historical_data = client
.historical_schedules_ending_now(&contract, 30.days())
.expect("historical schedule request failed");
println!("start: {:?}, end: {:?}", historical_data.start, historical_data.end);
for session in &historical_data.sessions {
println!("{session:?}");
}sourcepub fn historical_ticks_bid_ask(
&self,
contract: &Contract,
start: Option<OffsetDateTime>,
end: Option<OffsetDateTime>,
number_of_ticks: i32,
use_rth: bool,
ignore_size: bool
) -> Result<impl Iterator<Item = TickBidAsk>, Error>
pub fn historical_ticks_bid_ask( &self, contract: &Contract, start: Option<OffsetDateTime>, end: Option<OffsetDateTime>, number_of_ticks: i32, use_rth: bool, ignore_size: bool ) -> Result<impl Iterator<Item = TickBidAsk>, Error>
Requests historical time & sales data (Bid/Ask) for an instrument.
Arguments
contract- Contract object that is subject of querystart- Start time. Either start time or end time is specified.end- End time. Either start time or end time is specified.number_of_ticks- Number of distinct data points. Max currently 1000 per request.use_rth- Data from regular trading hours (true), or all available hours (false)ignore_size- A filter only used when the source price is Bid_Ask
Examples
use time::macros::datetime;
use ibapi::contracts::Contract;
use ibapi::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("TSLA");
let ticks = client
.historical_ticks_bid_ask(&contract, Some(datetime!(2023-04-15 0:00 UTC)), None, 100, true, false)
.expect("historical ticks request failed");
for tick in ticks {
println!("{tick:?}");
}sourcepub fn historical_ticks_mid_point(
&self,
contract: &Contract,
start: Option<OffsetDateTime>,
end: Option<OffsetDateTime>,
number_of_ticks: i32,
use_rth: bool
) -> Result<impl Iterator<Item = TickMidpoint>, Error>
pub fn historical_ticks_mid_point( &self, contract: &Contract, start: Option<OffsetDateTime>, end: Option<OffsetDateTime>, number_of_ticks: i32, use_rth: bool ) -> Result<impl Iterator<Item = TickMidpoint>, Error>
Requests historical time & sales data (Midpoint) for an instrument.
Arguments
contract- Contract object that is subject of querystart- Start time. Either start time or end time is specified.end- End time. Either start time or end time is specified.number_of_ticks- Number of distinct data points. Max currently 1000 per request.use_rth- Data from regular trading hours (true), or all available hours (false)
Examples
use time::macros::datetime;
use ibapi::contracts::Contract;
use ibapi::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("TSLA");
let ticks = client
.historical_ticks_mid_point(&contract, Some(datetime!(2023-04-15 0:00 UTC)), None, 100, true)
.expect("historical ticks request failed");
for tick in ticks {
println!("{tick:?}");
}sourcepub fn historical_ticks_trade(
&self,
contract: &Contract,
start: Option<OffsetDateTime>,
end: Option<OffsetDateTime>,
number_of_ticks: i32,
use_rth: bool
) -> Result<impl Iterator<Item = TickLast>, Error>
pub fn historical_ticks_trade( &self, contract: &Contract, start: Option<OffsetDateTime>, end: Option<OffsetDateTime>, number_of_ticks: i32, use_rth: bool ) -> Result<impl Iterator<Item = TickLast>, Error>
Requests historical time & sales data (Trades) for an instrument.
Arguments
contract- Contract object that is subject of querystart- Start time. Either start time or end time is specified.end- End time. Either start time or end time is specified.number_of_ticks- Number of distinct data points. Max currently 1000 per request.use_rth- Data from regular trading hours (true), or all available hours (false)
Examples
use time::macros::datetime;
use ibapi::contracts::Contract;
use ibapi::Client;
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("TSLA");
let ticks = client
.historical_ticks_trade(&contract, Some(datetime!(2023-04-15 0:00 UTC)), None, 100, true)
.expect("historical ticks request failed");
for tick in ticks {
println!("{tick:?}");
}sourcepub fn realtime_bars<'a>(
&'a self,
contract: &Contract,
bar_size: BarSize,
what_to_show: WhatToShow,
use_rth: bool
) -> Result<impl Iterator<Item = Bar> + 'a, Error>
pub fn realtime_bars<'a>( &'a self, contract: &Contract, bar_size: BarSize, what_to_show: WhatToShow, use_rth: bool ) -> Result<impl Iterator<Item = Bar> + 'a, Error>
Requests realtime bars.
This method will provide all the contracts matching the contract provided. It can also be used to retrieve complete options and futures chains. Though it is now (in API version > 9.72.12) advised to use reqSecDefOptParams for that purpose.
Arguments
contract- The Contract used as sample to query the available contracts. Typically, it will contain the Contract’s symbol, currency, security_type, and exchange.
Examples
use ibapi::Client;
use ibapi::contracts::Contract;
use ibapi::market_data::realtime::{BarSize, WhatToShow};
let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
let contract = Contract::stock("TSLA");
let bars = client.realtime_bars(&contract, BarSize::Sec5, WhatToShow::Trades, false).expect("request failed");
for (i, bar) in bars.enumerate().take(60) {
println!("bar[{i}]: {bar:?}");
}