Struct ibapi::Client

source ·
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

source

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:4002
  • client_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());
source

pub fn next_request_id(&self) -> i32

Returns the next request ID.

source

pub fn next_order_id(&self) -> i32

Returns and increments the order ID.

source

pub fn server_version(&self) -> i32

source

pub fn connection_time(&self) -> &OffsetDateTime

The time of the server when the client connected

source

pub fn managed_accounts(&self) -> String

Returns the managed accounts.

source

pub fn positions<'a>( &'a self ) -> Result<impl Iterator<Item = Position> + 'a, Error>

Get current Positions for all accessible accounts.

source

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);
}
source

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.

source

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);
}
source

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:?}")
}
source

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:?}")
}
source

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:?}");
}
source

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:?}")
}
source

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:?}")
}
source

pub fn global_cancel(&self) -> Result<(), Error>

Cancels all open Orders.

Examples
use ibapi::Client;

let mut client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");

client.global_cancel().expect("request failed");
source

pub fn next_valid_order_id(&self) -> Result<i32, Error>

Cancels all open Orders.

Examples
use ibapi::Client;

let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");

let next_valid_order_id = client.next_valid_order_id().expect("request failed");
println!("next_valid_order_id: {next_valid_order_id}");
source

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:?}")
}
source

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
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:?}"),
   }
}
source

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:?}");
source

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
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:?}");
}
source

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
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:?}");
}
source

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:?}");
}
source

pub fn historical_schedules_ending_now( &self, contract: &Contract, duration: Duration ) -> Result<Schedule, Error>

Requests historical::Schedule for interval ending at current time.

Arguments
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:?}");
}
source

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 query
  • start - 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:?}");
}
source

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 query
  • start - 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:?}");
}
source

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 query
  • start - 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:?}");
}
source

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:?}");
}
source

pub fn tick_by_tick_all_last<'a>( &'a self, contract: &Contract, number_of_ticks: i32, ignore_size: bool ) -> Result<impl Iterator<Item = Trade> + 'a, Error>

Requests tick by tick AllLast ticks.

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.
  • number_of_ticks - number of ticks.
  • ignore_size - ignore size flag.
source

pub fn tick_by_tick_bid_ask<'a>( &'a self, contract: &Contract, number_of_ticks: i32, ignore_size: bool ) -> Result<impl Iterator<Item = BidAsk> + 'a, Error>

Requests tick by tick BidAsk ticks.

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.
  • number_of_ticks - number of ticks.
  • ignore_size - ignore size flag.
source

pub fn tick_by_tick_last<'a>( &'a self, contract: &Contract, number_of_ticks: i32, ignore_size: bool ) -> Result<impl Iterator<Item = Trade> + 'a, Error>

Requests tick by tick Last ticks.

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.
  • number_of_ticks - number of ticks.
  • ignore_size - ignore size flag.
source

pub fn tick_by_tick_midpoint<'a>( &'a self, contract: &Contract, number_of_ticks: i32, ignore_size: bool ) -> Result<impl Iterator<Item = MidPoint> + 'a, Error>

Requests tick by tick MidPoint ticks.

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.
  • number_of_ticks - number of ticks.
  • ignore_size - ignore size flag.

Trait Implementations§

source§

impl Debug for Client

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Drop for Client

source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Client

§

impl !Send for Client

§

impl !Sync for Client

§

impl Unpin for Client

§

impl !UnwindSafe for Client

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> Pointable for T

§

const ALIGN: usize = mem::align_of::<T>()

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.