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.

Get Started → Read the recipes GitHub

340 ns
Tick read latency
~460 ns
Order send latency
5,900×
Faster than Java Gateway
2
Languages, one engine

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

The smallest possible IBX program: connect, wait for next_valid_id, disconnect.

What this shows

  • Reading credentials from environment variables.
  • Building an EClientConfig for the paper host.
  • Receiving next_valid_id — the signal that the session is fully established and ready for requests.

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(())
}

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_msgs until the end-of-stream marker arrives.
  • Reading con_id, primary exchange, and trading class out of ContractDetails.

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 Contract with con_id so the request is unambiguous.
  • Calling req_historical_data with duration / bar size / what-to-show.
  • Pumping callbacks with process_msgs until historical_data_end lands.
  • 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_data for top-of-book streaming.
  • Routing tick types through the tick_price callback (1=bid, 2=ask, 4=last).
  • Cancelling cleanly with cancel_mkt_data before 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_depth for multiple contracts.
  • Building an in-memory book from update_mkt_depth_l2 events (insert / update / delete ops).
  • 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_subscription with instrument / location / scan code.
  • Reading scanner_data rows (rank + ContractDetails) until scanner_data_end.
  • Cancelling cleanly with cancel_scanner_subscription before disconnecting.

The engine returns the con_id for each result. Resolve to a full contract with req_contract_details if you need symbol / exchange.

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_pnl from the pnl callback.
  • Cancelling cleanly with cancel_pnl before 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_id from client.next_order_id().
  • Building an Order with order_type = "LMT" and lmt_price set.
  • Reading order_status callbacks (PreSubmittedSubmitted).
  • Cancelling with cancel_order and observing the Cancelled terminal 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_id from client.next_order_id().
  • Building an Order with order_type = "STP" and the trigger in aux_price.
  • Reading order_status callbacks (PreSubmittedSubmitted).
  • Cancelling with cancel_order and observing the Cancelled terminal 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.

What this shows

  • Reading credentials from environment variables.
  • Calling EClient.connect(...) against the paper host.
  • Receiving next_valid_id — the signal that the session is fully established and ready for requests.

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()

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 returned ContractDetails.

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 Contract with con_id so the request is unambiguous.
  • Calling req_historical_data with 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_data for top-of-book streaming.
  • Routing tick types through the tick_price callback (1=bid, 2=ask, 4=last).
  • Cancelling cleanly with cancel_mkt_data before 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_depth for multiple contracts.
  • Building an in-memory book from update_mkt_depth_l2 events (insert / update / delete ops).
  • 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 via getattr).
  • Reading scanner_data rows (rank + ContractDetails) until scanner_data_end.
  • Cancelling cleanly with cancel_scanner_subscription before disconnecting.

The engine returns the con_id for each result. Resolve to a full contract with req_contract_details if you need symbol / exchange.

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_pnl from the pnl callback.
  • Cancelling cleanly with cancel_pnl before 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_id from next_valid_id.
  • Building an Order with order_type = "LMT" and lmt_price set.
  • Reading order_status callbacks (PreSubmittedSubmitted).
  • Cancelling with cancel_order and observing the Cancelled terminal 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_id from next_valid_id.
  • Building an Order with order_type = "STP" and the trigger in aux_price.
  • Reading order_status callbacks (PreSubmittedSubmitted).
  • Cancelling with cancel_order and observing the Cancelled terminal 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 orderId from next_valid_id.
  • Placing a limit order far from market and observing Submitted status.
  • Verifying it appears in req_open_orders with the expected permId.
  • Modifying the same orderId and confirming permId is stable across modify.
  • Walking the price toward market to trigger a fill, then querying req_executions.
  • Cancelling a fresh order and observing the Cancelled terminal 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.

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.5.0)

Auto-generated from source — do not edit.

Table of Contents

Connection

connect

Connect to IB and start the engine.

pub fn connect(config: &EClientConfig) -> Result<Self, Box<dyn std::error::Error>>
ParameterTypeDescription
config&EClientConfigConnection configuration (username, password, host, paper, core_id).

Returns: Result<Self, 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
ParameterTypeDescription
sharedArc<SharedState>Shared state handle.
control_txSender<ControlCommand>Control channel sender.
handlethread::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)
ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
instrumentInstrumentIdInstrument 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, )
ParameterTypeDescription
order_idu64Order identifier. Must be unique per session.
contractApiContractContract specification (symbol, secType, exchange, currency, etc.).
orderApiOrderOrder parameters (action, quantity, type, price, TIF, etc.).
instrumentInstrumentIdInstrument 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)
ParameterTypeDescription
con_idi64Contract ID. Unique per instrument.
instrumentInstrumentIdInstrument type for scanner (e.g. "STK", "FUT").

is_connected

Check if the client is connected.

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>
ParameterTypeDescription
key&strAccount 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)
ParameterTypeDescription
wrapper&mut impl WrapperWrapper 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)
ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
account&strAccount ID.
model_code&strModel portfolio code (empty for default).

cancel_pnl

Cancel PnL subscription.

pub fn cancel_pnl(&self, req_id: i64)
ParameterTypeDescription
req_idi64Request 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)
ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
account&strAccount ID.
model_code&strModel portfolio code (empty for default).
con_idi64Contract ID. Unique per instrument.

cancel_pnl_single

Cancel single-position PnL subscription.

pub fn cancel_pnl_single(&self, req_id: i64)
ParameterTypeDescription
req_idi64Request 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)
ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
group&strAccount group name (e.g. "All").
tags&strComma-separated account tags: "NetLiquidation,BuyingPower,...".

cancel_account_summary

Cancel account summary.

pub fn cancel_account_summary(&self, req_id: i64)
ParameterTypeDescription
req_idi64Request 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)
ParameterTypeDescription
subscribebooltrue to start updates, false to stop.
acct_code&strAccount 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)
ParameterTypeDescription
wrapper&mut impl WrapperWrapper 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, )
ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
account&strAccount ID.
model_code&strModel portfolio code (empty for default).
ledger_and_nlvboolIf true, include ledger and NLV data.
wrapper&mut impl WrapperWrapper callback receiver for synchronous delivery.

cancel_account_updates_multi

Cancel multi-account updates.

pub fn cancel_account_updates_multi(&self, _req_id: i64)
ParameterTypeDescription
req_idi64Request 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, )
ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
account&strAccount ID.
model_code&strModel portfolio code (empty for default).
wrapper&mut impl WrapperWrapper callback receiver for synchronous delivery.

cancel_positions_multi

Cancel multi-account positions.

pub fn cancel_positions_multi(&self, _req_id: i64)
ParameterTypeDescription
req_idi64Request 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>
ParameterTypeDescription
order_idi64Order identifier. Must be unique per session.
contract&ContractContract specification (symbol, secType, exchange, currency, etc.).
order&OrderOrder 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>
ParameterTypeDescription
order_idi64Order identifier. Must be unique per session.
manual_order_cancel_time&strManual cancel time (empty for immediate).

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)
ParameterTypeDescription
wrapper&mut impl WrapperWrapper 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)
ParameterTypeDescription
wrapper&mut impl WrapperWrapper callback receiver for synchronous delivery.

req_all_open_orders

Request all open orders.

