Repository navigation
6.1 reports TWS's link to IB (link_state) and rides out a TWS restart at connect (connect_retry_for), paces small historical bar requests (HistoricalPacer), fetches 1-second bars over ranges longer than 2000 seconds, and adds option contract listing, what-if analysis of any order, and fill pairing. No breaking changes.
What's New
TWS link state and connect retry (#1367, #1368)
Client::link_state() returns TWS's link to IB (Up, Lost { since } or Unknown { since }: nothing reported yet, which is also how a healthy session looks), each data farm's last status, and counters for restorations, 1101s and transport sessions; key what you learn on (session, epoch). It includes the notices of the connect's handshake, which a notice stream opened afterwards never sees. ClientBuilder::connect_retry_for(budget) retries the first connect while TWS turns it away as a restarting TWS does: a refused port, a reset handshake, or notice 10141 from a paper TWS. Thanks to @faysou for the contribution (#1367, #1368).
use ibapi::notices::TwsLink;
use std::time::Duration;
let client = Client::builder()
.address("127.0.0.1:4002")
.client_id(100)
.connect_retry_for(Duration::from_secs(60)) // ride out a TWS restart
.connect()
.await?;
let link = client.link_state();
match link.tws {
TwsLink::Up => println!("TWS reports its link to IB up"),
TwsLink::Lost { since } => println!("link to IB lost {:?} ago", since.elapsed()),
TwsLink::Unknown { since } => println!("nothing reported for {:?}", since.elapsed()),
_ => {}
}
println!("farms: {:?}, data lost {} times", link.farms, link.data_losses);Pace historical bar requests: HistoricalPacer (#1542)
Install one and requests of 30-second bars or smaller wait for a slot instead of drawing pacing violation 162. Default is IB's documented 60 requests per ten minutes; clones share one budget, so clients on one account can share it. Off unless installed.
use ibapi::market_data::historical::HistoricalPacer;
let client = Client::builder()
.address("127.0.0.1:4002")
.client_id(100)
.historical_pacer(HistoricalPacer::default()) // 60 small-bar requests per 10 minutes
.connect()
.await?;1-second bars over ranges longer than 2000 seconds (#1270)
historical_data(..).between(start, end).fetch() with BarSize::Sec splits a range over 2000 seconds into requests TWS accepts; every such range used to fail with 162 "invalid step: 1". A request failing partway returns Error::BarsBetween with the bars fetched so far, so the rest can be fetched later. Past about 60 requests (about 33 hours of 1-second bars), IB's pacing ends the fetch with BarsBetween; install a HistoricalPacer to wait instead. subscribe() sends one request, so it rejects such a range without sending. Thanks to @faysou for the contribution (#1270).
use time::macros::datetime;
let bars = client
.historical_data(contract, HistoricalBarSize::Sec)
.between(datetime!(2026-12-03 14:30 UTC), datetime!(2026-12-03 16:30 UTC))
.fetch()
.await;
match bars {
Ok(bars) => println!("{} bars", bars.bars.len()),
Err(Error::BarsBetween(partial)) => {
println!("stopped after {} bars: {}", partial.fetched.bars.len(), partial.error);
}
Err(e) => return Err(e),
}Completed bars from a keep-up-to-date stream: BarCompletion (#1293)
TWS repeats the forming bar every 5 seconds and never marks one final. BarCompletion::apply hands out each bar once as Completed, and its revisions as Forming; expire(grace) completes a last bar no update follows. Thanks to @faysou for the contribution (#1293).
use futures::StreamExt;
use ibapi::market_data::historical::{BarCompletion, StreamedBar};
let mut completion = BarCompletion::new(HistoricalBarSize::Min);
let mut updates = client
.historical_data(contract, HistoricalBarSize::Min)
.what_to_show(HistoricalWhatToShow::MidPoint)
.duration(1.days())
.subscribe_with_updates()
.await?;
while let Some(item) = updates.next().await {
if let SubscriptionItem::Data(update) = item? {
for bar in completion.apply(update) {
if let StreamedBar::Completed(bar) = bar {
println!("completed {bar:?}");
}
}
}
}List an underlying's option contracts: option_contracts (#1290)
One contract_details request for the options of a stock, ETF, index or future, narrowed by expiry, right, trading class or exchange. option_chain lists expiries and strikes, most of whose combinations are not listed contracts; this lists the contracts. Thanks to @faysou for the contribution (#1290).
use ibapi::contracts::ContractMonth;
let spy = Contract::stock("SPY").build();
let query = Contract::options_on(&spy)?
.expiring_in(ContractMonth::new(2026, 12)?)
.calls();
for option in client.option_contracts(query).await? {
println!("{} {:?}", option.contract.local_symbol, option.contract.strike);
}What-if analysis of any order: analyze_order (#1289)
Client::analyze_order(order_id, &contract, &order) analyzes an order built elsewhere, under the caller's id, and leaves the order unchanged. TWS counts a what-if's id as used and answers a later order under it, or under a lower id, with 103. OrderBuilder::analyze now calls it, and both return the frame with the margins: outside regular hours paper TWS sent a warning-only frame first, which analyze returned with every margin None. Thanks to @faysou for the contribution (#1289).
use ibapi::orders::{order_builder, Action};
let contract = Contract::stock("AAPL").build();
let order = order_builder::limit_order(Action::Buy, 100.0, 150.0);
let state = client.analyze_order(client.next_order_id(), &contract, &order).await?;
println!("initial margin after: {:?}, commission: {:?}", state.initial_margin_after, state.commission_and_fees);Pair executions with their commission reports: pair_executions (#1268)
Joins one executions reply into Fills, in execution order, and returns the rows that found no partner. ExecutionData::expects_commission_report() is false for the executions TWS sends no report for (combo-level and option exercise). Thanks to @faysou for the contribution (#1268).
use ibapi::orders::{pair_executions, ExecutionFilter};
use std::time::Duration;
let mut subscription = client.executions(ExecutionFilter::default()).await?;
let rows = subscription.collect_to_end_within(Duration::from_secs(10)).await?;
let (fills, unpaired) = pair_executions(rows);
for fill in &fills {
let fees = fill.commission.as_ref().map(|report| report.commission_and_fees);
println!("{} {} @ {}: {fees:?}", fill.execution.contract.symbol, fill.execution.execution.shares, fill.execution.execution.price);
}Execution and completion times: WireTime, time_utc (#1280, #1551)
Execution::time_parsed() and OrderState::completed_time_parsed() read the field in any of the gateway's renderings; time_utc() and completed_time_utc() return the instant when the gateway sends UTC. Zone names are passed through, not resolved. The fields stay String. Thanks to @faysou for the contribution (#1280).
use ibapi::WireTime;
match execution.time_parsed() {
Some(WireTime::Utc(instant)) => println!("at {instant}"), // gateway set to "UTC format"
Some(WireTime::Zoned { local, zone }) => println!("at {local} {zone}"), // zone not resolved
Some(WireTime::Other(text)) => println!("unrecognized: {text}"),
None => {}
}Combos from leg contracts: spread_from_legs (#1271)
Builds a BAG from the leg contracts contract_details returns, with the symbol and currency TWS expects. SpreadBuilder::build() now rejects leg ratios, single legs and repeated legs TWS refuses or leaves unanswered, without sending. Thanks to @faysou for the contribution (#1271).
use ibapi::contracts::LegAction;
// Leg contracts as `contract_details` returns them.
let vertical = Contract::spread_from_legs()
.leg(long_call, LegAction::Buy)
.done()
.leg(short_call, LegAction::Sell)
.done()
.build()?; // symbol "AAPL", currency from the first legRead a trailing order's trail: Order::trailing (#1274)
The inverse of trailing_stop and trailing_stop_limit, for orders you built and orders TWS sends back. None for other order types. Thanks to @faysou for the contribution (#1274).
use ibapi::orders::builder::TrailBy;
use ibapi::orders::{Order, TrailLimit, Trailing};
let order = Order::builder().sell(100).trailing_stop_limit(TrailBy::Percent(1.5), 148.0, 0.5).build()?;
assert_eq!(
order.trailing(),
Some(Trailing { trail: TrailBy::Percent(1.5), stop_price: Some(148.0), limit: Some(TrailLimit::Offset(0.5)) })
);Trade-price whatToShow per security type: trades_for (#1286)
trades_for returns AggTrades for crypto, None for forex, commodities and CFDs (no trade data), Trades otherwise; trades_for_updates is the keep-up-to-date variant. Thanks to @faysou for the contribution (#1286).
use ibapi::contracts::SecurityType;
assert_eq!(HistoricalWhatToShow::trades_for(&SecurityType::Crypto), Some(HistoricalWhatToShow::AggTrades));
assert_eq!(HistoricalWhatToShow::trades_for(&SecurityType::ForexPair), None);
assert_eq!(HistoricalWhatToShow::trades_for_updates(&SecurityType::Crypto), Some(HistoricalWhatToShow::Trades));Also new
ContractDetails::last_trade_date_time()joins the expiry date andlast_trade_time, wall clock with no zone applied, andFrom<ExpirationDate> for time::Date(#1276). Thanks to @faysou for the contribution.SoftDollarTier::is_unset()(#1546).
Changed
connect() fails with Error::PaperDisclaimerNotAccepted on notice 10141 from a paper TWS, instead of the connection reset that follows it. A caller's own retry loop that retried that reset should also retry this error, or use connect_retry_for (#1368, #1556).
Some calls now return Error::Timeout where 6.0.0 waited: analyze and analyze_order wait at most the client's one-shot timeout (30 s unless set) for a what-if reply (#1289), and contract_details(..).fetch() honors a one_shot_timeout you set, so a reply that takes longer than it now times out; with the default it still waits (#1318). analyze also returns TWS's 201 rejection as an error where 6.0.0 returned Ok (#1289).
Requests TWS refuses or leaves unanswered now fail before sending:
contract_detailsfor a BAG isInvalidArgument;option_chain/futures_option_chainwith contract id 0 isValidation(#1281). Thanks to @faysou for the contribution.subscribe_with_updates()withWhatToShow::AggTradesisInvalidArgument; TWS refused it with 321 on every type tried (#1286).SpreadBuilder::build()checks TWS's leg rules (#1271).
Client::resubscribing decides when to reopen a request ended with 10182 from link_state(), and no longer reopens when its notice stream lags (#1555).
Bug Fixes
Orders
- An order placed after
all_open_ordersno longer gets an id TWS refuses with 103 when another client's order was listed. Thanks to @faysou for the contribution (#1266). analyzereturns the margins and commission of a what-if order, and TWS's 201 rejection when the account can't carry it (#1289).
Reconnects
- A request or order registered just before a reconnect is refused with
Error::Reconnectinginstead of being written into the new session with nothing to cancel it; a blocking request waiting on the rate limiter goes out in the new session with a working subscription. Thanks to @faysou for the contribution (#1365).
Also fixed
- A
Duration::MAXtimeout no longer panics; it waits without a deadline. Thanks to @kolinabir for the contribution (#1553). contract_details(..).fetch()honorsClientBuilder::one_shot_timeout; it waited for good when TWS left the request unanswered. Thanks to @faysou for the contribution (#1318).betweenover a range shorter than 30 seconds asks for 30 seconds instead of failing with 321 (#1270).- Async
executionsreports itsrequest_id(), and itscancel_and_draindrains to the end marker (#1545).
See CHANGELOG.md for the full list.
Thanks to @faysou for the wire-fact docs on market depth and option open interest (#1294, #1296).