> Every Taji docs page as Markdown: https://docs.taji.is/llms.txt

# 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](https://www.ibkrguides.com/clientportal/aboutpapertradingaccounts.htm) (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](https://interactivebrokers.com/docs/tws-api/doc/connectivity/connectivity-behavior.md), fetched 2026-12-02). A second connection on a client id already in use is refused with error 326 ([Error Codes](https://interactivebrokers.com/docs/tws-api/doc/error/codes.md), 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](https://interactivebrokers.com/docs/tws-api/doc/tws-settings/daily-weekly-reauthentication.md), 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](https://interactivebrokers.com/docs/tws-api/doc/connectivity/logging-into-multiple-applications.md), 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](https://interactivebrokers.com/docs/tws-api/doc/introduction.md), 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](https://interactivebrokers.com/docs/tws-api/doc/accounts/managed-accounts.md), [Account summary](https://interactivebrokers.com/docs/tws-api/doc/accounts/summary.md), [Positions](https://interactivebrokers.com/docs/tws-api/doc/accounts/positions.md) |
| Contracts | `reqContractDetails`, `reqMatchingSymbols`, `reqSecDefOptParams`, `reqMarketRule` | [Contract details](https://interactivebrokers.com/docs/tws-api/doc/contracts/details.md), [Stock symbol search](https://interactivebrokers.com/docs/tws-api/doc/contracts/stock-symbol-search.md), [Option chains](https://interactivebrokers.com/docs/tws-api/doc/contracts/option-chains.md) |
| History | `reqHistoricalData`, `reqHistoricalTicks`, `reqHeadTimeStamp`, `reqHistogramData`, `reqHistoricalSchedule` | [Historical bars](https://interactivebrokers.com/docs/tws-api/doc/md/historical-bars.md), [Historical ticks](https://interactivebrokers.com/docs/tws-api/doc/md/historical-ticks.md), [Histogram data](https://interactivebrokers.com/docs/tws-api/doc/md/histogram-data.md) |
| Live data | `reqMarketDataType`, `reqMktData` (snapshot and stream), `reqRealTimeBars`, `reqTickByTickData`, `reqMktDepth`, `reqMktDepthExchanges`, `reqSmartComponents` | [Delayed data](https://interactivebrokers.com/docs/tws-api/doc/md/delayed-data.md), [5 second bars](https://interactivebrokers.com/docs/tws-api/doc/md/5-second-bars.md), [Tick-by-tick](https://interactivebrokers.com/docs/tws-api/doc/md/live-ticks.md), [Market depth](https://interactivebrokers.com/docs/tws-api/doc/md/market-depth.md) |
| Reference | `reqNewsProviders`, `reqHistoricalNews`, `reqNewsArticle`, `reqWshMetaData`, `reqWshEventData`, `reqScannerSubscription`, `reqScannerParameters` | [News](https://interactivebrokers.com/docs/tws-api/doc/news/introduction.md), [Wall Street Horizon](https://interactivebrokers.com/docs/tws-api/doc/wall-street-horizon/introduction.md), [Scanner subscription](https://interactivebrokers.com/docs/tws-api/doc/market-scanner/subscription.md) |
| Orders | `reqIds`, `placeOrder` (and its what-if), `cancelOrder`, `reqAllOpenOrders`, `reqCompletedOrders`, `reqExecutions`, `exerciseOptions` | [Next valid id](https://interactivebrokers.com/docs/tws-api/doc/next-valid-id.md), [Placing orders](https://interactivebrokers.com/docs/tws-api/doc/quick-start/placing-orders.md), [Modifying orders](https://interactivebrokers.com/docs/tws-api/doc/orders/modify-order.md), [Open orders](https://interactivebrokers.com/docs/tws-api/doc/order-management/open-orders.md), [Completed orders](https://interactivebrokers.com/docs/tws-api/doc/order-management/completed-orders.md), [Execution details](https://interactivebrokers.com/docs/tws-api/doc/order-management/execution-details.md), [Exercise options](https://interactivebrokers.com/docs/tws-api/doc/orders/exercise-options.md) |
| Errors and notices | the `error` callback, codes 100–10000+ | [Error codes](https://interactivebrokers.com/docs/tws-api/doc/error/codes.md), [Messages](https://interactivebrokers.com/docs/tws-api/doc/error/messages.md) |

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](https://interactivebrokers.github.io/tws-api/cryptocurrency.html), fetched 2026-12-02).

**Versions.** IB requires the current Stable or Latest TWS or Gateway, and a funded, opened IBKR Pro account ([Requirements](https://interactivebrokers.com/docs/tws-api/doc/notes-limitations/requirements.md), fetched 2026-12-02). The [IB Gateway Stable page](https://www.interactivebrokers.com/en/trading/ibgateway-stable.php) (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](https://docs.taji.is/catalog/ibkr.md#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](https://interactivebrokers.com/docs/tws-api/doc/md/delayed-data.md), fetched 2026-12-02). Fees, the acknowledgement IB requires and the non-professional declaration are in the README's [Fees and data subscriptions](https://docs.taji.is/catalog/ibkr.md#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](https://interactivebrokers.com/docs/tws-api/doc/pacing-limitations.md)).
- **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](https://interactivebrokers.com/docs/tws-api/doc/md/market-data-limitations.md)). At most 50 history requests may be open at once ([historical limitations](https://interactivebrokers.github.io/tws-api/historical_limitations.html)).
- **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](https://interactivebrokers.com/docs/tws-api/doc/md/5-second-bars.md)).
- **Tick-by-tick.** No options, no combos, indices only on CME, at most one request per instrument per 15 s ([Tick-by-tick](https://interactivebrokers.com/docs/tws-api/doc/md/live-ticks.md)).
- **Account summary.** Two active summary subscriptions at a time, each updating every three minutes ([Account summary](https://interactivebrokers.com/docs/tws-api/doc/accounts/summary.md)).
- **Order ids.** A client's order ids must strictly increase ([OrderId](https://interactivebrokers.com/docs/tws-api/doc/quick-start/order-id.md)). A modify is a `placeOrder` on the open order's id with the same fields but the changed one ([Modifying orders](https://interactivebrokers.com/docs/tws-api/doc/orders/modify-order.md)).

**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](https://docs.taji.is/catalog/ibkr.md#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](https://interactivebrokers.com/docs/tws-api/doc/order-management/master-client-id.md), fetched 2026-12-02). `Gateway::parse` in `plugins/ibkr/src/lib.rs` refuses 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 with `Asked.fixed` set, so Taji refuses to adopt them for a reprice and still cancels them at the venue.
- **`keepUpToDate` history.** Live bars come from `reqRealTimeBars` instead. The `keepUpToDate` path is not yet built.
- **`reqPnL` and `reqPnLSingle`.** They sit on the `Tws` seam 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::earnings` in `plugins/ibkr/src/data.rs` reads them and is tested, but no `Source` read 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`](https://docs.taji.is/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](https://docs.taji.is/catalog/ibkr.md#data)) | `reqMktData` generic tick 104 | same | [Tick types](https://interactivebrokers.github.io/tws-api/tick_types.html) |
| 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](https://interactivebrokers.github.io/tws-api/tick_types.html) |
| Shortable shares (tick 89): in an `instrument` body, and no `instrument` column holds it | `reqMktData` generic tick 236 | market data | [Tick types](https://interactivebrokers.github.io/tws-api/tick_types.html) |
| 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`](https://interactivebrokers.github.io/tws-api/classIBApi_1_1Bar.html) |
| 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](https://interactivebrokers.github.io/tws-api/historical_bars.html) |
| 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](https://interactivebrokers.github.io/tws-api/historical_time_and_sales.html), [Tick-by-tick](https://interactivebrokers.github.io/tws-api/tick_data.html), [Tick types](https://interactivebrokers.github.io/tws-api/tick_types.html) |
| 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](https://interactivebrokers.github.io/tws-api/tick_data.html), [Historical ticks](https://interactivebrokers.github.io/tws-api/historical_time_and_sales.html) |
| 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](https://interactivebrokers.github.io/tws-api/option_computations.html), [Tick types](https://interactivebrokers.github.io/tws-api/tick_types.html) |
| Regulatory imbalance (tick 61): in the live auction frame, with no `imbalance` column | `reqMktData` generic tick 225 | market data | [Tick types](https://interactivebrokers.github.io/tws-api/tick_types.html) |
| 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](https://interactivebrokers.github.io/tws-api/market_depth.html) |
| 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](https://interactivebrokers.github.io/tws-api/tick_types.html) |
| 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](https://interactivebrokers.github.io/tws-api/news.html) |
| 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](https://interactivebrokers.github.io/tws-api/market_scanners.html) |
| 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](https://interactivebrokers.github.io/tws-api/histograms.html) |
| 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`](https://interactivebrokers.github.io/tws-api/classIBApi_1_1ContractDetails.html) |

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-paper` and `ibkr-live`, each with its steps and refusal words.
- `plugins/ibkr/Cargo.toml`: the `ibapi = "=5.8.0"` pin, and the `fake` feature that the hub's tests use.
- `plugins/ibkr/src/lib.rs`: read `Plugin::build` first. 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`) and `Gateway`, the vault record parsed. It also maps errors: `IbkrError`, `From<ibapi::Error>` and `From<IbkrError> for BrokerageError`.
- `plugins/ibkr/src/tws.rs`: the `Tws` trait, which is every TWS call the adapter makes. Read `dial` first. This file also holds:
  - `connect` and `CONNECT_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`, `evict` and `WARM_EVERY`.
- `plugins/ibkr/src/link.rs`: `Auth`, the link check. Read `Auth::check`.
- `plugins/ibkr/src/venue.rs`: the venue's `FACTS`, its `LINK` facts, the link's listing (`accounts`, `listing`, `rows`, `env_holds`) and `Arm`, the `VenueArm`. Read `Arm::bind`.
- `plugins/ibkr/src/exec.rs`: `IbkrBroker`, the `ExecutionOps`. Read `IbkrBroker::place` first. This file also holds:
  - `orders_of`, which maps an intent to IB orders;
  - `feed`, which folds the order stream;
  - `watch` and `connectivity`, for the Gateway's 1100, 1101 and 1102 notices;
  - `resync`, which reads the venue's lists;
  - `ibkr_capabilities` and `ibkr_protection`.
- `plugins/ibkr/src/reads.rs`: `IbkrReads`, the `VenueReads`: money off `reqAccountSummary`, the clock, routes and a contract's multiplier.
- `plugins/ibkr/src/source.rs`: `Ibkr`, the data `Source`, with its `FACTS`, the `READS` table and the bars row `CAP`. Read `Ibkr::call` first, the gate every data read passes. This file also holds `seat`, `probe`, `history`, `read`, `raw_read`, `open_ticks` and the hub's dial with its 30 s latch (`dial`, `latched`, `fell`).
- `plugins/ibkr/src/data.rs`: `IbkrData` and 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_FORMAT` and the rest). Read `IbkrData`'s `*_raw` methods.
- `plugins/ibkr/src/history.rs`: `IbkrBars`, the `HistoricalData` over `reqHistoricalData`, and `Pacer`, the history pacing windows. It also holds `BARS_FORMAT` and `parse_bars`. Read `Pacer::pace` and `kept`.
- `plugins/ibkr/src/live.rs`: `IbkrLive`, the `LiveStream`. It folds 5 s real-time bars into minutes, one stream per symbol. Read `IbkrLive::open`.
- `plugins/ibkr/src/contract.rs`: a Taji symbol as an IB `Contract`. Read `contract_of` and `Resolver`; `spell` and `taji_symbol` go the other way.
- `plugins/ibkr/src/probe.rs`: what your market data grants per class, off one snapshot each. Read `verdict`.
- `plugins/ibkr/src/offer.rs`: `OFFER` and `VENUE_OFFER`, the cells the coverage page shows.
- `plugins/ibkr/src/fake.rs`: `FakeTws`, a scripted `Tws` that 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:

- `place` 1, whose comment reads "A point waits up to 5 s on its snapshot";
- `stream` 4, 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`, a `Facts`, has seat `Venue`, so the source is seated by a venue link and not by a key of its own. Its fields:
  - `grants_first: true` and `gated: 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 daily `ADJUSTED_LAST`; `rate_per_min: 6`.
  - `book`: 10 levels a side for equity, future and crypto.
- `venue::FACTS`, a `VenueFacts`, has two records, `ibkr` (paper) and `ibkr-live`, because a paper and a live login are two Gateways. `LINK` is `LinkMethod::Gateway` with `key` and `secret` revealed, since neither is a secret.
- `offer::OFFER` and `offer::VENUE_OFFER` declare the cells of the [coverage page](https://docs.taji.is/reference/coverage/ibkr.md).

**Link forms.** `ibkr-paper` and `ibkr-live` are both `kind = "start"` with no fields; their steps and refusal words are in [the manifest](https://github.com/TajiAI/Taji/blob/main/plugins/ibkr/taji-plugin.toml). `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:

1. A port with nothing on it (1 s TCP check, `listening`) is `not_running`.
2. A connection that fails the handshake is `unreachable`.
3. Error 326 moves to the next of client ids 1701, 1703 and 1705. All three held is `client_id`.
4. The listing is the validation: a login listing no account is `no_accounts`, and a paper form on a non-`DU` login, or the reverse, is `env`.

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

1. `GET /get/bars?symbols=equity:AAPL&…&provider=ibkr` reaches the hub, which checks its store first. For the uncovered part it calls `Source::history`.
2. `Ibkr::history` checks the 30 s latch, dials the hub's session (client id + 1) and returns `IbkrBars` over that session and its `Pacer`.
3. `IbkrBars` resolves AAPL to its conid once (`Resolver`, held for the process). It then pages backward through the span, one `reqHistoricalData` per step-table window. Before each page is sent, `Pacer::pace_ask` charges the 15 s, 2 s and 10-minute windows, and `Metered` charges one message against 50 a second.
4. Each answer is kept as a `BARS_FORMAT` page with a `request` entry that names no account (`kept`). `parse_bars` turns the pages into rows, and the hub stores and serves them.

**One order, end to end.**

1. `POST /verb/trading/orders/equity/place` passes the kernel's gates and enters the funnel described in the `//!` header of `engine/crates/taji-trading/src/root.rs`: risk gate, journal `IntentReceived`, then `ops.place_order`.
2. `IbkrBroker::place` builds the IB orders with `orders_of`. Under the session's `placing` lock, it takes an id from `reqIds` for each member, links children to the entry's id as their parent, sets `account` and `order_ref` (the intent id), and sends the batch with `Tws::place_orders`.
3. 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, `refused` re-reads the lists and the place answers `OrderRejected` in IB's words.
4. Otherwise it answers the book's `OrderSnapshot`, whose `order_id` is the intent id. The root asserts the `expected_ref` echo and journals `OrderAcked`. 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](https://docs.taji.is/catalog/ibkr.md#behaviour-and-limits), "Design choice"). This also means no IB key ever exists for Taji to hold: [ADR 0005](https://github.com/TajiAI/Taji/blob/main/docs/decisions/0005-no-key-reaches-a-client.md) holds trivially.
- **A `Tws` seam inside the crate.** `ibapi` keeps its message bus and decoders private, so the seam sits above the client (`//!` of `plugins/ibkr/src/tws.rs`). The same seam is what lets `FakeTws` drive 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_updates` therefore fans that stream out and reopens it after a reconnect (the doc comment on `Session`).
- **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.** `key` is `host:port` and `secret` is the client id, because the vault is the one record store (`Gateway` in `plugins/ibkr/src/lib.rs`).
- **Paper and live told apart by `DU`.** IB's paper logins list `DU` accounts and nothing else does. A paper row binds only a `DU` number 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`, ties `stream`).
- **`order_ref` is 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, and `order_ref` is echoed on every list and execution (`//!` of `plugins/ibkr/src/exec.rs`).
- **A group goes in one batch under one lock.** `reqIds` answers 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 answers `AckedUnconfirmed`.
- **`NotSent` only when nothing left.** A send that `ibapi` refused, or that failed on a down socket, is `NotSent`. Any other failure may have reached IB, so it is `AckedUnconfirmed` (`sent_err`), which reconcile resolves.
- **Pacing refuses, never waits.** `Pacer` and `Metered` refuse 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 `REDIAL` has passed, so reads do not each wait out the 5 s connect timeout (`Ibkr` in `plugins/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 (`Standing` in `plugins/ibkr/src/tws.rs`).
- **Bars on IB's stated basis.** TRADES bars adjust splits and not dividends, and daily `ADJUSTED_LAST` adds dividends. Each answer carries the basis IB states ([ADR 0007](https://github.com/TajiAI/Taji/blob/main/docs/decisions/0007-vendor-basis-as-given.md)).
- **An option's day is folded from its hours.** IB serves no option daily bars (162 "EODChart"), so `folds` in `plugins/ibkr/src/history.rs` builds the day from regular-hours bars.
- **Data reaches clients only as hub products.** No TWS shape crosses the wire ([ADR 0004](https://github.com/TajiAI/Taji/blob/main/docs/decisions/0004-capabilities-through-the-hub.md)). `raw.rs` keeps 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](https://docs.taji.is/catalog/ibkr.md#transport-and-limits), [Data](https://docs.taji.is/catalog/ibkr.md#data), [Orders](https://docs.taji.is/catalog/ibkr.md#orders) and [Symbology and gotchas](https://docs.taji.is/catalog/ibkr.md#symbology-and-gotchas). The mechanisms that enforce them:

- **Message budget** (`Metered`, `plugins/ibkr/src/tws.rs`). Every request is admitted against `ibkr-msgs`, 50 a second per connection. A refused request is never sent and answers `IbkrError::Budget`, which becomes `BrokerageError::RateLimited` with 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.
- **What a pacing refusal answers.** Inside IB the signal is error 100 or 162; there is no HTTP 429. Bars go through `BrokerageError::RateLimited` and every other data read through `Ibkr::call`'s `refusal`, which maps a pacing or budget refusal to `TradingError::RateLimited`. Either way the wire answers 429 `rate_limited` with `rest_after`. Nothing retries automatically.
- **Rate scopes.** `rate_limits` lists each held session's scopes by `host:port/client_id`: `messages`, `history_10m`, `history_burst`, `history_identical` and `stream`, 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.
  
  `Resolver` resolves each symbol to one USD conid and holds it for the process. A symbol listed on several USD exchanges is `Ambiguous`. A continuous future streams nothing live (`NO_CONTINUOUS`).
- **Refusals before the wire.** `offer.rs` and `ibkr_capabilities` declare what each class takes. A word IB has no field for is refused unsent (`unsent`), for example `add_liquidity`, `book_only`, fractional shares and `cashQty` outside 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`):

```json
{"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`):

```rust
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`):

```rust
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:

```rust
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`):

```rust
("<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):

```json
{
  "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`):

```rust
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`):

```rust
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](https://docs.taji.is/contribute/testing.md).

- **Offline, no Gateway:** `cargo test -p taji-ibkr`. Every module's tests drive `FakeTws`, which behaves like the Gateway where the Gateway's behaviour hides a bug: `reqIds` repeats an id until an order uses it, a completed order lists `order_id` -1, and the open list holds every client's orders. The hub's own tests read `source::FACTS` (`engine/crates/taji-trading/src/hub/plugin.rs`) and the `Auth` (`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:

  ```sh
  IBKR_PORT=4002 cargo test -p taji-ibkr --test live -- --ignored --test-threads=1 [filter]
  ```

  Without `IBKR_PORT` every test is a SKIP. A port that is not a paper port, or a login holding a non-`DU` account, panics before any call. `IBKR_HOST` defaults to `127.0.0.1` and `IBKR_CLIENT_ID` to 91; each test adds its own offset. The order tests rest and cancel paper orders. Fills run only under `LIVE_FILLS=1` during regular hours. `exercise_lapse_answers_a_frame` lapses only the contract `IBKR_LAPSE` names. 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.sh` runs this suite's read tests by name and never its order tests. Without `IBKR_PORT`, IBKR is a SKIP.
- **The walk, through a real kernel:** start a headless kernel as `AGENTS.md` describes, then run `python3 plugins/ibkr/scripts/ibkr_walk.py <wire port> <phase>` with `TAJI_STATE_DIR` set to that kernel's state dir and `IBKR_PORT` set to the paper Gateway's port. Run `link` first. 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 live `ibkr` row is linked.
- **Coverage cells:** the [coverage page](https://docs.taji.is/reference/coverage/ibkr.md) is generated from `offer.rs` and `source::FILLS` by the wire fixture command in `AGENTS.md`. Change them, then regenerate; never edit the page. `each_class_fills_what_facts_declares` in `plugins/ibkr/src/source.rs` fails when a decoder fills a column `FILLS` does not name, or the reverse.

## References

All fetched 2026-12-02.

- TWS API: [Introduction](https://interactivebrokers.com/docs/tws-api/doc/introduction.md), [Requirements](https://interactivebrokers.com/docs/tws-api/doc/notes-limitations/requirements.md), [TWS API Limitations](https://interactivebrokers.com/docs/tws-api/doc/notes-limitations/tws-api-limitations.md), [Architecture](https://interactivebrokers.com/docs/tws-api/doc/architecture.md), [Connectivity Behavior](https://interactivebrokers.com/docs/tws-api/doc/connectivity/connectivity-behavior.md), [Broken API socket connection](https://interactivebrokers.com/docs/tws-api/doc/connectivity/broken-api-socket-connection.md), [Logging into multiple applications](https://interactivebrokers.com/docs/tws-api/doc/connectivity/logging-into-multiple-applications.md), [Daily & Weekly Reauthentication](https://interactivebrokers.com/docs/tws-api/doc/tws-settings/daily-weekly-reauthentication.md).
- Limits: [Pacing Limitations](https://interactivebrokers.com/docs/tws-api/doc/pacing-limitations.md), [Market Data Limitations](https://interactivebrokers.com/docs/tws-api/doc/md/market-data-limitations.md), [historical limitations (legacy)](https://interactivebrokers.github.io/tws-api/historical_limitations.html).
- Market data: [Delayed data](https://interactivebrokers.com/docs/tws-api/doc/md/delayed-data.md), [Historical bars](https://interactivebrokers.com/docs/tws-api/doc/md/historical-bars.md), [Historical ticks](https://interactivebrokers.com/docs/tws-api/doc/md/historical-ticks.md), [Histogram data](https://interactivebrokers.com/docs/tws-api/doc/md/histogram-data.md), [5 second bars](https://interactivebrokers.com/docs/tws-api/doc/md/5-second-bars.md), [Tick-by-tick](https://interactivebrokers.com/docs/tws-api/doc/md/live-ticks.md), [Market depth](https://interactivebrokers.com/docs/tws-api/doc/md/market-depth.md).
- Contracts and reference: [Contract details](https://interactivebrokers.com/docs/tws-api/doc/contracts/details.md), [Option chains](https://interactivebrokers.com/docs/tws-api/doc/contracts/option-chains.md), [Stock symbol search](https://interactivebrokers.com/docs/tws-api/doc/contracts/stock-symbol-search.md), [News](https://interactivebrokers.com/docs/tws-api/doc/news/introduction.md), [Wall Street Horizon](https://interactivebrokers.com/docs/tws-api/doc/wall-street-horizon/introduction.md), [Scanner subscription](https://interactivebrokers.com/docs/tws-api/doc/market-scanner/subscription.md), [Cryptocurrency (legacy)](https://interactivebrokers.github.io/tws-api/cryptocurrency.html).
- Accounts and orders: [Managed accounts](https://interactivebrokers.com/docs/tws-api/doc/accounts/managed-accounts.md), [Account summary](https://interactivebrokers.com/docs/tws-api/doc/accounts/summary.md), [Positions](https://interactivebrokers.com/docs/tws-api/doc/accounts/positions.md), [PnL](https://interactivebrokers.com/docs/tws-api/doc/accounts/pnl.md), [Next valid id](https://interactivebrokers.com/docs/tws-api/doc/next-valid-id.md), [OrderId](https://interactivebrokers.com/docs/tws-api/doc/quick-start/order-id.md), [Placing orders](https://interactivebrokers.com/docs/tws-api/doc/quick-start/placing-orders.md), [Modifying orders](https://interactivebrokers.com/docs/tws-api/doc/orders/modify-order.md), [ClientId 0 and the Master Client ID](https://interactivebrokers.com/docs/tws-api/doc/order-management/master-client-id.md), [Open orders](https://interactivebrokers.com/docs/tws-api/doc/order-management/open-orders.md), [Completed orders](https://interactivebrokers.com/docs/tws-api/doc/order-management/completed-orders.md), [Execution details](https://interactivebrokers.com/docs/tws-api/doc/order-management/execution-details.md), [Exercise options](https://interactivebrokers.com/docs/tws-api/doc/orders/exercise-options.md).
- Errors: [Error codes](https://interactivebrokers.com/docs/tws-api/doc/error/codes.md), [Messages](https://interactivebrokers.com/docs/tws-api/doc/error/messages.md).
- Platform: [IB Gateway Stable](https://www.interactivebrokers.com/en/trading/ibgateway-stable.php), [About paper trading accounts](https://www.ibkrguides.com/clientportal/aboutpapertradingaccounts.htm).
- The client: [`ibapi` on crates.io](https://crates.io/crates/ibapi) (5.8.0, MIT, pinned).
