IBX
Direct IB connection engine. No Java Gateway. No middleman. Built in Rust for ultra-low-latency, available as both a Rust crate and a Python wheel.
Why IBX
No JVM, no gateway
Connect straight to the IB servers. No localhost hop, no garbage-collector pauses, no separate process to babysit.
Same API you already know
Drop-in compatible EClient / Wrapper callback shape. Port existing strategies without rewriting them.
Two languages, one core
The Python wheel is built from the same Rust engine via PyO3 — no second implementation, no parity drift.
Built for latency
Hot loop pinned to a core, zero-allocation tick parsing, lock-free dispatch. Tick reads in nanoseconds, not milliseconds.
Where to go next
- New here? → Getting Started — install, credentials, hello-world in both languages.
- Want to see real code? → Recipes for Rust and Python — end-to-end flows with full source from
examples/. - Looking up a specific call? → Rust API · Python API.
- Wondering what's wired up? → Endpoint Coverage.
Project status
IBX is under active development. The Rust and Python APIs track the official IB API surface; gaps are tracked in the Endpoint Coverage chapter.
Getting Started
Install
Rust
[dependencies]
ibx = { git = "https://github.com/deepentropy/ibx" }
Python
pip install git+https://github.com/deepentropy/ibx
Python wheels are built from the same Rust core via PyO3 / maturin. You need a working Rust toolchain to install from source.
Credentials
IBX connects directly to IB servers — there is no separate gateway process. Set your account credentials via environment variables:
export IB_USERNAME="your_username"
export IB_PASSWORD="your_password"
export IB_HOST="cdc1.ibllc.com" # paper-trading host
Never use a live account for testing. Use the paper account for unit and integration tests. The live account is only for read-only validation (login, contract details).
Hello, world
Rust
use ibx::api::client::{EClient, EClientConfig, Contract};
use ibx::api::wrapper::Wrapper;
use ibx::api::types::TickAttrib;
struct MyWrapper;
impl Wrapper for MyWrapper {
fn tick_price(&mut self, req_id: i64, tick_type: i32, price: f64, _: &TickAttrib) {
println!("tick_price req_id={req_id} type={tick_type} price={price}");
}
}
fn main() {
let mut client = EClient::connect(&EClientConfig {
username: std::env::var("IB_USERNAME").unwrap(),
password: std::env::var("IB_PASSWORD").unwrap(),
host: "cdc1.ibllc.com".into(),
paper: true,
core_id: None,
}).unwrap();
let spy = Contract { con_id: 756733, symbol: "SPY".into(), ..Default::default() };
client.req_mkt_data(1, &spy, "", false, false);
std::thread::sleep(std::time::Duration::from_secs(10));
}
Python
import os, threading
from ibx import EClient, EWrapper, Contract
class MyWrapper(EWrapper):
def tick_price(self, req_id, tick_type, price, attrib):
print(f"tick_price req_id={req_id} type={tick_type} price={price}")
w = MyWrapper()
c = EClient(w)
c.connect(
username=os.environ["IB_USERNAME"],
password=os.environ["IB_PASSWORD"],
host="cdc1.ibllc.com",
paper=True,
)
threading.Thread(target=c.run, daemon=True).start()
spy = Contract()
spy.con_id, spy.symbol, spy.sec_type = 756733, "SPY", "STK"
spy.exchange, spy.currency = "SMART", "USD"
c.req_mkt_data(1, spy, "", False)
Next steps
- Login (Rust) · Login (Python) — minimal connect /
next_valid_id/ disconnect - Streaming L2 Market Depth (Rust) — full L2 order book for two tickers
- Order Lifecycle (Python) — place / modify / cancel / fill on a single order
Login
The smallest possible IBX program: connect, wait for next_valid_id, disconnect.
Two flavors are shown below — paper for everyday testing and live for read-only validation against your real account.
Per the project rules, never send orders from a live account. Use live only for read-only checks (login, contract details).
What this shows
- Reading credentials from environment variables.
- Building an
EClientConfigwithpaper: true(paper) orpaper: false(live). - Receiving
next_valid_id— the signal that the session is fully established and ready for requests.
Paper
Run it
IB_USERNAME=... IB_PASSWORD=... cargo run --example hello_login
Source
//! Hello-world recipe: connect, request next_valid_id, disconnect.
//!
//! Usage: IB_USERNAME=... IB_PASSWORD=... cargo run --example hello_login
use std::env;
use ibx::api::client::{EClient, EClientConfig};
use ibx::api::wrapper::Wrapper;
#[derive(Default)]
struct LoginWrapper {
next_id: Option<i64>,
}
impl Wrapper for LoginWrapper {
fn next_valid_id(&mut self, order_id: i64) {
self.next_id = Some(order_id);
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = EClient::connect(&EClientConfig {
username: env::var("IB_USERNAME")?,
password: env::var("IB_PASSWORD")?,
host: "cdc1.ibllc.com".into(),
paper: true,
core_id: None,
})?;
let mut wrapper = LoginWrapper::default();
client.req_ids(&mut wrapper);
let next_id = wrapper.next_id.ok_or("did not receive next_valid_id")?;
println!("logged in. account = {}, next_valid_id = {next_id}", client.account_id);
client.disconnect();
Ok(())
}
Live
The live login may trigger a second-factor push. Approve it on your mobile
authenticator when prompted — the connect call blocks until the gate clears.
Run it
IB_LIVE_USERNAME=... IB_LIVE_PASSWORD=... cargo run --example hello_login_live
Source
//! Live-account login recipe: connect with `paper: false`, request next_valid_id,
//! disconnect. Read-only — no orders, no market data.
//!
//! When the live login triggers a second-factor push, approve it on your mobile
//! authenticator. The connect call blocks until the gate clears.
//!
//! Usage: IB_LIVE_USERNAME=... IB_LIVE_PASSWORD=... cargo run --example hello_login_live
use std::env;
use ibx::api::client::{EClient, EClientConfig};
use ibx::api::wrapper::Wrapper;
#[derive(Default)]
struct LoginWrapper {
next_id: Option<i64>,
}
impl Wrapper for LoginWrapper {
fn next_valid_id(&mut self, order_id: i64) {
self.next_id = Some(order_id);
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = EClient::connect(&EClientConfig {
username: env::var("IB_LIVE_USERNAME")?,
password: env::var("IB_LIVE_PASSWORD")?,
host: env::var("IB_HOST").unwrap_or_else(|_| "cdc1.ibllc.com".into()),
paper: false,
core_id: None,
})?;
let mut wrapper = LoginWrapper::default();
client.req_ids(&mut wrapper);
let next_id = wrapper.next_id.ok_or("did not receive next_valid_id")?;
println!("logged in LIVE. account = {}, next_valid_id = {next_id}", client.account_id);
client.disconnect();
Ok(())
}
Request Contract Details
Resolve a symbol on a paper session: connect, fire req_contract_details for AAPL, collect every matching contract, then disconnect when contract_details_end lands.
What this shows
- Building a partial
Contract(symbol + sec_type + exchange + currency). - Pumping callbacks with
process_msgsuntil the end-of-stream marker arrives. - Reading
con_id, primary exchange, and trading class out ofContractDetails.
Run it
IB_USERNAME=... IB_PASSWORD=... cargo run --example hello_contract_details
Source
//! Recipe: req_contract_details for AAPL on paper, print con_id and primary exchange.
//!
//! Usage: IB_USERNAME=... IB_PASSWORD=... cargo run --example hello_contract_details
use std::env;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use ibx::api::client::{Contract, EClient, EClientConfig};
use ibx::api::types::ContractDetails;
use ibx::api::wrapper::Wrapper;
#[derive(Default)]
struct State {
rows: Vec<ContractDetails>,
end_seen: bool,
}
struct DetailsWrapper {
state: Arc<Mutex<State>>,
}
impl Wrapper for DetailsWrapper {
fn contract_details(&mut self, _req_id: i64, details: &ContractDetails) {
self.state.lock().unwrap().rows.push(details.clone());
}
fn contract_details_end(&mut self, _req_id: i64) {
self.state.lock().unwrap().end_seen = true;
}
fn error(&mut self, req_id: i64, code: i64, msg: &str, _adv: &str) {
eprintln!("[error] req_id={req_id} code={code} msg={msg}");
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = EClient::connect(&EClientConfig {
username: env::var("IB_USERNAME")?,
password: env::var("IB_PASSWORD")?,
host: "cdc1.ibllc.com".into(),
paper: true,
core_id: None,
})?;
let state = Arc::new(Mutex::new(State::default()));
let mut wrapper = DetailsWrapper { state: state.clone() };
let aapl = Contract {
symbol: "AAPL".into(),
sec_type: "STK".into(),
exchange: "SMART".into(),
currency: "USD".into(),
..Default::default()
};
client.req_contract_details(1, &aapl)?;
let deadline = Instant::now() + Duration::from_secs(15);
while Instant::now() < deadline {
client.process_msgs(&mut wrapper);
if state.lock().unwrap().end_seen { break; }
std::thread::sleep(Duration::from_millis(20));
}
let s = state.lock().unwrap();
println!("matches: {}", s.rows.len());
for d in &s.rows {
println!(
" con_id={:>8} primary={:<10} trading_class={}",
d.contract.con_id, d.contract.primary_exchange, d.contract.trading_class,
);
}
drop(s);
client.disconnect();
Ok(())
}
Historical Bars
Fetch one trading day of 5-minute SPY bars and print the first and last.
What this shows
- Building a
Contractwithcon_idso the request is unambiguous. - Calling
req_historical_datawith duration / bar size / what-to-show. - Pumping callbacks with
process_msgsuntilhistorical_data_endlands. - Reading OHLCV out of
BarData.
Run it
IB_USERNAME=... IB_PASSWORD=... cargo run --example hello_bar_data
Source
//! Recipe: fetch 1 day of 5-minute SPY bars, print first/last bar.
//!
//! Usage: IB_USERNAME=... IB_PASSWORD=... cargo run --example hello_bar_data
use std::env;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use ibx::api::client::{Contract, EClient, EClientConfig};
use ibx::api::types::BarData;
use ibx::api::wrapper::Wrapper;
#[derive(Default)]
struct State {
bars: Vec<BarData>,
end_seen: bool,
}
struct BarsWrapper {
state: Arc<Mutex<State>>,
}
impl Wrapper for BarsWrapper {
fn historical_data(&mut self, _req_id: i64, bar: &BarData) {
self.state.lock().unwrap().bars.push(bar.clone());
}
fn historical_data_end(&mut self, _req_id: i64, _start: &str, _end: &str) {
self.state.lock().unwrap().end_seen = true;
}
fn error(&mut self, req_id: i64, code: i64, msg: &str, _adv: &str) {
eprintln!("[error] req_id={req_id} code={code} msg={msg}");
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = EClient::connect(&EClientConfig {
username: env::var("IB_USERNAME")?,
password: env::var("IB_PASSWORD")?,
host: "cdc1.ibllc.com".into(),
paper: true,
core_id: None,
})?;
let state = Arc::new(Mutex::new(State::default()));
let mut wrapper = BarsWrapper { state: state.clone() };
let spy = Contract {
con_id: 756733,
symbol: "SPY".into(),
sec_type: "STK".into(),
exchange: "SMART".into(),
currency: "USD".into(),
..Default::default()
};
client.req_historical_data(1, &spy, "", "1 D", "5 mins", "TRADES", true, 1, false)?;
let deadline = Instant::now() + Duration::from_secs(30);
while Instant::now() < deadline {
client.process_msgs(&mut wrapper);
if state.lock().unwrap().end_seen { break; }
std::thread::sleep(Duration::from_millis(20));
}
let s = state.lock().unwrap();
println!("bars: {}", s.bars.len());
if let (Some(first), Some(last)) = (s.bars.first(), s.bars.last()) {
println!(" first: {} O={} H={} L={} C={} V={}",
first.date, first.open, first.high, first.low, first.close, first.volume);
println!(" last : {} O={} H={} L={} C={} V={}",
last.date, last.open, last.high, last.low, last.close, last.volume);
}
drop(s);
client.disconnect();
Ok(())
}
Streaming Ticks
Subscribe to live SPY market data, collect ticks for 5 seconds, then print the latest bid / ask / last.
What this shows
- Calling
req_mkt_datafor top-of-book streaming. - Routing tick types through the
tick_pricecallback (1=bid, 2=ask, 4=last). - Cancelling cleanly with
cancel_mkt_databefore disconnecting.
Run it
IB_USERNAME=... IB_PASSWORD=... cargo run --example hello_tick_data
Source
//! Recipe: stream SPY market data for 5 seconds, print latest bid/ask/last.
//!
//! Usage: IB_USERNAME=... IB_PASSWORD=... cargo run --example hello_tick_data
use std::env;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use ibx::api::client::{Contract, EClient, EClientConfig};
use ibx::api::types::TickAttrib;
use ibx::api::wrapper::Wrapper;
#[derive(Default)]
struct State {
bid: f64,
ask: f64,
last: f64,
ticks: u64,
}
struct TickWrapper {
state: Arc<Mutex<State>>,
}
impl Wrapper for TickWrapper {
fn tick_price(&mut self, _req_id: i64, tick_type: i32, price: f64, _: &TickAttrib) {
let mut s = self.state.lock().unwrap();
s.ticks += 1;
match tick_type {
1 => s.bid = price,
2 => s.ask = price,
4 => s.last = price,
_ => {}
}
}
fn error(&mut self, req_id: i64, code: i64, msg: &str, _adv: &str) {
if !matches!(code, 2104 | 2106 | 2158) {
eprintln!("[error] req_id={req_id} code={code} msg={msg}");
}
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = EClient::connect(&EClientConfig {
username: env::var("IB_USERNAME")?,
password: env::var("IB_PASSWORD")?,
host: "cdc1.ibllc.com".into(),
paper: true,
core_id: None,
})?;
let state = Arc::new(Mutex::new(State::default()));
let mut wrapper = TickWrapper { state: state.clone() };
let spy = Contract {
con_id: 756733,
symbol: "SPY".into(),
sec_type: "STK".into(),
exchange: "SMART".into(),
currency: "USD".into(),
..Default::default()
};
let req_id = 1;
println!("streaming SPY for 5s…");
client.req_mkt_data(req_id, &spy, "", false, false)?;
let deadline = Instant::now() + Duration::from_secs(5);
while Instant::now() < deadline {
client.process_msgs(&mut wrapper);
std::thread::sleep(Duration::from_millis(20));
}
client.cancel_mkt_data(req_id)?;
let s = state.lock().unwrap();
println!("ticks: {} bid={:.2} ask={:.2} last={:.2}", s.ticks, s.bid, s.ask, s.last);
drop(s);
client.disconnect();
Ok(())
}
Streaming L2 Market Depth
End-to-end recipe: subscribe to Level-2 market depth for two tickers (AAPL + TSLA), maintain per-ticker bid/ask books from update_mkt_depth_l2 callbacks, and print the book on each update.
What this shows
- Connecting and waiting for
next_valid_id. - Subscribing to L2 with
req_mkt_depthfor multiple contracts. - Building an in-memory book from
update_mkt_depth_l2events (insert/update/deleteops). - Cleanly cancelling subscriptions and disconnecting.
Run it
IB_USERNAME=... IB_PASSWORD=... cargo run --example l2_aapl_tsla
Optional:
IB_HOST=cdc1.ibllc.com DURATION_SECS=30 cargo run --example l2_aapl_tsla
Source
//! Subscribe to L2 market depth for AAPL + TSLA and print the order book.
//!
//! Usage:
//! IB_USERNAME=user IB_PASSWORD=pass cargo run --example l2_aapl_tsla
//!
//! Optional env vars:
//! IB_HOST — gateway host (default: cdc1.ibllc.com)
//! DURATION_SECS — how long to collect data (default: 15)
use std::collections::HashMap;
use std::env;
use std::time::{Duration, Instant};
use ibx::api::client::{EClient, EClientConfig, Contract};
use ibx::api::wrapper::Wrapper;
// ── Book entry ──
#[derive(Debug, Clone)]
struct BookLevel {
price: f64,
size: f64,
market_maker: String,
}
// ── Per-ticker book ──
struct TickerBook {
symbol: String,
bids: HashMap<i32, BookLevel>, // position → level
asks: HashMap<i32, BookLevel>,
update_count: u64,
}
impl TickerBook {
fn new(symbol: &str) -> Self {
Self {
symbol: symbol.into(),
bids: HashMap::new(),
asks: HashMap::new(),
update_count: 0,
}
}
fn apply(&mut self, position: i32, market_maker: &str, operation: i32, side: i32, price: f64, size: f64) {
self.update_count += 1;
let book = if side == 1 { &mut self.bids } else { &mut self.asks };
match operation {
0 | 1 => { book.insert(position, BookLevel { price, size, market_maker: market_maker.into() }); }
2 => { book.remove(&position); }
_ => {}
}
}
fn print_summary(&self) {
let mut bids: Vec<_> = self.bids.values().collect();
let mut asks: Vec<_> = self.asks.values().collect();
bids.sort_by(|a, b| b.price.partial_cmp(&a.price).unwrap());
asks.sort_by(|a, b| a.price.partial_cmp(&b.price).unwrap());
println!("\n── {} ── ({} updates)", self.symbol, self.update_count);
println!(" Top 5 Asks:");
for level in asks.iter().take(5).rev() {
println!(" {:>10.2} x {:<10.0} {}", level.price, level.size, level.market_maker);
}
println!(" ─────────────────────────────");
println!(" Top 5 Bids:");
for level in bids.iter().take(5) {
println!(" {:>10.2} x {:<10.0} {}", level.price, level.size, level.market_maker);
}
}
}
// ── Wrapper that collects depth for 2 tickers ──
struct DepthWrapper {
books: HashMap<i64, TickerBook>, // req_id → book
errors: Vec<(i64, i64, String)>,
}
impl DepthWrapper {
fn new(tickers: &[(i64, &str)]) -> Self {
let mut books = HashMap::new();
for &(req_id, symbol) in tickers {
books.insert(req_id, TickerBook::new(symbol));
}
Self { books, errors: Vec::new() }
}
fn total_updates(&self) -> u64 {
self.books.values().map(|b| b.update_count).sum()
}
}
impl Wrapper for DepthWrapper {
fn error(&mut self, req_id: i64, error_code: i64, error_string: &str, _: &str) {
eprintln!(" error req_id={} code={} msg={}", req_id, error_code, error_string);
self.errors.push((req_id, error_code, error_string.into()));
}
fn update_mkt_depth(
&mut self, req_id: i64, position: i32, operation: i32,
side: i32, price: f64, size: f64,
) {
if let Some(book) = self.books.get_mut(&req_id) {
book.apply(position, "", operation, side, price, size);
}
}
fn update_mkt_depth_l2(
&mut self, req_id: i64, position: i32, market_maker: &str,
operation: i32, side: i32, price: f64, size: f64, _is_smart_depth: bool,
) {
if let Some(book) = self.books.get_mut(&req_id) {
book.apply(position, market_maker, operation, side, price, size);
}
}
}
// ── Contracts ──
fn aapl() -> Contract {
Contract {
con_id: 265598,
symbol: "AAPL".into(),
sec_type: "STK".into(),
exchange: "SMART".into(),
currency: "USD".into(),
..Default::default()
}
}
fn tsla() -> Contract {
Contract {
con_id: 76792991,
symbol: "TSLA".into(),
sec_type: "STK".into(),
exchange: "SMART".into(),
currency: "USD".into(),
..Default::default()
}
}
fn main() {
let username = env::var("IB_USERNAME").expect("IB_USERNAME required");
let password = env::var("IB_PASSWORD").expect("IB_PASSWORD required");
let host = env::var("IB_HOST").unwrap_or_else(|_| "cdc1.ibllc.com".into());
let duration_secs: u64 = env::var("DURATION_SECS")
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or(15);
println!("Connecting to {}...", host);
let client = EClient::connect(&EClientConfig {
username,
password,
host,
paper: true,
core_id: None,
}).expect("Failed to connect");
println!("Connected.");
// Subscribe to L2 depth for both tickers (5 rows, SmartDepth)
let num_rows = 5;
let is_smart = true;
let aapl_id: i64 = 1;
let tsla_id: i64 = 2;
println!("Subscribing AAPL (req_id={})", aapl_id);
client.req_mkt_depth(aapl_id, &aapl(), num_rows, is_smart)
.expect("Failed to subscribe AAPL depth");
println!("Subscribing TSLA (req_id={})", tsla_id);
client.req_mkt_depth(tsla_id, &tsla(), num_rows, is_smart)
.expect("Failed to subscribe TSLA depth");
// Poll for updates
let mut wrapper = DepthWrapper::new(&[(aapl_id, "AAPL"), (tsla_id, "TSLA")]);
let start = Instant::now();
let timeout = Duration::from_secs(duration_secs);
println!("Collecting depth data for {}s...", duration_secs);
while start.elapsed() < timeout {
client.process_msgs(&mut wrapper);
std::thread::sleep(Duration::from_millis(50));
}
// Print results
for book in wrapper.books.values() {
book.print_summary();
}
let total = wrapper.total_updates();
println!("\nTotal depth updates: {}", total);
// Cancel subscriptions
let _ = client.cancel_mkt_depth(aapl_id);
let _ = client.cancel_mkt_depth(tsla_id);
// Validate
for (req_id, book) in &wrapper.books {
assert!(
book.update_count > 0,
"No depth updates received for {} (req_id={})", book.symbol, req_id
);
assert!(
!book.bids.is_empty() || !book.asks.is_empty(),
"Empty book for {} (req_id={})", book.symbol, req_id
);
println!("✓ {} — {} updates, {} bid levels, {} ask levels",
book.symbol, book.update_count, book.bids.len(), book.asks.len());
}
assert!(total > 0, "Expected depth updates but got none");
println!("\nAll validations passed.");
}
Market Scanner
Subscribe to the TOP_PERC_GAIN scanner over US major stocks and print the top 10 results.
What this shows
- Calling
req_scanner_subscriptionwith instrument / location / scan code. - Reading
scanner_datarows (rank +ContractDetails) untilscanner_data_end. - Cancelling cleanly with
cancel_scanner_subscriptionbefore disconnecting.
Run it
IB_USERNAME=... IB_PASSWORD=... cargo run --example hello_scanner
Source
//! Recipe: subscribe to TOP_PERC_GAIN scanner, print first 10 results.
//!
//! Usage: IB_USERNAME=... IB_PASSWORD=... cargo run --example hello_scanner
use std::env;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use ibx::api::client::{EClient, EClientConfig};
use ibx::api::types::ContractDetails;
use ibx::api::wrapper::Wrapper;
#[derive(Default)]
struct State {
rows: Vec<(i32, ContractDetails)>,
end_seen: bool,
}
struct ScannerWrapper {
state: Arc<Mutex<State>>,
}
impl Wrapper for ScannerWrapper {
fn scanner_data(
&mut self, _req_id: i64, rank: i32, details: &ContractDetails,
_distance: &str, _benchmark: &str, _projection: &str, _legs: &str,
) {
self.state.lock().unwrap().rows.push((rank, details.clone()));
}
fn scanner_data_end(&mut self, _req_id: i64) {
self.state.lock().unwrap().end_seen = true;
}
fn error(&mut self, req_id: i64, code: i64, msg: &str, _adv: &str) {
if !matches!(code, 2104 | 2106 | 2158) {
eprintln!("[error] req_id={req_id} code={code} msg={msg}");
}
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = EClient::connect(&EClientConfig {
username: env::var("IB_USERNAME")?,
password: env::var("IB_PASSWORD")?,
host: "cdc1.ibllc.com".into(),
paper: true,
core_id: None,
})?;
let state = Arc::new(Mutex::new(State::default()));
let mut wrapper = ScannerWrapper { state: state.clone() };
let req_id = 1;
println!("subscribing TOP_PERC_GAIN, STK.US.MAJOR…");
client.req_scanner_subscription(req_id, "STK", "STK.US.MAJOR", "TOP_PERC_GAIN", 25)?;
let deadline = Instant::now() + Duration::from_secs(30);
while Instant::now() < deadline {
client.process_msgs(&mut wrapper);
if state.lock().unwrap().end_seen { break; }
std::thread::sleep(Duration::from_millis(20));
}
let mut s = state.lock().unwrap();
s.rows.sort_by_key(|(rank, _)| *rank);
println!("results: {}", s.rows.len());
for (rank, d) in s.rows.iter().take(10) {
println!(" #{rank:<3} {:<8} {:<6} con_id={}", d.contract.symbol, d.contract.primary_exchange, d.contract.con_id);
}
drop(s);
client.cancel_scanner_subscription(req_id)?;
client.disconnect();
Ok(())
}
Request Account PnL
Subscribe to the account-level live PnL stream, take the first update, then cancel and disconnect.
What this shows
- Reading the managed account name from
client.account_id. - Subscribing with
req_pnl(req_id, account, model_code). - Reading
daily_pnl,unrealized_pnl,realized_pnlfrom thepnlcallback. - Cancelling cleanly with
cancel_pnlbefore disconnecting.
Some fields stay zero until you have a position. Pair with the limit-order recipe if you want to see non-zero values.
Run it
IB_USERNAME=... IB_PASSWORD=... cargo run --example hello_pnl
Source
//! Recipe: subscribe to account-level PnL, take one update, then cancel.
//!
//! Usage: IB_USERNAME=... IB_PASSWORD=... cargo run --example hello_pnl
use std::env;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use ibx::api::client::{EClient, EClientConfig};
use ibx::api::wrapper::Wrapper;
#[derive(Default)]
struct State {
pnl: Option<(f64, f64, f64)>,
}
struct PnlWrapper {
state: Arc<Mutex<State>>,
}
impl Wrapper for PnlWrapper {
fn pnl(&mut self, _req_id: i64, daily: f64, unrealized: f64, realized: f64) {
self.state.lock().unwrap().pnl = Some((daily, unrealized, realized));
}
fn error(&mut self, req_id: i64, code: i64, msg: &str, _adv: &str) {
eprintln!("[error] req_id={req_id} code={code} msg={msg}");
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = EClient::connect(&EClientConfig {
username: env::var("IB_USERNAME")?,
password: env::var("IB_PASSWORD")?,
host: "cdc1.ibllc.com".into(),
paper: true,
core_id: None,
})?;
let account = client.account_id.clone();
println!("account: {account}");
let state = Arc::new(Mutex::new(State::default()));
let mut wrapper = PnlWrapper { state: state.clone() };
let req_id = 1;
client.req_pnl(req_id, &account, "");
let deadline = Instant::now() + Duration::from_secs(15);
while Instant::now() < deadline {
client.process_msgs(&mut wrapper);
if state.lock().unwrap().pnl.is_some() { break; }
std::thread::sleep(Duration::from_millis(20));
}
match state.lock().unwrap().pnl {
Some((daily, unrealized, realized)) => {
println!("daily={daily:.2} unrealized={unrealized:.2} realized={realized:.2}");
}
None => println!("no pnl update within 15s — try again with an open position"),
}
client.cancel_pnl(req_id);
client.disconnect();
Ok(())
}
Send a Limit Order
Place a non-marketable BUY LMT on SPY far below market, watch it acknowledge, then cancel it. End-to-end: connect → next_order_id → place → status → cancel → disconnect.
What this shows
- Allocating a fresh
order_idfromclient.next_order_id(). - Building an
Orderwithorder_type = "LMT"andlmt_priceset. - Reading
order_statuscallbacks (PreSubmitted→Submitted). - Cancelling with
cancel_orderand observing theCancelledterminal status.
Paper account only. The price is set far below market so it will not fill.
Run it
IB_USERNAME=... IB_PASSWORD=... cargo run --example hello_limit_order
Source
//! Recipe: place a non-marketable BUY LMT on SPY, watch Submitted, then cancel.
//!
//! Usage: IB_USERNAME=... IB_PASSWORD=... cargo run --example hello_limit_order
use std::env;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use ibx::api::client::{Contract, EClient, EClientConfig, Order};
use ibx::api::wrapper::Wrapper;
#[derive(Default)]
struct State {
statuses: Vec<(i64, String)>,
}
struct OrderWrapper {
state: Arc<Mutex<State>>,
}
impl Wrapper for OrderWrapper {
fn order_status(
&mut self, order_id: i64, status: &str, _filled: f64, _remaining: f64,
_avg_fill: f64, _perm_id: i64, _parent_id: i64, _last_fill: f64,
_client_id: i64, _why_held: &str, _mkt_cap_price: f64,
) {
println!("[status] oid={order_id} status={status}");
self.state.lock().unwrap().statuses.push((order_id, status.into()));
}
fn error(&mut self, req_id: i64, code: i64, msg: &str, _adv: &str) {
eprintln!("[error] req_id={req_id} code={code} msg={msg}");
}
}
fn pump_until<F: Fn(&State) -> bool>(
client: &EClient, wrapper: &mut OrderWrapper, state: &Arc<Mutex<State>>,
timeout: Duration, done: F,
) -> bool {
let deadline = Instant::now() + timeout;
while Instant::now() < deadline {
client.process_msgs(wrapper);
if done(&state.lock().unwrap()) { return true; }
std::thread::sleep(Duration::from_millis(20));
}
false
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = EClient::connect(&EClientConfig {
username: env::var("IB_USERNAME")?,
password: env::var("IB_PASSWORD")?,
host: "cdc1.ibllc.com".into(),
paper: true,
core_id: None,
})?;
let order_id = client.next_order_id();
let state = Arc::new(Mutex::new(State::default()));
let mut wrapper = OrderWrapper { state: state.clone() };
let spy = Contract {
con_id: 756733,
symbol: "SPY".into(),
sec_type: "STK".into(),
exchange: "SMART".into(),
currency: "USD".into(),
..Default::default()
};
let order = Order {
action: "BUY".into(),
total_quantity: 1.0,
order_type: "LMT".into(),
lmt_price: 1.00,
tif: "DAY".into(),
outside_rth: true,
..Default::default()
};
println!("placing BUY 1 SPY LMT 1.00 (oid={order_id})");
client.place_order(order_id, &spy, &order)?;
pump_until(&client, &mut wrapper, &state, Duration::from_secs(15),
|s| s.statuses.iter().any(|(id, st)| *id == order_id && st == "Submitted"));
println!("cancelling oid={order_id}");
client.cancel_order(order_id, "")?;
pump_until(&client, &mut wrapper, &state, Duration::from_secs(15),
|s| s.statuses.iter().any(|(id, st)| *id == order_id && st == "Cancelled"));
client.disconnect();
Ok(())
}
Send a Stop Order
Place a BUY STOP on SPY far above market — the trigger never fires, so the order stays resting. Watch the acknowledgement, then cancel it.
What this shows
- Allocating a fresh
order_idfromclient.next_order_id(). - Building an
Orderwithorder_type = "STP"and the trigger inaux_price. - Reading
order_statuscallbacks (PreSubmitted→Submitted). - Cancelling with
cancel_orderand observing theCancelledterminal status.
Paper account only. The trigger is set far above market so it will not fire — a real stop converts to a market order on touch.
Run it
IB_USERNAME=... IB_PASSWORD=... cargo run --example hello_stop_order
Source
//! Recipe: place a BUY STP on SPY far above market, watch Submitted, then cancel.
//!
//! Usage: IB_USERNAME=... IB_PASSWORD=... cargo run --example hello_stop_order
use std::env;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use ibx::api::client::{Contract, EClient, EClientConfig, Order};
use ibx::api::wrapper::Wrapper;
#[derive(Default)]
struct State {
statuses: Vec<(i64, String)>,
}
struct OrderWrapper {
state: Arc<Mutex<State>>,
}
impl Wrapper for OrderWrapper {
fn order_status(
&mut self, order_id: i64, status: &str, _filled: f64, _remaining: f64,
_avg_fill: f64, _perm_id: i64, _parent_id: i64, _last_fill: f64,
_client_id: i64, _why_held: &str, _mkt_cap_price: f64,
) {
println!("[status] oid={order_id} status={status}");
self.state.lock().unwrap().statuses.push((order_id, status.into()));
}
fn error(&mut self, req_id: i64, code: i64, msg: &str, _adv: &str) {
eprintln!("[error] req_id={req_id} code={code} msg={msg}");
}
}
fn pump_until<F: Fn(&State) -> bool>(
client: &EClient, wrapper: &mut OrderWrapper, state: &Arc<Mutex<State>>,
timeout: Duration, done: F,
) -> bool {
let deadline = Instant::now() + timeout;
while Instant::now() < deadline {
client.process_msgs(wrapper);
if done(&state.lock().unwrap()) { return true; }
std::thread::sleep(Duration::from_millis(20));
}
false
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = EClient::connect(&EClientConfig {
username: env::var("IB_USERNAME")?,
password: env::var("IB_PASSWORD")?,
host: "cdc1.ibllc.com".into(),
paper: true,
core_id: None,
})?;
let order_id = client.next_order_id();
let state = Arc::new(Mutex::new(State::default()));
let mut wrapper = OrderWrapper { state: state.clone() };
let spy = Contract {
con_id: 756733,
symbol: "SPY".into(),
sec_type: "STK".into(),
exchange: "SMART".into(),
currency: "USD".into(),
..Default::default()
};
let order = Order {
action: "BUY".into(),
total_quantity: 1.0,
order_type: "STP".into(),
aux_price: 9999.0,
tif: "GTC".into(),
outside_rth: true,
..Default::default()
};
println!("placing BUY 1 SPY STP 9999.00 (oid={order_id})");
client.place_order(order_id, &spy, &order)?;
pump_until(&client, &mut wrapper, &state, Duration::from_secs(15),
|s| s.statuses.iter().any(|(id, st)| *id == order_id && st == "Submitted"));
println!("cancelling oid={order_id}");
client.cancel_order(order_id, "")?;
pump_until(&client, &mut wrapper, &state, Duration::from_secs(15),
|s| s.statuses.iter().any(|(id, st)| *id == order_id && st == "Cancelled"));
client.disconnect();
Ok(())
}
Login
The smallest possible IBX program: connect, wait for next_valid_id, disconnect.
Two flavors are shown below — paper for everyday testing and live for read-only validation against your real account.
Per the project rules, never send orders from a live account. Use live only for read-only checks (login, contract details).
What this shows
- Reading credentials from environment variables.
- Calling
EClient.connect(...)withpaper=True(paper) orpaper=False(live). - Receiving
next_valid_id— the signal that the session is fully established and ready for requests.
Paper
Run it
IB_USERNAME=... IB_PASSWORD=... python examples/hello_login.py
Source
"""Hello-world recipe: connect, wait for next_valid_id, disconnect.
Usage:
IB_USERNAME=... IB_PASSWORD=... python examples/hello_login.py
"""
import os
import threading
from ibx import EClient, EWrapper
class LoginWrapper(EWrapper):
def __init__(self):
self.ready = threading.Event()
self.order_id = None
def next_valid_id(self, order_id):
self.order_id = order_id
self.ready.set()
w = LoginWrapper()
c = EClient(w)
c.connect(
username=os.environ["IB_USERNAME"],
password=os.environ["IB_PASSWORD"],
host="cdc1.ibllc.com",
paper=True,
)
threading.Thread(target=c.run, daemon=True).start()
if not w.ready.wait(timeout=15):
raise RuntimeError("did not receive next_valid_id")
print(f"logged in. next_valid_id = {w.order_id}")
c.disconnect()
Live
The live login may trigger a second-factor push. Approve it on your mobile
authenticator when prompted — connect() blocks until the gate clears.
Run it
IB_LIVE_USERNAME=... IB_LIVE_PASSWORD=... python examples/hello_login_live.py
Source
"""Live-account login recipe: connect with paper=False, wait for next_valid_id,
disconnect. Read-only — no orders, no market data.
When the live login triggers a second-factor push, approve it on your mobile
authenticator. The connect call blocks until the gate clears.
Usage:
IB_LIVE_USERNAME=... IB_LIVE_PASSWORD=... python examples/hello_login_live.py
"""
import os
import threading
from ibx import EClient, EWrapper
class LoginWrapper(EWrapper):
def __init__(self):
self.ready = threading.Event()
self.order_id = None
def next_valid_id(self, order_id):
self.order_id = order_id
self.ready.set()
w = LoginWrapper()
c = EClient(w)
c.connect(
username=os.environ["IB_LIVE_USERNAME"],
password=os.environ["IB_LIVE_PASSWORD"],
host=os.environ.get("IB_HOST", "cdc1.ibllc.com"),
paper=False,
)
threading.Thread(target=c.run, daemon=True).start()
if not w.ready.wait(timeout=60):
raise RuntimeError("did not receive next_valid_id")
print(f"logged in LIVE. next_valid_id = {w.order_id}")
c.disconnect()
Request Contract Details
Resolve a symbol on a paper session: connect, call req_contract_details for AAPL, collect every matching contract, then disconnect when contract_details_end lands.
What this shows
- Building a partial
Contract(symbol + sec_type + exchange + currency). - Driving the callback loop on a daemon thread with
EClient.run. - Reading
con_id, primary exchange, and trading class out of the returnedContractDetails.
Run it
IB_USERNAME=... IB_PASSWORD=... python examples/hello_contract_details.py
Source
"""Recipe: req_contract_details for AAPL on paper, print con_id and primary exchange.
Usage:
IB_USERNAME=... IB_PASSWORD=... python examples/hello_contract_details.py
"""
import os
import threading
from ibx import EClient, EWrapper, Contract
class DetailsWrapper(EWrapper):
def __init__(self):
self.connected = threading.Event()
self.rows = []
self.done = threading.Event()
def next_valid_id(self, order_id):
self.connected.set()
def contract_details(self, req_id, details):
self.rows.append(details)
def contract_details_end(self, req_id):
self.done.set()
def error(self, req_id, code, msg, advanced=""):
if code not in (2104, 2106, 2158):
print(f"[error] {code}: {msg}")
w = DetailsWrapper()
c = EClient(w)
c.connect(
username=os.environ["IB_USERNAME"],
password=os.environ["IB_PASSWORD"],
host="cdc1.ibllc.com",
paper=True,
)
threading.Thread(target=c.run, daemon=True).start()
if not w.connected.wait(timeout=15):
raise RuntimeError("connect failed")
aapl = Contract()
aapl.symbol = "AAPL"
aapl.sec_type = "STK"
aapl.exchange = "SMART"
aapl.currency = "USD"
c.req_contract_details(1, aapl)
if not w.done.wait(timeout=15):
raise RuntimeError("contract_details_end not received")
print(f"matches: {len(w.rows)}")
for d in w.rows:
print(f" con_id={d.contract.con_id:>8} "
f"primary={d.contract.primary_exchange:<10} "
f"trading_class={d.contract.trading_class}")
c.disconnect()
Historical Bars
Fetch one trading day of 5-minute SPY bars and print the first and last.
What this shows
- Building a
Contractwithcon_idso the request is unambiguous. - Calling
req_historical_datawith duration / bar size / what-to-show. - Driving the callback loop on a daemon thread with
EClient.run. - Reading OHLCV out of the bar object.
Run it
IB_USERNAME=... IB_PASSWORD=... python examples/hello_bar_data.py
Source
"""Recipe: fetch 1 day of 5-minute SPY bars, print first/last bar.
Usage:
IB_USERNAME=... IB_PASSWORD=... python examples/hello_bar_data.py
"""
import os
import threading
from ibx import EClient, EWrapper, Contract
class BarsWrapper(EWrapper):
def __init__(self):
self.connected = threading.Event()
self.bars = []
self.done = threading.Event()
def next_valid_id(self, order_id):
self.connected.set()
def historical_data(self, req_id, bar):
self.bars.append(bar)
def historical_data_end(self, req_id, start, end):
self.done.set()
def error(self, req_id, code, msg, advanced=""):
if code not in (2104, 2106, 2158):
print(f"[error] {code}: {msg}")
w = BarsWrapper()
c = EClient(w)
c.connect(
username=os.environ["IB_USERNAME"],
password=os.environ["IB_PASSWORD"],
host="cdc1.ibllc.com",
paper=True,
)
threading.Thread(target=c.run, daemon=True).start()
if not w.connected.wait(timeout=15):
raise RuntimeError("connect failed")
spy = Contract()
spy.con_id = 756733
spy.symbol = "SPY"
spy.sec_type = "STK"
spy.exchange = "SMART"
spy.currency = "USD"
c.req_historical_data(
1, spy,
end_date_time="",
duration_str="1 D",
bar_size_setting="5 mins",
what_to_show="TRADES",
use_rth=1,
)
if not w.done.wait(timeout=30):
raise RuntimeError("historical_data_end not received")
print(f"bars: {len(w.bars)}")
if w.bars:
first, last = w.bars[0], w.bars[-1]
print(f" first: {first.date} O={first.open} H={first.high} L={first.low} C={first.close} V={first.volume}")
print(f" last : {last.date} O={last.open} H={last.high} L={last.low} C={last.close} V={last.volume}")
c.disconnect()
Streaming Ticks
Subscribe to live SPY market data, collect ticks for 5 seconds, then print the latest bid / ask / last.
What this shows
- Calling
req_mkt_datafor top-of-book streaming. - Routing tick types through the
tick_pricecallback (1=bid, 2=ask, 4=last). - Cancelling cleanly with
cancel_mkt_databefore disconnecting.
Run it
IB_USERNAME=... IB_PASSWORD=... python examples/hello_tick_data.py
Source
"""Recipe: stream SPY market data for 5 seconds, print latest bid/ask/last.
Usage:
IB_USERNAME=... IB_PASSWORD=... python examples/hello_tick_data.py
"""
import os
import threading
import time
from ibx import EClient, EWrapper, Contract
class TickWrapper(EWrapper):
def __init__(self):
self.connected = threading.Event()
self.bid = 0.0
self.ask = 0.0
self.last = 0.0
self.ticks = 0
def next_valid_id(self, order_id):
self.connected.set()
def tick_price(self, req_id, tick_type, price, attrib):
self.ticks += 1
if tick_type == 1:
self.bid = price
elif tick_type == 2:
self.ask = price
elif tick_type == 4:
self.last = price
def tick_size(self, req_id, tick_type, size):
self.ticks += 1
def error(self, req_id, code, msg, advanced=""):
if code not in (2104, 2106, 2158):
print(f"[error] {code}: {msg}")
w = TickWrapper()
c = EClient(w)
c.connect(
username=os.environ["IB_USERNAME"],
password=os.environ["IB_PASSWORD"],
host="cdc1.ibllc.com",
paper=True,
)
threading.Thread(target=c.run, daemon=True).start()
if not w.connected.wait(timeout=15):
raise RuntimeError("connect failed")
spy = Contract()
spy.con_id = 756733
spy.symbol = "SPY"
spy.sec_type = "STK"
spy.exchange = "SMART"
spy.currency = "USD"
req_id = 1
print("streaming SPY for 5s…")
c.req_mkt_data(req_id, spy, "", False, False)
deadline = time.monotonic() + 5
while time.monotonic() < deadline:
time.sleep(0.1)
c.cancel_mkt_data(req_id)
print(f"ticks: {w.ticks} bid={w.bid:.2f} ask={w.ask:.2f} last={w.last:.2f}")
c.disconnect()
Streaming L2 Market Depth
End-to-end recipe: subscribe to Level-2 market depth for two tickers (AAPL + TSLA), maintain per-ticker bid/ask books from update_mkt_depth_l2 callbacks, and print top-of-book on shutdown.
What this shows
- Subscribing to L2 with
req_mkt_depthfor multiple contracts. - Building an in-memory book from
update_mkt_depth_l2events (insert/update/deleteops). - Cleanly cancelling subscriptions and disconnecting.
Paper accounts typically grant only one concurrent depth subscription. Expect one of the two tickers to receive zero updates.
Run it
IB_USERNAME=... IB_PASSWORD=... python examples/hello_l2.py
Optional:
DURATION_SECS=30 python examples/hello_l2.py
Source
"""Recipe: stream L2 market depth on AAPL + TSLA, print top-of-book on update.
Usage:
IB_USERNAME=... IB_PASSWORD=... python examples/hello_l2.py
"""
import os
import threading
import time
from ibx import EClient, EWrapper, Contract
class Book:
def __init__(self, symbol):
self.symbol = symbol
self.bids = {} # position -> (price, size, mm)
self.asks = {}
self.updates = 0
def apply(self, position, mm, operation, side, price, size):
self.updates += 1
book = self.bids if side == 1 else self.asks
if operation in (0, 1):
book[position] = (price, size, mm)
elif operation == 2:
book.pop(position, None)
def top(self):
bid = max(self.bids.values(), default=None, key=lambda v: v[0])
ask = min(self.asks.values(), default=None, key=lambda v: v[0])
return bid, ask
class L2Wrapper(EWrapper):
def __init__(self, books):
self.connected = threading.Event()
self.books = books # req_id -> Book
def next_valid_id(self, order_id):
self.connected.set()
def update_mkt_depth_l2(self, req_id, position, market_maker,
operation, side, price, size, is_smart_depth):
if req_id in self.books:
self.books[req_id].apply(position, market_maker, operation, side, price, size)
def error(self, req_id, code, msg, advanced=""):
if code not in (2104, 2106, 2158):
print(f"[error] {code}: {msg}")
def make_stk(con_id, symbol):
c = Contract()
c.con_id = con_id
c.symbol = symbol
c.sec_type = "STK"
c.exchange = "SMART"
c.currency = "USD"
return c
SUBSCRIPTIONS = [
(1, make_stk(265598, "AAPL")),
(2, make_stk(76792991, "TSLA")),
]
DURATION_SECS = int(os.environ.get("DURATION_SECS", "15"))
books = {req_id: Book(c.symbol) for req_id, c in SUBSCRIPTIONS}
w = L2Wrapper(books)
c = EClient(w)
c.connect(
username=os.environ["IB_USERNAME"],
password=os.environ["IB_PASSWORD"],
host="cdc1.ibllc.com",
paper=True,
)
threading.Thread(target=c.run, daemon=True).start()
if not w.connected.wait(timeout=15):
raise RuntimeError("connect failed")
for req_id, contract in SUBSCRIPTIONS:
c.req_mkt_depth(req_id, contract, num_rows=5)
print(f"streaming L2 for {DURATION_SECS}s…")
time.sleep(DURATION_SECS)
for req_id, _ in SUBSCRIPTIONS:
c.cancel_mkt_depth(req_id)
for book in books.values():
bid, ask = book.top()
bid_s = f"{bid[0]:.2f} x {bid[1]:.0f}" if bid else "—"
ask_s = f"{ask[0]:.2f} x {ask[1]:.0f}" if ask else "—"
print(f" {book.symbol:<5} updates={book.updates:>5} bid={bid_s:>14} ask={ask_s:<14}")
c.disconnect()
Market Scanner
Subscribe to the TOP_PERC_GAIN scanner over US major stocks and print the top 10 results.
What this shows
- Building a
ScannerSubscription-shaped object (IBX reads attributes viagetattr). - Reading
scanner_datarows (rank +ContractDetails) untilscanner_data_end. - Cancelling cleanly with
cancel_scanner_subscriptionbefore disconnecting.
Run it
IB_USERNAME=... IB_PASSWORD=... python examples/hello_scanner.py
Source
"""Recipe: subscribe to TOP_PERC_GAIN scanner, print first 10 results.
Usage:
IB_USERNAME=... IB_PASSWORD=... python examples/hello_scanner.py
"""
import os
import threading
from ibx import EClient, EWrapper
class ScannerSubscription:
def __init__(self):
self.instrument = "STK"
self.locationCode = "STK.US.MAJOR"
self.scanCode = "TOP_PERC_GAIN"
self.numberOfRows = 25
class ScannerWrapper(EWrapper):
def __init__(self):
self.connected = threading.Event()
self.rows = []
self.done = threading.Event()
def next_valid_id(self, order_id):
self.connected.set()
def scanner_data(self, req_id, rank, contract_details,
distance, benchmark, projection, legs_str):
self.rows.append((rank, contract_details))
def scanner_data_end(self, req_id):
self.done.set()
def error(self, req_id, code, msg, advanced=""):
if code not in (2104, 2106, 2158):
print(f"[error] {code}: {msg}")
w = ScannerWrapper()
c = EClient(w)
c.connect(
username=os.environ["IB_USERNAME"],
password=os.environ["IB_PASSWORD"],
host="cdc1.ibllc.com",
paper=True,
)
threading.Thread(target=c.run, daemon=True).start()
if not w.connected.wait(timeout=15):
raise RuntimeError("connect failed")
req_id = 1
print("subscribing TOP_PERC_GAIN, STK.US.MAJOR…")
c.req_scanner_subscription(req_id, ScannerSubscription())
if not w.done.wait(timeout=30):
print(f"(scanner_data_end not received; got {len(w.rows)} rows so far)")
w.rows.sort(key=lambda r: r[0])
print(f"results: {len(w.rows)}")
for rank, d in w.rows[:10]:
print(f" #{rank:<3} {d.contract.symbol:<8} {d.contract.primary_exchange:<6} con_id={d.contract.con_id}")
c.cancel_scanner_subscription(req_id)
c.disconnect()
Request Account PnL
Subscribe to the account-level live PnL stream, take the first update, then cancel and disconnect.
What this shows
- Reading the managed account name from the client (
get_account_id). - Subscribing with
req_pnl(req_id, account). - Reading
daily_pnl,unrealized_pnl,realized_pnlfrom thepnlcallback. - Cancelling cleanly with
cancel_pnlbefore disconnecting.
Some fields stay zero until you have a position. Pair with the limit-order recipe if you want to see non-zero values.
Run it
IB_USERNAME=... IB_PASSWORD=... python examples/hello_pnl.py
Source
"""Recipe: subscribe to account-level PnL, take one update, then cancel.
Usage:
IB_USERNAME=... IB_PASSWORD=... python examples/hello_pnl.py
"""
import os
import threading
from ibx import EClient, EWrapper
class PnlWrapper(EWrapper):
def __init__(self):
self.connected = threading.Event()
self.got_pnl = threading.Event()
self.pnl_data = None
def next_valid_id(self, order_id):
self.connected.set()
def pnl(self, req_id, daily_pnl, unrealized_pnl, realized_pnl):
self.pnl_data = (daily_pnl, unrealized_pnl, realized_pnl)
self.got_pnl.set()
def error(self, req_id, code, msg, advanced=""):
if code not in (2104, 2106, 2158):
print(f"[error] {code}: {msg}")
w = PnlWrapper()
c = EClient(w)
c.connect(
username=os.environ["IB_USERNAME"],
password=os.environ["IB_PASSWORD"],
host="cdc1.ibllc.com",
paper=True,
)
threading.Thread(target=c.run, daemon=True).start()
if not w.connected.wait(timeout=15):
raise RuntimeError("connect failed")
account = c.get_account_id()
print(f"account: {account}")
req_id = 1
c.req_pnl(req_id, account)
if w.got_pnl.wait(timeout=15):
daily, unrealized, realized = w.pnl_data
print(f"daily={daily:.2f} unrealized={unrealized:.2f} realized={realized:.2f}")
else:
print("no pnl update within 15s — try again with an open position")
c.cancel_pnl(req_id)
c.disconnect()
Send a Limit Order
Place a non-marketable BUY LMT on SPY far below market, watch it acknowledge, then cancel it. End-to-end: connect → next_valid_id → place → status → cancel → disconnect.
What this shows
- Allocating an
order_idfromnext_valid_id. - Building an
Orderwithorder_type = "LMT"andlmt_priceset. - Reading
order_statuscallbacks (PreSubmitted→Submitted). - Cancelling with
cancel_orderand observing theCancelledterminal status.
Paper account only. The price is set far below market so it will not fill.
Run it
IB_USERNAME=... IB_PASSWORD=... python examples/hello_limit_order.py
Source
"""Recipe: place a non-marketable BUY LMT on SPY, watch Submitted, then cancel.
Usage:
IB_USERNAME=... IB_PASSWORD=... python examples/hello_limit_order.py
"""
import os
import threading
from ibx import EClient, EWrapper, Contract, Order
class OrderWrapper(EWrapper):
def __init__(self):
self.next_id = None
self.connected = threading.Event()
self.submitted = threading.Event()
self.cancelled = threading.Event()
def next_valid_id(self, order_id):
self.next_id = order_id
self.connected.set()
def order_status(self, order_id, status, filled, remaining,
avg_fill_price, perm_id, parent_id,
last_fill_price, client_id, why_held, mkt_cap_price):
print(f"[status] oid={order_id} status={status}")
if status == "Submitted":
self.submitted.set()
if status == "Cancelled":
self.cancelled.set()
def error(self, req_id, code, msg, advanced=""):
if code not in (2104, 2106, 2158):
print(f"[error] {code}: {msg}")
w = OrderWrapper()
c = EClient(w)
c.connect(
username=os.environ["IB_USERNAME"],
password=os.environ["IB_PASSWORD"],
host="cdc1.ibllc.com",
paper=True,
)
threading.Thread(target=c.run, daemon=True).start()
if not w.connected.wait(timeout=15):
raise RuntimeError("connect failed")
order_id = w.next_id
spy = Contract()
spy.con_id = 756733
spy.symbol = "SPY"
spy.sec_type = "STK"
spy.exchange = "SMART"
spy.currency = "USD"
order = Order()
order.action = "BUY"
order.total_quantity = 1
order.order_type = "LMT"
order.lmt_price = 1.00
order.tif = "DAY"
order.outside_rth = True
print(f"placing BUY 1 SPY LMT 1.00 (oid={order_id})")
c.place_order(order_id, spy, order)
w.submitted.wait(timeout=15)
print(f"cancelling oid={order_id}")
c.cancel_order(order_id, "")
w.cancelled.wait(timeout=15)
c.disconnect()
Send a Stop Order
Place a BUY STOP on SPY far above market — the trigger never fires, so the order stays resting. Watch the acknowledgement, then cancel it.
What this shows
- Allocating an
order_idfromnext_valid_id. - Building an
Orderwithorder_type = "STP"and the trigger inaux_price. - Reading
order_statuscallbacks (PreSubmitted→Submitted). - Cancelling with
cancel_orderand observing theCancelledterminal status.
Paper account only. The trigger is set far above market so it will not fire — a real stop converts to a market order on touch.
Run it
IB_USERNAME=... IB_PASSWORD=... python examples/hello_stop_order.py
Source
"""Recipe: place a BUY STP on SPY far above market, watch Submitted, then cancel.
Usage:
IB_USERNAME=... IB_PASSWORD=... python examples/hello_stop_order.py
"""
import os
import threading
from ibx import EClient, EWrapper, Contract, Order
class OrderWrapper(EWrapper):
def __init__(self):
self.next_id = None
self.connected = threading.Event()
self.submitted = threading.Event()
self.cancelled = threading.Event()
def next_valid_id(self, order_id):
self.next_id = order_id
self.connected.set()
def order_status(self, order_id, status, filled, remaining,
avg_fill_price, perm_id, parent_id,
last_fill_price, client_id, why_held, mkt_cap_price):
print(f"[status] oid={order_id} status={status}")
if status == "Submitted":
self.submitted.set()
if status == "Cancelled":
self.cancelled.set()
def error(self, req_id, code, msg, advanced=""):
if code not in (2104, 2106, 2158):
print(f"[error] {code}: {msg}")
w = OrderWrapper()
c = EClient(w)
c.connect(
username=os.environ["IB_USERNAME"],
password=os.environ["IB_PASSWORD"],
host="cdc1.ibllc.com",
paper=True,
)
threading.Thread(target=c.run, daemon=True).start()
if not w.connected.wait(timeout=15):
raise RuntimeError("connect failed")
order_id = w.next_id
spy = Contract()
spy.con_id = 756733
spy.symbol = "SPY"
spy.sec_type = "STK"
spy.exchange = "SMART"
spy.currency = "USD"
order = Order()
order.action = "BUY"
order.total_quantity = 1
order.order_type = "STP"
order.aux_price = 9999.0
order.tif = "GTC"
order.outside_rth = True
print(f"placing BUY 1 SPY STP 9999.00 (oid={order_id})")
c.place_order(order_id, spy, order)
w.submitted.wait(timeout=15)
print(f"cancelling oid={order_id}")
c.cancel_order(order_id, "")
w.cancelled.wait(timeout=15)
c.disconnect()
Order Lifecycle
End-to-end recipe: full order state machine on SPY — place, modify, cancel, partial fill, executions query.
What this shows
- Allocating a fresh
orderIdfromnext_valid_id. - Placing a limit order far from market and observing
Submittedstatus. - Verifying it appears in
req_open_orderswith the expectedpermId. - Modifying the same
orderIdand confirmingpermIdis stable across modify. - Walking the price toward market to trigger a fill, then querying
req_executions. - Cancelling a fresh order and observing the
Cancelledterminal status. - Flattening any residual position before disconnecting.
Run it
IB_USERNAME=... IB_PASSWORD=... python examples/ex96_order_lifecycle.py
Use the paper account. Never run order examples against a live account.
Source
"""Example #96: Order Lifecycle — Place, Modify, Cancel, Partial Fill (SPY).
Full order state machine: place → modify → cancel, plus fill handling.
Exercises permId routing, order status transitions, and execution queries.
Issue steps (executed exactly as specified):
1. reqIds() — get next valid orderId
2. placeOrder() — SPY 100 shares, LMT far from market
3. reqOpenOrders() — verify order appears with correct permId
4. placeOrder() (same orderId, new price closer to market) — modify
5. Observe orderStatus — permId must stay the same across modify
6. placeOrder() (same orderId, price at market) — trigger a fill
7. reqExecutions() — verify execDetails with correct fill qty/price
8. Place another LMT far from market, then cancelOrder() — verify Cancelled
Usage:
IB_USERNAME=xxx IB_PASSWORD=xxx python examples/ex96_order_lifecycle.py
Ref: https://github.com/deepentropy/ib-agent/issues/96
"""
import os
import sys
import time
import threading
from ibx import EWrapper, EClient, Contract, Order
SPY_CON_ID = 756733
class Wrapper(EWrapper):
def __init__(self):
super().__init__()
self.connected = threading.Event()
self.next_id = 0
self.order_statuses = [] # (order_id, status, filled, remaining, perm_id)
self.perm_ids = {} # order_id -> perm_id
self.open_orders = [] # (order_id, contract, order)
self.executions = [] # (req_id, contract, execution)
self.got_status = threading.Event()
self.got_fill = threading.Event()
self.got_cancelled = threading.Event()
self.got_open_order_end = threading.Event()
self.got_exec_end = threading.Event()
# Price discovery
self.last_price = 0.0
self.got_tick = threading.Event()
def next_valid_id(self, order_id):
self.next_id = order_id
self.connected.set()
def managed_accounts(self, accounts_list):
pass
def connect_ack(self):
pass
def tick_price(self, req_id, tick_type, price, attrib):
if price > 0 and tick_type in (1, 2, 4):
self.last_price = price
self.got_tick.set()
def tick_size(self, req_id, tick_type, size):
pass
def order_status(self, order_id, status, filled, remaining,
avg_fill_price, perm_id, parent_id,
last_fill_price, client_id, why_held, mkt_cap_price):
self.order_statuses.append((order_id, status, filled, remaining, perm_id))
self.perm_ids[order_id] = perm_id
print(f" [status] oid={order_id} status={status} filled={filled} "
f"remaining={remaining} permId={perm_id}")
self.got_status.set()
if status == "Filled" or filled > 0:
self.got_fill.set()
if status == "Cancelled":
self.got_cancelled.set()
def open_order(self, order_id, contract, order, order_state):
self.open_orders.append((order_id, contract, order))
def open_order_end(self):
self.got_open_order_end.set()
def exec_details(self, req_id, contract, execution):
self.executions.append((req_id, contract, execution))
print(f" [exec] symbol={contract.symbol} exec={execution}")
def exec_details_end(self, req_id):
self.got_exec_end.set()
def commission_and_fees_report(self, commission_and_fees_report):
pass
def error(self, req_id, error_code, error_string, advanced_order_reject_json=""):
if error_code not in (2104, 2106, 2158, 202):
print(f" [error] {error_code}: {error_string}")
def make_spy():
c = Contract()
c.con_id = SPY_CON_ID
c.symbol = "SPY"
c.sec_type = "STK"
c.exchange = "SMART"
c.currency = "USD"
return c
def alloc_id(wrapper):
oid = wrapper.next_id
wrapper.next_id += 1
return oid
def get_price(client, wrapper):
spy = make_spy()
client.req_mkt_data(9999, spy, "", False)
got = wrapper.got_tick.wait(timeout=30)
client.cancel_mkt_data(9999)
if not got or wrapper.last_price <= 0:
return None
return wrapper.last_price
def last_status_for(wrapper, oid):
"""Return last (status, remaining) for a given order_id, or (None, None)."""
matches = [s for s in wrapper.order_statuses if s[0] == oid]
if matches:
return matches[-1][1], matches[-1][3]
return None, None
def run_example():
username = os.environ.get("IB_USERNAME", "")
password = os.environ.get("IB_PASSWORD", "")
if not username or not password:
print("Set IB_USERNAME and IB_PASSWORD")
sys.exit(1)
w = Wrapper()
c = EClient(w)
c.connect(username=username, password=password,
host=os.environ.get("IB_HOST", "cdc1.ibllc.com"), paper=True)
t = threading.Thread(target=c.run, daemon=True)
t.start()
assert w.connected.wait(timeout=15), "Connection failed"
print(f"Connected. nextValidId={w.next_id}")
spy = make_spy()
results = {} # step -> pass/fail
filled_qty = 0 # track how many shares we need to flatten
# ── Price discovery ──────────────────────────────────────────────────
price = get_price(c, w)
if price is None:
# Use last known close as fallback when market is closed
price = float(os.environ.get("SPY_PRICE", "630.0"))
print(f"No live price — using fallback: {price}")
else:
print(f"SPY last price: {price}")
# ══════════════════════════════════════════════════════════════════════
# Step 1: reqIds — get next valid orderId
# ══════════════════════════════════════════════════════════════════════
print("\n=== Step 1: reqIds ===")
oid1 = alloc_id(w)
print(f" orderId={oid1}")
results["1_reqIds"] = "PASS"
# ══════════════════════════════════════════════════════════════════════
# Step 2: placeOrder — SPY 100 shares, LMT far from market
# ══════════════════════════════════════════════════════════════════════
print("\n=== Step 2: placeOrder (100 shares LMT far from market) ===")
order1 = Order()
order1.action = "BUY"
order1.total_quantity = 100
order1.order_type = "LMT"
order1.lmt_price = round(price * 0.80, 2) # 20% below market
order1.tif = "GTC"
order1.outside_rth = True
c.place_order(oid1, spy, order1)
assert w.got_status.wait(timeout=30), "No order status received"
perm_id_place = w.perm_ids.get(oid1, 0)
assert perm_id_place > 0, f"permId should be positive, got {perm_id_place}"
print(f" permId on place: {perm_id_place}")
print(f" lmt_price={order1.lmt_price} (20% below market)")
results["2_place"] = "PASS"
# ══════════════════════════════════════════════════════════════════════
# Step 3: reqOpenOrders — verify order appears with correct permId
# ══════════════════════════════════════════════════════════════════════
print("\n=== Step 3: reqOpenOrders ===")
c.req_open_orders()
assert w.got_open_order_end.wait(timeout=15), "open_order_end not received"
our = [o for o in w.open_orders if o[0] == oid1]
assert len(our) > 0, "Our order should appear in open orders"
print(f" Found {len(our)} open order(s) for oid={oid1}")
results["3_reqOpenOrders"] = "PASS"
# ══════════════════════════════════════════════════════════════════════
# Step 4: placeOrder (same orderId, new price) — modify
# ══════════════════════════════════════════════════════════════════════
print("\n=== Step 4: Modify order (same orderId, price closer to market) ===")
w.got_status.clear()
order1.lmt_price = round(price * 0.90, 2) # 10% below — still won't fill
c.place_order(oid1, spy, order1)
assert w.got_status.wait(timeout=15), "No status on modify"
status_after_modify, remaining_after_modify = last_status_for(w, oid1)
modify_ok = status_after_modify == "Submitted" and remaining_after_modify == 100.0
print(f" new lmt_price={order1.lmt_price} (10% below market)")
print(f" status after modify: {status_after_modify}, remaining: {remaining_after_modify}")
if modify_ok:
results["4_modify"] = "PASS"
else:
results["4_modify"] = f"FAIL (expected Submitted/100, got {status_after_modify}/{remaining_after_modify})"
# ══════════════════════════════════════════════════════════════════════
# Step 5: Verify permId stable across modify
# ══════════════════════════════════════════════════════════════════════
print("\n=== Step 5: Verify permId stability ===")
perm_id_modify = w.perm_ids[oid1]
perm_stable = perm_id_place == perm_id_modify
print(f" permId after modify: {perm_id_modify} (stable={perm_stable})")
results["5_permId_stable"] = "PASS" if perm_stable else f"FAIL ({perm_id_place} → {perm_id_modify})"
# ══════════════════════════════════════════════════════════════════════
# Step 6: placeOrder (same orderId, price at market) — trigger fill
# ══════════════════════════════════════════════════════════════════════
print("\n=== Step 6: Modify to market price (trigger fill) ===")
time.sleep(2) # let gateway settle after first modify
w.got_status.clear()
w.got_fill.clear()
# Re-fetch price in case it moved
w.got_tick.clear()
c.req_mkt_data(9998, spy, "", False)
if w.got_tick.wait(timeout=10) and w.last_price > 0:
price = w.last_price
c.cancel_mkt_data(9998)
order1.lmt_price = round(price * 1.02, 2) # slightly above market
c.place_order(oid1, spy, order1)
got_fill = w.got_fill.wait(timeout=30)
if got_fill:
fill_statuses = [s for s in w.order_statuses
if s[0] == oid1 and (s[1] == "Filled" or s[2] > 0)]
if fill_statuses:
filled_qty = int(fill_statuses[-1][2]) # how much was filled
perm_id_fill = w.perm_ids[oid1]
print(f" Fill confirmed: qty={filled_qty}, permId={perm_id_fill}")
results["6_fill_via_modify"] = "PASS"
else:
results["6_fill_via_modify"] = "FAIL (got_fill but no fill status)"
else:
status_now, _ = last_status_for(w, oid1)
print(f" No fill via modify (status={status_now})")
results["6_fill_via_modify"] = f"FAIL (no fill, status={status_now})"
# ══════════════════════════════════════════════════════════════════════
# Step 7: reqExecutions — verify execDetails
# ══════════════════════════════════════════════════════════════════════
print("\n=== Step 7: reqExecutions ===")
c.req_executions(8001)
w.got_exec_end.wait(timeout=15)
spy_execs = [e for e in w.executions if e[1].symbol == "SPY"]
if spy_execs:
print(f" Found {len(spy_execs)} SPY execution(s)")
results["7_reqExecutions"] = "PASS"
else:
print(" No SPY executions (expected if step 6 failed)")
results["7_reqExecutions"] = "FAIL (no executions)" if got_fill else "SKIP (no fill in step 6)"
# ══════════════════════════════════════════════════════════════════════
# Step 8: Place another LMT far from market, then cancelOrder
# ══════════════════════════════════════════════════════════════════════
print("\n=== Step 8: Place another LMT far, then cancelOrder ===")
w.got_status.clear()
w.got_cancelled.clear()
oid2 = alloc_id(w)
order2 = Order()
order2.action = "BUY"
order2.total_quantity = 100
order2.order_type = "LMT"
order2.lmt_price = round(price * 0.80, 2) # 20% below
order2.tif = "GTC"
order2.outside_rth = True
c.place_order(oid2, spy, order2)
assert w.got_status.wait(timeout=30), "No status for cancel-test order"
submitted = [s for s in w.order_statuses if s[0] == oid2 and s[1] == "Submitted"]
assert len(submitted) > 0, "Cancel-test order should be Submitted"
print(f" Order {oid2} submitted, permId={w.perm_ids.get(oid2, 0)}")
c.cancel_order(oid2, "")
got_cancel = w.got_cancelled.wait(timeout=15)
if got_cancel:
cancel_statuses = [s for s in w.order_statuses if s[0] == oid2 and s[1] == "Cancelled"]
assert len(cancel_statuses) > 0, "Should have Cancelled status"
print(f" Order {oid2} cancelled OK")
results["8_cancel"] = "PASS"
else:
results["8_cancel"] = "FAIL (cancel not confirmed within 15s)"
# ══════════════════════════════════════════════════════════════════════
# Cleanup: flatten any position from step 6
# ══════════════════════════════════════════════════════════════════════
if filled_qty > 0:
print(f"\n=== Cleanup: Sell {filled_qty} to flatten ===")
oid3 = alloc_id(w)
sell = Order()
sell.action = "SELL"
sell.total_quantity = filled_qty
sell.order_type = "MKT"
sell.tif = "DAY"
c.place_order(oid3, spy, sell)
time.sleep(5)
c.disconnect()
t.join(timeout=5)
# ══════════════════════════════════════════════════════════════════════
# Summary
# ══════════════════════════════════════════════════════════════════════
print("\n" + "=" * 60)
print("RESULTS SUMMARY")
print("=" * 60)
for step, result in results.items():
mark = "PASS" if result == "PASS" else "FAIL"
print(f" [{mark}] {step}: {result}")
passed = sum(1 for r in results.values() if r == "PASS")
total = len(results)
print(f"\n {passed}/{total} steps passed")
print("=" * 60)
if passed == total:
print("\n✓ Example #96 complete — all steps passed")
else:
print(f"\n✗ Example #96 complete — {total - passed} step(s) failed")
sys.exit(1)
if __name__ == "__main__":
run_example()
Rust API
The full Rust API reference is published on docs.rs/ibx — auto-generated from doc comments on every release.
Quick links
ibx::api::client::EClient— request side of the APIibx::api::wrapper::Wrapper— callback trait you implementibx::api::client::Contract— instrument descriptoribx::api::client::Order— order descriptor
Snapshot reference (this release)
A markdown snapshot of the Rust surface — grouped by area, with signatures and field tables — is included below for offline reading. It is regenerated on each release.
Rust API Reference (v0.7.1)
Auto-generated from source — do not edit.
Table of Contents
- EClient: Connection
- EClient: Account & Portfolio
- EClient: Orders
- EClient: Market Data
- EClient: Reference Data
- EClient: Gateway-Local & Stubs
- Wrapper Callbacks
Connection
connect
Connect to IB and start the engine.
pub fn connect(config: &EClientConfig) -> Result<Self, Box<dyn std::error::Error>>
| Parameter | Type | Description |
|---|---|---|
config | &EClientConfig | Connection configuration (username, password, host, paper, core_id). |
Returns: Result<Self, Box<dyn std::error::Error>>
connect_with_events
Connect to IB and start the engine with an [Event] channel attached. Returns the client plus a receiver carrying every [Event] the engine produces. This is a second, optional delivery path that runs alongside process_msgs() — it does not replace it, and nothing is removed from the wrapper callbacks when it is in use. The channel is bounded by capacity; the engine never blocks on it, so a consumer that falls behind loses events rather than slowing the hot loop. Drain it from a thread that is not the one calling process_msgs(), or keep capacity generous. Attaching a channel makes the engine build events it would otherwise skip, which for bar batches and contract definitions means one deep copy each. Use connect() when you only need the wrapper callbacks (ibx#242).
pub fn connect_with_events( config: &EClientConfig, capacity: usize, ) -> Result<(Self, Receiver<Event>), Box<dyn std::error::Error>>
| Parameter | Type | Description |
|---|---|---|
config | &EClientConfig | Connection configuration (username, password, host, paper, core_id). |
capacity | usize |
Returns: Result<(Self, Receiver<Event>), Box<dyn std::error::Error>>
from_parts
Construct from pre-built components (for testing or custom setups).
pub fn from_parts( shared: Arc<SharedState>, control_tx: Sender<ControlCommand>, handle: thread::JoinHandle<()>, account_id: String, ) -> Self
| Parameter | Type | Description |
|---|---|---|
shared | Arc<SharedState> | Shared state handle. |
control_tx | Sender<ControlCommand> | Control channel sender. |
handle | thread::JoinHandle<( | Background thread handle. |
Returns: Self
map_req_instrument
Map a reqId to an InstrumentId (for testing without a live engine).
pub fn map_req_instrument(&self, req_id: i64, instrument: InstrumentId)
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
instrument | InstrumentId | Instrument type for scanner (e.g. "STK", "FUT"). |
track_order_for_test
Pre-populate the order tracker (for testing the dispatcher path without going through the engine's place-order flow).
pub fn track_order_for_test( &self, order_id: u64, contract: ApiContract, order: ApiOrder, instrument: InstrumentId, )
| Parameter | Type | Description |
|---|---|---|
order_id | u64 | Order identifier. Must be unique per session. |
contract | ApiContract | Contract specification (symbol, secType, exchange, currency, etc.). |
order | ApiOrder | Order parameters (action, quantity, type, price, TIF, etc.). |
instrument | InstrumentId | Instrument type for scanner (e.g. "STK", "FUT"). |
seed_instrument
Pre-seed a con_id → InstrumentId mapping (for testing without a live engine).
pub fn seed_instrument(&self, con_id: i64, instrument: InstrumentId)
| Parameter | Type | Description |
|---|---|---|
con_id | i64 | Contract ID. Unique per instrument. |
instrument | InstrumentId | Instrument type for scanner (e.g. "STK", "FUT"). |
is_connected
False after disconnect(), and after a process_msgs() call that observed the engine stopping (ibx#242).
pub fn is_connected(&self) -> bool
Returns: bool
disconnect
Disconnect from IB. Sends Shutdown to the hot loop, waits for the background thread to exit, and marks the client as disconnected.
pub fn disconnect(&self)
ccp_session_id
Session ID surfaced to webapp REST clients as x-ccp-session-id.
pub fn ccp_session_id(&self) -> String
Returns: String
misc_url
Logical-name → host URL lookup from the gateway logon MiscUrls push (e.g. region_dam). Returns None when the gateway did not push this key.
pub fn misc_url(&self, key: &str) -> Option<String>
| Parameter | Type | Description |
|---|---|---|
key | &str | Account value key (e.g. "NetLiquidation", "BuyingPower"). |
Returns: Option<String>
session_token_bytes
Canonical big-endian session-token bytes (leading zeros stripped) captured at connect. Round-trips through BigUint::from_bytes_be to the SRP shared secret K and is the second SHA-1 input for SSO Authenticate-TWS bodies.
pub fn session_token_bytes(&self) -> &[u8]
Returns: &[u8]
token_type
stoken_type discriminator captured at connect ("st", "tst", "zenith", or empty for the SRP-only path). Sent verbatim in SSO authenticator bodies.
pub fn token_type(&self) -> &str
Returns: &str
Account & Portfolio
req_positions
Request positions. Waits for server-pushed account data before delivering, then calls position_end.
pub fn req_positions(&self, wrapper: &mut impl Wrapper)
| Parameter | Type | Description |
|---|---|---|
wrapper | &mut impl Wrapper | Wrapper callback receiver for synchronous delivery. |
req_pnl
Subscribe to account PnL updates.
pub fn req_pnl(&self, req_id: i64, _account: &str, _model_code: &str)
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
account | &str | Account ID. |
model_code | &str | Model portfolio code (empty for default). |
cancel_pnl
Cancel PnL subscription.
pub fn cancel_pnl(&self, req_id: i64)
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
req_pnl_single
Subscribe to single-position PnL updates.
pub fn req_pnl_single(&self, req_id: i64, _account: &str, _model_code: &str, con_id: i64)
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
account | &str | Account ID. |
model_code | &str | Model portfolio code (empty for default). |
con_id | i64 | Contract ID. Unique per instrument. |
cancel_pnl_single
Cancel single-position PnL subscription.
pub fn cancel_pnl_single(&self, req_id: i64)
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
req_account_summary
Request account summary.
pub fn req_account_summary(&self, req_id: i64, _group: &str, tags: &str)
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
group | &str | Account group name (e.g. "All"). |
tags | &str | Comma-separated account tags: "NetLiquidation,BuyingPower,...". |
cancel_account_summary
Cancel account summary.
pub fn cancel_account_summary(&self, req_id: i64)
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
req_account_updates
Subscribe to account updates.
pub fn req_account_updates(&self, subscribe: bool, _acct_code: &str)
| Parameter | Type | Description |
|---|---|---|
subscribe | bool | true to start updates, false to stop. |
acct_code | &str | Account code (e.g. "DU1234567"). |
cancel_positions
Cancel positions subscription.
pub fn cancel_positions(&self)
req_managed_accts
Request managed accounts.
pub fn req_managed_accts(&self, wrapper: &mut impl Wrapper)
| Parameter | Type | Description |
|---|---|---|
wrapper | &mut impl Wrapper | Wrapper callback receiver for synchronous delivery. |
req_account_updates_multi
Request account updates for multiple accounts/models.
pub fn req_account_updates_multi( &self, _req_id: i64, _account: &str, _model_code: &str, _ledger_and_nlv: bool, wrapper: &mut impl Wrapper, )
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
account | &str | Account ID. |
model_code | &str | Model portfolio code (empty for default). |
ledger_and_nlv | bool | If true, include ledger and NLV data. |
wrapper | &mut impl Wrapper | Wrapper callback receiver for synchronous delivery. |
cancel_account_updates_multi
Cancel multi-account updates.
pub fn cancel_account_updates_multi(&self, _req_id: i64)
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
req_positions_multi
Request positions for multiple accounts/models.
pub fn req_positions_multi( &self, _req_id: i64, _account: &str, _model_code: &str, wrapper: &mut impl Wrapper, )
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
account | &str | Account ID. |
model_code | &str | Model portfolio code (empty for default). |
wrapper | &mut impl Wrapper | Wrapper callback receiver for synchronous delivery. |
cancel_positions_multi
Cancel multi-account positions.
pub fn cancel_positions_multi(&self, _req_id: i64)
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
account
Read account state snapshot.
pub fn account(&self) -> AccountState
Returns: AccountState
Orders
place_order
Place an order.
pub fn place_order(&self, order_id: i64, contract: &Contract, order: &Order) -> Result<(), String>
| Parameter | Type | Description |
|---|---|---|
order_id | i64 | Order identifier. Must be unique per session. |
contract | &Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
order | &Order | Order parameters (action, quantity, type, price, TIF, etc.). |
Returns: Result<(), String>
cancel_order
Cancel an order.
pub fn cancel_order(&self, order_id: i64, _manual_order_cancel_time: &str) -> Result<(), String>
| Parameter | Type | Description |
|---|---|---|
order_id | i64 | Order identifier. Must be unique per session. |
manual_order_cancel_time | &str | Manual cancel time (empty for immediate). |
Returns: Result<(), String>
cancel_order_by_perm_id
Cancel an order identified by permId — stable across sessions. permId is the broker-assigned identifier returned in order_status callbacks and surfaced in account tools. Useful for cancelling an order placed in a prior session, where the local order_id is not retained. Per ib-agent#154 the CCP cancel frame is orderId-only, so ibx looks up the local order_id from permId in the open-order cache (populated by place_order callbacks or by the CCP session-recovery push hydrated in handle_exec_report). Fails if perm_id is not currently tracked.
pub fn cancel_order_by_perm_id(&self, perm_id: i64) -> Result<(), String>
| Parameter | Type | Description |
|---|---|---|
perm_id | i64 | Permanent order ID assigned by the server. |
Returns: Result<(), String>
req_global_cancel
Cancel all orders.
pub fn req_global_cancel(&self) -> Result<(), String>
Returns: Result<(), String>
req_ids
Request next valid order ID.
pub fn req_ids(&self, wrapper: &mut impl Wrapper)
| Parameter | Type | Description |
|---|---|---|
wrapper | &mut impl Wrapper | Wrapper callback receiver for synchronous delivery. |
next_order_id
Get the next order ID (local counter).
pub fn next_order_id(&self) -> i64
Returns: i64
req_open_orders
Request open orders for this client.
pub fn req_open_orders(&self, wrapper: &mut impl Wrapper)
| Parameter | Type | Description |
|---|---|---|
wrapper | &mut impl Wrapper | Wrapper callback receiver for synchronous delivery. |
req_all_open_orders
Request all open orders.
pub fn req_all_open_orders(&self, wrapper: &mut impl Wrapper)
| Parameter | Type | Description |
|---|---|---|
wrapper | &mut impl Wrapper | Wrapper callback receiver for synchronous delivery. |
req_completed_orders
Request completed orders. Immediately delivers all archived completed orders, then calls completed_orders_end.
pub fn req_completed_orders(&self, wrapper: &mut impl Wrapper)
| Parameter | Type | Description |
|---|---|---|
wrapper | &mut impl Wrapper | Wrapper callback receiver for synchronous delivery. |
req_auto_open_orders
Automatically bind future orders to this client.
pub fn req_auto_open_orders(&self, _b_auto_bind: bool)
| Parameter | Type | Description |
|---|---|---|
b_auto_bind | bool | If true, auto-bind future orders to this client. |
req_executions
Request execution reports. Replays stored executions (optionally filtered), firing exec_details + commission_and_fees_report for each, then exec_details_end.
pub fn req_executions(&self, req_id: i64, filter: &ExecutionFilter, wrapper: &mut impl Wrapper)
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
filter | &ExecutionFilter | Execution filter (client_id, acct_code, time, symbol, sec_type, exchange, side). |
wrapper | &mut impl Wrapper | Wrapper callback receiver for synchronous delivery. |
parse_algo_params
Parse algo strategy and TagValue params into internal AlgoParams.
pub fn parse_algo_params(strategy: &str, params: &[TagValue]) -> Result<AlgoParams, String>
| Parameter | Type | Description |
|---|---|---|
strategy | &str | Algo strategy name (e.g. "Vwap", "Twap"). |
params | &[TagValue] | Algo parameter list. |
Returns: Result<AlgoParams, String>
Market Data
req_mkt_data
Subscribe to market data. When snapshot is true, delivers the first available quote then calls tick_snapshot_end and auto-cancels the subscription. generic_tick_list is NOT transmitted to the gateway, with one exception: "292" additionally subscribes per-contract news. Other generic tick types (RTVolume and friends) have no emission path, and tick_generic never fires (ibx#234). Delayed data cannot be requested either — see req_market_data_type.
pub fn req_mkt_data( &self, req_id: i64, contract: &Contract, generic_tick_list: &str, snapshot: bool, regulatory_snapshot: bool, ) -> Result<(), String>
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
contract | &Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
generic_tick_list | &str | Comma-separated generic tick IDs (e.g. "233" for RT volume). |
snapshot | bool | If true, delivers one quote then auto-cancels. |
regulatory_snapshot | bool | If true, request a regulatory snapshot (additional fees may apply). |
Returns: Result<(), String>
req_mkt_data_ex
Like [req_mkt_data], but encodes the market-data mode per-request via FIX field 9887, allowing parallel realtime + frozen subscriptions for the same contract: | mode_9887 | mode | wire shape | |-------------|------------------|---| | 0 | REALTIME | 264=442 (BID_ASK) + 264=443 (LAST), no 9887 | | 1 | DELAYED | 264=1 (TOP) + 9887=1 | | 2 | FROZEN | 264=1 (TOP) + 9887=2 | | 3 | DELAYED_FROZEN | 264=1 (TOP) + 9887=3 | The frozen sub keeps thinly-traded names streaming after-hours when the realtime feed is silent. Issue 3-4 parallel calls per contract with different modes and pick whichever feed has data.
pub fn req_mkt_data_ex( &self, req_id: i64, contract: &Contract, generic_tick_list: &str, snapshot: bool, _regulatory_snapshot: bool, mode_9887: i32, ) -> Result<(), String>
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
contract | &Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
generic_tick_list | &str | Comma-separated generic tick IDs (e.g. "233" for RT volume). |
snapshot | bool | If true, delivers one quote then auto-cancels. |
regulatory_snapshot | bool | If true, request a regulatory snapshot (additional fees may apply). |
mode_9887 | i32 |
Returns: Result<(), String>
cancel_mkt_data
Cancel market data.
pub fn cancel_mkt_data(&self, req_id: i64) -> Result<(), String>
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
Returns: Result<(), String>
req_tick_by_tick_data
Subscribe to tick-by-tick data.
pub fn req_tick_by_tick_data( &self, req_id: i64, contract: &Contract, tick_type: &str, _number_of_ticks: i32, _ignore_size: bool, ) -> Result<(), String>
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
contract | &Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
tick_type | &str | Tick type ID or tick-by-tick type string. |
number_of_ticks | i32 | Maximum number of ticks to return. |
ignore_size | bool | If true, ignore size in tick-by-tick data. |
Returns: Result<(), String>
cancel_tick_by_tick_data
Cancel tick-by-tick data.
pub fn cancel_tick_by_tick_data(&self, req_id: i64) -> Result<(), String>
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
Returns: Result<(), String>
req_mkt_depth
Subscribe to market depth (L2 order book).
pub fn req_mkt_depth( &self, req_id: i64, contract: &Contract, num_rows: i32, is_smart_depth: bool, ) -> Result<(), String>
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
contract | &Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
num_rows | i32 | Number of order book rows to subscribe to. |
is_smart_depth | bool | If true, aggregate depth from multiple exchanges via SMART. |
Returns: Result<(), String>
cancel_mkt_depth
Cancel market depth.
pub fn cancel_mkt_depth(&self, req_id: i64) -> Result<(), String>
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
Returns: Result<(), String>
req_real_time_bars
Subscribe to real-time 5-second bars.
pub fn req_real_time_bars( &self, req_id: i64, contract: &Contract, _bar_size: i32, what_to_show: &str, use_rth: bool, ) -> Result<(), String>
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
contract | &Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
bar_size | i32 | Bar size: "1 min", "5 mins", "1 hour", "1 day", etc. |
what_to_show | &str | Data type: "TRADES", "MIDPOINT", "BID", "ASK", "BID_ASK", etc. |
use_rth | bool | If true, only return data from Regular Trading Hours. |
Returns: Result<(), String>
cancel_real_time_bars
Cancel real-time bars.
pub fn cancel_real_time_bars(&self, req_id: i64) -> Result<(), String>
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
Returns: Result<(), String>
req_ping
Set market data type preference (1=live, 2=frozen, 3=delayed, 4=delayed-frozen). Request an auth-connection round-trip time sample (ibx#158): sends a lightweight liveness probe with no side effects on subscriptions, contract caches, or pacing budgets. The result lands asynchronously — poll last_rtt() after a moment. No-op while a probe is already in flight or the connection is down.
pub fn req_ping(&self) -> Result<(), String>
Returns: Result<(), String>
last_rtt
Last measured auth-connection round-trip time, if any (ibx#158). A gauge, not a benchmark: the sample is the interval from a probe to the first inbound traffic that followed it, which on an active feed can undercount by racing data already in flight. Also sampled automatically whenever liveness sends its own probe.
pub fn last_rtt(&self) -> Option<std::time::Duration>
Returns: Option<std::time::Duration>
req_market_data_type
NOT supported end to end (ibx#234): the requested type is stored locally but never sent to the gateway, so subscriptions always deliver realtime data and delayed tick variants never arrive. Requesting a non-realtime type logs a warning, and the market_data_type callback reports the DELIVERED type (realtime) rather than echoing the request.
pub fn req_market_data_type(&self, market_data_type: i32)
| Parameter | Type | Description |
|---|---|---|
market_data_type | i32 | 1=live, 2=frozen, 3=delayed, 4=delayed-frozen. |
set_news_providers
Set news provider codes for per-contract news ticks.
pub fn set_news_providers(&self, providers: &str)
| Parameter | Type | Description |
|---|---|---|
providers | &str | News provider list. |
quote
Zero-copy SeqLock quote read. Maps reqId → InstrumentId → SeqLock. Returns None if the reqId is not mapped to a subscription.
pub fn quote(&self, req_id: i64) -> Option<Quote>
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
Returns: Option<Quote>
quote_by_instrument
Direct SeqLock read by InstrumentId (for callers who track IDs themselves). Returns None for an out-of-range id — this used to panic (ibx#234).
pub fn quote_by_instrument(&self, instrument: InstrumentId) -> Option<Quote>
| Parameter | Type | Description |
|---|---|---|
instrument | InstrumentId | Instrument type for scanner (e.g. "STK", "FUT"). |
Returns: Option<Quote>
Reference Data
req_historical_data
Request historical data.
pub fn req_historical_data( &self, req_id: i64, contract: &Contract, end_date_time: &str, duration: &str, bar_size: &str, what_to_show: &str, use_rth: bool, _format_date: i32, keep_up_to_date: bool, ) -> Result<(), String>
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
contract | &Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
end_date_time | &str | End date/time in "YYYYMMDD HH:MM:SS" format, or empty for now. |
duration | &str | Duration string, e.g. "1 D", "1 W", "1 M", "1 Y". |
bar_size | &str | Bar size: "1 min", "5 mins", "1 hour", "1 day", etc. |
what_to_show | &str | Data type: "TRADES", "MIDPOINT", "BID", "ASK", "BID_ASK", etc. |
use_rth | bool | If true, only return data from Regular Trading Hours. |
format_date | i32 | Date format: 1="YYYYMMDD HH:MM:SS", 2=Unix seconds. |
keep_up_to_date | bool | If true, continue receiving updates after initial history. |
Returns: Result<(), String>
cancel_historical_data
Cancel historical data.
pub fn cancel_historical_data(&self, req_id: i64) -> Result<(), String>
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
Returns: Result<(), String>
req_head_time_stamp
Request head timestamp.
pub fn req_head_time_stamp( &self, req_id: i64, contract: &Contract, what_to_show: &str, use_rth: bool, _format_date: i32, ) -> Result<(), String>
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
contract | &Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
what_to_show | &str | Data type: "TRADES", "MIDPOINT", "BID", "ASK", "BID_ASK", etc. |
use_rth | bool | If true, only return data from Regular Trading Hours. |
format_date | i32 | Date format: 1="YYYYMMDD HH:MM:SS", 2=Unix seconds. |
Returns: Result<(), String>
req_contract_details
Request contract details.
pub fn req_contract_details(&self, req_id: i64, contract: &Contract) -> Result<(), String>
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
contract | &Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
Returns: Result<(), String>
req_mkt_depth_exchanges
Request available exchanges for market depth.
pub fn req_mkt_depth_exchanges(&self) -> Result<(), String>
Returns: Result<(), String>
req_matching_symbols
Request matching symbols.
pub fn req_matching_symbols(&self, req_id: i64, pattern: &str) -> Result<(), String>
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
pattern | &str | Symbol search pattern. |
Returns: Result<(), String>
cancel_head_time_stamp
Cancel head timestamp request.
pub fn cancel_head_time_stamp(&self, req_id: i64) -> Result<(), String>
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
Returns: Result<(), String>
req_market_rule
Request market rule by ID. Looks up cached market rules delivered during connection init.
pub fn req_market_rule(&self, market_rule_id: i32, wrapper: &mut impl crate::api::wrapper::Wrapper)
| Parameter | Type | Description |
|---|---|---|
market_rule_id | i32 | Market rule ID. |
wrapper | &mut impl crate::api::wrapper::Wrapper | Wrapper callback receiver for synchronous delivery. |
req_news_bulletins
Subscribe to news bulletins.
pub fn req_news_bulletins(&self, _all_msgs: bool)
| Parameter | Type | Description |
|---|---|---|
all_msgs | bool | If true, receive all existing bulletins on subscribe. |
cancel_news_bulletins
Cancel news bulletin subscription.
pub fn cancel_news_bulletins(&self)
req_scanner_parameters
Request scanner parameters XML.
pub fn req_scanner_parameters(&self) -> Result<(), String>
Returns: Result<(), String>
req_scanner_subscription
Subscribe to a market scanner.
pub fn req_scanner_subscription( &self, req_id: i64, instrument: &str, location_code: &str, scan_code: &str, max_items: u32, ) -> Result<(), String>
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
instrument | &str | Instrument type for scanner (e.g. "STK", "FUT"). |
location_code | &str | Scanner location (e.g. "STK.US.MAJOR"). |
scan_code | &str | Scanner code (e.g. "TOP_PERC_GAIN", "HIGH_OPT_IMP_VOLAT"). |
max_items | u32 | Maximum number of scanner results. |
Returns: Result<(), String>
cancel_scanner_subscription
Cancel a scanner subscription.
pub fn cancel_scanner_subscription(&self, req_id: i64) -> Result<(), String>
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
Returns: Result<(), String>
req_historical_news
Request historical news headlines.
pub fn req_historical_news( &self, req_id: i64, con_id: i64, provider_codes: &str, start_time: &str, end_time: &str, max_results: u32, ) -> Result<(), String>
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
con_id | i64 | Contract ID. Unique per instrument. |
provider_codes | &str | Pipe-separated news provider codes. |
start_time | &str | Start date/time for news query. |
end_time | &str | End date/time for news query. |
max_results | u32 | Maximum number of results. |
Returns: Result<(), String>
req_news_article
Request a news article by provider and article ID.
pub fn req_news_article(&self, req_id: i64, provider_code: &str, article_id: &str) -> Result<(), String>
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
provider_code | &str | News provider code (e.g. "BRFG"). |
article_id | &str | News article identifier. |
Returns: Result<(), String>
req_fundamental_data
Request fundamental data (e.g. ReportSnapshot, ReportsFinSummary).
pub fn req_fundamental_data(&self, req_id: i64, contract: &Contract, report_type: &str) -> Result<(), String>
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
contract | &Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
report_type | &str | Report type: "ReportSnapshot", "ReportsFinSummary", "RESC", etc. |
Returns: Result<(), String>
cancel_fundamental_data
Cancel fundamental data.
pub fn cancel_fundamental_data(&self, req_id: i64) -> Result<(), String>
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
Returns: Result<(), String>
req_histogram_data
Request price histogram data.
pub fn req_histogram_data(&self, req_id: i64, contract: &Contract, use_rth: bool, period: &str) -> Result<(), String>
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
contract | &Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
use_rth | bool | If true, only return data from Regular Trading Hours. |
period | &str | Histogram period, e.g. "1week", "1month". |
Returns: Result<(), String>
cancel_histogram_data
Cancel histogram data.
pub fn cancel_histogram_data(&self, req_id: i64) -> Result<(), String>
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
Returns: Result<(), String>
req_historical_ticks
Request historical tick data.
pub fn req_historical_ticks( &self, req_id: i64, contract: &Contract, start_date_time: &str, end_date_time: &str, number_of_ticks: i32, what_to_show: &str, use_rth: bool, ) -> Result<(), String>
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
contract | &Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
start_date_time | &str | Start date/time for tick query. |
end_date_time | &str | End date/time in "YYYYMMDD HH:MM:SS" format, or empty for now. |
number_of_ticks | i32 | Maximum number of ticks to return. |
what_to_show | &str | Data type: "TRADES", "MIDPOINT", "BID", "ASK", "BID_ASK", etc. |
use_rth | bool | If true, only return data from Regular Trading Hours. |
Returns: Result<(), String>
req_historical_schedule
Request historical trading schedule.
pub fn req_historical_schedule( &self, req_id: i64, contract: &Contract, end_date_time: &str, duration: &str, use_rth: bool, ) -> Result<(), String>
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
contract | &Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
end_date_time | &str | End date/time in "YYYYMMDD HH:MM:SS" format, or empty for now. |
duration | &str | Duration string, e.g. "1 D", "1 W", "1 M", "1 Y". |
use_rth | bool | If true, only return data from Regular Trading Hours. |
Returns: Result<(), String>
Gateway-Local & Stubs
req_smart_components
Request smart routing components for a BBO exchange. Gateway-local — returns component exchanges from init data.
pub fn req_smart_components(&self, req_id: i64, _bbo_exchange: &str, wrapper: &mut impl Wrapper)
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
bbo_exchange | &str | BBO exchange for smart component lookup (e.g. "SMART"). |
wrapper | &mut impl Wrapper | Wrapper callback receiver for synchronous delivery. |
req_news_providers
Request available news providers. Gateway-local — returns provider list from init data.
pub fn req_news_providers(&self, wrapper: &mut impl Wrapper)
| Parameter | Type | Description |
|---|---|---|
wrapper | &mut impl Wrapper | Wrapper callback receiver for synchronous delivery. |
req_current_time
Request current server time. Returns local system time (no server round-trip).
pub fn req_current_time(&self, wrapper: &mut impl Wrapper)
| Parameter | Type | Description |
|---|---|---|
wrapper | &mut impl Wrapper | Wrapper callback receiver for synchronous delivery. |
request_fa
Request FA data. Not yet implemented.
pub fn request_fa(&self, _fa_data_type: i32)
| Parameter | Type | Description |
|---|---|---|
fa_data_type | i32 | FA data type (1=Groups, 2=Profiles, 3=Aliases). |
replace_fa
Replace FA data. Not yet implemented.
pub fn replace_fa(&self, _req_id: i64, _fa_data_type: i32, _cxml: &str)
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
fa_data_type | i32 | FA data type (1=Groups, 2=Profiles, 3=Aliases). |
cxml | &str | FA XML configuration data. |
query_display_groups
Query display groups. Not yet implemented.
pub fn query_display_groups(&self, _req_id: i64)
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
subscribe_to_group_events
Subscribe to display group events. Not yet implemented.
pub fn subscribe_to_group_events(&self, _req_id: i64, _group_id: i32)
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
group_id | i32 | Display group ID. |
unsubscribe_from_group_events
Unsubscribe from display group events. Not yet implemented.
pub fn unsubscribe_from_group_events(&self, _req_id: i64)
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
update_display_group
Update display group. Not yet implemented.
pub fn update_display_group(&self, _req_id: i64, _contract_info: &str)
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
contract_info | &str | Display group contract info string. |
req_soft_dollar_tiers
Request soft dollar tiers. Gateway-local — returns tiers parsed from CCP logon tag 6560.
pub fn req_soft_dollar_tiers(&self, req_id: i64, wrapper: &mut impl Wrapper)
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
wrapper | &mut impl Wrapper | Wrapper callback receiver for synchronous delivery. |
req_family_codes
Request family codes. Gateway-local — returns codes parsed from CCP logon tag 6823.
pub fn req_family_codes(&self, wrapper: &mut impl Wrapper)
| Parameter | Type | Description |
|---|---|---|
wrapper | &mut impl Wrapper | Wrapper callback receiver for synchronous delivery. |
set_server_log_level
Set server log level.
pub fn set_server_log_level(&self, log_level: i32)
| Parameter | Type | Description |
|---|---|---|
log_level | i32 | Log level: 1=error, 2=warn, 3=info, 4=debug, 5=trace. |
req_user_info
Request user info. Gateway-local — returns whiteBrandingId from CCP logon.
pub fn req_user_info(&self, req_id: i64, wrapper: &mut impl Wrapper)
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
wrapper | &mut impl Wrapper | Wrapper callback receiver for synchronous delivery. |
req_wsh_meta_data
Request WSH metadata. Not yet implemented.
pub fn req_wsh_meta_data(&self, _req_id: i64)
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
req_wsh_event_data
Request WSH event data. Not yet implemented.
pub fn req_wsh_event_data(&self, _req_id: i64)
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
Wrapper Callbacks
connect_ack
Connection acknowledged.
connection_closed
Connection has been closed.
next_valid_id
Next valid order ID from the server.
| Parameter | Type | Description |
|---|---|---|
order_id | i64 | Order identifier. Must be unique per session. |
managed_accounts
Comma-separated list of managed account IDs.
| Parameter | Type | Description |
|---|---|---|
accounts_list | &str | Comma-separated account IDs. |
error
Error or informational message from the server.
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
error_code | i64 | Error code. |
error_string | &str | Error message. |
advanced_order_reject_json | &str | JSON with advanced rejection details. |
current_time
Current server time (Unix seconds).
| Parameter | Type | Description |
|---|---|---|
time | i64 | Tick timestamp (Unix seconds). |
tick_price
Price tick update (bid, ask, last, etc.).
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
tick_type | i32 | Tick type ID or tick-by-tick type string. |
price | f64 | Tick price. |
attrib | &TickAttrib | Tick attributes. |
tick_size
Size tick update (bid size, ask size, volume, etc.).
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
tick_type | i32 | Tick type ID or tick-by-tick type string. |
size | f64 | Tick size. |
tick_string
String tick (e.g. last trade timestamp).
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
tick_type | i32 | Tick type ID or tick-by-tick type string. |
value | &str | Account value. |
tick_generic
Generic numeric tick value.
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
tick_type | i32 | Tick type ID or tick-by-tick type string. |
value | f64 | Account value. |
tick_snapshot_end
Snapshot delivery complete; subscription auto-cancelled.
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
market_data_type
Market data type changed (1=live, 2=frozen, 3=delayed, 4=delayed-frozen).
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
market_data_type | i32 | 1=live, 2=frozen, 3=delayed, 4=delayed-frozen. |
order_status
Order status update (filled, remaining, avg price, etc.).
| Parameter | Type | Description |
|---|---|---|
order_id | i64 | Order identifier. Must be unique per session. |
status | &str | Order status string ("Submitted", "Filled", "Cancelled", etc.). |
filled | f64 | Cumulative filled quantity. |
remaining | f64 | Remaining quantity. |
avg_fill_price | f64 | Average fill price. |
perm_id | i64 | Permanent order ID assigned by the server. |
parent_id | i64 | Parent order ID (0 if no parent). |
last_fill_price | f64 | Price of the last fill. |
client_id | i64 | Client ID (unused — single-client engine). |
why_held | &str | Reason the order is held (e.g. "locate"). |
mkt_cap_price | f64 | Market cap price for the order. |
open_order
Open order details (contract, order, state).
| Parameter | Type | Description |
|---|---|---|
order_id | i64 | Order identifier. Must be unique per session. |
contract | &Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
order | &Order | Order parameters (action, quantity, type, price, TIF, etc.). |
order_state | &OrderState | Order state (status, margin, commission info). |
open_order_end
End of open orders list.
exec_details
Execution fill details.
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
contract | &Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
execution | &Execution | Execution details (exec_id, time, price, shares, etc.). |
exec_details_end
End of execution details list.
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
commission_and_fees_report
Commission and fees report for an execution.
| Parameter | Type | Description |
|---|---|---|
report | &CommissionAndFeesReport | Commission report (exec_id, commission, currency, realized P&L). |
update_account_value
Account value update (key/value/currency).
| Parameter | Type | Description |
|---|---|---|
key | &str | Account value key (e.g. "NetLiquidation", "BuyingPower"). |
value | &str | Account value. |
currency | &str | Currency code (e.g. "USD"). |
account_name | &str | Account identifier. |
update_portfolio
Portfolio position update.
| Parameter | Type | Description |
|---|---|---|
contract | &Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
position | f64 | Book position (row index) or position size. |
market_price | f64 | Current market price. |
market_value | f64 | Current market value of position. |
average_cost | f64 | Average cost basis. |
unrealized_pnl | f64 | Unrealized profit/loss. |
realized_pnl | f64 | Realized profit/loss. |
account_name | &str | Account identifier. |
update_account_time
Account update timestamp.
| Parameter | Type | Description |
|---|---|---|
timestamp | &str | Timestamp string. |
account_download_end
Account data delivery complete.
| Parameter | Type | Description |
|---|---|---|
account | &str | Account ID. |
account_summary
Account summary tag/value entry.
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
account | &str | Account ID. |
tag | &str | Account tag name (e.g. "NetLiquidation"). |
value | &str | Account value. |
currency | &str | Currency code (e.g. "USD"). |
account_summary_end
End of account summary.
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
position
Position entry (account, contract, size, avg cost).
| Parameter | Type | Description |
|---|---|---|
account | &str | Account ID. |
contract | &Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
pos | f64 | Position size (decimal shares). |
avg_cost | f64 | Average cost per share. |
position_end
End of positions list.
pnl
Account P&L update (daily, unrealized, realized).
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
daily_pnl | f64 | Daily profit/loss. |
unrealized_pnl | f64 | Unrealized profit/loss. |
realized_pnl | f64 | Realized profit/loss. |
pnl_single
Single-position P&L update.
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
pos | f64 | Position size (decimal shares). |
daily_pnl | f64 | Daily profit/loss. |
unrealized_pnl | f64 | Unrealized profit/loss. |
realized_pnl | f64 | Realized profit/loss. |
value | f64 | Account value. |
historical_data
Historical OHLCV bar.
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
bar | &BarData | Bar data (date, open, high, low, close, volume, wap, bar_count). |
historical_data_end
End of historical data delivery.
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
start | &str | Period start date/time. |
end | &str | Period end date/time. |
historical_data_update
Real-time bar update (keep_up_to_date=true).
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
bar | &BarData | Bar data (date, open, high, low, close, volume, wap, bar_count). |
head_timestamp
Earliest available data timestamp.
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
head_timestamp | &str | Earliest available data timestamp string. |
contract_details
Contract definition details.
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
details | &ContractDetails | Contract details object. |
contract_details_end
End of contract details.
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
symbol_samples
Matching symbol search results.
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
descriptions | &[ContractDescription] | Array of matching contract descriptions. |
tick_by_tick_all_last
Tick-by-tick last trade.
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
tick_type | i32 | Tick type ID or tick-by-tick type string. |
time | i64 | Tick timestamp (Unix seconds). |
price | f64 | Tick price. |
size | f64 | Tick size. |
attrib | &TickAttribLast | Tick attributes. |
exchange | &str | Exchange name. |
special_conditions | &str | Special trade conditions. |
tick_by_tick_bid_ask
Tick-by-tick bid/ask quote.
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
time | i64 | Tick timestamp (Unix seconds). |
bid_price | f64 | Bid price. |
ask_price | f64 | Ask price. |
bid_size | f64 | Bid size. |
ask_size | f64 | Ask size. |
attrib | &TickAttribBidAsk | Tick attributes. |
tick_by_tick_mid_point
Tick-by-tick midpoint.
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
time | i64 | Tick timestamp (Unix seconds). |
mid_point | f64 | Midpoint price. |
scanner_data
Scanner result entry (rank, contract, distance).
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
rank | i32 | Scanner result rank (0-based). |
details | &ContractDetails | Contract details object. |
distance | &str | Scanner distance metric. |
benchmark | &str | Scanner benchmark. |
projection | &str | Scanner projection. |
legs_str | &str | Combo legs description. |
scanner_data_end
End of scanner results.
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
scanner_parameters
Scanner parameters XML.
| Parameter | Type | Description |
|---|---|---|
xml | &str | XML string. |
update_news_bulletin
News bulletin message.
| Parameter | Type | Description |
|---|---|---|
msg_id | i64 | Bulletin message ID. |
msg_type | i32 | Bulletin message type (1=regular, 2=exchange). |
message | &str | Bulletin message text. |
orig_exchange | &str | Originating exchange. |
tick_news
Per-contract news tick.
| Parameter | Type | Description |
|---|---|---|
ticker_id | i64 | Ticker/request ID. |
timestamp | i64 | Timestamp string. |
provider_code | &str | News provider code (e.g. "BRFG"). |
article_id | &str | News article identifier. |
headline | &str | News headline text. |
extra_data | &str | Additional tick data. |
historical_news
Historical news headline.
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
time | &str | Tick timestamp (Unix seconds). |
provider_code | &str | News provider code (e.g. "BRFG"). |
article_id | &str | News article identifier. |
headline | &str | News headline text. |
historical_news_end
End of historical news.
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
has_more | bool | If true, more results available. |
news_article
Full news article text.
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
article_type | i32 | Article type: 0=plain text, 1=HTML. |
article_text | &str | Full article body. |
real_time_bar
Real-time 5-second OHLCV bar.
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
date | i64 | Bar date string. |
open | f64 | Open price. |
high | f64 | High price. |
low | f64 | Low price. |
close | f64 | Close price. |
volume | f64 | Volume. |
wap | f64 | Volume-weighted average price. |
count | i32 | Trade count. |
historical_ticks
Historical tick data (Last, BidAsk, or Midpoint).
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
ticks | &HistoricalTickData | Historical tick data. |
done | bool | If true, all ticks have been delivered. |
historical_ticks_bid_ask
Historical bid/ask ticks.
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
ticks | &HistoricalTickData | Historical tick data. |
done | bool | If true, all ticks have been delivered. |
historical_ticks_last
Historical last-trade ticks.
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
ticks | &HistoricalTickData | Historical tick data. |
done | bool | If true, all ticks have been delivered. |
tick_option_computation
Option implied vol / greeks computation.
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
tick_type | i32 | Tick type ID or tick-by-tick type string. |
tick_attrib | i32 | |
implied_vol | f64 | Implied volatility. |
delta | f64 | Option delta. |
opt_price | f64 | Option theoretical price. |
pv_dividend | f64 | Present value of dividends. |
gamma | f64 | Option gamma. |
vega | f64 | Option vega. |
theta | f64 | Option theta. |
und_price | f64 | Underlying price. |
security_definition_option_parameter
Option chain parameters (strikes, expirations).
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
exchange | &str | Exchange name. |
underlying_con_id | i64 | Underlying contract ID. |
trading_class | &str | Trading class. |
multiplier | &str | Contract multiplier. |
expirations | &[String] | Available expiration dates. |
strikes | &[f64] | Available strike prices. |
security_definition_option_parameter_end
End of option chain parameters.
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
delta_neutral_validation
Delta-neutral validation response.
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
con_id | i64 | Contract ID. Unique per instrument. |
delta | f64 | Option delta. |
price | f64 | Tick price. |
histogram_data
Price distribution histogram.
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
items | &[(f64, i64 | Histogram entries [(price, count)]. |
market_rule
Market rule: price increment schedule.
| Parameter | Type | Description |
|---|---|---|
market_rule_id | i64 | Market rule ID. |
price_increments | &[PriceIncrement] | Price increment rules [{low_edge, increment}]. |
completed_order
Completed (filled/cancelled) order details.
| Parameter | Type | Description |
|---|---|---|
contract | &Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
order | &Order | Order parameters (action, quantity, type, price, TIF, etc.). |
order_state | &OrderState | Order state (status, margin, commission info). |
completed_orders_end
End of completed orders list.
historical_schedule
Historical trading schedule (exchange hours).
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
start_date_time | &str | Start date/time for tick query. |
end_date_time | &str | End date/time in "YYYYMMDD HH:MM:SS" format, or empty for now. |
time_zone | &str | Timezone string (e.g. "US/Eastern"). |
sessions | &[(String, String, String | Trading sessions [(ref_date, open, close)]. |
fundamental_data
Fundamental data (XML/JSON).
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
data | &str | Raw data string (XML/JSON). |
update_mkt_depth
L2 book update (single exchange).
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
position | i32 | Book position (row index) or position size. |
operation | i32 | Book operation: 0=insert, 1=update, 2=delete. |
side | i32 | Book side: 0=ask, 1=bid. Or order side "BOT"/"SLD". |
price | f64 | Tick price. |
size | f64 | Tick size. |
update_mkt_depth_l2
L2 book update (with market maker).
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
position | i32 | Book position (row index) or position size. |
market_maker | &str | Market maker ID. |
operation | i32 | Book operation: 0=insert, 1=update, 2=delete. |
side | i32 | Book side: 0=ask, 1=bid. Or order side "BOT"/"SLD". |
price | f64 | Tick price. |
size | f64 | Tick size. |
is_smart_depth | bool | If true, aggregate depth from multiple exchanges via SMART. |
mkt_depth_exchanges
Available exchanges for market depth.
| Parameter | Type | Description |
|---|---|---|
descriptions | &[crate::types::DepthMktDataDescription] | Array of matching contract descriptions. |
tick_req_params
Tick parameters: min tick size, BBO exchange, snapshot permissions.
| Parameter | Type | Description |
|---|---|---|
ticker_id | i64 | Ticker/request ID. |
min_tick | f64 | Minimum tick size. |
bbo_exchange | &str | BBO exchange for smart component lookup (e.g. "SMART"). |
snapshot_permissions | i64 | Snapshot permissions bitmask. |
smart_components
SMART routing component exchanges.
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
components | &[crate::types::SmartComponent] | Smart routing component exchanges. |
news_providers
Available news providers list.
| Parameter | Type | Description |
|---|---|---|
providers | &[crate::types::NewsProvider] | News provider list. |
soft_dollar_tiers
Soft dollar tier list.
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
tiers | &[crate::types::SoftDollarTier] | Soft dollar tier list. |
family_codes
Family codes linking related accounts.
| Parameter | Type | Description |
|---|---|---|
codes | &[crate::types::FamilyCode] | Family code list. |
user_info
User info (white branding ID).
| Parameter | Type | Description |
|---|---|---|
req_id | i64 | Request identifier. Used to match responses to requests. |
white_branding_id | &str | White branding ID (empty for standard accounts). |
Python API
The Python surface mirrors the Rust API and is generated from the same source on every release.
Python API Reference (v0.7.1)
Auto-generated from source — do not edit.
Table of Contents
- EClient: Connection
- EClient: Account & Portfolio
- EClient: Orders
- EClient: Market Data
- EClient: Reference Data
- EClient: Gateway-Local & Stubs
- EWrapper Callbacks
Connection
new
Create a new EClient (or EWrapper) instance.
def new(wrapper))
| Parameter | Type | Description |
|---|---|---|
wrapper | Py<PyAny> | Wrapper callback receiver for synchronous delivery. |
connect
Connect to IB and start the engine. Live logins (paper=False) enter a second-factor approval window and block until the factor is approved (mobile push) or the deadline fires (ib_key_timeout_secs, default ~18 min). This is a human approval gate, not a hang. To bound or avoid it: use paper=True, pass a smaller ib_key_timeout_secs, or run connect() on a worker thread with your own timeout. Paper logins skip the gate entirely. Set RUST_LOG=info to see a log line when the wait begins. Multiple EClient instances can run concurrently in one process; each owns its own state, sockets, and engine thread, and connect() does not serialize across instances. If you pin engines via core_id, give each a distinct value. See ibx#203 / ibx#207.
def connect(host="cdc1.ibllc.com".to_string(), port=0, client_id=0, username="".to_string(), password="".to_string(), paper=true, core_id=None, ib_key_timeout_secs=None, ib_key_token_sub_type=None))
| Parameter | Type | Description |
|---|---|---|
host | str | Server hostname. |
port | int | Port number (unused — ibx connects directly). |
client_id | int | Client ID (unused — single-client engine). |
username | str | Account username. |
password | str | Account password. |
paper | bool | If true, connect to paper trading. If false, connect blocks on the live second-factor approval window (see method note). |
core_id | usize or None | CPU core affinity for the hot loop thread. Use a distinct value per engine when running several in one process. |
ib_key_timeout_secs | int or None | Live second-factor approval timeout in seconds (default ~18 min). Lower it to fail fast on unattended live logins; ignored for paper. |
ib_key_token_sub_type | str or None | Account-specific second-factor token sub-type (default "2a"); ignored for paper. |
disconnect
Disconnect from IB.
def disconnect()
is_connected
Check if connected.
def is_connected()
run
Run the event loop.
def run()
get_account_id
Get the account ID.
def get_account_id()
Account & Portfolio
req_pnl
Request P&L updates for the account.
def req_pnl(req_id, account, model_code=""))
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
account | str | Account ID. |
model_code | str | Model portfolio code (empty for default). |
cancel_pnl
Cancel P&L subscription.
def cancel_pnl(req_id)
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
req_pnl_single
Request P&L for a single position.
def req_pnl_single(req_id, account, model_code, con_id))
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
account | str | Account ID. |
model_code | str | Model portfolio code (empty for default). |
con_id | int | Contract ID. Unique per instrument. |
cancel_pnl_single
Cancel single-position P&L subscription.
def cancel_pnl_single(req_id)
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
req_account_summary
Request account summary.
def req_account_summary(req_id, group_name, tags))
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
group_name | str | Account group name (e.g. "All"). |
tags | str | Comma-separated account tags: "NetLiquidation,BuyingPower,...". |
cancel_account_summary
Cancel account summary.
def cancel_account_summary(req_id)
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
req_positions
Request all positions.
def req_positions()
cancel_positions
Cancel positions.
def cancel_positions()
req_account_updates
Request account updates.
def req_account_updates(subscribe, _acct_code=""))
| Parameter | Type | Description |
|---|---|---|
subscribe | bool | true to start updates, false to stop. |
acct_code | str | Account code (e.g. "DU1234567"). |
req_managed_accts
Request managed accounts list.
def req_managed_accts()
req_account_updates_multi
Request account updates for multiple accounts/models.
def req_account_updates_multi(req_id, account, model_code, ledger_and_nlv=false))
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
account | str | Account ID. |
model_code | str | Model portfolio code (empty for default). |
ledger_and_nlv | bool | If true, include ledger and NLV data. |
cancel_account_updates_multi
Cancel multi-account updates.
def cancel_account_updates_multi(req_id)
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
req_positions_multi
Request positions across multiple accounts/models.
def req_positions_multi(req_id, account, model_code))
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
account | str | Account ID. |
model_code | str | Model portfolio code (empty for default). |
cancel_positions_multi
Cancel multi-account positions.
def cancel_positions_multi(req_id)
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
account_snapshot
Read account state snapshot. Returns a dict with all account values.
def account_snapshot()
Orders
place_order
Place an order.
def place_order(order_id, contract, order)
| Parameter | Type | Description |
|---|---|---|
order_id | int | Order identifier. Must be unique per session. |
contract | Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
order | Order | Order parameters (action, quantity, type, price, TIF, etc.). |
cancel_order
Cancel an order.
def cancel_order(order_id, manual_order_cancel_time=""))
| Parameter | Type | Description |
|---|---|---|
order_id | int | Order identifier. Must be unique per session. |
manual_order_cancel_time | str | Manual cancel time (empty for immediate). |
req_global_cancel
Cancel all orders globally.
def req_global_cancel()
req_ids
Request next valid order ID.
def req_ids(num_ids=1))
| Parameter | Type | Description |
|---|---|---|
num_ids | int | Number of IDs to reserve (unused). |
next_order_id
Get the next order ID (local counter, auto-increments).
def next_order_id()
req_open_orders
Request all open orders for this client.
def req_open_orders()
req_all_open_orders
Request all open orders across all clients.
def req_all_open_orders()
req_auto_open_orders
Automatically bind future orders to this client.
def req_auto_open_orders(b_auto_bind))
| Parameter | Type | Description |
|---|---|---|
b_auto_bind | bool | If true, auto-bind future orders to this client. |
req_executions
Request execution reports.
def req_executions(req_id, exec_filter=None))
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
exec_filter | Py<PyAny> or None |
req_completed_orders
Request completed orders.
def req_completed_orders(api_only=false))
| Parameter | Type | Description |
|---|---|---|
api_only | bool |
Market Data
set_news_providers
Set news provider codes for per-contract news ticks (e.g. "BRFG*BRFUPDN").
def set_news_providers(providers))
| Parameter | Type | Description |
|---|---|---|
providers | str | News provider list. |
req_mkt_data
Request market data for a contract.
def req_mkt_data(req_id, contract, generic_tick_list="", snapshot=false, regulatory_snapshot=false, mkt_data_options=Vec::new()))
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
contract | Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
generic_tick_list | str | Comma-separated generic tick IDs (e.g. "233" for RT volume). |
snapshot | bool | If true, delivers one quote then auto-cancels. |
regulatory_snapshot | bool | If true, request a regulatory snapshot (additional fees may apply). |
mkt_data_options | list |
cancel_mkt_data
Cancel market data subscription.
def cancel_mkt_data(req_id)
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
req_tick_by_tick_data
Request tick-by-tick data.
def req_tick_by_tick_data(req_id, contract, tick_type, number_of_ticks=0, ignore_size=false))
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
contract | Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
tick_type | str | Tick type ID or tick-by-tick type string. |
number_of_ticks | int | Maximum number of ticks to return. |
ignore_size | bool | If true, ignore size in tick-by-tick data. |
cancel_tick_by_tick_data
Cancel tick-by-tick data.
def cancel_tick_by_tick_data(req_id)
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
req_ping
Request an auth-connection round-trip time sample (ibx#158): sends a lightweight liveness probe with no side effects on subscriptions, contract caches, or pacing budgets. Poll last_rtt_ms() after a moment for the result.
def req_ping()
last_rtt_ms
Last measured auth-connection round-trip time in milliseconds, or None if never measured (ibx#158). A gauge, not a benchmark — see req_ping. Also sampled automatically by the engine's own liveness probes.
def last_rtt_ms()
req_market_data_type
NOT supported end to end (ibx#234): the requested type (1=live, 2=frozen, 3=delayed, 4=delayed-frozen) is stored locally but never sent to the gateway, so subscriptions always deliver realtime data and delayed tick variants never arrive. Requesting a non-realtime type logs a warning, and the market_data_type callback reports the DELIVERED type (realtime) rather than echoing the request.
def req_market_data_type(market_data_type)
| Parameter | Type | Description |
|---|---|---|
market_data_type | int | 1=live, 2=frozen, 3=delayed, 4=delayed-frozen. |
req_mkt_depth
Request market depth (L2 order book).
def req_mkt_depth(req_id, contract, num_rows=5, is_smart_depth=false, mkt_depth_options=Vec::new()))
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
contract | Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
num_rows | int | Number of order book rows to subscribe to. |
is_smart_depth | bool | If true, aggregate depth from multiple exchanges via SMART. |
mkt_depth_options | list |
cancel_mkt_depth
Cancel market depth.
def cancel_mkt_depth(req_id, is_smart_depth=false))
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
is_smart_depth | bool | If true, aggregate depth from multiple exchanges via SMART. |
req_real_time_bars
Request real-time 5-second bars.
def req_real_time_bars(req_id, contract, bar_size=5, what_to_show="TRADES", use_rth=0, real_time_bars_options=Vec::new()))
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
contract | Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
bar_size | int | Bar size: "1 min", "5 mins", "1 hour", "1 day", etc. |
what_to_show | str | Data type: "TRADES", "MIDPOINT", "BID", "ASK", "BID_ASK", etc. |
use_rth | int | If true, only return data from Regular Trading Hours. |
real_time_bars_options | list |
cancel_real_time_bars
Cancel real-time bars.
def cancel_real_time_bars(req_id)
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
quote
Zero-copy SeqLock quote read by req_id. Returns a dict with bid, ask, last, bid_size, ask_size, last_size, volume, high, low, open, close, or None if the req_id is not mapped.
def quote(req_id)
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
quote_by_instrument
Zero-copy SeqLock quote read by InstrumentId. Returns a dict with bid, ask, last, bid_size, ask_size, last_size, volume, high, low, open, close, or None if not connected.
def quote_by_instrument(instrument)
| Parameter | Type | Description |
|---|---|---|
instrument | int | Instrument type for scanner (e.g. "STK", "FUT"). |
Reference Data
req_historical_data
Request historical bar data.
def req_historical_data(req_id, contract, end_date_time, duration_str, bar_size_setting, what_to_show, use_rth, format_date=1, keep_up_to_date=false, chart_options=Vec::new()))
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
contract | Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
end_date_time | str | End date/time in "YYYYMMDD HH:MM:SS" format, or empty for now. |
duration_str | str | Duration string, e.g. "1 D", "1 W", "1 M", "1 Y". |
bar_size_setting | str | Bar size: "1 min", "5 mins", "1 hour", "1 day", etc. |
what_to_show | str | Data type: "TRADES", "MIDPOINT", "BID", "ASK", "BID_ASK", etc. |
use_rth | int | If true, only return data from Regular Trading Hours. |
format_date | int | Date format: 1="YYYYMMDD HH:MM:SS", 2=Unix seconds. |
keep_up_to_date | bool | If true, continue receiving updates after initial history. |
chart_options | list |
cancel_historical_data
Cancel historical data.
def cancel_historical_data(req_id)
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
req_head_time_stamp
Request head timestamp.
def req_head_time_stamp(req_id, contract, what_to_show, use_rth, format_date=1))
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
contract | Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
what_to_show | str | Data type: "TRADES", "MIDPOINT", "BID", "ASK", "BID_ASK", etc. |
use_rth | int | If true, only return data from Regular Trading Hours. |
format_date | int | Date format: 1="YYYYMMDD HH:MM:SS", 2=Unix seconds. |
cancel_head_time_stamp
Cancel head timestamp request.
def cancel_head_time_stamp(req_id)
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
req_contract_details
Request contract details.
def req_contract_details(req_id, contract)
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
contract | Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
req_mkt_depth_exchanges
Request available exchanges for market depth.
def req_mkt_depth_exchanges()
req_matching_symbols
Search for matching symbols.
def req_matching_symbols(req_id, pattern)
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
pattern | str | Symbol search pattern. |
req_scanner_subscription
Request scanner subscription.
def req_scanner_subscription(req_id, subscription, scanner_subscription_options=Vec::new()))
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
subscription | Py<PyAny> | Scanner subscription parameters. |
scanner_subscription_options | list |
cancel_scanner_subscription
Cancel scanner subscription.
def cancel_scanner_subscription(req_id)
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
req_scanner_parameters
Request scanner parameters XML.
def req_scanner_parameters()
req_news_article
Request a news article.
def req_news_article(req_id, provider_code, article_id, news_article_options=Vec::new()))
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
provider_code | str | News provider code (e.g. "BRFG"). |
article_id | str | News article identifier. |
news_article_options | list |
req_historical_news
Request historical news.
def req_historical_news(req_id, con_id, provider_codes, start_date_time, end_date_time, total_results, historical_news_options=Vec::new()))
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
con_id | int | Contract ID. Unique per instrument. |
provider_codes | str | Pipe-separated news provider codes. |
start_date_time | str | Start date/time for tick query. |
end_date_time | str | End date/time in "YYYYMMDD HH:MM:SS" format, or empty for now. |
total_results | int | Maximum number of news results. |
historical_news_options | list |
req_fundamental_data
Request fundamental data.
def req_fundamental_data(req_id, contract, report_type, fundamental_data_options=Vec::new()))
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
contract | Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
report_type | str | Report type: "ReportSnapshot", "ReportsFinSummary", "RESC", etc. |
fundamental_data_options | list |
cancel_fundamental_data
Cancel fundamental data.
def cancel_fundamental_data(req_id)
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
req_historical_ticks
Request historical tick data.
def req_historical_ticks(req_id, contract, start_date_time="", end_date_time="", number_of_ticks=1000, what_to_show="TRADES", use_rth=1, ignore_size=false, misc_options=Vec::new()))
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
contract | Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
start_date_time | str | Start date/time for tick query. |
end_date_time | str | End date/time in "YYYYMMDD HH:MM:SS" format, or empty for now. |
number_of_ticks | int | Maximum number of ticks to return. |
what_to_show | str | Data type: "TRADES", "MIDPOINT", "BID", "ASK", "BID_ASK", etc. |
use_rth | int | If true, only return data from Regular Trading Hours. |
ignore_size | bool | If true, ignore size in tick-by-tick data. |
misc_options | list |
req_market_rule
Request market rule details.
def req_market_rule(market_rule_id)
| Parameter | Type | Description |
|---|---|---|
market_rule_id | int | Market rule ID. |
req_histogram_data
Request histogram data.
def req_histogram_data(req_id, contract, use_rth, time_period))
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
contract | Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
use_rth | bool | If true, only return data from Regular Trading Hours. |
time_period | str | Histogram time period. |
cancel_histogram_data
Cancel histogram data.
def cancel_histogram_data(req_id)
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
req_historical_schedule
Request historical trading schedule.
def req_historical_schedule(req_id, contract, end_date_time="", duration_str="1 M", use_rth=true))
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
contract | Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
end_date_time | str | End date/time in "YYYYMMDD HH:MM:SS" format, or empty for now. |
duration_str | str | Duration string, e.g. "1 D", "1 W", "1 M", "1 Y". |
use_rth | bool | If true, only return data from Regular Trading Hours. |
Gateway-Local & Stubs
calculate_implied_volatility
Calculate option implied volatility. Not yet implemented.
def calculate_implied_volatility(req_id, contract, option_price, under_price, implied_vol_options=Vec::new()))
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
contract | Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
option_price | float | Option market price. |
under_price | float | Underlying asset price. |
implied_vol_options | list |
calculate_option_price
Calculate option theoretical price. Not yet implemented.
def calculate_option_price(req_id, contract, volatility, under_price, opt_prc_options=Vec::new()))
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
contract | Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
volatility | float | Implied volatility. |
under_price | float | Underlying asset price. |
opt_prc_options | list |
cancel_calculate_implied_volatility
Cancel implied volatility calculation.
def cancel_calculate_implied_volatility(req_id)
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
cancel_calculate_option_price
Cancel option price calculation.
def cancel_calculate_option_price(req_id)
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
exercise_options
Exercise options. Not yet implemented.
def exercise_options(req_id, contract, exercise_action, exercise_quantity, account, _override))
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
contract | Contract | Contract specification (symbol, secType, exchange, currency, etc.). |
exercise_action | int | 1=exercise, 2=lapse. |
exercise_quantity | int | Number of contracts to exercise. |
account | str | Account ID. |
override | int | Override flag for exercise. |
req_sec_def_opt_params
Request option chain parameters. Not yet implemented.
def req_sec_def_opt_params(req_id, underlying_symbol, fut_fop_exchange="", underlying_sec_type="STK", underlying_con_id=0))
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
underlying_symbol | str | Underlying symbol (e.g. "AAPL"). |
fut_fop_exchange | str | Exchange for futures/FOP options. |
underlying_sec_type | str | Underlying security type (e.g. "STK"). |
underlying_con_id | int | Underlying contract ID. |
req_news_bulletins
Subscribe to news bulletins.
def req_news_bulletins(all_msgs=true))
| Parameter | Type | Description |
|---|---|---|
all_msgs | bool | If true, receive all existing bulletins on subscribe. |
cancel_news_bulletins
Cancel news bulletin subscription.
def cancel_news_bulletins()
req_current_time
Request current server time.
def req_current_time()
request_fa
Request FA data. Not yet implemented.
def request_fa(_fa_data_type)
| Parameter | Type | Description |
|---|---|---|
fa_data_type | int | FA data type (1=Groups, 2=Profiles, 3=Aliases). |
replace_fa
Replace FA data. Not yet implemented.
def replace_fa(req_id, fa_data_type, cxml))
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
fa_data_type | int | FA data type (1=Groups, 2=Profiles, 3=Aliases). |
cxml | str | FA XML configuration data. |
query_display_groups
Query display groups.
def query_display_groups(req_id)
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
subscribe_to_group_events
Subscribe to display group events.
def subscribe_to_group_events(req_id, group_id)
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
group_id | int | Display group ID. |
unsubscribe_from_group_events
Unsubscribe from display group events.
def unsubscribe_from_group_events(req_id)
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
update_display_group
Update display group.
def update_display_group(req_id, contract_info)
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
contract_info | str | Display group contract info string. |
req_smart_components
Request SMART routing component exchanges.
def req_smart_components(req_id, bbo_exchange)
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
bbo_exchange | str | BBO exchange for smart component lookup (e.g. "SMART"). |
req_news_providers
Request available news providers.
def req_news_providers()
req_soft_dollar_tiers
Request soft dollar tiers.
def req_soft_dollar_tiers(req_id)
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
req_family_codes
Request family codes.
def req_family_codes()
set_server_log_level
Set server log level (1=error..5=trace).
def set_server_log_level(log_level=2))
| Parameter | Type | Description |
|---|---|---|
log_level | int | Log level: 1=error, 2=warn, 3=info, 4=debug, 5=trace. |
req_user_info
Request user info (white branding ID).
def req_user_info(req_id)
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
req_wsh_meta_data
Request Wall Street Horizon metadata. Not yet implemented.
def req_wsh_meta_data(req_id)
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
req_wsh_event_data
Request Wall Street Horizon event data. Not yet implemented.
def req_wsh_event_data(req_id, wsh_event_data=None))
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
wsh_event_data | Py<PyAny> or None |
EWrapper Callbacks
new
Create a new EClient (or EWrapper) instance.
| Parameter | Type | Description |
|---|---|---|
args | Bound<'_, pyo3::types::PyTuple> | |
kwargs | Bound<'_, pyo3::types::PyDict> or None |
connect_ack
Connection acknowledged.
connection_closed
Connection has been closed.
next_valid_id
Next valid order ID from the server.
| Parameter | Type | Description |
|---|---|---|
order_id | int | Order identifier. Must be unique per session. |
managed_accounts
Comma-separated list of managed account IDs.
| Parameter | Type | Description |
|---|---|---|
accounts_list | str | Comma-separated account IDs. |
error
Error or informational message from the server.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
error_code | int | Error code. |
error_string | str | Error message. |
advanced_order_reject_json | str | JSON with advanced rejection details. |
current_time
Current server time (Unix seconds).
| Parameter | Type | Description |
|---|---|---|
time | int | Tick timestamp (Unix seconds). |
tick_price
Price tick update (bid, ask, last, etc.).
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
tick_type | int | Tick type ID or tick-by-tick type string. |
price | float | Tick price. |
attrib | Py<PyAny> | Tick attributes. |
tick_size
Size tick update (bid size, ask size, volume, etc.).
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
tick_type | int | Tick type ID or tick-by-tick type string. |
size | float | Tick size. |
tick_string
String tick (e.g. last trade timestamp).
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
tick_type | int | Tick type ID or tick-by-tick type string. |
value | str | Account value. |
tick_generic
Generic numeric tick value.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
tick_type | int | Tick type ID or tick-by-tick type string. |
value | float | Account value. |
tick_snapshot_end
Snapshot delivery complete; subscription auto-cancelled.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
market_data_type
Market data type changed (1=live, 2=frozen, 3=delayed, 4=delayed-frozen).
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
market_data_type | int | 1=live, 2=frozen, 3=delayed, 4=delayed-frozen. |
order_status
Order status update (filled, remaining, avg price, etc.).
| Parameter | Type | Description |
|---|---|---|
order_id | int | Order identifier. Must be unique per session. |
status | str | Order status string ("Submitted", "Filled", "Cancelled", etc.). |
filled | float | Cumulative filled quantity. |
remaining | float | Remaining quantity. |
avg_fill_price | float | Average fill price. |
perm_id | int | Permanent order ID assigned by the server. |
parent_id | int | Parent order ID (0 if no parent). |
last_fill_price | float | Price of the last fill. |
client_id | int | Client ID (unused — single-client engine). |
why_held | str | Reason the order is held (e.g. "locate"). |
mkt_cap_price | float | Market cap price for the order. |
open_order
Open order details (contract, order, state).
| Parameter | Type | Description |
|---|---|---|
order_id | int | Order identifier. Must be unique per session. |
contract | Py<PyAny> | Contract specification (symbol, secType, exchange, currency, etc.). |
order | Py<PyAny> | Order parameters (action, quantity, type, price, TIF, etc.). |
order_state | Py<PyAny> | Order state (status, margin, commission info). |
open_order_end
End of open orders list.
exec_details
Execution fill details.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
contract | Py<PyAny> | Contract specification (symbol, secType, exchange, currency, etc.). |
execution | Py<PyAny> | Execution details (exec_id, time, price, shares, etc.). |
exec_details_end
End of execution details list.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
commission_and_fees_report
Commission and fees report for an execution.
| Parameter | Type | Description |
|---|---|---|
commission_and_fees_report | Py<PyAny> |
update_account_value
Account value update (key/value/currency).
| Parameter | Type | Description |
|---|---|---|
key | str | Account value key (e.g. "NetLiquidation", "BuyingPower"). |
value | str | Account value. |
currency | str | Currency code (e.g. "USD"). |
account_name | str | Account identifier. |
update_portfolio
Portfolio position update.
| Parameter | Type | Description |
|---|---|---|
contract | Py<PyAny> | Contract specification (symbol, secType, exchange, currency, etc.). |
position | float | Book position (row index) or position size. |
market_price | float | Current market price. |
market_value | float | Current market value of position. |
average_cost | float | Average cost basis. |
unrealized_pnl | float | Unrealized profit/loss. |
realized_pnl | float | Realized profit/loss. |
account_name | str | Account identifier. |
update_account_time
Account update timestamp.
| Parameter | Type | Description |
|---|---|---|
timestamp | str | Timestamp string. |
account_download_end
Account data delivery complete.
| Parameter | Type | Description |
|---|---|---|
account | str | Account ID. |
account_summary
Account summary tag/value entry.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
account | str | Account ID. |
tag | str | Account tag name (e.g. "NetLiquidation"). |
value | str | Account value. |
currency | str | Currency code (e.g. "USD"). |
account_summary_end
End of account summary.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
position
Position entry (account, contract, size, avg cost).
| Parameter | Type | Description |
|---|---|---|
account | str | Account ID. |
contract | Py<PyAny> | Contract specification (symbol, secType, exchange, currency, etc.). |
pos | float | Position size (decimal shares). |
avg_cost | float | Average cost per share. |
position_end
End of positions list.
pnl
Account P&L update (daily, unrealized, realized).
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
daily_pnl | float | Daily profit/loss. |
unrealized_pnl | float | Unrealized profit/loss. |
realized_pnl | float | Realized profit/loss. |
pnl_single
Single-position P&L update.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
pos | float | Position size (decimal shares). |
daily_pnl | float | Daily profit/loss. |
unrealized_pnl | float | Unrealized profit/loss. |
realized_pnl | float | Realized profit/loss. |
value | float | Account value. |
historical_data
Historical OHLCV bar.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
bar | Py<PyAny> | Bar data (date, open, high, low, close, volume, wap, bar_count). |
historical_data_end
End of historical data delivery.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
start | str | Period start date/time. |
end | str | Period end date/time. |
historical_data_update
Real-time bar update (keep_up_to_date=true).
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
bar | Py<PyAny> | Bar data (date, open, high, low, close, volume, wap, bar_count). |
head_timestamp
Earliest available data timestamp.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
head_timestamp | str | Earliest available data timestamp string. |
contract_details
Contract definition details.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
contract_details | Py<PyAny> |
contract_details_end
End of contract details.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
symbol_samples
Matching symbol search results.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
contract_descriptions | Py<PyAny> |
tick_by_tick_all_last
Tick-by-tick last trade.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
tick_type | int | Tick type ID or tick-by-tick type string. |
time | int | Tick timestamp (Unix seconds). |
price | float | Tick price. |
size | float | Tick size. |
tick_attrib_last | Py<PyAny> | |
exchange | str | Exchange name. |
special_conditions | str | Special trade conditions. |
tick_by_tick_bid_ask
Tick-by-tick bid/ask quote.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
time | int | Tick timestamp (Unix seconds). |
bid_price | float | Bid price. |
ask_price | float | Ask price. |
bid_size | float | Bid size. |
ask_size | float | Ask size. |
tick_attrib_bid_ask | Py<PyAny> |
tick_by_tick_mid_point
Tick-by-tick midpoint.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
time | int | Tick timestamp (Unix seconds). |
mid_point | float | Midpoint price. |
scanner_data
Scanner result entry (rank, contract, distance).
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
rank | int | Scanner result rank (0-based). |
contract_details | Py<PyAny> | |
distance | str | Scanner distance metric. |
benchmark | str | Scanner benchmark. |
projection | str | Scanner projection. |
legs_str | str | Combo legs description. |
scanner_data_end
End of scanner results.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
scanner_parameters
Scanner parameters XML.
| Parameter | Type | Description |
|---|---|---|
xml | str | XML string. |
news_providers
Available news providers list.
| Parameter | Type | Description |
|---|---|---|
news_providers | Py<PyAny> |
news_article
Full news article text.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
article_type | int | Article type: 0=plain text, 1=HTML. |
article_text | str | Full article body. |
historical_news
Historical news headline.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
time | str | Tick timestamp (Unix seconds). |
provider_code | str | News provider code (e.g. "BRFG"). |
article_id | str | News article identifier. |
headline | str | News headline text. |
historical_news_end
End of historical news.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
has_more | bool | If true, more results available. |
tick_news
Per-contract news tick.
| Parameter | Type | Description |
|---|---|---|
ticker_id | int | Ticker/request ID. |
time_stamp | int | Timestamp string. |
provider_code | str | News provider code (e.g. "BRFG"). |
article_id | str | News article identifier. |
headline | str | News headline text. |
extra_data | str | Additional tick data. |
update_mkt_depth
L2 book update (single exchange).
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
position | int | Book position (row index) or position size. |
operation | int | Book operation: 0=insert, 1=update, 2=delete. |
side | int | Book side: 0=ask, 1=bid. Or order side "BOT"/"SLD". |
price | float | Tick price. |
size | float | Tick size. |
update_mkt_depth_l2
L2 book update (with market maker).
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
position | int | Book position (row index) or position size. |
market_maker | str | Market maker ID. |
operation | int | Book operation: 0=insert, 1=update, 2=delete. |
side | int | Book side: 0=ask, 1=bid. Or order side "BOT"/"SLD". |
price | float | Tick price. |
size | float | Tick size. |
is_smart_depth | bool | If true, aggregate depth from multiple exchanges via SMART. |
mkt_depth_exchanges
Available exchanges for market depth.
| Parameter | Type | Description |
|---|---|---|
depth_mkt_data_descriptions | Py<PyAny> |
real_time_bar
Real-time 5-second OHLCV bar.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
date | int | Bar date string. |
open | float | Open price. |
high | float | High price. |
low | float | Low price. |
close | float | Close price. |
volume | float | Volume. |
wap | float | Volume-weighted average price. |
count | int | Trade count. |
historical_ticks
Historical tick data (Last, BidAsk, or Midpoint).
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
ticks | Py<PyAny> | Historical tick data. |
done | bool | If true, all ticks have been delivered. |
historical_ticks_bid_ask
Historical bid/ask ticks.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
ticks | Py<PyAny> | Historical tick data. |
done | bool | If true, all ticks have been delivered. |
historical_ticks_last
Historical last-trade ticks.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
ticks | Py<PyAny> | Historical tick data. |
done | bool | If true, all ticks have been delivered. |
tick_option_computation
Option implied vol / greeks computation.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
tick_type | int | Tick type ID or tick-by-tick type string. |
tick_attrib | int | |
implied_vol | float | Implied volatility. |
delta | float | Option delta. |
opt_price | float | Option theoretical price. |
pv_dividend | float | Present value of dividends. |
gamma | float | Option gamma. |
vega | float | Option vega. |
theta | float | Option theta. |
und_price | float | Underlying price. |
security_definition_option_parameter
Option chain parameters (strikes, expirations).
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
exchange | str | Exchange name. |
underlying_con_id | int | Underlying contract ID. |
trading_class | str | Trading class. |
multiplier | str | Contract multiplier. |
expirations | Py<PyAny> | Available expiration dates. |
strikes | Py<PyAny> | Available strike prices. |
security_definition_option_parameter_end
End of option chain parameters.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
fundamental_data
Fundamental data (XML/JSON).
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
data | str | Raw data string (XML/JSON). |
update_news_bulletin
News bulletin message.
| Parameter | Type | Description |
|---|---|---|
msg_id | int | Bulletin message ID. |
msg_type | int | Bulletin message type (1=regular, 2=exchange). |
message | str | Bulletin message text. |
orig_exchange | str | Originating exchange. |
receive_fa
Financial advisor data received.
| Parameter | Type | Description |
|---|---|---|
fa_data_type | int | FA data type (1=Groups, 2=Profiles, 3=Aliases). |
xml | str | XML string. |
replace_fa_end
Financial advisor replace complete.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
text | str | Informational text. |
position_multi
Multi-account position entry.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
account | str | Account ID. |
model_code | str | Model portfolio code (empty for default). |
contract | Py<PyAny> | Contract specification (symbol, secType, exchange, currency, etc.). |
pos | float | Position size (decimal shares). |
avg_cost | float | Average cost per share. |
position_multi_end
End of multi-account positions.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
account_update_multi
Multi-account value update.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
account | str | Account ID. |
model_code | str | Model portfolio code (empty for default). |
key | str | Account value key (e.g. "NetLiquidation", "BuyingPower"). |
value | str | Account value. |
currency | str | Currency code (e.g. "USD"). |
account_update_multi_end
End of multi-account updates.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
display_group_list
Display group list.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
groups | str | FA group definitions. |
display_group_updated
Display group updated.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
contract_info | str | Display group contract info string. |
market_rule
Market rule: price increment schedule.
| Parameter | Type | Description |
|---|---|---|
market_rule_id | int | Market rule ID. |
price_increments | Py<PyAny> | Price increment rules [{low_edge, increment}]. |
smart_components
SMART routing component exchanges.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
smart_component_map | Py<PyAny> |
soft_dollar_tiers
Soft dollar tier list.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
tiers | Py<PyAny> | Soft dollar tier list. |
family_codes
Family codes linking related accounts.
| Parameter | Type | Description |
|---|---|---|
family_codes | Py<PyAny> |
histogram_data
Price distribution histogram.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
items | Py<PyAny> | Histogram entries [(price, count)]. |
user_info
User info (white branding ID).
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
white_branding_id | str | White branding ID (empty for standard accounts). |
wsh_meta_data
Wall Street Horizon metadata.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
data_json | str |
wsh_event_data
Wall Street Horizon event data.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
data_json | str |
completed_order
Completed (filled/cancelled) order details.
| Parameter | Type | Description |
|---|---|---|
contract | Py<PyAny> | Contract specification (symbol, secType, exchange, currency, etc.). |
order | Py<PyAny> | Order parameters (action, quantity, type, price, TIF, etc.). |
order_state | Py<PyAny> | Order state (status, margin, commission info). |
completed_orders_end
End of completed orders list.
order_bound
Order bound to a perm ID.
| Parameter | Type | Description |
|---|---|---|
order_id | int | Order identifier. Must be unique per session. |
api_client_id | int | |
api_order_id | int |
tick_req_params
Tick parameters: min tick size, BBO exchange, snapshot permissions.
| Parameter | Type | Description |
|---|---|---|
ticker_id | int | Ticker/request ID. |
min_tick | float | Minimum tick size. |
bbo_exchange | str | BBO exchange for smart component lookup (e.g. "SMART"). |
snapshot_permissions | int | Snapshot permissions bitmask. |
bond_contract_details
Bond contract details.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
contract_details | Py<PyAny> |
delta_neutral_validation
Delta-neutral validation response.
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
delta_neutral_contract | Py<PyAny> |
historical_schedule
Historical trading schedule (exchange hours).
| Parameter | Type | Description |
|---|---|---|
req_id | int | Request identifier. Used to match responses to requests. |
start_date_time | str | Start date/time for tick query. |
end_date_time | str | End date/time in "YYYYMMDD HH:MM:SS" format, or empty for now. |
time_zone | str | Timezone string (e.g. "US/Eastern"). |
sessions | Py<PyAny> | Trading sessions [(ref_date, open, close)]. |
Endpoint Coverage
Coverage of the official IB API surface — what's implemented, what's stubbed, what's pending.
API Coverage Matrix (v0.7.1)
Auto-generated from source — do not edit.
Canonical IB API methods vs ibx implementation status.
- Y = Implemented
- STUB = Accepts call but not wired to server (logs warning or no-op)
- - = Not present
Summary
| IB API | Rust | Python | |
|---|---|---|---|
| EClient methods | 77 | 63 impl, 8 stub | 63 impl, 14 stub |
| EWrapper callbacks | 81 | 66 impl, 3 stub | 70 impl, 11 stub |
EClient Methods
| Category | IB API Method | C++ Name | Rust | Python |
|---|---|---|---|---|
| Connection | connect | eConnect | Y | Y |
disconnect | eDisconnect | Y | Y | |
is_connected | isConnected | Y | Y | |
set_server_log_level | setServerLogLevel | Y | Y | |
req_current_time | reqCurrentTime | Y | Y | |
| Market Data | req_mkt_data | reqMktData | Y | Y |
cancel_mkt_data | cancelMktData | Y | Y | |
req_market_data_type | reqMarketDataType | Y | Y | |
req_tick_by_tick_data | reqTickByTickData | Y | Y | |
cancel_tick_by_tick_data | cancelTickByTickData | Y | Y | |
req_mkt_depth | reqMktDepth | Y | Y | |
cancel_mkt_depth | cancelMktDepth | Y | Y | |
req_mkt_depth_exchanges | reqMktDepthExchanges | Y | Y | |
req_smart_components | reqSmartComponents | Y | Y | |
req_real_time_bars | reqRealTimeBars | Y | Y | |
cancel_real_time_bars | cancelRealTimeBars | Y | Y | |
| Historical Data | req_historical_data | reqHistoricalData | Y | Y |
cancel_historical_data | cancelHistoricalData | Y | Y | |
req_head_time_stamp | reqHeadTimeStamp | Y | Y | |
cancel_head_time_stamp | cancelHeadTimestamp | Y | Y | |
req_historical_ticks | reqHistoricalTicks | Y | Y | |
req_histogram_data | reqHistogramData | Y | Y | |
cancel_histogram_data | cancelHistogramData | Y | Y | |
req_historical_schedule | reqHistoricalSchedule | Y | Y | |
| Orders | place_order | placeOrder | Y | Y |
cancel_order | cancelOrder | Y | Y | |
req_open_orders | reqOpenOrders | Y | Y | |
req_all_open_orders | reqAllOpenOrders | Y | Y | |
req_auto_open_orders | reqAutoOpenOrders | Y | Y | |
req_ids | reqIds | Y | Y | |
req_global_cancel | reqGlobalCancel | Y | Y | |
req_completed_orders | reqCompletedOrders | Y | Y | |
| Executions | req_executions | reqExecutions | Y | Y |
| Account | req_account_updates | reqAccountUpdates | Y | Y |
req_account_summary | reqAccountSummary | Y | Y | |
cancel_account_summary | cancelAccountSummary | Y | Y | |
req_positions | reqPositions | Y | Y | |
cancel_positions | cancelPositions | Y | Y | |
req_pnl | reqPnL | Y | Y | |
cancel_pnl | cancelPnL | Y | Y | |
req_pnl_single | reqPnLSingle | Y | Y | |
cancel_pnl_single | cancelPnLSingle | Y | Y | |
req_managed_accts | reqManagedAccts | Y | Y | |
req_account_updates_multi | reqAccountUpdatesMulti | Y | Y | |
cancel_account_updates_multi | cancelAccountUpdatesMulti | Y | Y | |
req_positions_multi | reqPositionsMulti | Y | Y | |
cancel_positions_multi | cancelPositionsMulti | Y | Y | |
| Contract | req_contract_details | reqContractDetails | Y | Y |
req_matching_symbols | reqMatchingSymbols | Y | Y | |
req_market_rule | reqMarketRule | Y | Y | |
| Scanner | req_scanner_parameters | reqScannerParameters | Y | Y |
req_scanner_subscription | reqScannerSubscription | Y | Y | |
cancel_scanner_subscription | cancelScannerSubscription | Y | Y | |
| News | req_news_providers | reqNewsProviders | Y | Y |
req_news_article | reqNewsArticle | Y | Y | |
req_historical_news | reqHistoricalNews | Y | Y | |
req_news_bulletins | reqNewsBulletins | Y | Y | |
cancel_news_bulletins | cancelNewsBulletins | Y | Y | |
| Fundamental | req_fundamental_data | reqFundamentalData | Y | Y |
cancel_fundamental_data | cancelFundamentalData | Y | Y | |
| Options | calculate_implied_volatility | calculateImpliedVolatility | - | STUB |
cancel_calculate_implied_volatility | cancelCalculateImpliedVolatility | - | STUB | |
calculate_option_price | calculateOptionPrice | - | STUB | |
cancel_calculate_option_price | cancelCalculateOptionPrice | - | STUB | |
exercise_options | exerciseOptions | - | STUB | |
req_sec_def_opt_params | reqSecDefOptParams | - | STUB | |
| Reference | req_soft_dollar_tiers | reqSoftDollarTiers | Y | Y |
req_family_codes | reqFamilyCodes | Y | Y | |
req_user_info | reqUserInfo | Y | Y | |
| Financial Advisor | request_fa | requestFA | STUB | STUB |
replace_fa | replaceFA | STUB | STUB | |
| Display Groups | query_display_groups | queryDisplayGroups | STUB | STUB |
subscribe_to_group_events | subscribeToGroupEvents | STUB | STUB | |
unsubscribe_from_group_events | unsubscribeFromGroupEvents | STUB | STUB | |
update_display_group | updateDisplayGroup | STUB | STUB | |
| WSH | req_wsh_meta_data | reqWshMetaData | STUB | STUB |
req_wsh_event_data | reqWshEventData | STUB | STUB |
EWrapper Callbacks
| Category | Callback | Rust | Python |
|---|---|---|---|
| Connection | connect_ack | Y | Y |
connection_closed | Y | Y | |
next_valid_id | Y | Y | |
managed_accounts | Y | Y | |
error | Y | Y | |
current_time | Y | Y | |
| Market Data | tick_price | Y | Y |
tick_size | Y | Y | |
tick_string | Y | Y | |
tick_generic | Y | Y | |
tick_snapshot_end | Y | Y | |
market_data_type | Y | Y | |
tick_req_params | Y | Y | |
| Orders | order_status | Y | Y |
open_order | Y | Y | |
open_order_end | Y | Y | |
order_bound | - | STUB | |
| Executions | exec_details | Y | Y |
exec_details_end | Y | Y | |
commission_and_fees_report | Y | Y | |
| Account | update_account_value | Y | Y |
update_portfolio | Y | Y | |
update_account_time | Y | Y | |
account_download_end | Y | Y | |
account_summary | Y | Y | |
account_summary_end | Y | Y | |
position | Y | Y | |
position_end | Y | Y | |
pnl | Y | Y | |
pnl_single | Y | Y | |
position_multi | - | Y | |
position_multi_end | - | Y | |
account_update_multi | - | Y | |
account_update_multi_end | - | Y | |
| Contract | contract_details | Y | Y |
contract_details_end | Y | Y | |
bond_contract_details | - | STUB | |
symbol_samples | Y | Y | |
| Historical Data | historical_data | Y | Y |
historical_data_end | Y | Y | |
historical_data_update | Y | Y | |
head_timestamp | Y | Y | |
historical_ticks | Y | Y | |
historical_ticks_bid_ask | Y | Y | |
historical_ticks_last | Y | Y | |
histogram_data | Y | Y | |
historical_schedule | Y | Y | |
| Market Depth | update_mkt_depth | Y | Y |
update_mkt_depth_l2 | Y | Y | |
mkt_depth_exchanges | Y | Y | |
| Tick-by-Tick | tick_by_tick_all_last | Y | Y |
tick_by_tick_bid_ask | Y | Y | |
tick_by_tick_mid_point | Y | Y | |
| Scanner | scanner_data | Y | Y |
scanner_data_end | Y | Y | |
scanner_parameters | Y | Y | |
| News | news_providers | Y | Y |
news_article | Y | Y | |
historical_news | Y | Y | |
historical_news_end | Y | Y | |
tick_news | Y | Y | |
update_news_bulletin | Y | Y | |
| Real-Time Bars | real_time_bar | Y | Y |
| Fundamental | fundamental_data | Y | Y |
| Market Rules | market_rule | Y | Y |
| Completed Orders | completed_order | Y | Y |
completed_orders_end | Y | Y | |
| Options | tick_option_computation | Y | Y |
security_definition_option_parameter | STUB | STUB | |
security_definition_option_parameter_end | STUB | STUB | |
| Reference | smart_components | Y | Y |
soft_dollar_tiers | Y | Y | |
family_codes | Y | Y | |
user_info | Y | Y | |
| FA | receive_fa | - | STUB |
replace_fa_end | - | STUB | |
| Display Groups | display_group_list | - | STUB |
display_group_updated | - | STUB | |
| Other | delta_neutral_validation | STUB | STUB |
| WSH | wsh_meta_data | - | STUB |
wsh_event_data | - | STUB |