pub fn req_all_open_orders(&self, wrapper: &mut impl Wrapper)
ParameterTypeDescription
wrapper&mut impl WrapperWrapper 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)
ParameterTypeDescription
wrapper&mut impl WrapperWrapper 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)
ParameterTypeDescription
b_auto_bindboolIf 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)
ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
filter&ExecutionFilterExecution filter (client_id, acct_code, time, symbol, sec_type, exchange, side).
wrapper&mut impl WrapperWrapper 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>
ParameterTypeDescription
strategy&strAlgo 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.

pub fn req_mkt_data( &self, req_id: i64, contract: &Contract, generic_tick_list: &str, snapshot: bool, regulatory_snapshot: bool, ) -> Result<(), String>
ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
contract&ContractContract specification (symbol, secType, exchange, currency, etc.).
generic_tick_list&strComma-separated generic tick IDs (e.g. "233" for RT volume).
snapshotboolIf true, delivers one quote then auto-cancels.
regulatory_snapshotboolIf 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>
ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
contract&ContractContract specification (symbol, secType, exchange, currency, etc.).
generic_tick_list&strComma-separated generic tick IDs (e.g. "233" for RT volume).
snapshotboolIf true, delivers one quote then auto-cancels.
regulatory_snapshotboolIf true, request a regulatory snapshot (additional fees may apply).
mode_9887i32

Returns: Result<(), String>


cancel_mkt_data

Cancel market data.

pub fn cancel_mkt_data(&self, req_id: i64) -> Result<(), String>
ParameterTypeDescription
req_idi64Request 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>
ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
contract&ContractContract specification (symbol, secType, exchange, currency, etc.).
tick_type&strTick type ID or tick-by-tick type string.
number_of_ticksi32Maximum number of ticks to return.
ignore_sizeboolIf 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>
ParameterTypeDescription
req_idi64Request 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>
ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
contract&ContractContract specification (symbol, secType, exchange, currency, etc.).
num_rowsi32Number of order book rows to subscribe to.
is_smart_depthboolIf 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>
ParameterTypeDescription
req_idi64Request 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>
ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
contract&ContractContract specification (symbol, secType, exchange, currency, etc.).
bar_sizei32Bar size: "1 min", "5 mins", "1 hour", "1 day", etc.
what_to_show&strData type: "TRADES", "MIDPOINT", "BID", "ASK", "BID_ASK", etc.
use_rthboolIf 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>
ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.

Returns: Result<(), String>


req_market_data_type

Set market data type preference (1=live, 2=frozen, 3=delayed, 4=delayed-frozen).

pub fn req_market_data_type(&self, market_data_type: i32)
ParameterTypeDescription
market_data_typei321=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)
ParameterTypeDescription
providers&strNews 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>
ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.

Returns: Option<Quote>


quote_by_instrument

Direct SeqLock read by InstrumentId (for callers who track IDs themselves).

pub fn quote_by_instrument(&self, instrument: InstrumentId) -> Quote
ParameterTypeDescription
instrumentInstrumentIdInstrument type for scanner (e.g. "STK", "FUT").

Returns: 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>
ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
contract&ContractContract specification (symbol, secType, exchange, currency, etc.).
end_date_time&strEnd date/time in "YYYYMMDD HH:MM:SS" format, or empty for now.
duration&strDuration string, e.g. "1 D", "1 W", "1 M", "1 Y".
bar_size&strBar size: "1 min", "5 mins", "1 hour", "1 day", etc.
what_to_show&strData type: "TRADES", "MIDPOINT", "BID", "ASK", "BID_ASK", etc.
use_rthboolIf true, only return data from Regular Trading Hours.
format_datei32Date format: 1="YYYYMMDD HH:MM:SS", 2=Unix seconds.
keep_up_to_dateboolIf 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>
ParameterTypeDescription
req_idi64Request 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>
ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
contract&ContractContract specification (symbol, secType, exchange, currency, etc.).
what_to_show&strData type: "TRADES", "MIDPOINT", "BID", "ASK", "BID_ASK", etc.
use_rthboolIf true, only return data from Regular Trading Hours.
format_datei32Date 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>
ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
contract&ContractContract 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>
ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
pattern&strSymbol 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>
ParameterTypeDescription
req_idi64Request 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)
ParameterTypeDescription
market_rule_idi32Market rule ID.
wrapper&mut impl crate::api::wrapper::WrapperWrapper callback receiver for synchronous delivery.

req_news_bulletins

Subscribe to news bulletins.

pub fn req_news_bulletins(&self, _all_msgs: bool)
ParameterTypeDescription
all_msgsboolIf 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>
ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
instrument&strInstrument type for scanner (e.g. "STK", "FUT").
location_code&strScanner location (e.g. "STK.US.MAJOR").
scan_code&strScanner code (e.g. "TOP_PERC_GAIN", "HIGH_OPT_IMP_VOLAT").
max_itemsu32Maximum 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>
ParameterTypeDescription
req_idi64Request 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>
ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
con_idi64Contract ID. Unique per instrument.
provider_codes&strPipe-separated news provider codes.
start_time&strStart date/time for news query.
end_time&strEnd date/time for news query.
max_resultsu32Maximum 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>
ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
provider_code&strNews provider code (e.g. "BRFG").
article_id&strNews 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>
ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
contract&ContractContract specification (symbol, secType, exchange, currency, etc.).
report_type&strReport 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>
ParameterTypeDescription
req_idi64Request 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>
ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
contract&ContractContract specification (symbol, secType, exchange, currency, etc.).
use_rthboolIf true, only return data from Regular Trading Hours.
period&strHistogram 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>
ParameterTypeDescription
req_idi64Request 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>
ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
contract&ContractContract specification (symbol, secType, exchange, currency, etc.).
start_date_time&strStart date/time for tick query.
end_date_time&strEnd date/time in "YYYYMMDD HH:MM:SS" format, or empty for now.
number_of_ticksi32Maximum number of ticks to return.
what_to_show&strData type: "TRADES", "MIDPOINT", "BID", "ASK", "BID_ASK", etc.
use_rthboolIf 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>
ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
contract&ContractContract specification (symbol, secType, exchange, currency, etc.).
end_date_time&strEnd date/time in "YYYYMMDD HH:MM:SS" format, or empty for now.
duration&strDuration string, e.g. "1 D", "1 W", "1 M", "1 Y".
use_rthboolIf 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)
ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
bbo_exchange&strBBO exchange for smart component lookup (e.g. "SMART").
wrapper&mut impl WrapperWrapper 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)
ParameterTypeDescription
wrapper&mut impl WrapperWrapper 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)
ParameterTypeDescription
wrapper&mut impl WrapperWrapper callback receiver for synchronous delivery.

request_fa

Request FA data. Not yet implemented.

pub fn request_fa(&self, _fa_data_type: i32)
ParameterTypeDescription
fa_data_typei32FA 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)
ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
fa_data_typei32FA data type (1=Groups, 2=Profiles, 3=Aliases).
cxml&strFA XML configuration data.

query_display_groups

Query display groups. Not yet implemented.

pub fn query_display_groups(&self, _req_id: i64)
ParameterTypeDescription
req_idi64Request 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)
ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
group_idi32Display group ID.

unsubscribe_from_group_events

Unsubscribe from display group events. Not yet implemented.

pub fn unsubscribe_from_group_events(&self, _req_id: i64)
ParameterTypeDescription
req_idi64Request 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)
ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
contract_info&strDisplay 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)
ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
wrapper&mut impl WrapperWrapper 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)
ParameterTypeDescription
wrapper&mut impl WrapperWrapper callback receiver for synchronous delivery.

set_server_log_level

