Interactive Brokers: how it works
Interactive Brokers (IB) is a brokerage you reach through software you run yourself: IB Gateway or Trader Workstation (TWS) holds your login, and programs talk to it over a local TCP socket, the TWS API. Taji takes two things from it: your IB account as an order venue (orders, positions, balances), and IB's market data as a data source (bars, quotes, prints, chains, reference reads, live streams). The plugin is one compiled-in crate, plugins/ibkr, built on the MIT ibapi crate pinned at 5.8.0. It reaches no internet host: every call goes to the Gateway on 127.0.0.1, which talks to IB.
The vendor
Hosts and environments. There is no IB host in Taji's egress table. You install IB Gateway or TWS on your machine and log in; it listens on a socket port, by default 4002 (Gateway, paper), 4001 (Gateway, live), 7497 (TWS, paper) and 7496 (TWS, live). Paper and live are two separate logins, so two separate Gateway sessions. A paper login lists accounts whose numbers start with DU. IB's paper trading guide (fetched 2026-12-02) says paper starts with USD 1,000,000, simulates fills from the top of the book with no deep book access, and always simulates stops and other complex order types.
Auth model. Taji holds no IB credential, token or key. You type your username, password and second factor into the Gateway's own window, and the Gateway keeps the session. The API connection itself carries only a client id, an integer that names the connecting program. IB allows up to 32 client applications on one TWS or Gateway at once (Connectivity Behavior, fetched 2026-12-02). A second connection on a client id already in use is refused with error 326 (Error Codes, fetched 2026-12-02).
There is nothing for Taji to refresh. The session's lifetime is the Gateway's:
- IB recommends "Auto restart" under Lock and Exit so the Gateway restarts daily without a login.
- The weekly cycle starts on Monday and needs a manual login (Daily & Weekly Reauthentication, fetched 2026-12-02).
- You cannot log into two trading applications with one username at once. A Client Portal login on the Gateway's username stops the Gateway reconnecting after the next server reset (Logging into multiple applications, fetched 2026-12-02).
The API family. The TWS API is one family: "a TCP Socket Protocol API", and any library that sends and receives the same messages is a conforming client (Introduction, fetched 2026-12-02). Requests carry a request id, and answers come back asynchronously as callbacks. IB's own docs pages for each request Taji makes:
| Area | Requests | IB's page (fetched 2026-12-02) |
|---|---|---|
| Accounts | reqManagedAccts, reqAccountSummary, reqPositions | Managed accounts, Account summary, Positions |
| Contracts | reqContractDetails, reqMatchingSymbols, reqSecDefOptParams, reqMarketRule | Contract details, Stock symbol search, Option chains |
| History | reqHistoricalData, reqHistoricalTicks, reqHeadTimeStamp, reqHistogramData, reqHistoricalSchedule | Historical bars, Historical ticks, Histogram data |
| Live data | reqMarketDataType, reqMktData (snapshot and stream), reqRealTimeBars, reqTickByTickData, reqMktDepth, reqMktDepthExchanges, reqSmartComponents | Delayed data, 5 second bars, Tick-by-tick, Market depth |
| Reference | reqNewsProviders, reqHistoricalNews, reqNewsArticle, reqWshMetaData, reqWshEventData, reqScannerSubscription, reqScannerParameters | News, Wall Street Horizon, Scanner subscription |
| Orders | reqIds, placeOrder (and its what-if), cancelOrder, reqAllOpenOrders, reqCompletedOrders, reqExecutions, exerciseOptions | Next valid id, Placing orders, Modifying orders, Open orders, Completed orders, Execution details, Exercise options |
| Errors and notices | the error callback, codes 100–10000+ | Error codes, Messages |
Crypto rides the same family on the PAXOS exchange. A crypto market order takes only IOC and a market buy must carry cashQty. A crypto limit order takes IOC or Minutes, which cancels after 5 minutes (Cryptocurrency, fetched 2026-12-02).
Versions. IB requires the current Stable or Latest TWS or Gateway, and a funded, opened IBKR Pro account (Requirements, fetched 2026-12-02). The IB Gateway Stable page (fetched 2026-12-02) fills its version number in by script, so the static page names none. The API version the adapter was read against is in the README's Behaviour and limits.
Accounts and entitlements. One login lists one or more account numbers (reqManagedAccts). Market data is a per-username subscription. Without one, reqMarketDataType(3) asks for IB's free delayed data, "15 – 20 minutes delayed", sent on delayed tick ids 66 to 76 (Delayed data, fetched 2026-12-02). Fees, the acknowledgement IB requires and the non-professional declaration are in the README's Fees and data subscriptions.
The vendor's stated limits (each fetched 2026-12-02):
- Message rate. API requests are capped at market-data lines ÷ 2 per second, so 50 a second at the default 100 lines. Past it the Gateway answers error 100, and a third breach ends the session (Pacing Limitations).
- History pacing. IB counts a pacing violation for identical history requests within 15 s, six or more on one contract, exchange and tick type within 2 s, or more than 60 in any 10 minutes. A BID_ASK request counts twice (Market Data Limitations). At most 50 history requests may be open at once (historical limitations).
- Real-time bars. Only 5-second bars, under the same 60-per-10-minutes pacing, and each counts as a Level 1 line (5 second bars).
- Tick-by-tick. No options, no combos, indices only on CME, at most one request per instrument per 15 s (Tick-by-tick).
- Account summary. Two active summary subscriptions at a time, each updating every three minutes (Account summary).
- Order ids. A client's order ids must strictly increase (OrderId). A modify is a
placeOrderon the open order's id with the same fields but the changed one (Modifying orders).
What Taji does not use:
- The Client Portal Web API and its OAuth 1.0a and 2.0 flows. The Client Portal Gateway needs a daily browser login, OAuth 1.0a is for third parties, and OAuth 2.0 is not offered to individuals (README Access).
- FIX CTCI. The Gateway's login step picks "IB API" instead. A FIX path is not yet built.
- Client id 0 and the Master API client id. These see every client's orders and TWS's own (ClientId 0 and the Master Client ID, fetched 2026-12-02).
Gateway::parseinplugins/ibkr/src/lib.rsrefuses 0, because that client could see and cancel every other client's orders. As a result, orders another client placed list under their perm id withAsked.fixedset, so Taji refuses to adopt them for a reprice and still cancels them at the venue. keepUpToDatehistory. Live bars come fromreqRealTimeBarsinstead. ThekeepUpToDatepath is not yet built.reqPnLandreqPnLSingle. They sit on theTwsseam and the live suite calls them, but no Taji read does. Not yet built.- Live news headlines. Taji has no live news product, so it serves news history only.
- Fundamentals. IB removed them from the TWS API in 10.47 (comment in
plugins/ibkr/src/offer.rs). - Wall Street Horizon earnings.
data::earningsinplugins/ibkr/src/data.rsreads them and is tested, but noSourceread routes the earnings product to it. Not yet built.
Offered, not read
What Taji reads, down to each field it fills, is docs/reference/coverage/ibkr.md. A stats read keeps IB's figures whole in its body; the statistics rows take a few. What IB serves past that, all fetched 2026-12-04 from IB's TWS API pages on interactivebrokers.github.io (IBKR Campus's .md pages answer a fetch with 403):
| Offered | Endpoint | Plan | Source |
|---|---|---|---|
| Option historical volatility (tick 23): never requested, as IB refuses generic tick 104 on a stock (321, README Data) | reqMktData generic tick 104 | same | Tick types |
13- and 26-week highs and lows (15 to 18), 90-day average volume (21), average option volume (87), trade count, trade rate and volume rate (54 to 56), RT Volume's price, size and VWAP (48, 77): in the stats body, with no statistics row | reqMktData generic ticks 165, 105, 293 to 295, 233, 375 | market data | Tick types |
Shortable shares (tick 89): in an instrument body, and no instrument column holds it | reqMktData generic tick 236 | market data | Tick types |
A bar's trade count, "the number of trades during the bar's timespan (only available for TRADES)": kept in a stored page, and trade_count is never set | reqHistoricalData | market data | IBApi.Bar |
| Bars of BID, ASK, BID_ASK and MIDPOINT on a stock, option or future: Taji asks TRADES, ADJUSTED_LAST, a coin's AGGTRADES and a currency pair's MIDPOINT | reqHistoricalData whatToShow | market data | Historical bars |
A print's exchange (exchange of a historical or tick-by-tick last, tick 84), which print_at and print drop so a trade's exchange and a quote's last_exchange stay null; a quote's bid and ask exchanges ("for stock and options", ticks 32 and 33), named in the point row and dropped by quote_row; a last's pastLimit and a bid/ask's bidPastLow and askPastHigh | reqHistoricalTicks, reqTickByTickData, reqMktData | market data | Historical ticks, Tick-by-tick, Tick types |
Tick-by-tick BidAsk and MidPoint streams (no options, indices only on CME), and historical midpoint ticks: live quotes ride reqMktData | reqTickByTickData, reqHistoricalTicks | market data | Tick-by-tick, Historical ticks |
An option's model price, underlying price and pvDividend: Greeks holds the first two and chains has no column for them (theo), and the bid, ask and last computations (ticks 10 to 12, 80 to 82) are not read. IB sends no rho | reqMktData option computations | the option's and its underlying's market data | Option computations, Tick types |
Regulatory imbalance (tick 61): in the live auction frame, with no imbalance column | reqMktData generic tick 225 | market data | Tick types |
A depth level's market maker or, on smart depth, its exchange: folded away when levels merge by price, and depth has no column for it | reqMktDepth, updateMktDepthL2 | a depth subscription | Market depth |
A dividend's other two figures of tick 59, which the code reads as trailing and forward 12-month totals (past_12m, next_12m): in the dividend frame, and corporate_actions has no column for them. IB's page says only "Contract's dividends" | reqMktData generic tick 456 | market data (IB: direct-route where SMART gives none) | Tick types |
A headline's extraData: kept in the raw of a stored headline, and IB's page does not define it | reqHistoricalNews | an API news subscription | News |
A scan row's distance, benchmark, projection and legsStr: dropped, and IB's page does not define them; it states the scanner returns no market data fields | reqScannerSubscription | not stated | Market scanner |
Histogram data (price level and size over a period): read as a kind=histogram body, and no statistics row holds it | reqHistogramData | not stated | Histograms |
A contract's conId, trading class, contract month, valid exchanges, order types, market rule ids, underConId and industry subcategory: in a stored instrument body, and no instrument or details column holds them | reqContractDetails | none stated | ContractDetails |
Two fields are not declared as fills because IB's pages do not support them. ContractDetails.cusip is "for Bonds only", so an equity's details cusip is not declared, though the decoder maps it. WAP is stated "only available for TRADES", so no vwap is declared of a pair's AGGTRADES bars, a currency pair's MIDPOINT bars or an index's. A quote's halted is declared of a stock alone, and a future option chain's greeks are not declared: no page or capture states them.
Code map
plugins/ibkr/taji-plugin.toml: the manifest. It has one[[sources]]and two[[link]]forms,ibkr-paperandibkr-live, each with its steps and refusal words.plugins/ibkr/Cargo.toml: theibapi = "=5.8.0"pin, and thefakefeature that the hub's tests use.plugins/ibkr/src/lib.rs: readPlugin::buildfirst. This file also owns the port and client-id constants (PAPER_PORTS,LIVE_PORTS,CLIENT_IDS), the link's discovery walk (discover,try_gateway,Miss) andGateway, the vault record parsed. It also maps errors:IbkrError,From<ibapi::Error>andFrom<IbkrError> for BrokerageError.plugins/ibkr/src/tws.rs: theTwstrait, which is every TWS call the adapter makes. Readdialfirst. This file also holds:connectandCONNECT_TIMEOUT;Session, the process's one connection per host, port and client id, with its fanned-out order stream and standing account summary;Metered, the message budget and history pacer wrapped around each session;rate_limits,evictandWARM_EVERY.
plugins/ibkr/src/link.rs:Auth, the link check. ReadAuth::check.plugins/ibkr/src/venue.rs: the venue'sFACTS, itsLINKfacts, the link's listing (accounts,listing,rows,env_holds) andArm, theVenueArm. ReadArm::bind.plugins/ibkr/src/exec.rs:IbkrBroker, theExecutionOps. ReadIbkrBroker::placefirst. This file also holds:orders_of, which maps an intent to IB orders;feed, which folds the order stream;watchandconnectivity, for the Gateway's 1100, 1101 and 1102 notices;resync, which reads the venue's lists;ibkr_capabilitiesandibkr_protection.
plugins/ibkr/src/reads.rs:IbkrReads, theVenueReads: money offreqAccountSummary, the clock, routes and a contract's multiplier.plugins/ibkr/src/source.rs:Ibkr, the dataSource, with itsFACTS, theREADStable and the bars rowCAP. ReadIbkr::callfirst, the gate every data read passes. This file also holdsseat,probe,history,read,raw_read,open_ticksand the hub's dial with its 30 s latch (dial,latched,fell).plugins/ibkr/src/data.rs:IbkrDataand the free functions behind each non-bar read: quote, history ticks, search, instrument, chains, generic ticks, stat series, histogram, news, WSH, scanner, calendar, clock, routes.plugins/ibkr/src/raw.rs: the non-bar reads as a pull keeps them, one JSON frame per read under a versioned format (SEARCH_FORMATand the rest). ReadIbkrData's*_rawmethods.plugins/ibkr/src/history.rs:IbkrBars, theHistoricalDataoverreqHistoricalData, andPacer, the history pacing windows. It also holdsBARS_FORMATandparse_bars. ReadPacer::paceandkept.plugins/ibkr/src/live.rs:IbkrLive, theLiveStream. It folds 5 s real-time bars into minutes, one stream per symbol. ReadIbkrLive::open.plugins/ibkr/src/contract.rs: a Taji symbol as an IBContract. Readcontract_ofandResolver;spellandtaji_symbolgo the other way.plugins/ibkr/src/probe.rs: what your market data grants per class, off one snapshot each. Readverdict.plugins/ibkr/src/offer.rs:OFFERandVENUE_OFFER, the cells the coverage page shows.plugins/ibkr/src/fake.rs:FakeTws, a scriptedTwsthat records every venue-changing call and mimics the Gateway's quirks.plugins/ibkr/tests/live.rs: the live suite against a paper Gateway.plugins/ibkr/scripts/ibkr_walk.py: the walk, a set of phases run through a headless kernel's wire.
How it plugs into Taji
Composition. engine/crates/taji-open/src/lib.rs adds taji_ibkr::Plugin::default. Plugin::build registers three things: source::Ibkr (the data source), venue::Arm (the order venue) and link::Auth (the link check). The build's ties in engine/crates/taji-open/ties/src/lib.rs rank IBKR:
place1, whose comment reads "A point waits up to 5 s on its snapshot";stream4, behind Robinhood's poll;- in the reference orders for news, corporate actions, statistics and imbalance.
SDK traits implemented.
| Trait | Type | File |
|---|---|---|
Source | Ibkr | plugins/ibkr/src/source.rs |
HistoricalData | IbkrBars | plugins/ibkr/src/history.rs |
LiveStream | IbkrLive | plugins/ibkr/src/live.rs |
VenueArm | Arm | plugins/ibkr/src/venue.rs |
ExecutionOps | IbkrBroker | plugins/ibkr/src/exec.rs |
VenueReads | IbkrReads | plugins/ibkr/src/reads.rs |
Auth | Auth | plugins/ibkr/src/link.rs |
There is no ReconcileOps: reconcile goes through ExecutionOps::orders_since and positions, which read IB's lists.
Statics.
source::FACTS, aFacts, has seatVenue, so the source is seated by a venue link and not by a key of its own. Its fields:grants_first: trueandgated: InstrumentClass::ALL: every class is gated on what your plan grants.permits: 50: IB's cap on open history requests.bars_cap: CAP: seven classes; split, and split-dividend-spinoff on dailyADJUSTED_LAST;rate_per_min: 6.book: 10 levels a side for equity, future and crypto.
venue::FACTS, aVenueFacts, has two records,ibkr(paper) andibkr-live, because a paper and a live login are two Gateways.LINKisLinkMethod::Gatewaywithkeyandsecretrevealed, since neither is a secret.offer::OFFERandoffer::VENUE_OFFERdeclare the cells of the coverage page.
Link forms. ibkr-paper and ibkr-live are both kind = "start" with no fields; their steps and refusal words are in the manifest. POST /verb/link/venue/link runs Auth::check, which calls venue::accounts, which walks this env's ports on 127.0.0.1 with discover. For each candidate:
- A port with nothing on it (1 s TCP check,
listening) isnot_running. - A connection that fails the handshake is
unreachable. - Error 326 moves to the next of client ids 1701, 1703 and 1705. All three held is
client_id. - The listing is the validation: a login listing no account is
no_accounts, and a paper form on a non-DUlogin, or the reverse, isenv.
The refusal is the furthest any candidate got. What gets sealed is {key: "host:port", secret: "<client id>"}. Auth::hosts is empty, because the Gateway is on this machine and outside the egress table. A typed key and secret replace the walk; that is the scripted override.
Sessions. tws::dial keeps one connection per (host, port, client_id) for the whole process, shared by every row, reboot and link. The venue arm and the link use the record's client id (Gateway::session(0)). The data source uses that id plus 1 (HUB_CLIENT in plugins/ibkr/src/source.rs), which is why CLIENT_IDS are odd. connect dials with ibapi's reconnect_forever, waits at most 5 s, and asks for delayed market data once. Every session is wrapped in Metered.
Surfaces and the calls behind them.
| Taji surface | IB call | File |
|---|---|---|
GET /get/bars (history) | reqHistoricalData: TRADES; daily ADJUSTED_LAST; crypto AGGTRADES; forex MIDPOINT | plugins/ibkr/src/history.rs |
| live 1m bars (the hub's feed) | reqRealTimeBars, 5 s, folded to 1m | plugins/ibkr/src/live.rs |
GET /get/quotes (now) | reqMktData snapshot; reqSmartComponents for exchange names | plugins/ibkr/src/data.rs (quote, exchange_names) |
GET /get/quotes, GET /get/trades (span) | reqHistoricalTicks BID_ASK and TRADES | plugins/ibkr/src/data.rs (quotes_between, trades_between) |
GET /get/search | reqMatchingSymbols, reqContractDetails | plugins/ibkr/src/data.rs, plugins/ibkr/src/raw.rs |
GET /get/instrument | reqContractDetails, reqMarketRule | plugins/ibkr/src/data.rs (instrument) |
GET /get/chains | reqSecDefOptParams, per-expiry reqContractDetails, snapshots with option computations | plugins/ibkr/src/data.rs (chain, future_option_chain) |
GET /get/statistics | generic ticks 165, 233, 236, 411, 588 on reqMktData; reqHistogramData; stat bars | plugins/ibkr/src/data.rs, plugins/ibkr/src/raw.rs |
GET /get/corporate_actions | generic tick 456 | plugins/ibkr/src/source.rs (actions_raw) |
GET /get/news | reqNewsProviders, reqHistoricalNews, reqNewsArticle | plugins/ibkr/src/data.rs (news) |
GET /get/screener | reqScannerSubscription, reqScannerParameters | plugins/ibkr/src/data.rs (screener) |
/ws/market quotes, trades, depth, status, imbalance | reqMktData stream (ticks 49, 225), reqTickByTickData AllLast, reqMktDepth 10 rows | plugins/ibkr/src/source.rs (open_ticks) |
| account equity, cash, buying power, margin | reqAccountSummary | plugins/ibkr/src/reads.rs (money) |
| positions | reqPositions | plugins/ibkr/src/exec.rs (held) |
| orders and reconcile | reqAllOpenOrders, reqCompletedOrders, reqExecutions, the order stream | plugins/ibkr/src/exec.rs (resync, feed) |
POST /verb/trading/orders/<class>/place | reqIds, placeOrder | plugins/ibkr/src/exec.rs (place) |
POST /verb/trading/orders/<class>/preview | placeOrder with what-if | plugins/ibkr/src/exec.rs (preview) |
POST /verb/trading/<acct>/orders/<id>/reprice | placeOrder on the open order's id | plugins/ibkr/src/exec.rs (replace) |
POST /verb/trading/<acct>/orders/<id>/cancel | cancelOrder | plugins/ibkr/src/exec.rs (cancel) |
POST /verb/trading/<acct>/positions/<contract>/exercise | exerciseOptions | plugins/ibkr/src/exec.rs (exercise) |
| venue clock, routes, point value | SPY's reqContractDetails hours and reqCurrentTime; reqMktDepthExchanges; reqContractDetails multiplier | plugins/ibkr/src/data.rs (clock, routes), plugins/ibkr/src/reads.rs |
One read, end to end: a 1m bar span.
GET /get/bars?symbols=equity:AAPL&…&provider=ibkrreaches the hub, which checks its store first. For the uncovered part it callsSource::history.Ibkr::historychecks the 30 s latch, dials the hub's session (client id + 1) and returnsIbkrBarsover that session and itsPacer.IbkrBarsresolves AAPL to its conid once (Resolver, held for the process). It then pages backward through the span, onereqHistoricalDataper step-table window. Before each page is sent,Pacer::pace_askcharges the 15 s, 2 s and 10-minute windows, andMeteredcharges one message against 50 a second.- Each answer is kept as a
BARS_FORMATpage with arequestentry that names no account (kept).parse_barsturns the pages into rows, and the hub stores and serves them.
One order, end to end.
POST /verb/trading/orders/equity/placepasses the kernel's gates and enters the funnel described in the//!header ofengine/crates/taji-trading/src/root.rs: risk gate, journalIntentReceived, thenops.place_order.IbkrBroker::placebuilds the IB orders withorders_of. Under the session'splacinglock, it takes an id fromreqIdsfor each member, links children to the entry's id as their parent, setsaccountandorder_ref(the intent id), and sends the batch withTws::place_orders.- It waits up to 2 s (
ANSWER_WAIT) for IB's first word on each member. A refusal arrives as an error notice; if one does,refusedre-reads the lists and the place answersOrderRejectedin IB's words. - Otherwise it answers the book's
OrderSnapshot, whoseorder_idis the intent id. The root asserts theexpected_refecho and journalsOrderAcked. Fills arrive on the order stream (feed) and the refresh pass books them.
Why it is built this way
- TWS API through your own Gateway, via
ibapi. Taji ships no IB code. IB's own download is non-commercial with no redistribution, while implementing the protocol is sanctioned (README Behaviour and limits, "Design choice"). This also means no IB key ever exists for Taji to hold: ADR 0005 holds trivially. - A
Twsseam inside the crate.ibapikeeps its message bus and decoders private, so the seam sits above the client (//!ofplugins/ibkr/src/tws.rs). The same seam is what letsFakeTwsdrive every unit test. - One process-wide session per client id. The Gateway refuses a second connection on a held id (326), and a connection takes one order stream.
Session::order_updatestherefore fans that stream out and reopens it after a reconnect (the doc comment onSession). - Arm and source on separate client ids. The two build their clients independently, and a Gateway takes 32 (comment on
HUB_CLIENT). - The vault record is an address, not a secret.
keyishost:portandsecretis the client id, because the vault is the one record store (Gatewayinplugins/ibkr/src/lib.rs). - Paper and live told apart by
DU. IB's paper logins listDUaccounts and nothing else does. A paper row binds only aDUnumber and a live row never does (env_holds), so the paper form cannot mint a row on a funded login. - Delayed data asked once at connect. IB serves live data where you subscribe and delayed where you do not (
connect). The probe then learns each class's grant from one snapshot (AAPL, BTC, SPX, ES's front contract and its first option), so the hub ranks a delayed class behind real-time providers (probe.rs, tiesstream). order_refis the order's key; the perm id is the native id. IB's order id is unique per client id only, and a completed order lists it as -1. The perm id is global and permanent, andorder_refis echoed on every list and execution (//!ofplugins/ibkr/src/exec.rs).- A group goes in one batch under one lock.
reqIdsanswers the same id until an order uses it, so no other order may take an id between members (IbkrBroker::place,FakeTws's header). If the batch fails midway, every member is cancelled so none rests untracked, and the place answersAckedUnconfirmed. NotSentonly when nothing left. A send thatibapirefused, or that failed on a down socket, isNotSent. Any other failure may have reached IB, so it isAckedUnconfirmed(sent_err), which reconcile resolves.- Pacing refuses, never waits.
PacerandMeteredrefuse a request unsent and name the real release time. An error 100 holds the message budget for 1 s, since IB names no wait. A 162 pacing answer carries a 10-minute bound, IB's rolling window (From<ibapi::Error>). - 50 messages a second, fixed. Market-data lines are not readable over the API, so the budget sits at the 100-line floor (
MSGS_PER_SECOND). - A 30 s latch on a Gateway that failed. A dial that found nothing is not retried until
REDIALhas passed, so reads do not each wait out the 5 s connect timeout (Ibkrinplugins/ibkr/src/source.rs). A warm ping every 60 s re-dials a Gateway that came back (WARM_EVERY). - One standing account summary per session. The Gateway frees none on
cancelAccountSummary(paper, 2026-10-27), and a connection holds two. The session therefore opens one summary on all tags and drains it (Standinginplugins/ibkr/src/tws.rs). - Bars on IB's stated basis. TRADES bars adjust splits and not dividends, and daily
ADJUSTED_LASTadds dividends. Each answer carries the basis IB states (ADR 0007). - An option's day is folded from its hours. IB serves no option daily bars (162 "EODChart"), so
foldsinplugins/ibkr/src/history.rsbuilds the day from regular-hours bars. - Data reaches clients only as hub products. No TWS shape crosses the wire (ADR 0004).
raw.rskeeps IB's frames for replay, and the hub's parse produces the typed rows.
Constraints and limits
The measured numbers are owned by the README's Transport and limits, Data, Orders and Symbology and gotchas. The mechanisms that enforce them:
-
Message budget (
Metered,plugins/ibkr/src/tws.rs). Every request is admitted againstibkr-msgs, 50 a second per connection. A refused request is never sent and answersIbkrError::Budget, which becomesBrokerageError::RateLimitedwith the budget's release time. -
History pacer (
Pacer,plugins/ibkr/src/history.rs). It enforces three windows per connection:- 60 requests in 10 minutes (
PER_WINDOW, held for every bar size, not only bars of 30 s or less); - 5 on one contract in 2 s (
PER_CONTRACT); - no identical bar request within 15 s (
IDENTICAL).
A span needing more requests than the window has left is refused before the first page leaves.
- 60 requests in 10 minutes (
-
What a pacing refusal answers. Inside IB the signal is error 100 or 162; there is no HTTP 429. Bars go through
BrokerageError::RateLimitedand every other data read throughIbkr::call'srefusal, which maps a pacing or budget refusal toTradingError::RateLimited. Either way the wire answers 429rate_limitedwithrest_after. Nothing retries automatically. -
Rate scopes.
rate_limitslists each held session's scopes byhost:port/client_id:messages,history_10m,history_burst,history_identicalandstream, the count of symbols holding a live line. The stream scope has no quota, because lines are unreadable. -
Lines. A live chain streams at most 40 contracts (
CHAIN_LINES), opened 25 ms apart (OPEN_GAP), out of the default 100 lines. A chain read lists at most 200 contracts (CHAIN_CONTRACTS). Tick-by-tick on one symbol re-opens no sooner than 15 s (TICK_BY_TICK_GAP). -
Timeouts. Connect 5 s, a one-shot list 10 s (
LIST_TIMEOUT), a probe snapshot 5 s, news bodies 10 s in total (BODIES_BUDGET). -
Entitlements. Each class is gated on the probe's verdict. The codes 354, 10089, 10167, 162 and 10189 read as
Refused(probe::REFUSED), and a live bar stream refused for a missing subscription ends, keeping IB's words as its reason (fold,plugins/ibkr/src/live.rs). A class with no grant is passed over for the next provider. -
Symbology (
plugins/ibkr/src/contract.rs). Each asset class maps to an IB contract type:- equity is STK;
- an option, OCC or TradeStation spelling, is OPT;
- a dated future is FUT, and the front continuous one is CONTFUT;
- an option on a future is FOP;
- a crypto pair is CRYPTO on PAXOS;
- a currency pair is CASH on IDEALPRO;
- an index is IND.
Resolverresolves each symbol to one USD conid and holds it for the process. A symbol listed on several USD exchanges isAmbiguous. A continuous future streams nothing live (NO_CONTINUOUS). -
Refusals before the wire.
offer.rsandibkr_capabilitiesdeclare what each class takes. A word IB has no field for is refused unsent (unsent), for exampleadd_liquidity,book_only, fractional shares andcashQtyoutside crypto.
Examples
No raw TWS socket capture is committed: the crate has no plugins/ibkr/tests/fixtures directory. The live suite and the walk print their records to the terminal and commit none. A capture would come from the walk's bars and data phases against a paper Gateway. Each example below is copied from a test body or the wire fixture, with account numbers masked as <ACCT> and ids as pN.
The link finds a Gateway. The window posts the paper form (engine/crates/taji/tests/fixtures/wire/link-forms.json, the ibkr-paper form's post):
{"route": "link/venue/link", "body": {"env": "paper", "venue": "ibkr"}}
With 1701 held on port 4002, the walk moves to the next id (a_held_id_walks_the_band_and_the_whole_band_held_is_client_id, plugins/ibkr/src/lib.rs):
let (found, tried) = walk(&[4002], &[((4002, 1701), Miss::ClientId)]).await;
assert_eq!(found, Ok((4002, 1703)));
assert_eq!(tried, ["try 4002:1701", "try 4002:1703"]);
The listing decides the env (an_ibkr_listing_of_the_other_env_mints_nothing, plugins/ibkr/src/venue.rs):
assert_eq!(rows(Env::Live, paper(), kind), Err("env")); // paper() lists one "DU…" account
assert_eq!(rows(Env::Paper, vec!["<ACCT>".into()], kind), Err("env")); // a funded "U…" account
assert_eq!(rows(Env::Paper, Vec::new(), kind), Err("no_accounts"));
An order reaches IB's fields. A GTC buy limit of 1 AAPL at 100 becomes this placeOrder. The assertions are the limit row of the_four_shapes_place_and_their_status_round_trips (plugins/ibkr/src/exec.rs), with the test's loop variables written out:
let placed = broker.place_order("", &intent).await.unwrap();
assert_eq!(placed.state, "pendingsubmit");
assert_eq!(Some(placed.order_id.clone()), placed.ref_id); // the intent id, p1
assert_eq!(contract.contract_id, 100_001); // the AAPL contract
assert_eq!(order.order_type, "LMT");
assert_eq!(order.limit_price, Some(100.0));
assert_eq!(order.tif.as_str(), "GTC");
assert_eq!(order.action, Action::Buy);
assert_eq!(order.total_quantity, 1.0);
assert_eq!(order.account, "<ACCT>");
assert_eq!(order.order_ref, "p1");
The same test pushes IB's statuses on the order stream: Submitted with 0 filled reads submitted; Submitted with 0.5 reads partially_filled; and Filled still reads partially_filled until the execution and its commission report land.
The account's money. IB's summary rows come back verbatim, one account's only (money_is_the_accounts_own_summary_verbatim, plugins/ibkr/src/reads.rs):
("<ACCT>", "NetLiquidation", "1000000.00"),
("<ACCT>", "TotalCashValue", "999000.50"),
("<ACCT>", "BuyingPower", "4000000.00"),
// → Money { equity: "1000000.00", cash: Some("999000.50"), maintenance_margin: None, … }
The refresh pass (poll_money, engine/crates/taji-trading/src/root.rs) puts that on the account row that GET /read/trading/book answers (engine/crates/taji/tests/fixtures/wire/trading-book.json, trimmed):
{
"brokerage": "ibkr",
"id": "<ACCT>",
"arm": "live",
"equity": "100000.00",
"cash": "50000.00",
"buying_power": "200000",
"classes": ["equity", "option", "future", "crypto", "future_option"],
"liveness": "delayed",
"state": "bound",
…
}
A bar request and its pacing. Every page a pull keeps names its request this way (kept, plugins/ibkr/src/history.rs). An equity's 24h span asks SMART, then OVERNIGHT (a_raw_answer_parses_to_the_read_with_no_client):
json!({
"method": "reqHistoricalData",
"url": "tws",
"params": {
"conid": …, "symbol": …, "local_symbol": …, "security_type": …,
"exchange": …, // "SMART", then "OVERNIGHT"
"currency": …, "end": …, "duration": …, "bar_size": …,
"what_to_show": …, "use_rth": …,
},
})
With the 10-minute window full, the 61st request answers RateLimited and nothing is sent (the_sixty_first_request_in_ten_minutes_is_refused):
fill(&bars.pacer, PER_WINDOW);
let refused = bars.get_bars(&it("equity:AAPL"), Timeframe::Daily, MON, MON + DAY).await;
assert!(matches!(refused, Err(BrokerageError::RateLimited { .. })));
assert!(fake.asked.lock().unwrap().is_empty());
The kernel answers that read 429 rate_limited with {provider: "ibkr", rest_after}. No IBKR capture of that body is committed; the wire fixture's 429 example is another provider's.
Testing
Which checks a change needs: testing.
-
Offline, no Gateway:
cargo test -p taji-ibkr. Every module's tests driveFakeTws, which behaves like the Gateway where the Gateway's behaviour hides a bug:reqIdsrepeats an id until an order uses it, a completed order listsorder_id-1, and the open list holds every client's orders. The hub's own tests readsource::FACTS(engine/crates/taji-trading/src/hub/plugin.rs) and theAuth(engine/crates/taji-trading/src/arms.rs). -
The live suite, paper only: with IB Gateway logged into paper and its API enabled, from the repo root:
IBKR_PORT=4002 cargo test -p taji-ibkr --test live -- --ignored --test-threads=1 [filter]Without
IBKR_PORTevery test is a SKIP. A port that is not a paper port, or a login holding a non-DUaccount, panics before any call.IBKR_HOSTdefaults to127.0.0.1andIBKR_CLIENT_IDto 91; each test adds its own offset. The order tests rest and cancel paper orders. Fills run only underLIVE_FILLS=1during regular hours.exercise_lapse_answers_a_framelapses only the contractIBKR_LAPSEnames. You need no key, but you do need the Gateway; with no Gateway, report the suite as skipped. -
Every vendor's read tests:
engine/crates/taji-open/scripts/vendor_live.shruns this suite's read tests by name and never its order tests. WithoutIBKR_PORT, IBKR is a SKIP. -
The walk, through a real kernel: start a headless kernel as
AGENTS.mddescribes, then runpython3 plugins/ibkr/scripts/ibkr_walk.py <wire port> <phase>withTAJI_STATE_DIRset to that kernel's state dir andIBKR_PORTset to the paper Gateway's port. Runlinkfirst. The phases, their guards and the opt-ins that fill (WALK_MARKET=1, regular hours only;WALK_EXERCISE*) are in the script's header. The walk refuses to run if a liveibkrrow is linked. -
Coverage cells: the coverage page is generated from
offer.rsandsource::FILLSby the wire fixture command inAGENTS.md. Change them, then regenerate; never edit the page.each_class_fills_what_facts_declaresinplugins/ibkr/src/source.rsfails when a decoder fills a columnFILLSdoes not name, or the reverse.
References
All fetched 2026-12-02.
- TWS API: Introduction, Requirements, TWS API Limitations, Architecture, Connectivity Behavior, Broken API socket connection, Logging into multiple applications, Daily & Weekly Reauthentication.
- Limits: Pacing Limitations, Market Data Limitations, historical limitations (legacy).
- Market data: Delayed data, Historical bars, Historical ticks, Histogram data, 5 second bars, Tick-by-tick, Market depth.
- Contracts and reference: Contract details, Option chains, Stock symbol search, News, Wall Street Horizon, Scanner subscription, Cryptocurrency (legacy).
- Accounts and orders: Managed accounts, Account summary, Positions, PnL, Next valid id, OrderId, Placing orders, Modifying orders, ClientId 0 and the Master Client ID, Open orders, Completed orders, Execution details, Exercise options.
- Errors: Error codes, Messages.
- Platform: IB Gateway Stable, About paper trading accounts.
- The client:
ibapion crates.io (5.8.0, MIT, pinned).