Migrating from ib_async v2.x to v3.0
This guide walks you through every change you’ll likely encounter
when upgrading from ib_async v2.x to v3.0. Most existing code keeps
working — the breaking-change surface is concentrated in three areas:
Financial numerics are
Decimal | Noneend-to-end (wasfloat).commissionrenamed tocommissionAndFeesonCommissionReportandOrderState. The old name still works with a deprecation warning.Several hot-path records are now slotted-frozen dataclasses (were
NamedTuple). Equality and pickling still work; indexing does not.
If your code does basic order placement and reads back fills, you likely need to do nothing — the deprecation aliases cover the common case. The sections below walk through each change in order of likely impact.
Quickstart — what changed in 30 seconds
# 1. Decimal-native numerics. The unset sentinel is None, not NaN.
order = ib.placeOrder(Stock("AAPL"), LimitOrder("BUY", 100, 50.5))
if order.order.lmtPrice: # safe — was a truthy-NaN trap in v2.x
...
# order.order.lmtPrice is Decimal("50.5"), not 50.5
# 2. commission was renamed to commissionAndFees.
fill.commissionReport.commissionAndFees # canonical, v3.0+
fill.commissionReport.commission # still works, DeprecationWarning
# 3. NamedTuples are now slotted-frozen dataclasses.
av = AccountValue(
account="DU111",
tag="NetLiquidation",
value="12345.67",
currency="USD",
modelCode="",
)
av.tag, av.value # works
av[1] # TypeError — use av.tag instead
av._asdict() # gone — use dataclasses.asdict(av)
If those three points cover your usage, you can stop reading. The sections below detail edge cases.
1. Financial numerics → Decimal | None
Why
IBKR’s API surface speaks string-encoded decimals on the wire for
order sizes, prices, and commissions. v2.x decoded these as Python
float, which silently lost precision on fractional-share quantities
and option prices. v3.0 decodes directly to Decimal, with None as
the unset sentinel.
Decimal('NaN') is never used as the unset sentinel. v2.x had a
silent truthy trap: bool(Decimal('NaN')) returns True, so
if order.lmtPrice: fired on unset orders.
What’s affected
Every monetary or quantity field on the following types is now
Decimal | None:
Type |
Fields |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
renamed |
|
retyped |
Trade.filled() and Trade.remaining() also return Decimal (they
returned float); filled() is Decimal(0) when nothing has filled.
Migration
Construction from floats still works. v3.0 funnels float input
through str() to bound binary-float imprecision:
LimitOrder("BUY", 100, 50.5)
# Internally: lmtPrice = Decimal("50.5"), not Decimal(50.5)
# (Decimal(50.5) would be 50.500000000000000000000000000000)
Arithmetic must use Decimal-compatible types. Mixing Decimal
and float raises TypeError:
# v2.x — fine
order.lmtPrice * 1.05
# v3.0 — TypeError
order.lmtPrice * 1.05
# v3.0 — fix: keep it Decimal
from decimal import Decimal
order.lmtPrice * Decimal("1.05")
# or: float at the boundary
float(order.lmtPrice) * 1.05
Boolean checks on unset Decimal fields now do what you expect:
# v2.x: bool(Decimal('NaN')) == True, so this fired on unset orders.
# v3.0: lmtPrice is None when unset; bool(None) == False — safe.
if order.lmtPrice:
pricing_logic(order.lmtPrice)
JSON encoders that didn’t handle Decimal will need a custom encoder:
import json
from decimal import Decimal
class DecimalEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Decimal):
return str(obj)
return super().default(obj)
json.dumps(order_dict, cls=DecimalEncoder)
HistogramData.count → HistogramData.size is a field rename,
not an alias. Update:
# v2.x
[(h.price, h.count) for h in histogram]
# v3.0
[(h.price, h.size) for h in histogram]
PnLSingle.position is now Decimal | None instead of int.
Fractional positions (crypto / fractional shares) no longer
truncate.
The wider None-is-unset sweep
The Decimal | None shift above is the most visible part of a
broader convention change: every field that previously held an IBKR
magic sentinel (UNSET_INTEGER = 2**31-1, UNSET_DOUBLE = 1.79e308,
UNSET_LONG = 2**63-1, UNSET_DECIMAL, or nan) now defaults to
None. About 140 fields are affected across Order (~25),
OrderStateNumeric (18), Ticker (80), RealTimeBar (which replaced
ticker.Bar),
PnL / PnLSingle (7), ScannerSubscription, ExecutionFilter,
and ContractDetails.aggGroup. The change applies to plain int /
float fields too — not just Decimal:
# v2.x
if order.parentId == UNSET_INTEGER:
... # unset
if math.isnan(ticker.bid):
... # no quote yet
# v3.0
if order.parentId is None:
... # unset
if ticker.bid is None:
... # no quote yet
Helpers like util.isNan continue to work on legacy float fields
but return False for None; callers checking unsetness should
prefer is None explicitly.
OptionComputation arithmetic follows it too. A greek IBKR did not
compute is None, and a spread built with +, - or * keeps it so:
a result field is None when either leg’s field is None, where v2.x
counted the unknown leg as 0:
spread = longGreeks - shortGreeks
if spread.delta is not None:
... # IBKR computed both legs' delta
Ticker.marketDataType follows the same rule. It started as 1 (live)
before IBKR said anything; it is now None until IBKR reports the type
it serves the stream with, then a MarketDataType (LIVE, FROZEN,
DELAYED, DELAYED_FROZEN, equal to IBKR’s 1 to 4). Prices can arrive
before the type, and a request for live data may be served delayed:
# v2.x: 1 even when IBKR had not reported a type
if ticker.marketDataType == 1:
...
# v3.0
if ticker.marketDataType is MarketDataType.LIVE:
... # IBKR reported live data for this stream
If you stamp None onto a non-Optional plain-scalar field of an
Order / Contract / ScannerSubscription / ExecutionFilter /
ComboLeg / DeltaNeutralContract and then send it, v3.0 coalesces
the None back to the dataclass default at the wire boundary.
The previous behaviour was either a crash or the IBKR magic
sentinel landing on the wire (which TWS rejects with
Error 135: Can't find order with id = 2147483647).
2. commission → commissionAndFees rename
Why
IBKR renamed the field on CommissionReport and OrderState to
match the wire-level name. The value carries the
combined broker commission + exchange fees + regulatory fees — the
new name is more accurate.
Migration
The legacy commission attribute still works in v3.0 with a
DeprecationWarning. It will be removed in v4.0. The constructor
takes commissionAndFees= only: CommissionReport(commission=...) and
OrderState(commission=...) raise TypeError.
# v3.0+ canonical
fill.commissionReport.commissionAndFees
CommissionReport(commissionAndFees=Decimal("1.25"))
state.commissionAndFees
# Still works, emits DeprecationWarning
fill.commissionReport.commission
state.commission
The same applies to write access: report.commission = X and
state.commission = X both emit DeprecationWarning and route to
commissionAndFees.
To find call sites:
grep -rn "\.commission\b" your_code/
grep -rn "commission=" your_code/
To suppress the warning during your migration period:
import warnings
warnings.filterwarnings(
"ignore", message=".*commissionAndFees.*", category=DeprecationWarning
)
3. NamedTuple → slotted-frozen dataclass
Why
NamedTuple allocates a regular tuple; on the hot tick path that’s
extra GC pressure for no win. @dataclass(slots=True, frozen=True)
gives equivalent immutability + hashability without the tuple
allocation, and rejects typo’d attribute assignments at runtime.
What’s affected
AccountValue, Position, PortfolioItem, Fill, TickData,
HistoricalTick, HistoricalTickBidAsk, HistoricalTickLast,
TickByTickAllLast, TickByTickBidAsk, TickByTickMidPoint,
MktDepthData, DOMLevel, PriceIncrement, OrderAllocation,
OrderCancel, IneligibilityReason.
What still works
Positional construction:
AccountValue("DU111", "NetLiquidation", "12345.67", "USD", "").Keyword construction:
AccountValue(tag="NetLiquidation", ...).Field access by name:
av.tag,av.value.Equality and hashability:
av == other,set([av]).Pickle:
pickle.dumps(av)andpickle.loads(...).isinstance(av, AccountValue).
What changed
Was ( |
Now (slotted dataclass) |
Migration |
|---|---|---|
|
|
Use |
|
|
Iterate explicit fields |
|
gone |
|
|
gone |
|
|
gone |
|
|
|
slots reject this |
tickByTick*.time semantics
TickByTickAllLast.time, TickByTickBidAsk.time, and
TickByTickMidPoint.time are now populated from the wire-supplied
exchange epoch via datetime.fromtimestamp(time, defaultTimezone),
not the wrapper’s local-clock lastTime. Latency-sensitive code that
compared tickByTick.time to datetime.now() needs to account for
the wire timestamp lag from the exchange.
4. New IB.* public methods
v3.0 adds 14 methods that were missing from the v2.x surface:
IB.reqCurrentTimeInMillisAsync()IB.setServerLogLevel(logLevel)IB.reqSoftDollarTiersAsync()IB.reqFamilyCodesAsync()IB.cancelHeadTimeStamp(reqId)— settles awaiting future withCancelledErrorIB.cancelHistogramData(reqId)— settles awaiting future withCancelledErrorIB.queryDisplayGroups(reqId)IB.subscribeToGroupEvents(reqId, groupId)IB.updateDisplayGroup(reqId, contractInfo)IB.unsubscribeFromGroupEvents(reqId)IB.cancelContractData(reqId)— protobuf-only, server >= 215IB.cancelHistoricalTicks(reqId)— protobuf-only, server >= 215IB.reqConfigAsync()— protobuf-only, server >= 219IB.updateConfigAsync(...)— protobuf-only, server >= 219
Plus Client.setOptionalCapabilities(...).
Cancel-async semantics changed
IB.cancelHeadTimeStamp, IB.cancelHistogramData,
IB.cancelContractData, and IB.cancelHistoricalTicks now settle
the matching reqXxxAsync future with asyncio.CancelledError.
In v2.x these calls sent the wire cancel but never woke the
awaiter — TWS sends no End frame after these four cancels, so
await ib.reqHeadTimeStampAsync(...) hung forever.
# v3.0 pattern
async def fetch_with_cancel():
fut = ib.reqHeadTimeStampAsync(contract, "TRADES", True, 1)
ib.cancelHeadTimeStamp(reqId)
try:
result = await fut
except asyncio.CancelledError:
return None # awaiter now wakes; was hang-forever in v2.x
Matching a reqId to its stream
v2.x kept Wrapper.reqId2Ticker and Wrapper.ticker2ReqId. They are
gone: every live stream is a read-only Stream of its own type, with its
reqId and exactly the data it has. MarketDataStream,
SnapshotStream, TickByTickStream (with its tickType) and
MarketDepthStream are TickerStreams, with a contract and the
ticker they fill. RealTimeBarsStream and HistoricalBarsStream have
a contract and their bars. ScannerStream has its scanData, and
PnLStream and PnLSingleStream their account, modelCode and PnL.
ib.streams() # {reqId: Stream} for every live stream
ib.streams(contract) # {reqId: Stream} for the streams on that instrument
ib.stream(reqId) # the live Stream with that reqId, or None
# v2.x: ticker = ib.wrapper.reqId2Ticker[reqId]
stream = ib.stream(reqId)
ticker = stream.ticker if isinstance(stream, TickerStream) else None
# v2.x: reqId = ib.wrapper.ticker2ReqId["mktData"][ticker]
ib.streams(ticker.contract) # {12: MarketDataStream(reqId=12, ...), ...}
ib.streams(contract) matches the instrument, not the object: by conId,
a bag by its legs. Any Contract for the instrument finds its streams,
such as ticker.contract or one made later.
Most code needs neither: a Ticker delivers its ticks through
updateEvent, tickByTicks and domTicks.
An error that ends a stream removes it before errorEvent fires, so
ib.stream(reqId) finds nothing there. streamErrorEvent carries the
stream instead, and tells apart the streams on one contract:
def onStreamError(stream, errorCode, errorString, ended):
if isinstance(stream, MarketDepthStream) and ended:
... # this contract's depth stream ended; its market data runs on
ib.streamErrorEvent += onStreamError
rerouteMktDataReqEvent and rerouteMktDepthReqEvent carry the
Stream too: (stream, conId, exchange).
5. Order shape additions
Attached-order ids
Order gained four fields for bracket / OCO linkage:
slOrderId: int | None = None— stop-loss order idslOrderType: str = ""ptOrderId: int | None = None— profit-target order idptOrderType: str = ""
Read on receive; write on send. Brackets and OCO groups now round-trip the linkage instead of silently losing it.
OrderCancel envelope for cancelOrder
IB.cancelOrder(orderId) accepts an optional orderCancel
argument carrying CME-compliance fields:
from ib_async.order import OrderCancel
ib.cancelOrder(
orderId=42,
orderCancel=OrderCancel(
manualOrderCancelTime="20300101 09:30:00",
extOperator="ext", # gate 192
manualOrderIndicator=1, # gate 192
),
)
reqGlobalCancel similarly accepts an optional OrderCancel.
Without one, the call works exactly as it did in v2.x.
ExecutionFilter expanded
ExecutionFilter gained lastNDays: int and
specificDates: list[int] (UTC date ordinals) so you can narrow
reqExecutions queries without walking the full session.
RealTimeBar.endTime removed
RealTimeBar.endTime is gone. It was a v2.x-era field that was
never populated from the wire — the realtime-bar message carries
only time — and the wrapper hardcoded -1 into it on every
bar. If you read bar.endTime you were always reading -1; if you
derived an end-of-window timestamp, compute it from bar.time
(5-second windows: bar.time + timedelta(seconds=5)).
Specialized order behaviour fields
Order gained seven fields:
allowPreOpen: bool = False— allow routing during the pre-open auctiondeactivate: bool = False— kill the order on fill or completionpostOnly: bool = False— reject the order if it would immediately match (maker-only)ignoreOpenAuction: bool = False— bypass the opening auctionseekPriceImprovement: int | None = NonewhatIfType: int | None = NonehedgeMaxSize: int | None = None
All accept None (or the bool default) to mean “leave at server
default.” Read on receive; write on send.
Compliance / origination fields preserved on send
Five Order fields were populated on receive but silently dropped
on send before v3.0:
customerAccount, professionalCustomer, bondAccruedInterest,
includeOvernight, submitter.
A fetched-then-replaced order in v2.x lost its originating-session tagging on the wire — significant because IBKR uses these fields for regulatory logging. v3.0 writes them through. No code change is required; any v2.x re-place workflow now preserves the linkage automatically.
Order fields that never reached TWS are removed
Order.auctionStrategy, eTradeOnly, firmQuoteOnly, nbboPriceCap,
faProfile, basisPoints and basisPointsType are gone, along with the
AuctionLimitOrder constructor. IBKR’s Order protobuf message has no
field for any of them, so TWS / IB Gateway 10.51 never received or sent
their values. IBKR’s own 10.51 clients drop auctionStrategy the same
way. An AuctionLimitOrder went out as a plain limit order. Remove these
fields from your code; setting one as a constructor keyword now raises
TypeError.
OrderState.transform() covers OutsideRTH variants
OrderState.numeric() and OrderState.formatted() previously left
the nine *OutsideRTH margin / equity / commission variants as raw
wire strings, transforming only the regular nine. v3.0 applies the
transformer to all eighteen. If you depended on the OutsideRTH
fields staying as raw strings, switch to direct field access on the
OrderState instance instead of the transformer methods.
5b. Ticker surface additions
Two additive enhancements to Ticker that don’t change any v2.x
behaviour but are worth knowing about:
Ticker.tickAttrib
priceSizeTick now sets Ticker.tickAttrib from the wire-supplied
TickAttrib payload (canAutoExecute / pastLimit / preOpen).
Previously the attribute existed but was never populated. Read it
as ticker.tickAttrib after any price/size tick:
ticker = ib.reqMktData(contract)
ib.sleep(2)
if ticker.tickAttrib and ticker.tickAttrib.pastLimit:
print("quote is past limit")
Ticker.news
A bounded per-Ticker ring of the most recent five news headlines
for the underlying contract:
ticker = ib.reqMktData(contract, genericTickList="mdoff,292")
ib.sleep(5)
for tick in ticker.news:
print(tick.timeStamp, tick.headline)
Maxlen is 5. The global IB.tickNewsEvent / wrapper.newsTicks
still fan out to all subscribers — Ticker.news is an additive
per-contract surface, not a replacement.
Re-subscribing with a different genericTickList
While a streaming reqMktData subscription for a contract is live,
calling reqMktData again for that contract returns the same Ticker
without sending a new request, even if genericTickList or
mktDataOptions differ. To change them, cancel first:
ib.cancelMktData(contract)
ticker = ib.reqMktData(contract, genericTickList="233,236")
The second call returns a new Ticker, unless a tick-by-tick or depth stream kept the old one live (see the next section). Use the Ticker it returns.
A Ticker ends with its streams
The streams on one contract (reqMktData, reqTickByTickData,
reqMktDepth) share one Ticker while any of them runs, as in v2.x.
In v2.x a Ticker stayed in the pool after its streams were cancelled:
ib.ticker() and ib.tickers() kept returning it with its last prices,
and the next request for the contract handed it back, old bid and ask
included, until new ticks overwrote them. A field IBKR did not send again
stayed stale. Its time kept advancing for any stream, so timestamps
did not show it. In v3.0 a Ticker shows only live streams:
When one stream ends while others go on, the fields only it filled are cleared: market data fills the quote and every generic field, tick-by-tick
Last/AllLastthe last trade,BidAskthe quote, depth the book. A field another live stream fills stays.When the last stream ends (a cancel, an error that ends it, a disconnect), the Ticker ends: its
updateEventis done, soasync forover it stops andawait ticker.updateEventraisesValueErrorinstead of waiting forever. It keeps its last values for whoever holds it.ib.ticker(contract)returnsNone, andib.tickers()lists only live Tickers.The next stream for the contract starts a new, empty Ticker.
ticker = ib.reqMktData(contract)
...
ib.cancelMktData(contract)
print(ticker.bid) # the last bid, from the ended stream
assert ticker.updateEvent.done() and ib.ticker(contract) is None
ticker = ib.reqMktData(contract) # a new Ticker, empty until IBKR sends
Code that keeps a Ticker across a cancel and a new request, or across a reconnect (which already gave new Tickers in v2.x), must use the Ticker the new request returns. Snapshots are unchanged: each has a Ticker of its own, done when the snapshot ends.
Market depth: Ticker.dom and read-only snapshots
The depth book now lives in ticker.dom (a DepthBook), and the
existing views return read-only snapshots:
ticker.domBids/ticker.domAsksareSequence[DOMLevel](tuples, best price first) instead of the book’s own lists. Code that sorted, appended to or edited them in place must copy first:bids = list(ticker.domBids). Compare with()or use truthiness (not ticker.domBids), not== [].ticker.domBidsDict/ticker.domAsksDictare snapshot mappings keyed by row; writing to one no longer changes the book.None of these are
Ticker(...)constructor arguments any more.
Single-exchange depth (isSmartDepth=False) is also fixed: rows now
shift on mid-book inserts and deletes, so the book stays best-first
with no duplicate levels.
5c. Bars from live ticks are RealTimeBars
The bars timebars(), tickbars() and volumebars() build from a
ticker’s ticks are now RealTimeBars, the type of IBKR’s real-time
bars, instead of ticker.Bar (which is gone):
Prices and volume are
Decimal, as on IBKR’s bars. A tick’s float price reads as theDecimalit prints as (10.25→Decimal('10.25')).wapis the bar’s volume-weighted average price,Nonefor a bar without volume (such as a midpoint bar).RealTimeBar.open_isopen, as onBarData, for IBKR’s real-time bars too.Each operator emits its completed bar.
tickbars()andvolumebars()used to emit their wholebarslist; all three now emit theRealTimeBarthat completed. Theirbarsstill holds every bar (or, withmaxBars=, the last that many completed ones), the last in progress.bars.updateEvent(bars, hasNewBar)fires on every change of the bars:hasNewBar=Truewhen the last bar has just completed,Falsewhen the bar in progress otherwise changes (a tick, or a time bar starting flat at the last close).tickbars()andvolumebars()used to fire only on completion.A completed bar never changes:
RealTimeBaris frozen, and the bar in progress is replaced by a newRealTimeBaron each tick.A midpoint tick without a bid and ask (no price) is skipped, where it used to fail the aggregation;
tickbars(0)andvolumebars(0)raiseValueError.
timebars(timer) uses the timer’s value as each bar’s time, so give it a
timer of datetimes: Event.timerange(start=0, step=60) for one-minute
bars on the minute. A naive timer time (as that timer emits) becomes an
aware local time, with its UTC offset, where it used to stay naive: compare
bar times with aware datetimes (datetime.now().astimezone()). Ordering an
aware time against a naive one (<, >) raises TypeError, and ==
between them is quietly False, so a lookup by a naive time finds nothing.
6. AccountValue.decimalValue stricter
The decimalValue property now:
Returns
Nonefor tags not inMONETARY_ACCOUNT_VALUE_TAGS(the currency-denominated whitelist). Non-monetary tags likeLeverage,DayTradesRemaining,SegmentTitle,BillableSize,ColumnPrio, andAccountTypereturnNoneeven when their value strings parse as numbers.Returns
Nonefor IBKR UNSET sentinels and NaN / Infinity strings (e.g."1.7976931348623157E308","2147483647","NaN").
If your code relied on decimalValue resolving any numeric tag,
query the raw .value field directly:
# v2.x — worked for any numeric-string tag
leverage_str = av.value if av.tag == "Leverage" else None
# v3.0 — same pattern works; decimalValue returns None for Leverage now
if av.tag == "Leverage":
leverage_str = av.value # still a string on the wire
6a. Order types are constructors that return Order
MarketOrder, LimitOrder, StopOrder and StopLimitOrder were
subclasses of Order. In v3.0 they, and the other order types, are
functions in ib_async.ordertypes that return a plain Order with the
fields IBKR expects (see the Order types page):
order = LimitOrder("BUY", 100, 50.25) # unchanged call
type(order) is Order # was LimitOrder
dataclasses.replace(order, lmtPrice=Decimal("50.30")) # now works
MarketOnCloseOrder("SELL", 100)
TrailingStopOrder("SELL", 100, trailingPercent=2.0)
SnapToMidpointOrder("BUY", 100, offset=0.01)
Import them from
ib_async(orib_async.ordertypes); they are no longer inib_async.order.isinstance(order, LimitOrder)no longer works; it never did for orders read back from TWS. Useorder.orderType, orib_async.ordertypes.specOf(order), which names the order type of anyOrder.reprshowsOrder(..., orderType='LMT', ...), as for orders read back from TWS.Construction is checked: a missing required value, both of a pair where one is needed (
trailingAmount/trailingPercent), or setting a field the type sets itself (LimitOnOpenOrder(..., tif="DAY")) raisesOrderTypeError. OtherOrderfields (tif,outsideRth,account, …) are keyword arguments, as before.MidpriceOrderandRelativeOrderrequire their price cap: IBKR rejects those orders without one.
ib_async.ordertypes.checkOrder(contract, order) lists what IBKR’s
documentation says against an order for a contract (a product or exchange
it is not offered for), as advice before sending.
6b. DataFrames: polars replaces pandas
util.df() and FlexReport.df() return a polars
DataFrame (polars 2.0+) instead of a pandas one, and util.barplot()
accepts it. Install the extra:
pip install "ib_async[polars]"
Decimalfields become polarsDecimalcolumns, and time-zone-awaredatetimes keep their zone (a fixed offset, as fromdatetime.astimezone(), becomes UTC, the same instant). An ib_async object in a field, such asPosition.contract, is stored as itself (anObjectcolumn).labels=keeps those columns in that order. An unknown label raisesColumnNotFoundError; it used to be ignored.No objects give an empty DataFrame, not
None.
# v2.x (pandas)
df = util.df(bars)
df["sma"] = df["close"].rolling(20).mean()
df.to_csv("bars.csv", index=False)
# v3.0 (polars)
import polars as pl
df = util.df(bars)
df = df.with_columns(pl.col("close").rolling_mean(20).alias("sma"))
df.write_csv("bars.csv")
Code that still needs pandas can convert with util.df(bars).to_pandas()
(requires pandas and pyarrow).
polars runs on CPython only. On PyPy, util.pandasDf(bars) builds a
pandas DataFrame from the same inputs, with the same labels=, and
util.barplot() accepts it. pandas is not a dependency of ib_async;
install it yourself.
6c. Data request values are typed; durationStr is checked
whatToShow and barSizeSetting of the historical and real-time data
requests are typed with the values IBKR documents, accepted as plain
strings or as enum members:
ib.reqHistoricalData(contract, "", "30 D", "1 hour", "TRADES", True)
ib.reqHistoricalData(contract, "", "30 D", BarSize.HOUR_1, WhatToShow.TRADES, True)
Nothing changes at runtime for these values. A type checker now reports a
typo, and a value a method does not take (real-time bars take only
TRADES, MIDPOINT, BID and ASK). Code that passes a str variable
fails type checking: give the variable the parameter’s type
(ib_async.datarequests.HistoricalData, BarSizeSetting, …), or parse
it into the enum, as argparse.add_argument(type=BarSize, choices=list(BarSize)) does.
durationStr of reqHistoricalData, and a str numDays of
reqHistoricalSchedule, must be a positive whole number, a space and a
unit ('30 D', '1 Y'): anything else raises ValueError before the
request is sent, where IBKR used to refuse it.
6d. Contract equality: bags and continuous futures
Contract.__eq__ used to count two contracts equal whenever they had
the same conId. Two cases no longer do; those contracts compare every
field instead, so equal contracts always hash alike:
Bags. IBKR gives many different spreads one combo conId (such as
28812380): two bags are equal only field for field, and each spread gets its own market data, identified by its legs (bags hash by their legs, symbol and exchange). The legs count in the order given: IBKR quotes a spread by its legs as listed, so the same legs in another order are another request, with its ownTicker.Continuous futures. A
ContFuturehas its front future’s conId, but is not that future: they are no longer equal, and each gets its own market data subscription andTicker. TwoContFutures still compare by conId.
6e. No methods patched onto classes
Importing ib_async used to add four methods to every ib_async dataclass. A class now has the methods its own body defines. The plain functions do the same work:
v2.x |
v3.0 |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
update() and util.dataclassUpdate changed the object in place, so
everything holding it (a Trade’s contract and order, the caller of
qualifyContracts) saw the change; setting its attributes still does
that. dataclasses.replace is no substitute: it makes a copy (sharing
lists such as comboLegs), and on Stock, Option and the other
Contract subclasses it raises TypeError (their constructors set
secType themselves). Use it for the frozen records, such as
AccountValue, which cannot be changed in place. To change a live
order, start from ordertypes.modifiedOrder(trade.order, ...).
6f. Unreadable input raises instead of passing through
util.parseIBDatetimeraisesValueErrorfor an unknown time zone name. It also raisesValueErrorfor an epoch outside thedatetimerange. In v2.x an unknown zone produced a naive or wrong datetime. The request methods report this error as a failure of the request. For example,reqHeadTimeStampAsyncraises instead of returning a wrong time.FlexReport.load()raisesFlexErrorfor a file that is not XML. In v2.x the XML parser raised its own error instead.TickData.priceisfloat | None. A size tick on a side with no price yet is logged withprice=None. v2.x produced the same value, but the annotation wasfloat.Watchdoghas asleepfield. It defaults toasyncio.sleepand is used for the startup and retry waits. Tests pass their own function.
7. Wire-protocol details (mostly transparent)
You almost certainly do not need to do anything for this section. v3.0 speaks only protobuf, to TWS / IB Gateway 10.51 (server version 226) and later.
The exceptions where you might care:
Client.sendMsg signature changed
If you subclass Client and override sendMsg, the signature
changed:
# v2.x
def sendMsg(self, msg: str) -> None: ...
# v3.0
def sendMsg(self, msg: bytes | None) -> None: ...
The None value is used internally to drain the throttle queue.
Protobuf only, TWS / IB Gateway 10.51 and later
v3.0 connects only to TWS / IB Gateway 10.51 or later (server
version 226), the oldest IBKR accepts API connections from;
Client.MinClientVersion is 226. Every request goes out as its
protobuf message and every answer is read as protobuf, so the text
encoder and decoder are gone: Client.send, Client.useProtoBuf,
Decoder.interpret and the decoder’s per-message text handlers. If
you inspect raw outbound frames in tests, each one is a 4-byte
big-endian wire msgId (canonical + 200) followed by the serialized
protobuf message. The one text message still read is tickEFP, which
has no protobuf form.
Client.MaxClientVersion raised to 228
Client.MaxClientVersion is now 228, TWS API 10.53 (was 178 in
v2.x). The v2.x cap silently disabled every wire-protocol feature
gated above 178 — no v2.x deployment could reach the protobuf gates
(201+), the FA-profile desupport (177), the CME-tagging rewrite (192),
the new errorMsg layout (194), or any of the ~25 newer features. If
you subclass Client and override MaxClientVersion, update your
override.
TWS / IB Gateway 10.51 still connects at 226. The 10.53 additions need 10.53 at the other end:
Order.includeEarlyandOrder.conditionsIncludeEarly(228), the early pre-session. On an older TWS / IB Gateway,placeOrderraisesValueErrorfor them and sends nothing, as IBKR’s own client refuses them, because the older server has no field for them.includeOvernightandconditionsIncludeOvernightstill work; IBKR marks them deprecated in 10.53, in favor of the early fields.Ticker.comboImpliedBidandcomboImpliedAsk(227), with generic tick760on a combo.Thirteen
OrderStatefields describing the order’s working state, such asaveragePrice,submitTimeandroutingStrategy.
7b. Silent bugs in v2.x against modern TWS that v3.0 fixes
If you’ve been running v2.x against TWS / Gateway server >= 192, several wire-protocol details have been silently mis-encoded or mis-decoded. Upgrading to v3.0 starts these working without any code change on your end:
MaxClientVersion = 178cap kept every gate 201+ feature unreachable. v3.0 ships at 228.errorMsgdecoder mis-shifted on server >= 194 (ERROR_TIME gate); server errors landed on the wrongreqId.cancelOrderwire frame was corrupted on server >= 192 (CME tagging fields); the cancel still worked but the audit trail carried bad fields.placeOrderbinary path was missing gates 179-225, so any order touching new fields (parametrized days, attached orders, CME tagging, customerAccount, professionalCustomer, bondAccruedInterest, includeOvernight, submitter) was rejected by 183+ servers.historicalDataHISTORICAL_DATA_ENDmsgId changed at server >= 196 — v2.x silently dropped the End frame, soreqHistoricalDataAsynccould hang.tickOptionComputationwas a tautology returning the sentinel-2.0for vega and theta instead of mapping toNone.PnLSingle.positionwas typedintand truncated fractional positions (crypto, fractional shares) on the wire.commissionReportarriving beforeexecDetailswas either silently dropped or leaked memory unboundedly; v3.0 parks the early arrivals in a 1024-entry FIFO and replays them when the matching execDetails lands.AccountValue.decimalValuesurfaced the IBKR UNSET sentinel string (1.7976931348623157E308) as a legitimateNetLiquidationreading — a position-sizing booby trap.Order._toDecimalletDecimal('NaN')from user code propagate to the wire (truthy + silently corrupt). v3.0 filters NaN / Infinity toNone.
No migration action is required for any of these — they were silent bugs and the fix is purely correct behaviour. List them out so you can update any v2.x workarounds you may have written.
8. Recommended migration checklist
Run your existing tests under v3.0. Type-check failures point to most
Decimal | Nonesites.Audit numeric arithmetic on Order / OrderStatus / Execution / CommissionReport fields. Mix Decimal with
Decimalor float at the boundary withfloat(...).Audit
if x:checks on Decimal fields. WithNoneas the unset sentinel, the guard does what you expect (falsy when unset) — but if you previously depended onDecimal('NaN')being silently truthy, your logic inverts.grep -rn "\.commission\b" your_code/and migrate read sites tocommissionAndFees.grep -rn "commission=" your_code/and change constructor call sites tocommissionAndFees=(the old keyword raisesTypeError).grep -rn "HistogramData.*count\b" your_code/and migrate tosize.Audit
AccountValue.decimalValuecallers for non-currency tag access. Use the raw.valuefor tags outside the whitelist.Update
Client.sendMsgsubclasses to acceptbytes | None.Update positional indexing on tick / depth records (
av[1]→av.tag).Tighten cancel-async error handling — awaiter now raises
CancelledErroron cancel; previously hung.Import order types from
ib_asyncand replace anyisinstance(order, LimitOrder)checks withorder.orderTypeorspecOf(order)(section 6a).Port DataFrame code to polars:
util.df()andFlexReport.df()return polars DataFrames (section 6b).Port tick-built bars to
RealTimeBar(open_→open,Decimalvalues, operators emit the completed bar, time bars’ times are aware; section 5c).Type
whatToShow/barSizeSettingvariables with the parameter types or enums, and check computed durations (section 6c).Check contract comparisons of bags and continuous futures: they no longer equal another contract by a shared conId (section 6d).
grep -rnE "\.(dict|tuple|nonDefaults)\(\)|\.update\(|dataclassUpdate\(" your_code/for calls on ib_async objects, and use theutilfunctions or attribute assignment (section 6e).Use the Ticker each
reqMktData/reqTickByTickData/reqMktDepthreturns: a Ticker ends with its last stream, andib.ticker()/ib.tickers()return only live ones (section 5b).Test against a real TWS / IB Gateway 10.51 or later before shipping; v3.0 does not connect to an older one.
9. Getting help
Open an issue on GitHub if you hit an unexpected breakage.
Check the changelog for the full per-release summary.
Run with
python -W error::DeprecationWarningto surface every v2.x-flavoured call site as an actual failure — easier than grep alone.
v3.0 — full upgrade window: April 2026 → v4.0 release.
v4.0 will remove the commission deprecation alias.