Set server log level.

pub fn set_server_log_level(&self, log_level: i32)
ParameterTypeDescription
log_leveli32Log 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)
ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
wrapper&mut impl WrapperWrapper 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)
ParameterTypeDescription
req_idi64Request 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)
ParameterTypeDescription
req_idi64Request 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.

ParameterTypeDescription
order_idi64Order identifier. Must be unique per session.

managed_accounts

Comma-separated list of managed account IDs.

ParameterTypeDescription
accounts_list&strComma-separated account IDs.

error

Error or informational message from the server.

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
error_codei64Error code.
error_string&strError message.
advanced_order_reject_json&strJSON with advanced rejection details.

current_time

Current server time (Unix seconds).

ParameterTypeDescription
timei64Tick timestamp (Unix seconds).

tick_price

Price tick update (bid, ask, last, etc.).

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
tick_typei32Tick type ID or tick-by-tick type string.
pricef64Tick price.
attrib&TickAttribTick attributes.

tick_size

Size tick update (bid size, ask size, volume, etc.).

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
tick_typei32Tick type ID or tick-by-tick type string.
sizef64Tick size.

tick_string

String tick (e.g. last trade timestamp).

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
tick_typei32Tick type ID or tick-by-tick type string.
value&strAccount value.

tick_generic

Generic numeric tick value.

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
tick_typei32Tick type ID or tick-by-tick type string.
valuef64Account value.

tick_snapshot_end

Snapshot delivery complete; subscription auto-cancelled.

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.

market_data_type

Market data type changed (1=live, 2=frozen, 3=delayed, 4=delayed-frozen).

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
market_data_typei321=live, 2=frozen, 3=delayed, 4=delayed-frozen.

order_status

Order status update (filled, remaining, avg price, etc.).

ParameterTypeDescription
order_idi64Order identifier. Must be unique per session.
status&strOrder status string ("Submitted", "Filled", "Cancelled", etc.).
filledf64Cumulative filled quantity.
remainingf64Remaining quantity.
avg_fill_pricef64Average fill price.
perm_idi64Permanent order ID assigned by the server.
parent_idi64Parent order ID (0 if no parent).
last_fill_pricef64Price of the last fill.
client_idi64Client ID (unused — single-client engine).
why_held&strReason the order is held (e.g. "locate").
mkt_cap_pricef64Market cap price for the order.

open_order

Open order details (contract, order, state).

ParameterTypeDescription
order_idi64Order identifier. Must be unique per session.
contract&ContractContract specification (symbol, secType, exchange, currency, etc.).
order&OrderOrder parameters (action, quantity, type, price, TIF, etc.).
order_state&OrderStateOrder state (status, margin, commission info).

open_order_end

End of open orders list.


exec_details

Execution fill details.

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
contract&ContractContract specification (symbol, secType, exchange, currency, etc.).
execution&ExecutionExecution details (exec_id, time, price, shares, etc.).

exec_details_end

End of execution details list.

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.

commission_and_fees_report

Commission and fees report for an execution.

ParameterTypeDescription
report&CommissionAndFeesReportCommission report (exec_id, commission, currency, realized P&L).

update_account_value

Account value update (key/value/currency).

ParameterTypeDescription
key&strAccount value key (e.g. "NetLiquidation", "BuyingPower").
value&strAccount value.
currency&strCurrency code (e.g. "USD").
account_name&strAccount identifier.

update_portfolio

Portfolio position update.

ParameterTypeDescription
contract&ContractContract specification (symbol, secType, exchange, currency, etc.).
positionf64Book position (row index) or position size.
market_pricef64Current market price.
market_valuef64Current market value of position.
average_costf64Average cost basis.
unrealized_pnlf64Unrealized profit/loss.
realized_pnlf64Realized profit/loss.
account_name&strAccount identifier.

update_account_time

Account update timestamp.

ParameterTypeDescription
timestamp&strTimestamp string.

account_download_end

Account data delivery complete.

ParameterTypeDescription
account&strAccount ID.

account_summary

Account summary tag/value entry.

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
account&strAccount ID.
tag&strAccount tag name (e.g. "NetLiquidation").
value&strAccount value.
currency&strCurrency code (e.g. "USD").

account_summary_end

End of account summary.

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.

position

Position entry (account, contract, size, avg cost).

ParameterTypeDescription
account&strAccount ID.
contract&ContractContract specification (symbol, secType, exchange, currency, etc.).
posf64Position size (decimal shares).
avg_costf64Average cost per share.

position_end

End of positions list.


pnl

Account P&L update (daily, unrealized, realized).

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
daily_pnlf64Daily profit/loss.
unrealized_pnlf64Unrealized profit/loss.
realized_pnlf64Realized profit/loss.

pnl_single

Single-position P&L update.

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
posf64Position size (decimal shares).
daily_pnlf64Daily profit/loss.
unrealized_pnlf64Unrealized profit/loss.
realized_pnlf64Realized profit/loss.
valuef64Account value.

historical_data

Historical OHLCV bar.

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
bar&BarDataBar data (date, open, high, low, close, volume, wap, bar_count).

historical_data_end

End of historical data delivery.

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
start&strPeriod start date/time.
end&strPeriod end date/time.

historical_data_update

Real-time bar update (keep_up_to_date=true).

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
bar&BarDataBar data (date, open, high, low, close, volume, wap, bar_count).

head_timestamp

Earliest available data timestamp.

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
head_timestamp&strEarliest available data timestamp string.

contract_details

Contract definition details.

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
details&ContractDetailsContract details object.

contract_details_end

End of contract details.

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.

symbol_samples

Matching symbol search results.

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
descriptions&[ContractDescription]Array of matching contract descriptions.

tick_by_tick_all_last

Tick-by-tick last trade.

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
tick_typei32Tick type ID or tick-by-tick type string.
timei64Tick timestamp (Unix seconds).
pricef64Tick price.
sizef64Tick size.
attrib&TickAttribLastTick attributes.
exchange&strExchange name.
special_conditions&strSpecial trade conditions.

tick_by_tick_bid_ask

Tick-by-tick bid/ask quote.

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
timei64Tick timestamp (Unix seconds).
bid_pricef64Bid price.
ask_pricef64Ask price.
bid_sizef64Bid size.
ask_sizef64Ask size.
attrib&TickAttribBidAskTick attributes.

tick_by_tick_mid_point

Tick-by-tick midpoint.

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
timei64Tick timestamp (Unix seconds).
mid_pointf64Midpoint price.

scanner_data

Scanner result entry (rank, contract, distance).

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
ranki32Scanner result rank (0-based).
details&ContractDetailsContract details object.
distance&strScanner distance metric.
benchmark&strScanner benchmark.
projection&strScanner projection.
legs_str&strCombo legs description.

scanner_data_end

End of scanner results.

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.

scanner_parameters

Scanner parameters XML.

ParameterTypeDescription
xml&strXML string.

update_news_bulletin

News bulletin message.

ParameterTypeDescription
msg_idi64Bulletin message ID.
msg_typei32Bulletin message type (1=regular, 2=exchange).
message&strBulletin message text.
orig_exchange&strOriginating exchange.

tick_news

Per-contract news tick.

ParameterTypeDescription
ticker_idi64Ticker/request ID.
timestampi64Timestamp string.
provider_code&strNews provider code (e.g. "BRFG").
article_id&strNews article identifier.
headline&strNews headline text.
extra_data&strAdditional tick data.

