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:

  1. Financial numerics are Decimal | None end-to-end (was float).

  2. commission renamed to commissionAndFees on CommissionReport and OrderState. The old name still works with a deprecation warning.

  3. 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

Order

totalQuantity, filledQuantity, lmtPrice, auxPrice, trailStopPrice, trailingPercent, lmtPriceOffset, triggerPrice, adjustedStopPrice, adjustedStopLimitPrice, adjustedTrailingAmount

OrderStatus

filled, remaining, avgFillPrice, lastFillPrice, mktCapPrice

OrderState

commissionAndFees, minCommission, maxCommission

Execution

shares, cumQty, price, avgPrice, evMultiplier

CommissionReport

commissionAndFees, realizedPNL, yield_

ContractDetails

minTick, minSize, sizeIncrement, suggestedSizeIncrement, evMultiplier, coupon

Position, PortfolioItem

position, avgCost, marketPrice, marketValue, averageCost, unrealizedPNL, realizedPNL

BarData, RealTimeBar

open, high, low, close, volume, average / wap

HistogramData

renamed count: int → size: Decimal | None

PnLSingle

retyped position: int → position: Decimal | None

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) and pickle.loads(...).

  • isinstance(av, AccountValue).

What changed

Was (NamedTuple)

Now (slotted dataclass)

Migration

av[1] (indexing)

TypeError

Use av.tag (named)

for f in av: ...

TypeError

Iterate explicit fields

av._asdict()

gone

dataclasses.asdict(av)

av._replace(tag="X")

gone

dataclasses.replace(av, tag="X")

av._fields

gone

[f.name for f in dataclasses.fields(av)]

av.custom = 1