historical_news

Historical news headline.

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
time&strTick timestamp (Unix seconds).
provider_code&strNews provider code (e.g. "BRFG").
article_id&strNews article identifier.
headline&strNews headline text.

historical_news_end

End of historical news.

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
has_moreboolIf true, more results available.

news_article

Full news article text.

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
article_typei32Article type: 0=plain text, 1=HTML.
article_text&strFull article body.

real_time_bar

Real-time 5-second OHLCV bar.

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
datei64Bar date string.
openf64Open price.
highf64High price.
lowf64Low price.
closef64Close price.
volumef64Volume.
wapf64Volume-weighted average price.
counti32Trade count.

historical_ticks

Historical tick data (Last, BidAsk, or Midpoint).

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
ticks&HistoricalTickDataHistorical tick data.
doneboolIf true, all ticks have been delivered.

historical_ticks_bid_ask

Historical bid/ask ticks.

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
ticks&HistoricalTickDataHistorical tick data.
doneboolIf true, all ticks have been delivered.

historical_ticks_last

Historical last-trade ticks.

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
ticks&HistoricalTickDataHistorical tick data.
doneboolIf true, all ticks have been delivered.

tick_option_computation

Option implied vol / greeks computation.

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
tick_typei32Tick type ID or tick-by-tick type string.
tick_attribi32
implied_volf64Implied volatility.
deltaf64Option delta.
opt_pricef64Option theoretical price.
pv_dividendf64Present value of dividends.
gammaf64Option gamma.
vegaf64Option vega.
thetaf64Option theta.
und_pricef64Underlying price.

security_definition_option_parameter

Option chain parameters (strikes, expirations).

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
exchange&strExchange name.
underlying_con_idi64Underlying contract ID.
trading_class&strTrading class.
multiplier&strContract multiplier.
expirations&[String]Available expiration dates.
strikes&[f64]Available strike prices.

security_definition_option_parameter_end

End of option chain parameters.

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.

delta_neutral_validation

Delta-neutral validation response.

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
con_idi64Contract ID. Unique per instrument.
deltaf64Option delta.
pricef64Tick price.

histogram_data

Price distribution histogram.

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
items&[(f64, i64Histogram entries [(price, count)].

market_rule

Market rule: price increment schedule.

ParameterTypeDescription
market_rule_idi64Market rule ID.
price_increments&[PriceIncrement]Price increment rules [{low_edge, increment}].

completed_order

Completed (filled/cancelled) order details.

ParameterTypeDescription
contract&ContractContract specification (symbol, secType, exchange, currency, etc.).
order&OrderOrder parameters (action, quantity, type, price, TIF, etc.).
order_state&OrderStateOrder state (status, margin, commission info).

completed_orders_end

End of completed orders list.


historical_schedule

Historical trading schedule (exchange hours).

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
start_date_time&strStart date/time for tick query.
end_date_time&strEnd date/time in "YYYYMMDD HH:MM:SS" format, or empty for now.
time_zone&strTimezone string (e.g. "US/Eastern").
sessions&[(String, String, StringTrading sessions [(ref_date, open, close)].

fundamental_data

Fundamental data (XML/JSON).

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
data&strRaw data string (XML/JSON).

update_mkt_depth

L2 book update (single exchange).

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
positioni32Book position (row index) or position size.
operationi32Book operation: 0=insert, 1=update, 2=delete.
sidei32Book side: 0=ask, 1=bid. Or order side "BOT"/"SLD".
pricef64Tick price.
sizef64Tick size.

update_mkt_depth_l2

L2 book update (with market maker).

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
positioni32Book position (row index) or position size.
market_maker&strMarket maker ID.
operationi32Book operation: 0=insert, 1=update, 2=delete.
sidei32Book side: 0=ask, 1=bid. Or order side "BOT"/"SLD".
pricef64Tick price.
sizef64Tick size.
is_smart_depthboolIf true, aggregate depth from multiple exchanges via SMART.

mkt_depth_exchanges

Available exchanges for market depth.

ParameterTypeDescription
descriptions&[crate::types::DepthMktDataDescription]Array of matching contract descriptions.

tick_req_params

Tick parameters: min tick size, BBO exchange, snapshot permissions.

ParameterTypeDescription
ticker_idi64Ticker/request ID.
min_tickf64Minimum tick size.
bbo_exchange&strBBO exchange for smart component lookup (e.g. "SMART").
snapshot_permissionsi64Snapshot permissions bitmask.

smart_components

SMART routing component exchanges.

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
components&[crate::types::SmartComponent]Smart routing component exchanges.

news_providers

Available news providers list.

ParameterTypeDescription
providers&[crate::types::NewsProvider]News provider list.

soft_dollar_tiers

Soft dollar tier list.

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
tiers&[crate::types::SoftDollarTier]Soft dollar tier list.

family_codes

Family codes linking related accounts.

ParameterTypeDescription
codes&[crate::types::FamilyCode]Family code list.

user_info

User info (white branding ID).

ParameterTypeDescription
req_idi64Request identifier. Used to match responses to requests.
white_branding_id&strWhite 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.5.0)

Auto-generated from source — do not edit.

Table of Contents

Connection

new

Create a new EClient (or EWrapper) instance.

def new(wrapper))
ParameterTypeDescription
wrapperPyObjectWrapper callback receiver for synchronous delivery.

connect

Connect to IB and start the engine.

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))
ParameterTypeDescription
hoststrServer hostname.
portintPort number (unused — ibx connects directly).
client_idintClient ID (unused — single-client engine).
usernamestrAccount username.
passwordstrAccount password.
paperboolIf true, connect to paper trading.
core_idusize or NoneCPU core affinity for the hot loop thread.
ib_key_timeout_secsint or None
ib_key_token_sub_typestr or None

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=""))
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
accountstrAccount ID.
model_codestrModel portfolio code (empty for default).

cancel_pnl

Cancel P&L subscription.

def cancel_pnl(req_id)
ParameterTypeDescription
req_idintRequest 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))
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
accountstrAccount ID.
model_codestrModel portfolio code (empty for default).
con_idintContract ID. Unique per instrument.

cancel_pnl_single

Cancel single-position P&L subscription.

def cancel_pnl_single(req_id)
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.

req_account_summary

Request account summary.

def req_account_summary(req_id, group_name, tags))
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
group_namestrAccount group name (e.g. "All").
tagsstrComma-separated account tags: "NetLiquidation,BuyingPower,...".

cancel_account_summary

Cancel account summary.

def cancel_account_summary(req_id)
ParameterTypeDescription
req_idintRequest 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=""))
ParameterTypeDescription
subscribebooltrue to start updates, false to stop.
acct_codestrAccount 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))
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
accountstrAccount ID.
model_codestrModel portfolio code (empty for default).
ledger_and_nlvboolIf true, include ledger and NLV data.

cancel_account_updates_multi

Cancel multi-account updates.

def cancel_account_updates_multi(req_id)
ParameterTypeDescription
req_idintRequest 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))
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
accountstrAccount ID.
model_codestrModel portfolio code (empty for default).

cancel_positions_multi

Cancel multi-account positions.

def cancel_positions_multi(req_id)
ParameterTypeDescription
req_idintRequest 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)
ParameterTypeDescription
order_idintOrder identifier. Must be unique per session.
contractContractContract specification (symbol, secType, exchange, currency, etc.).
orderOrderOrder parameters (action, quantity, type, price, TIF, etc.).

cancel_order

Cancel an order.

def cancel_order(order_id, manual_order_cancel_time=""))
ParameterTypeDescription
order_idintOrder identifier. Must be unique per session.
manual_order_cancel_timestrManual 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))
ParameterTypeDescription
num_idsintNumber 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))
ParameterTypeDescription
b_auto_bindboolIf true, auto-bind future orders to this client.

req_executions

Request execution reports.

def req_executions(req_id, exec_filter=None))
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
exec_filterPyObject or None

req_completed_orders

Request completed orders.

def req_completed_orders(api_only=false))
ParameterTypeDescription
api_onlybool

Market Data

set_news_providers

Set news provider codes for per-contract news ticks (e.g. "BRFG*BRFUPDN").

def set_news_providers(providers))
ParameterTypeDescription
providersstrNews 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()))
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
contractContractContract specification (symbol, secType, exchange, currency, etc.).
generic_tick_liststrComma-separated generic tick IDs (e.g. "233" for RT volume).
snapshotboolIf true, delivers one quote then auto-cancels.
regulatory_snapshotboolIf true, request a regulatory snapshot (additional fees may apply).
mkt_data_optionslist

cancel_mkt_data

Cancel market data subscription.

def cancel_mkt_data(req_id)
ParameterTypeDescription
req_idintRequest 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))
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
contractContractContract specification (symbol, secType, exchange, currency, etc.).
tick_typestrTick type ID or tick-by-tick type string.
number_of_ticksintMaximum number of ticks to return.
ignore_sizeboolIf 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)
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.

req_market_data_type

Set market data type (1=live, 2=frozen, 3=delayed, 4=delayed-frozen).

def req_market_data_type(market_data_type)
ParameterTypeDescription
market_data_typeint1=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()))
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
contractContractContract specification (symbol, secType, exchange, currency, etc.).
num_rowsintNumber of order book rows to subscribe to.
is_smart_depthboolIf true, aggregate depth from multiple exchanges via SMART.
mkt_depth_optionslist

cancel_mkt_depth

Cancel market depth.

def cancel_mkt_depth(req_id, is_smart_depth=false))
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
is_smart_depthboolIf 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()))
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
contractContractContract specification (symbol, secType, exchange, currency, etc.).
bar_sizeintBar size: "1 min", "5 mins", "1 hour", "1 day", etc.
what_to_showstrData type: "TRADES", "MIDPOINT", "BID", "ASK", "BID_ASK", etc.
use_rthintIf true, only return data from Regular Trading Hours.
real_time_bars_optionslist

cancel_real_time_bars

Cancel real-time bars.

def cancel_real_time_bars(req_id)
ParameterTypeDescription
req_idintRequest 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)
ParameterTypeDescription
req_idintRequest 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)
ParameterTypeDescription
instrumentintInstrument 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()))
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
contractContractContract specification (symbol, secType, exchange, currency, etc.).
end_date_timestrEnd date/time in "YYYYMMDD HH:MM:SS" format, or empty for now.
duration_strstrDuration string, e.g. "1 D", "1 W", "1 M", "1 Y".
bar_size_settingstrBar size: "1 min", "5 mins", "1 hour", "1 day", etc.
what_to_showstrData type: "TRADES", "MIDPOINT", "BID", "ASK", "BID_ASK", etc.
use_rthintIf true, only return data from Regular Trading Hours.
format_dateintDate format: 1="YYYYMMDD HH:MM:SS", 2=Unix seconds.
keep_up_to_dateboolIf true, continue receiving updates after initial history.
chart_optionslist

cancel_historical_data

Cancel historical data.

def cancel_historical_data(req_id)
ParameterTypeDescription
req_idintRequest 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))
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
contractContractContract specification (symbol, secType, exchange, currency, etc.).
what_to_showstrData type: "TRADES", "MIDPOINT", "BID", "ASK", "BID_ASK", etc.
use_rthintIf true, only return data from Regular Trading Hours.
format_dateintDate format: 1="YYYYMMDD HH:MM:SS", 2=Unix seconds.

cancel_head_time_stamp

Cancel head timestamp request.

def cancel_head_time_stamp(req_id)
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.

req_contract_details

Request contract details.

def req_contract_details(req_id, contract)
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
contractContractContract 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)
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
patternstrSymbol search pattern.

req_scanner_subscription

Request scanner subscription.

def req_scanner_subscription(req_id, subscription, scanner_subscription_options=Vec::new()))
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
subscriptionPyObjectScanner subscription parameters.
scanner_subscription_optionslist

cancel_scanner_subscription

Cancel scanner subscription.

def cancel_scanner_subscription(req_id)
ParameterTypeDescription
req_idintRequest 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()))
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
provider_codestrNews provider code (e.g. "BRFG").
article_idstrNews article identifier.
news_article_optionslist

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()))
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
con_idintContract ID. Unique per instrument.
provider_codesstrPipe-separated news provider codes.
start_date_timestrStart date/time for tick query.
end_date_timestrEnd date/time in "YYYYMMDD HH:MM:SS" format, or empty for now.
total_resultsintMaximum number of news results.
historical_news_optionslist

req_fundamental_data

Request fundamental data.

def req_fundamental_data(req_id, contract, report_type, fundamental_data_options=Vec::new()))
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
contractContractContract specification (symbol, secType, exchange, currency, etc.).
report_typestrReport type: "ReportSnapshot", "ReportsFinSummary", "RESC", etc.
fundamental_data_optionslist

cancel_fundamental_data

Cancel fundamental data.

def cancel_fundamental_data(req_id)
ParameterTypeDescription
req_idintRequest 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()))
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
contractContractContract specification (symbol, secType, exchange, currency, etc.).
start_date_timestrStart date/time for tick query.
end_date_timestrEnd date/time in "YYYYMMDD HH:MM:SS" format, or empty for now.
number_of_ticksintMaximum number of ticks to return.
what_to_showstrData type: "TRADES", "MIDPOINT", "BID", "ASK", "BID_ASK", etc.
use_rthintIf true, only return data from Regular Trading Hours.
ignore_sizeboolIf true, ignore size in tick-by-tick data.
misc_optionslist

req_market_rule

Request market rule details.

def req_market_rule(market_rule_id)
ParameterTypeDescription
market_rule_idintMarket rule ID.

req_histogram_data

Request histogram data.

def req_histogram_data(req_id, contract, use_rth, time_period))
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
contractContractContract specification (symbol, secType, exchange, currency, etc.).
use_rthboolIf true, only return data from Regular Trading Hours.
time_periodstrHistogram time period.

cancel_histogram_data

Cancel histogram data.

def cancel_histogram_data(req_id)
ParameterTypeDescription
req_idintRequest 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))
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
contractContractContract specification (symbol, secType, exchange, currency, etc.).
end_date_timestrEnd date/time in "YYYYMMDD HH:MM:SS" format, or empty for now.
duration_strstrDuration string, e.g. "1 D", "1 W", "1 M", "1 Y".
use_rthboolIf 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()))
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
contractContractContract specification (symbol, secType, exchange, currency, etc.).
option_pricefloatOption market price.
under_pricefloatUnderlying asset price.
implied_vol_optionslist

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()))
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
contractContractContract specification (symbol, secType, exchange, currency, etc.).
volatilityfloatImplied volatility.
under_pricefloatUnderlying asset price.
opt_prc_optionslist