AttributeError

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 with CancelledError

  • IB.cancelHistogramData(reqId) — settles awaiting future with CancelledError

  • IB.queryDisplayGroups(reqId)

  • IB.subscribeToGroupEvents(reqId, groupId)

  • IB.updateDisplayGroup(reqId, contractInfo)

  • IB.unsubscribeFromGroupEvents(reqId)

  • IB.cancelContractData(reqId) — protobuf-only, server >= 215

  • IB.cancelHistoricalTicks(reqId) — protobuf-only, server >= 215

  • IB.reqConfigAsync() — protobuf-only, server >= 219

  • IB.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 id

  • slOrderType: str = ""

  • ptOrderId: int | None = None — profit-target order id

  • ptOrderType: 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 auction

  • deactivate: bool = False — kill the order on fill or completion

  • postOnly: bool = False — reject the order if it would immediately match (maker-only)

  • ignoreOpenAuction: bool = False — bypass the opening auction

  • seekPriceImprovement: int | None = None

  • whatIfType: int | None = None

  • hedgeMaxSize: 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 / AllLast the last trade, BidAsk the 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 updateEvent is done, so async for over it stops and await ticker.updateEvent raises ValueError instead of waiting forever. It keeps its last values for whoever holds it. ib.ticker(contract) returns None, and ib.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.domAsks are Sequence[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.domAsksDict are 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 the Decimal it prints as (10.25 → Decimal('10.25')).

  • wap is the bar’s volume-weighted average price, None for a bar without volume (such as a midpoint bar).

  • RealTimeBar.open_ is open, as on BarData, for IBKR’s real-time bars too.

  • Each operator emits its completed bar. tickbars() and volumebars() used to emit their whole bars list; all three now emit the RealTimeBar that completed. Their bars still holds every bar (or, with maxBars=, the last that many completed ones), the last in progress.

  • bars.updateEvent(bars, hasNewBar) fires on every change of the bars: hasNewBar=True when the last bar has just completed, False when the bar in progress otherwise changes (a tick, or a time bar starting flat at the last close). tickbars() and volumebars() used to fire only on completion.

  • A completed bar never changes: RealTimeBar is frozen, and the bar in progress is replaced by a new RealTimeBar on each tick.

  • A midpoint tick without a bid and ask (no price) is skipped, where it used to fail the aggregation; tickbars(0) and volumebars(0) raise ValueError.

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:

  1. Returns None for tags not in MONETARY_ACCOUNT_VALUE_TAGS (the currency-denominated whitelist). Non-monetary tags like Leverage, DayTradesRemaining, SegmentTitle, BillableSize, ColumnPrio, and AccountType return None even when their value strings parse as numbers.

  2. Returns None for 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 (or ib_async.ordertypes); they are no longer in ib_async.order.

  • isinstance(order, LimitOrder) no longer works; it never did for orders read back from TWS. Use order.orderType, or ib_async.ordertypes.specOf(order), which names the order type of any Order.

  • repr shows Order(..., 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")) raises OrderTypeError. Other Order fields (tif, outsideRth, account, …) are keyword arguments, as before.

  • MidpriceOrder and RelativeOrder require 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]"
  • Decimal fields become polars Decimal columns, and time-zone-aware datetimes keep their zone (a fixed offset, as from datetime.astimezone(), becomes UTC, the same instant). An ib_async object in a field, such as Position.contract, is stored as itself (an Object column).

  • labels= keeps those columns in that order. An unknown label raises ColumnNotFoundError; 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 own Ticker.

  • Continuous futures. A ContFuture has its front future’s conId, but is not that future: they are no longer equal, and each gets its own market data subscription and Ticker. Two ContFutures 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

obj.dict()

util.dataclassAsDict(obj)

obj.tuple()

util.dataclassAsTuple(obj)

obj.nonDefaults()

util.dataclassNonDefaults(obj)

obj.update(field=value)

obj.field = value

util.dataclassUpdate(obj, field=value)

obj.field = value

obj.update(other) / util.dataclassUpdate(obj, other)

for f in dataclasses.fields(other): setattr(obj, f.name, getattr(other, f.name))

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.parseIBDatetime raises ValueError for an unknown time zone name. It also raises ValueError for an epoch outside the datetime range. 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, reqHeadTimeStampAsync raises instead of returning a wrong time.

  • FlexReport.load() raises FlexError for a file that is not XML. In v2.x the XML parser raised its own error instead.

  • TickData.price is float | None. A size tick on a side with no price yet is logged with price=None. v2.x produced the same value, but the annotation was float.

  • Watchdog has a sleep field. It defaults to asyncio.sleep and 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.includeEarly and Order.conditionsIncludeEarly (228), the early pre-session. On an older TWS / IB Gateway, placeOrder raises ValueError for them and sends nothing, as IBKR’s own client refuses them, because the older server has no field for them. includeOvernight and conditionsIncludeOvernight still work; IBKR marks them deprecated in 10.53, in favor of the early fields.

  • Ticker.comboImpliedBid and comboImpliedAsk (227), with generic tick 760 on a combo.

  • Thirteen OrderState fields describing the order’s working state, such as averagePrice, submitTime and routingStrategy.


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 = 178 cap kept every gate 201+ feature unreachable. v3.0 ships at 228.

  • errorMsg decoder mis-shifted on server >= 194 (ERROR_TIME gate); server errors landed on the wrong reqId.

  • cancelOrder wire frame was corrupted on server >= 192 (CME tagging fields); the cancel still worked but the audit trail carried bad fields.

  • placeOrder binary 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.

  • historicalData HISTORICAL_DATA_END msgId changed at server >= 196 — v2.x silently dropped the End frame, so reqHistoricalDataAsync could hang.

  • tickOptionComputation was a tautology returning the sentinel -2.0 for vega and theta instead of mapping to None.

  • PnLSingle.position was typed int and truncated fractional positions (crypto, fractional shares) on the wire.

  • commissionReport arriving before execDetails was 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.decimalValue surfaced the IBKR UNSET sentinel string (1.7976931348623157E308) as a legitimate NetLiquidation reading — a position-sizing booby trap.

  • Order._toDecimal let Decimal('NaN') from user code propagate to the wire (truthy + silently corrupt). v3.0 filters NaN / Infinity to None.

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.



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::DeprecationWarning to 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.