cancel_calculate_implied_volatility

Cancel implied volatility calculation.

def cancel_calculate_implied_volatility(req_id)
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.

cancel_calculate_option_price

Cancel option price calculation.

def cancel_calculate_option_price(req_id)
ParameterTypeDescription
req_idintRequest 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))
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
contractContractContract specification (symbol, secType, exchange, currency, etc.).
exercise_actionint1=exercise, 2=lapse.
exercise_quantityintNumber of contracts to exercise.
accountstrAccount ID.
overrideintOverride 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))
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
underlying_symbolstrUnderlying symbol (e.g. "AAPL").
fut_fop_exchangestrExchange for futures/FOP options.
underlying_sec_typestrUnderlying security type (e.g. "STK").
underlying_con_idintUnderlying contract ID.

req_news_bulletins

Subscribe to news bulletins.

def req_news_bulletins(all_msgs=true))
ParameterTypeDescription
all_msgsboolIf 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)
ParameterTypeDescription
fa_data_typeintFA 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))
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
fa_data_typeintFA data type (1=Groups, 2=Profiles, 3=Aliases).
cxmlstrFA XML configuration data.

query_display_groups

Query display groups.

def query_display_groups(req_id)
ParameterTypeDescription
req_idintRequest 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)
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
group_idintDisplay group ID.

unsubscribe_from_group_events

Unsubscribe from display group events.

def unsubscribe_from_group_events(req_id)
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.

update_display_group

Update display group.

def update_display_group(req_id, contract_info)
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
contract_infostrDisplay group contract info string.

req_smart_components

Request SMART routing component exchanges.

def req_smart_components(req_id, bbo_exchange)
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
bbo_exchangestrBBO 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)
ParameterTypeDescription
req_idintRequest 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))
ParameterTypeDescription
log_levelintLog 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)
ParameterTypeDescription
req_idintRequest 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)
ParameterTypeDescription
req_idintRequest 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))
ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
wsh_event_dataPyObject or None

EWrapper Callbacks

new

Create a new EClient (or EWrapper) instance.

ParameterTypeDescription
argsBound<'_, pyo3::types::PyTuple>
kwargsBound<'_, 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.

ParameterTypeDescription
order_idintOrder identifier. Must be unique per session.

managed_accounts

Comma-separated list of managed account IDs.

ParameterTypeDescription
accounts_liststrComma-separated account IDs.

error

Error or informational message from the server.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
error_codeintError code.
error_stringstrError message.
advanced_order_reject_jsonstrJSON with advanced rejection details.

current_time

Current server time (Unix seconds).

ParameterTypeDescription
timeintTick timestamp (Unix seconds).

tick_price

Price tick update (bid, ask, last, etc.).

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
tick_typeintTick type ID or tick-by-tick type string.
pricefloatTick price.
attribPyObjectTick attributes.

tick_size

Size tick update (bid size, ask size, volume, etc.).

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
tick_typeintTick type ID or tick-by-tick type string.
sizefloatTick size.

tick_string

String tick (e.g. last trade timestamp).

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
tick_typeintTick type ID or tick-by-tick type string.
valuestrAccount value.

tick_generic

Generic numeric tick value.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
tick_typeintTick type ID or tick-by-tick type string.
valuefloatAccount value.

tick_snapshot_end

Snapshot delivery complete; subscription auto-cancelled.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.

market_data_type

Market data type changed (1=live, 2=frozen, 3=delayed, 4=delayed-frozen).

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
market_data_typeint1=live, 2=frozen, 3=delayed, 4=delayed-frozen.

order_status

Order status update (filled, remaining, avg price, etc.).

ParameterTypeDescription
order_idintOrder identifier. Must be unique per session.
statusstrOrder status string ("Submitted", "Filled", "Cancelled", etc.).
filledfloatCumulative filled quantity.
remainingfloatRemaining quantity.
avg_fill_pricefloatAverage fill price.
perm_idintPermanent order ID assigned by the server.
parent_idintParent order ID (0 if no parent).
last_fill_pricefloatPrice of the last fill.
client_idintClient ID (unused — single-client engine).
why_heldstrReason the order is held (e.g. "locate").
mkt_cap_pricefloatMarket cap price for the order.

open_order

Open order details (contract, order, state).

ParameterTypeDescription
order_idintOrder identifier. Must be unique per session.
contractPyObjectContract specification (symbol, secType, exchange, currency, etc.).
orderPyObjectOrder parameters (action, quantity, type, price, TIF, etc.).
order_statePyObjectOrder state (status, margin, commission info).

open_order_end

End of open orders list.


exec_details

Execution fill details.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
contractPyObjectContract specification (symbol, secType, exchange, currency, etc.).
executionPyObjectExecution details (exec_id, time, price, shares, etc.).

exec_details_end

End of execution details list.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.

commission_and_fees_report

Commission and fees report for an execution.

ParameterTypeDescription
commission_and_fees_reportPyObject

update_account_value

Account value update (key/value/currency).

ParameterTypeDescription
keystrAccount value key (e.g. "NetLiquidation", "BuyingPower").
valuestrAccount value.
currencystrCurrency code (e.g. "USD").
account_namestrAccount identifier.

update_portfolio

Portfolio position update.

ParameterTypeDescription
contractPyObjectContract specification (symbol, secType, exchange, currency, etc.).
positionfloatBook position (row index) or position size.
market_pricefloatCurrent market price.
market_valuefloatCurrent market value of position.
average_costfloatAverage cost basis.
unrealized_pnlfloatUnrealized profit/loss.
realized_pnlfloatRealized profit/loss.
account_namestrAccount identifier.

update_account_time

Account update timestamp.

ParameterTypeDescription
timestampstrTimestamp string.

account_download_end

Account data delivery complete.

ParameterTypeDescription
accountstrAccount ID.

account_summary

Account summary tag/value entry.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
accountstrAccount ID.
tagstrAccount tag name (e.g. "NetLiquidation").
valuestrAccount value.
currencystrCurrency code (e.g. "USD").

account_summary_end

End of account summary.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.

position

Position entry (account, contract, size, avg cost).

ParameterTypeDescription
accountstrAccount ID.
contractPyObjectContract specification (symbol, secType, exchange, currency, etc.).
posfloatPosition size (decimal shares).
avg_costfloatAverage cost per share.

position_end

End of positions list.


pnl

Account P&L update (daily, unrealized, realized).

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
daily_pnlfloatDaily profit/loss.
unrealized_pnlfloatUnrealized profit/loss.
realized_pnlfloatRealized profit/loss.

pnl_single

Single-position P&L update.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
posfloatPosition size (decimal shares).
daily_pnlfloatDaily profit/loss.
unrealized_pnlfloatUnrealized profit/loss.
realized_pnlfloatRealized profit/loss.
valuefloatAccount value.

historical_data

Historical OHLCV bar.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
barPyObjectBar data (date, open, high, low, close, volume, wap, bar_count).

historical_data_end

End of historical data delivery.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
startstrPeriod start date/time.
endstrPeriod end date/time.

historical_data_update

Real-time bar update (keep_up_to_date=true).

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
barPyObjectBar data (date, open, high, low, close, volume, wap, bar_count).

head_timestamp

Earliest available data timestamp.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
head_timestampstrEarliest available data timestamp string.

contract_details

Contract definition details.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
contract_detailsPyObject

contract_details_end

End of contract details.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.

symbol_samples

Matching symbol search results.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
contract_descriptionsPyObject

tick_by_tick_all_last

Tick-by-tick last trade.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
tick_typeintTick type ID or tick-by-tick type string.
timeintTick timestamp (Unix seconds).
pricefloatTick price.
sizefloatTick size.
tick_attrib_lastPyObject
exchangestrExchange name.
special_conditionsstrSpecial trade conditions.

tick_by_tick_bid_ask

Tick-by-tick bid/ask quote.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
timeintTick timestamp (Unix seconds).
bid_pricefloatBid price.
ask_pricefloatAsk price.
bid_sizefloatBid size.
ask_sizefloatAsk size.
tick_attrib_bid_askPyObject

tick_by_tick_mid_point

Tick-by-tick midpoint.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
timeintTick timestamp (Unix seconds).
mid_pointfloatMidpoint price.

scanner_data

Scanner result entry (rank, contract, distance).

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
rankintScanner result rank (0-based).
contract_detailsPyObject
distancestrScanner distance metric.
benchmarkstrScanner benchmark.
projectionstrScanner projection.
legs_strstrCombo legs description.

scanner_data_end

End of scanner results.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.

scanner_parameters

Scanner parameters XML.

ParameterTypeDescription
xmlstrXML string.

news_providers

Available news providers list.

ParameterTypeDescription
news_providersPyObject

news_article

Full news article text.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
article_typeintArticle type: 0=plain text, 1=HTML.
article_textstrFull article body.

historical_news

Historical news headline.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
timestrTick timestamp (Unix seconds).
provider_codestrNews provider code (e.g. "BRFG").
article_idstrNews article identifier.
headlinestrNews headline text.

historical_news_end

End of historical news.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
has_moreboolIf true, more results available.

tick_news

Per-contract news tick.

ParameterTypeDescription
ticker_idintTicker/request ID.
time_stampintTimestamp string.
provider_codestrNews provider code (e.g. "BRFG").
article_idstrNews article identifier.
headlinestrNews headline text.
extra_datastrAdditional tick data.

update_mkt_depth

L2 book update (single exchange).

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
positionintBook position (row index) or position size.
operationintBook operation: 0=insert, 1=update, 2=delete.
sideintBook side: 0=ask, 1=bid. Or order side "BOT"/"SLD".
pricefloatTick price.
sizefloatTick size.

update_mkt_depth_l2

L2 book update (with market maker).

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
positionintBook position (row index) or position size.
market_makerstrMarket maker ID.
operationintBook operation: 0=insert, 1=update, 2=delete.
sideintBook side: 0=ask, 1=bid. Or order side "BOT"/"SLD".
pricefloatTick price.
sizefloatTick size.
is_smart_depthboolIf true, aggregate depth from multiple exchanges via SMART.

mkt_depth_exchanges

Available exchanges for market depth.

ParameterTypeDescription
depth_mkt_data_descriptionsPyObject

real_time_bar

Real-time 5-second OHLCV bar.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
dateintBar date string.
openfloatOpen price.
highfloatHigh price.
lowfloatLow price.
closefloatClose price.
volumefloatVolume.
wapfloatVolume-weighted average price.
countintTrade count.

historical_ticks

Historical tick data (Last, BidAsk, or Midpoint).

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
ticksPyObjectHistorical tick data.
doneboolIf true, all ticks have been delivered.

historical_ticks_bid_ask

Historical bid/ask ticks.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
ticksPyObjectHistorical tick data.
doneboolIf true, all ticks have been delivered.

historical_ticks_last

Historical last-trade ticks.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
ticksPyObjectHistorical tick data.
doneboolIf true, all ticks have been delivered.

tick_option_computation

Option implied vol / greeks computation.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
tick_typeintTick type ID or tick-by-tick type string.
tick_attribint
implied_volfloatImplied volatility.
deltafloatOption delta.
opt_pricefloatOption theoretical price.
pv_dividendfloatPresent value of dividends.
gammafloatOption gamma.
vegafloatOption vega.
thetafloatOption theta.
und_pricefloatUnderlying price.

security_definition_option_parameter

Option chain parameters (strikes, expirations).

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
exchangestrExchange name.
underlying_con_idintUnderlying contract ID.
trading_classstrTrading class.
multiplierstrContract multiplier.
expirationsPyObjectAvailable expiration dates.
strikesPyObjectAvailable strike prices.

security_definition_option_parameter_end

End of option chain parameters.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.

fundamental_data

Fundamental data (XML/JSON).

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
datastrRaw data string (XML/JSON).

update_news_bulletin

News bulletin message.

ParameterTypeDescription
msg_idintBulletin message ID.
msg_typeintBulletin message type (1=regular, 2=exchange).
messagestrBulletin message text.
orig_exchangestrOriginating exchange.

receive_fa

Financial advisor data received.

ParameterTypeDescription
fa_data_typeintFA data type (1=Groups, 2=Profiles, 3=Aliases).
xmlstrXML string.

replace_fa_end

Financial advisor replace complete.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
textstrInformational text.

position_multi

Multi-account position entry.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
accountstrAccount ID.
model_codestrModel portfolio code (empty for default).
contractPyObjectContract specification (symbol, secType, exchange, currency, etc.).
posfloatPosition size (decimal shares).
avg_costfloatAverage cost per share.

position_multi_end

End of multi-account positions.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.

account_update_multi

Multi-account value update.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
accountstrAccount ID.
model_codestrModel portfolio code (empty for default).
keystrAccount value key (e.g. "NetLiquidation", "BuyingPower").
valuestrAccount value.
currencystrCurrency code (e.g. "USD").

account_update_multi_end

End of multi-account updates.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.

display_group_list

Display group list.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
groupsstrFA group definitions.

display_group_updated

Display group updated.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
contract_infostrDisplay group contract info string.

market_rule

Market rule: price increment schedule.

ParameterTypeDescription
market_rule_idintMarket rule ID.
price_incrementsPyObjectPrice increment rules [{low_edge, increment}].

smart_components

SMART routing component exchanges.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
smart_component_mapPyObject

soft_dollar_tiers

Soft dollar tier list.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
tiersPyObjectSoft dollar tier list.

family_codes

Family codes linking related accounts.

ParameterTypeDescription
family_codesPyObject

histogram_data

Price distribution histogram.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
itemsPyObjectHistogram entries [(price, count)].

user_info

User info (white branding ID).

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
white_branding_idstrWhite branding ID (empty for standard accounts).

wsh_meta_data

Wall Street Horizon metadata.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
data_jsonstr

wsh_event_data

Wall Street Horizon event data.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
data_jsonstr

completed_order

Completed (filled/cancelled) order details.

ParameterTypeDescription
contractPyObjectContract specification (symbol, secType, exchange, currency, etc.).
orderPyObjectOrder parameters (action, quantity, type, price, TIF, etc.).
order_statePyObjectOrder state (status, margin, commission info).

completed_orders_end

End of completed orders list.


order_bound

Order bound to a perm ID.

ParameterTypeDescription
order_idintOrder identifier. Must be unique per session.
api_client_idint
api_order_idint

tick_req_params

Tick parameters: min tick size, BBO exchange, snapshot permissions.

ParameterTypeDescription
ticker_idintTicker/request ID.
min_tickfloatMinimum tick size.
bbo_exchangestrBBO exchange for smart component lookup (e.g. "SMART").
snapshot_permissionsintSnapshot permissions bitmask.

bond_contract_details

Bond contract details.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
contract_detailsPyObject

delta_neutral_validation

Delta-neutral validation response.

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
delta_neutral_contractPyObject

historical_schedule

Historical trading schedule (exchange hours).

ParameterTypeDescription
req_idintRequest identifier. Used to match responses to requests.
start_date_timestrStart date/time for tick query.
end_date_timestrEnd date/time in "YYYYMMDD HH:MM:SS" format, or empty for now.
time_zonestrTimezone string (e.g. "US/Eastern").
sessionsPyObjectTrading 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.5.0)

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 APIRustPython
EClient methods7763 impl, 8 stub63 impl, 14 stub
EWrapper callbacks8166 impl, 3 stub70 impl, 11 stub

EClient Methods

CategoryIB API MethodC++ NameRustPython
ConnectionconnecteConnectYY
disconnecteDisconnectYY
is_connectedisConnectedYY
set_server_log_levelsetServerLogLevelYY
req_current_timereqCurrentTimeYY
Market Datareq_mkt_datareqMktDataYY
cancel_mkt_datacancelMktDataYY
req_market_data_typereqMarketDataTypeYY
req_tick_by_tick_datareqTickByTickDataYY
cancel_tick_by_tick_datacancelTickByTickDataYY
req_mkt_depthreqMktDepthYY
cancel_mkt_depthcancelMktDepthYY
req_mkt_depth_exchangesreqMktDepthExchangesYY
req_smart_componentsreqSmartComponentsYY
req_real_time_barsreqRealTimeBarsYY
cancel_real_time_barscancelRealTimeBarsYY
Historical Datareq_historical_datareqHistoricalDataYY
cancel_historical_datacancelHistoricalDataYY
req_head_time_stampreqHeadTimeStampYY
cancel_head_time_stampcancelHeadTimestampYY
req_historical_ticksreqHistoricalTicksYY
req_histogram_datareqHistogramDataYY
cancel_histogram_datacancelHistogramDataYY
req_historical_schedulereqHistoricalScheduleYY
Ordersplace_orderplaceOrderYY
cancel_ordercancelOrderYY
req_open_ordersreqOpenOrdersYY
req_all_open_ordersreqAllOpenOrdersYY
req_auto_open_ordersreqAutoOpenOrdersYY
req_idsreqIdsYY
req_global_cancelreqGlobalCancelYY
req_completed_ordersreqCompletedOrdersYY
Executionsreq_executionsreqExecutionsYY
Accountreq_account_updatesreqAccountUpdatesYY
req_account_summaryreqAccountSummaryYY
cancel_account_summarycancelAccountSummaryYY
req_positionsreqPositionsYY
cancel_positionscancelPositionsYY
req_pnlreqPnLYY
cancel_pnlcancelPnLYY
req_pnl_singlereqPnLSingleYY
cancel_pnl_singlecancelPnLSingleYY
req_managed_acctsreqManagedAcctsYY
req_account_updates_multireqAccountUpdatesMultiYY
cancel_account_updates_multicancelAccountUpdatesMultiYY
req_positions_multireqPositionsMultiYY
cancel_positions_multicancelPositionsMultiYY
Contractreq_contract_detailsreqContractDetailsYY
req_matching_symbolsreqMatchingSymbolsYY
req_market_rulereqMarketRuleYY
Scannerreq_scanner_parametersreqScannerParametersYY
req_scanner_subscriptionreqScannerSubscriptionYY
cancel_scanner_subscriptioncancelScannerSubscriptionYY
Newsreq_news_providersreqNewsProvidersYY
req_news_articlereqNewsArticleYY
req_historical_newsreqHistoricalNewsYY
req_news_bulletinsreqNewsBulletinsYY
cancel_news_bulletinscancelNewsBulletinsYY
Fundamentalreq_fundamental_datareqFundamentalDataYY
cancel_fundamental_datacancelFundamentalDataYY
Optionscalculate_implied_volatilitycalculateImpliedVolatility-STUB
cancel_calculate_implied_volatilitycancelCalculateImpliedVolatility-STUB
calculate_option_pricecalculateOptionPrice-STUB
cancel_calculate_option_pricecancelCalculateOptionPrice-STUB
exercise_optionsexerciseOptions-STUB
req_sec_def_opt_paramsreqSecDefOptParams-STUB
Referencereq_soft_dollar_tiersreqSoftDollarTiersYY
req_family_codesreqFamilyCodesYY
req_user_inforeqUserInfoYY
Financial Advisorrequest_farequestFASTUBSTUB
replace_fareplaceFASTUBSTUB
Display Groupsquery_display_groupsqueryDisplayGroupsSTUBSTUB
subscribe_to_group_eventssubscribeToGroupEventsSTUBSTUB
unsubscribe_from_group_eventsunsubscribeFromGroupEventsSTUBSTUB
update_display_groupupdateDisplayGroupSTUBSTUB
WSHreq_wsh_meta_datareqWshMetaDataSTUBSTUB
req_wsh_event_datareqWshEventDataSTUBSTUB

EWrapper Callbacks

CategoryCallbackRustPython
Connectionconnect_ackYY
connection_closedYY
next_valid_idYY
managed_accountsYY
errorYY
current_timeYY
Market Datatick_priceYY
tick_sizeYY
tick_stringYY
tick_genericYY
tick_snapshot_endYY
market_data_typeYY
tick_req_paramsYY
Ordersorder_statusYY
open_orderYY
open_order_endYY
order_bound-STUB
Executionsexec_detailsYY
exec_details_endYY
commission_and_fees_reportYY
Accountupdate_account_valueYY
update_portfolioYY
update_account_timeYY
account_download_endYY
account_summaryYY
account_summary_endYY
positionYY
position_endYY
pnlYY
pnl_singleYY
position_multi-Y
position_multi_end-Y
account_update_multi-Y
account_update_multi_end-Y
Contractcontract_detailsYY
contract_details_endYY
bond_contract_details-STUB
symbol_samplesYY
Historical Datahistorical_dataYY
historical_data_endYY
historical_data_updateYY
head_timestampYY
historical_ticksYY
historical_ticks_bid_askYY
historical_ticks_lastYY
histogram_dataYY
historical_scheduleYY
Market Depthupdate_mkt_depthYY
update_mkt_depth_l2YY
mkt_depth_exchangesYY
Tick-by-Ticktick_by_tick_all_lastYY
tick_by_tick_bid_askYY
tick_by_tick_mid_pointYY
Scannerscanner_dataYY
scanner_data_endYY
scanner_parametersYY
Newsnews_providersYY
news_articleYY
historical_newsYY
historical_news_endYY
tick_newsYY
update_news_bulletinYY
Real-Time Barsreal_time_barYY
Fundamentalfundamental_dataYY
Market Rulesmarket_ruleYY
Completed Orderscompleted_orderYY
completed_orders_endYY
Optionstick_option_computationYY
security_definition_option_parameterSTUBSTUB
security_definition_option_parameter_endSTUBSTUB
Referencesmart_componentsYY
soft_dollar_tiersYY
family_codesYY
user_infoYY
FAreceive_fa-STUB
replace_fa_end-STUB
Display Groupsdisplay_group_list-STUB
display_group_updated-STUB
Otherdelta_neutral_validationSTUBSTUB
WSHwsh_meta_data-STUB
wsh_event_data-STUB