Resolution

All pages

IBKR, super smooth: research, audit, and build plan

Scope: making the Interactive Brokers path reliable enough that the owner's day is one login on the phone and a signature per order. The research covers what IBKR documents, what the community has established, and what is still unknown. It was done on 2026-09-25/26 against commit a832123, with about 12 web fetches and about 45 downloads of IBKR's markdown doc pages (every page under ibkrcampus.com/docs/web-api/... has a clean .md twin, indexed at https://www.interactivebrokers.com/docs/web-api/llms.txt).

Fixed constraints, which this plan never relaxes:

  • The fund never stores the broker password.
  • The owner signs every order and the go-live.
  • The only broker secret the fund may hold is a read-only reporting token.

Tags used throughout:

  • [doc] comes from IBKR's own documentation.
  • [community] comes from maintained open-source projects or user reports.
  • [unverified] is established knowledge not re-checked in this pass. Confirm it on the paper account before relying on it.

0. The OAuth question, settled

Answer: no. Keep the Client Portal Gateway with the owner's own browser login, once a day.

  • OAuth 2.0 is closed to us. IBKR's registration page says it outright: "OAuth 2.0 is not available to Individual account structures." It is for licensed organisations, financial advisers and introducing brokers. [doc] ibkrcampus.com/docs/web-api/oauth-2-0/register.md
  • OAuth 1.0a "first party" is officially for institutions.
    • IBKR "classifies first party entities as institutions". Applicants email apiintegration@interactivebrokers.com, and approved groups get a Self Service Portal link. [doc]
    • A new consumer key only works after the midnight reset. Before then it answers 401 Invalid Consumer. [doc]
    • The Extended page still says "If you are an IB customer who registered using the Self-Service OAuth page…". That page is oauth-1-0a-extended.md.
  • Individuals have in practice registered anyway. They used the self-service page (ndcdyn.interactivebrokers.com/sso/Login?action=OAUTH&RL=1) on live and paper accounts.
    • IBKR API support was quoted as "not aware of any technical limitations".
    • Activation took from 24 hours to two weeks, sometimes only after the weekend restart.
    • Source: ibind's docs/oauth/oauth_1a.md. [community]
    • So it can work, but it is undocumented for individuals and can be withdrawn at any time.
  • Why no, even where it works:
    • Registration produces a 9-character consumer key, a signing RSA key, an encryption RSA key, Diffie-Hellman parameters, and an access token plus secret.
    • Together these mint live-session tokens (about 24 hours each) with no 2FA and no human in the loop.
    • That bundle is a standing trading credential. It is strictly more dangerous than the password the fund already refuses to store, because it bypasses IB Key.
    • It breaks the premise that a human unlocks the broker each day.
  • Where it could be reconsidered. A future multi-owner, hosted edition would have a firm (not an individual) apply for first-party OAuth, and hold the keys in an HSM or KMS the owner controls. That is a different product and out of scope here.

The stored-credential login tools (IBeam-style Selenium injection, IBC for TWS) are also no by default.

  • IBeam's README describes itself as "Not so secure… you'll need to store the credentials somewhere". Its mitigations are Docker secrets (still plaintext inside the running container) and GCP Secret Manager. [community] github.com/Voyz/ibeam
  • An honest version of "credentials only in a store the owner controls" would look like this: a password manager on the owner's phone fills the IBKR login page that the fund shows over Tailscale.
    • That is not automation. It is the owner logging in with autofill, and it is exactly what this plan builds.
    • Anything that lets the box log in without the owner acting needs the box to read the password at 08:00. At that point the fund stores the password, whatever the store is called.
  • Also, 2FA through IB Key still needs a tap on the phone for a live account. Full automation either disables 2FA (never) or still wakes the owner.

1. Client Portal Gateway session lifecycle

What the session is

  • The gateway is a Java proxy (clientportal.gw.zip, run with bin/run.sh root/conf.yaml) that listens on https://localhost:5000 with a self-signed certificate. [doc]
  • IBKR "does not support an automated authentication process". The owner must "reauthenticate… daily". [doc] (CP Gateway FAQ)
  • The login must happen in a browser, and API calls come through the same gateway. /gw/api, /oauth and /oauth2 paths are not served by it. [doc]
  • A User-Agent header is required. The code sends one, resolution (src/broker/ibkr.ts:96). [doc]

How long it lasts

  • A session lasts at most 24 hours. It resets at midnight in the region's reference city (New York, Zug or Hong Kong). European accounts are served from Zug. [doc]
  • IServer maintenance in Europe falls around 01:00 CE(S)T. The Web API has a weekly maintenance window on Saturday evening. [doc]
  • The session drops after about 6 minutes without requests. A brokerage session that goes unused for 5 minutes ends. [doc]
  • The documented keepalive is POST /tickle about once a minute. /tickle itself is limited to 1 request per second. [doc]

Status flags (GET /iserver/auth/status): authenticated, connected, competing, established, fail, message. [doc]

Re-auth sequence

  • When connected:true, authenticated:false, call POST /iserver/auth/ssodh/init?publish=true&compete=true.
  • Wait about 2 seconds, then GET /iserver/accounts and require a non-empty list.
  • Then re-apply any question suppression, because it is per session.
  • This revives the brokerage session only while the SSO session is still valid. After the daily reset nothing but a browser login works. [doc]
  • /iserver/reauthenticate is deprecated. [doc]

Competing sessions

  • IBKR allows one brokerage session per username across all platforms: TWS, IBKR Mobile, the Client Portal website, and the gateway. [doc]
  • If the owner opens IBKR Mobile to look at the account with the same username, the fund's session is kicked and competing:true appears.
  • The documented fix is a second username on the same account. Market data is billed per username, so the subscription is paid twice. For EU non-professional bundles that is a few EUR a month. [doc] [unverified: exact fees]

Paper

  • The paper account has its own username. There is no paper/live switch in the gateway. [doc]
  • Paper needs a live account that is fully opened and funded, on IBKR Pro. [doc]
  • Paper account ids start with DU, live ones with U. /portfolio/accounts returns isPaper per account. [doc]
  • So the fund can tell paper from live. The claim in docs/operating.md:286 that it cannot is wrong.

2. Order flow

Placing

  • POST /iserver/account/{acct}/orders with body {"orders":[{...}]}. [doc]
    • Fields: conid, orderType, side, tif, quantity, price, cOID, listingExchange, outsideRTH, cashQty.
    • For currency conversion: isCcyConv and fxQty.
  • A rejection comes back as HTTP 200 with {"error": ...}. [doc]
    • Examples: "Invalid order price fields", and "no sec defs returned" for a bad conid.
    • A malformed body gives 400.

The reply chain

  • Warnings arrive as [{"id","message":[...],"isSuppressed":false,"messageIds":["o163"],"messageOptions":...}]. [doc]
  • The fund answers each with POST /iserver/reply/{id} {"confirmed":true}. Replies can chain. [doc]
  • An unanswered reply invalidates the order when the next order is placed. Confirming it later times out with 503. [doc]
  • IBKR: "Developers should not attempt to place another order until the previous order has been fully acknowledged." [doc]

Suppression

  • POST /iserver/questions/suppress {"messageIds":[...]} lasts for the brokerage session. /iserver/questions/suppress/reset undoes it. Suppression also changes what the what-if returns. [doc]
  • Suppressible ids that matter here:
idWhat it warns about
o163price is a percentage away from market
o354no market data
o382tick size
o383size limit
o403will fill immediately
o451total value limit
o10151market order risk
o10153mandatory cap price
o10164, o10223cash quantity
o10336limited liquidity
p12price-management algorithm

What-if

  • POST /iserver/account/{acct}/orders/whatif takes the same body. [doc]
  • It returns amount{amount,commission,total}, equity{current,change,after}, initial{current,change,after}, maintenance{...}, position{...}, warn and error.
  • It needs a market-data snapshot for the contract first. A warning like 21/You are trying to submit an order without having market data arrives in warn, not in error.

Modify and cancel

  • Modify is POST /iserver/account/{acct}/order/{orderId} with the full original order as a single object. [doc]
  • Cancel is DELETE on the same path. It answers {"msg":"Request was submitted"}, which "does not [mean] the order ticket itself has been canceled". [doc]
  • PendingCancel and PreCancelled can still fill. [doc]

Monitoring

  • GET /iserver/account/orders lists the current brokerage session's orders, at most 1000. It needs a pre-flight call. [doc]
    • The fund's client order id comes back as order_ref.
    • force=true clears the cache, and "Submission will appear as a blank array". You must call again to get data.
    • Filtering the list stops the websocket sor topic until the next force=true.
  • GET /iserver/account/trades?days=N returns today plus up to six earlier days. It includes execution_id, order_ref, commission (no currency field), net_amount and trade_time_r. [doc]
    • IBKR: "It is advised to call this endpoint once per session." It is paced at 1 request per 5 seconds.
  • Order status values are Inactive, PendingSubmit, PreSubmitted, Submitted, Filled, PendingCancel, PreCancelled, Cancelled and WarnState. [doc]
    • Inactive also means "created, not yet transmitted". It is not only a reject.
  • Websocket topics (wss://localhost:5000/v1/api/ws): sor for orders, str for trades, spl for P&L, ssd for account summary, sld for ledger. [doc]

3. Market data

  • GET /iserver/marketdata/snapshot?conids=...&fields=... takes up to 100 conids and 50 fields, within the default 100 market-data lines. [doc]
  • The first call is a pre-flight and returns only conids. Call again for values. [doc]
  • Field 31 (last) can carry a prefix: C means the value is the prior close, H means halted. [doc]
  • Field 6509 is availability. [doc] market-data-availability.md
    • The first character is the timeline:
      • R real-time
      • D delayed 15 to 20 minutes
      • Z frozen
      • Y frozen delayed
      • N not subscribed
      • O means the annual Market Data API Acknowledgement has not been signed
    • The second character is P (snapshot) or p (consolidated). The third is always B.
  • Useful fields: 31 last, 84 bid, 86 ask, 7295 open, 7741 prior close, 6509 availability, and 55 symbol. [doc]
  • Streaming: smd+CONID+{"fields":[...]} subscribes and umd+CONID+{} unsubscribes. [doc]
  • EU exchanges need paid subscriptions per username. Without one, the snapshot comes back delayed (D) or N. [doc] [unverified: exact bundle names for Euronext, Xetra, LSE and SIX]

4. Portfolio and ledger

  • Call GET /portfolio/accounts before any other /portfolio call. It is paced at 1 request per 5 seconds. [doc]
  • GET /portfolio/{acct}/positions/{page} returns up to 100 positions per page. The data is cached, and POST /portfolio/{acct}/positions/invalidate clears the cache. /portfolio2/{acct}/positions is the newer, less-cached endpoint. [doc]
  • GET /portfolio/{acct}/ledger is cash by currency: cashbalance, settledcash, exchangerate, interest, netliquidationvalue, and a BASE row. [doc]
    • This is the only way to see that a USD buy left a negative USD balance.
  • GET /portfolio/{acct}/summary returns availablefunds, excessliquidity and so on, in base currency only. [doc]

5. Flex Web Service (read-only reconciliation)

Token

  • Set up in Client Portal under Reporting, then Flex Queries, then Flex Web Service Configuration. [doc]
  • A token lasts between 6 hours and 1 year and can be IP-restricted. [doc]
  • It is reporting-only and cannot trade, so it is the one broker secret the fund may hold.
  • Recommended settings: a one-year token restricted to the box's public IP, with its expiry date shown in the app.

Calls

  1. GET https://ndcdyn.interactivebrokers.com/AccountManagement/FlexWebService/SendRequest?t={token}&q={queryId}&v=3 returns <Status>Success</Status><ReferenceCode>. [doc]
    • Optional parameters: p (period), or fd and td (date range, sent together).
  2. GET .../GetStatement?t={token}&q={ReferenceCode}&v=3 returns the XML statement. [doc]
    • Poll while it answers 1019 (generation in progress).
  3. Pacing is 1 request per second and 10 per minute per token. Error 1018 means too many requests. [doc]

Error codes to map

CodeMeaning
1001, 1004, 1009, 1021try again shortly
1005settlement data not ready
1003statement not available
1012token expired
1013IP restriction
1014query invalid
1015token invalid
1018pacing
1019generation in progress

Source: [doc] flex-web-service/error-codes.md.

The Activity Flex Query to create

  • Sections: Trades (executions), CashTransactions (dividends, withholding tax, fees, interest, deposits), CorporateActions, OpenPositions, CashReport (per currency), ConversionRates, and Transfers. [unverified: exact section names in the query builder]
  • Include the audit-trail fields so trades carry order references. [doc] including-audit-trail-fields.md
  • Statements are final after settlement. Run the daily pull after about 07:00 CET for the previous day. Before that, 1005 is expected.

6. EU specifics

  • Entity [unverified]
    • Dutch and other EEA residents are clients of Interactive Brokers Ireland Ltd, regulated by the Central Bank of Ireland (the migration from IB UK ran in 2021).
    • UK residents stay with Interactive Brokers (U.K.) Ltd.
    • The entity decides investor-compensation cover and PRIIPs treatment. Show it in the wizard, read from the account, so the owner knows.
  • PRIIPs/KID [unverified in this pass; well established]
    • EU retail clients cannot buy funds and ETFs without an EU KID. That blocks US-domiciled ETFs such as VOO and VTI. Single stocks are unaffected.
    • The failure arrives as an order reject or reply message, not at contract lookup. So the what-if must run before the owner signs, otherwise the owner signs something IBKR will refuse.
    • The repo's SOFT rule L-EU-KID (docs/eu.md) already warns. The what-if gives the broker's own answer.
  • UCITS alternatives are shown for information, not as a recommendation. Examples: IWDA / SWDA (iShares Core MSCI World, IE00B4L5Y983; IWDA trades in EUR on AEB and in USD on LSE, SWDA in GBP on LSE, and EUNL in EUR on Xetra) and VWCE (Vanguard FTSE All-World Acc, IE00BK5BQT80, Xetra in EUR). [unverified: listing currencies]
    • The universe benchmark is IWDA.AS, so its currency must be read from IBKR, not assumed.
  • FX [unverified: current tariff]
    • Buying a USD, GBP, DKK or CHF stock from EUR cash does not convert automatically. IBKR leaves a negative balance in that currency, which is a margin loan charged interest.
    • In a cash account IBKR may refuse the order instead.
    • An explicit conversion is a separate FX order: the conid for the pair (for example EUR.USD) on IDEALPRO, with isCcyConv:true, fxQty, and cash quantity. [doc: fields]
    • The IBKR Pro FX commission is about 0.2 basis points of value, with a USD 2 minimum. Conversions below IDEALPRO's minimum size are odd lots, filled at a slightly worse price.
  • Base currency EUR. summary and ledger BASE are in EUR. Commissions arrive in the trade's currency (the trades endpoint gives no currency field; Flex does).
  • Units [unverified]
    • LSE prices on some data sources are in pence (GBp). The repo's market data is Yahoo .L, which quotes GBp.
    • If IBKR quotes the same line in GBP, the collar sees a 100x gap and rejects. That fails safe, but it blocks every UK trade. Normalise at mapping time.
  • Dividend withholding. US dividends carry 15% withholding with a W-8BEN on file; Dutch treaty relief applies. Flex CashTransactions carries it as Withholding Tax, and it should be reconciled as its own line.

7. Rate limits and error codes

Pacing

  • The global limit is 10 requests per second per session. Excess gets 429, violators may go to a 10-minute penalty box, and repeat offenders are blocked. [doc]
  • Per-endpoint limits [doc]:
EndpointLimit
/iserver/marketdata/snapshot10 per second
/iserver/account/orders1 per 5 seconds
/iserver/account/trades1 per 5 seconds
/iserver/account/pnl/partitioned1 per 5 seconds
/portfolio/accounts1 per 5 seconds
/tickle1 per second
/sso/validate1 per minute
/pa/*1 per 15 minutes

Failure modes the fund must name to the owner

SignalMeaningWhat the owner should see
TLS error on connectself-signed certificate, not pinned"The broker connection's certificate changed. Nothing was sent."
connection refusedgateway process down"The broker gateway is not running."
401no brokerage session (idle, reset, or a restart)"IBKR needs you to log in. [Log in]"
authenticated:false, connected:trueSSO alive, brokerage session gonehandled by ssodh/init; the owner is told only if it fails
competing:truesame username logged in elsewhere"IBKR Mobile or the website took the session. Log in again here, or use the fund's own username."
"no bridge" / 503 on /iserverbackend bridge not up after login, or maintenance"IBKR is still starting the session" (retry for about 30 seconds), then "IBKR is in maintenance"
429pacingnever shown. Back off; after two in a row, stop polling for 60 seconds.
200 {error} on orderbusiness rejectIBKR's text, quoted, plus which rule it resembles
reply o354no market datablock; ask the owner to fix market data, never auto-confirm
1012/1015 (Flex)token expired or invalid"The reporting token expired on …; create a new one."

ISIN to conid

  • GET /iserver/secdef/search?symbol=... searches by symbol, or by company name with name=true. [doc]
  • Passing an ISIN as symbol is widely reported to work for stocks. [community, unverified]
  • GET /trsrv/stocks?symbols=ASML lists every contract for a symbol with conid, exchange and isUS, "typically differentiated based on currency of the primary exchange". [doc]
  • Then GET /iserver/contract/{conid}/info gives currency, exchange and validExchanges. [doc]
  • Choosing the listing: prefer the contract whose primary exchange matches the universe listing's MIC (XAMS→AEB, XETR→IBIS, XPAR→SBF, XLON→LSE, XSWX→EBS, XCSE→CSE, XMIL→BVME, XMAD→BM, XBRU→ENEXT.BE) and whose currency matches.
    • Never take the first search hit. Never route US-listed ADRs for an EU name.
  • Pin listingExchange on the order only when the owner wants to avoid SMART routing. SMART with the correct conid is normally the better price.

8. Gateway in Docker, login over Tailscale

Images

  • IBKR publishes no official Docker image for the CP Gateway. [doc, by absence]
  • voyz/ibeam is maintained and wraps the CP Gateway, but its purpose is injecting stored credentials. Rejected under the constraints. [community]
  • gnzsnz/ib-gateway and similar images are TWS/IB Gateway plus IBC: the socket API, not the Web API. Not applicable. [community]
  • Recommendation: build our own small image.
    • eclipse-temurin:17-jre plus clientportal.gw.zip from download2.interactivebrokers.com/portal/clientportal.gw.zip, pinned by sha256 and checked at build time.
    • Our own root/conf.yaml, running as a non-root user, and no credentials anywhere.

conf.yaml

  • The stock file's ips.allow covers 127.0.0.1 and a few ranges. A request from the app container comes from the compose bridge (172.x) and is refused with a bare 403 or a closed socket unless allowed. [community]
  • Pin a compose subnet (for example 172.30.47.0/24) and allow exactly that range plus 127.0.0.1.

TLS

  • Keep the self-signed certificate, but pin it. On first contact the wizard shows the SHA-256 fingerprint and the owner accepts it. Later connections verify against the pinned fingerprint.
  • Today the code turns verification off for any loopback-like host (src/broker/ibkr.ts:90,95).

Login from the phone

  • The owner opens a fund URL on the tailnet. The app reverse-proxies only the login paths of the gateway (/sso/*, the login page's static assets, and / redirects) and refuses /v1/api/* from outside.
    • The trading API is then never exposed on the tailnet, even to the owner's own devices.
    • The gateway sees the proxy as its client, which satisfies the same-machine login rule.
    • [unverified: the exact set of paths the login page loads. Record them once on paper and allowlist them; the fake gateway fixture pins them.]
  • Fallback if the path proxy proves brittle: tailscale serve --https=5443 https+insecure://127.0.0.1:5000, with a Tailscale ACL limited to the owner's phone and on only while a login is pending. This exposes the whole API to that one device.
  • Never use funnel.

Health

  • Process health is the compose healthcheck: any HTTP answer from https://localhost:5000/.
  • Session health (auth/status) belongs to the session supervisor, not to Docker. An unauthenticated gateway is healthy and waiting for the owner.

9. Audit of the current code (commit a832123)

File references are to src/ unless noted. Severity: A can send a wrong or duplicate order, or report a false state about money; B makes live trading fragile or halts it spuriously; C is polish.

A: correctness around real money

  1. Timeouts become "Nothing was sent" (broker/ibkr.ts:109-110, gateway/gateway.ts:96-97).
    • What happens:
      • Every socket error, including the 15-second timeout that fires after the order POST or the reply confirm was written, becomes VenueUnavailable.
      • The gateway then tells the owner "Nothing was sent; the approval stays open".
      • Nothing is saved to venue_orders before acceptance (ibkr.ts:355-358).
    • Why it matters: the order may be live at IBKR while the fund believes it was never sent.
    • What is needed: a distinct ambiguous state, and a pre-send save.
  2. The duplicate check reads an array that is always blank (broker/ibkr.ts:296).
    • What happens:
      • lookup() calls /iserver/account/orders?force=true once and trusts the result.
      • IBKR documents that force=true makes that response a blank array.
      • The endpoint also covers the current session only.
    • Why it matters: after a restart, recover() (gateway/gateway.ts:122-148) resends, finds nothing, and submits again. The duplicate cOID is either rejected, so a live order becomes "rejected" in the fund (an orphan), or placed twice.
    • The fake gateway returns data on the first call (test/helpers/fake-ibkr.ts:96-97), which hides this.
  3. Every broker warning is confirmed blindly (broker/ibkr.ts:344-353).
    • What happens: up to five replies are confirmed with no allowlist. That includes o354 (submitting without market data), o10153 (cap price), o10336 (limited liquidity) and any PRIIPs-style or margin warning.
    • Why it matters: the owner signed an order, not IBKR's later warnings. The notices are kept, but only after the fact.
  4. The "no margin" check ignores currency (broker/ibkr.ts:327-332, gateway/gateway.ts:161-176).
    • What happens:
      • available() is base-currency availablefunds from /summary (ibkr.ts:232-239).
      • A USD, GBP, DKK or CHF buy passes when there is enough EUR.
      • There is no FX leg anywhere, so IBKR leaves a negative foreign-currency balance.
    • Why it matters: that negative balance is a loan. reconcile() checks positions only, never cash per currency, so the loan is invisible to the fund.
  5. The collar can price off stale data (broker/ibkr.ts:66-70, 198-208).
    • What happens:
      • num() strips the C (prior close) and H (halted) prefixes from field 31.
      • Field 6509 is never requested, so delayed, frozen, not-subscribed and acknowledgement-missing data all pass as a reference price.
    • Why it matters: combined with gap 3, an order can go out priced against yesterday's close with o354 auto-confirmed.
  6. The contract is not verified (broker/ibkr.ts:160-183).
    • What happens:
      • Mapping is secdef/search?symbol= matched on a description string equal to the IBKR exchange code.
      • No ISIN, no currency check, no contract/info confirmation.
      • Yahoo's .L pence and IBKR's price units are never reconciled.
    • Why it matters: the collar would catch a 100x unit gap, but only at order time, after the owner has signed the go-live terms that include the mapping.

B: fragility that halts or confuses live trading

  1. No keepalive outside live, and no re-auth (firm/firm.ts:687-692, main.ts:76-78, broker/ibkr.ts:150).
    • What happens:
      • The heartbeat returns early unless s.live, so during paper rehearsal, the wizard, and the go-live itself the session idles out after about 6 minutes.
      • tickle() discards the response.
      • There is no ssodh/init, no competing or established handling (ibkr.ts:118-133), and no notification to the owner when the session drops (notify/notify.ts:10 has no login kind).
    • Why it matters: the session dies silently and nobody is told.
  2. The portfolio primer never re-runs (broker/ibkr.ts:212-217).
    • What happens: portfolioPrimed stays true for the life of the process, but IBKR needs /portfolio/accounts again after each new session.
    • Why it matters: after the daily re-login, /portfolio calls can fail or return stale data until a restart.
  3. Pacing violations are built in.
    • Each submit() makes about five calls to auth/status and /iserver/accounts (account() at ibkr.ts:141-147 is called from lookup, submit, positions and available).
    • refresh() calls /iserver/account/trades?days=7 once per working order every minute (ibkr.ts:368). That endpoint allows 1 call per 5 seconds and IBKR advises once per session.
    • liveTerms() runs mapUniverse() (sequential secdef/search for the whole universe) on every broker panel load (firm/firm.ts:639), and the panel reloads whenever live changes (web/views/broker.js:11-86).
    • There is no 429 handling anywhere.
    • Why it matters: the result is a 10-minute penalty box at the worst moment.
  4. Reconciliation raises false alarms (gateway/gateway.ts:161-176, broker/ibkr.ts:220-229, firm/firm.ts:694-702).
    • What happens:
      • Positions come from the cached /portfolio/{acct}/positions/0 with no invalidate.
      • Two consecutive differences raise a recon halt, which can happen right after a fill, before the cache refreshes.
      • There is no Flex statement reconciliation, so dividends, withholding, fees, interest and corporate actions never meet the Record.
    • Note: the schema already has corpaction.recorded, corpaction.applied and recon.discontinuity (record/schemas.ts:98-100), but no broker source feeds them.
  5. The what-if only runs in setup (setup/routes.ts:113-140).
    • What happens:
      • The ticket the owner signs never shows IBKR's commission, margin impact, or warnings.
      • The dry run calls anything that doesn't match /reject|error/ "ok", so a 21/…without market data warning passes.
  6. Paper and live look the same (docs/operating.md:286, broker/ibkr.ts:118-133).
    • isPaper and the DU prefix are ignored. The go-live terms don't record which kind of login was checked.
  7. Status handling is wrong in places (broker/ibkr.ts:365-397).
    • Inactive is mapped to rejected (:385), but it also means "not yet transmitted".
    • Cancel is treated as done when the DELETE answers (:391-397). PendingCancel and PreCancelled can still fill.
    • Fill fee has no currency (:376); it is booked in the order currency at gateway/gateway.ts:105-119.
    • There is no modify.
  8. TLS verification is off for any "loopback" host, including host.docker.internal (broker/ibkr.ts:90,95).
    • There is no certificate pinning.
    • IBKR_STRICT_TLS=1 can't work with the self-signed certificate, so in practice everyone runs unverified.
  9. There is no gateway in compose (compose.yaml:45-48).
    • The gateway is a manual Java process on the host (docs/operating.md:244-343).
    • ips.allow for the Docker bridge is undocumented, and the troubleshooting row (docs/operating.md:574) doesn't mention it.
  10. Errors reach the owner raw (broker/ibkr.ts:106, firm/assist.ts:94-95).
    • 401 becomes IbkrError with HTTP 401, which gateway.execute does not catch as venue-down.
    • A 200 {error} is only recognised inside submit.

C: polish

  1. positions/0 reads only the first page (fine up to 100 positions).
  2. lookup() misses orders from earlier days. Use trades?days=7 or Flex for recovery.
  3. The Venue interface (broker/venue.ts) has no whatIf, session, cash or modify, so the paper venue cannot rehearse any of them.
  4. The fake gateway (test/helpers/fake-ibkr.ts, 119 lines) is hand-written and optimistic:
    • one reply per order
    • no blank pre-flight on snapshots or orders
    • no 429, 401 or competing
    • no 6509 or C prefix
    • no recorded fixtures

10. Build plan: IBKR super smooth

Effort: S is about half a day, M is 1 to 2 days, L is 3 to 5 days, for one developer with the test suite green at each step. The order is by risk removed per day spent. Items 1 to 3 must land before anyone connects a live account.

1. Call layer and error taxonomy (M), which fixes gaps 1, 9 and 16

  • Files:
    • new src/broker/ibkr/http.ts, split out of ibkr.ts:88-114
    • new src/broker/ibkr/errors.ts
    • src/broker/venue.ts
    • src/gateway/gateway.ts:84-102
  • Token-bucket pacing: 8 requests per second globally, plus per-endpoint buckets taken from the table in section 7.
  • 429 handling: back off, and after two in a row pause everything for 60 seconds.
  • One session() cache of about 5 seconds for auth/status and accounts. This replaces account() calling status() on every use.
  • Classify every outcome into: unreachable | tls | unauthenticated | competing | bridge | paced | rejected | ambiguous.
    • ambiguous means the request was written but no response came back. It is raised by the order POST and the reply confirm, and never reported as "Nothing was sent".
    • The gateway records order.ambiguous and asks the owner to wait while the fund checks IBKR.
  • Owner-readable messages live in one table, with the owner's next action. Dutch and English come from the existing i18n.
  • Pre-send save: save the order to venue_orders with state sending before the POST.
  • Two-step lookup: call force=true, wait, call again, and also check trades?days=7. Only treat an order as unknown after both come back empty.
  • Cancel semantics: cancel enters cancelling, and becomes cancelled only on a Cancelled status.

2. Recorded-fixture fake gateway (M), which fixes gap 20 and underpins everything after

  • Files:
    • test/helpers/fake-ibkr.ts, rewritten as a fixture player
    • new test/fixtures/ibkr/*.json
    • new test/ibkr-quirks.test.ts
  • Fixtures are recorded once against the paper account by a throwaway recorder. Account ids and cookies are redacted, and the recorder is not shipped.
  • Scripted quirks:
    • blank pre-flight on snapshots and on orders?force=true
    • chained replies (o163 then o354)
    • 429
    • 401 in the middle of a sequence
    • competing:true
    • a timeout after the order is written
    • C/H prefixes and 6509 = D, N and O
    • PendingCancel then Filled
    • a partially filled order
    • GBp versus GBP
  • Every later item lands with a test against these quirks.

3. Reply-chain handling (S), which fixes gap 3

  • File: src/broker/ibkr.ts:344-353, moved into a new src/broker/ibkr/replies.ts.
  • Allowlist by messageIds:
    • Auto-confirm only warnings already covered by what the owner signed: o163 (price is inside our own collar) and o403 (will fill immediately, for a marketable limit).
    • Refuse o354 (no market data), o10153, o10336, o451, o383, any id not on the list, and any message mentioning KID or PRIIPs. Refusing means answering {"confirmed":false}, recording the text, and returning rejected with IBKR's words.
  • No session-wide suppression. Per-order answers keep every warning on the record.
  • Never place the next order until the chain is resolved. Use a per-account mutex in the call layer.

4. Session supervisor (M), which fixes gaps 7, 8 and 12

  • Files:
    • new src/broker/ibkr/session.ts
    • src/firm/firm.ts:687-702
    • src/main.ts:76-78
    • src/notify/notify.ts:10, adding kinds broker_login and broker_session
    • web/views/broker.js
  • Always on whenever BROKER=ibkr, not only when live. Tickle every 55 seconds, read the status flags each time, and track session age.
  • On authenticated:false: call ssodh/init?publish=true&compete=true, wait 2 seconds, verify /iserver/accounts, re-prime /portfolio/accounts, then clear portfolioPrimed and the session cache.
  • On competing or a failed re-auth: push one notification with the login link, then remind only when an order is waiting.
  • Morning push: on trading days, send the login link at the owner's chosen time (default 08:45 Europe/Amsterdam, before Euronext opens). Never send one between 22:00 and 07:00.
  • Paper or live: read isPaper and the account prefix from /portfolio/accounts. Show it everywhere and record it in the go-live terms. Refuse go-live on a paper login, and refuse rehearsal on a live one.

5. Gateway container and phone login (M), which fixes gaps 14 and 15

  • Files:
    • compose.yaml
    • new deploy/ibkr-gateway/Dockerfile
    • new deploy/ibkr-gateway/conf.yaml
    • new src/server/gateway-login.ts, the login-path proxy
    • src/broker/ibkr.ts:31-42
    • docs/operating.md:244-343, 574
  • An ibkr-gateway service behind a compose profile (--profile ibkr).
    • The image is pinned by sha256, runs as non-root, has no ports published to the host, and has a healthcheck on process health only.
    • It sits on a fixed compose subnet, and conf.yaml ips.allow lists exactly that subnet plus 127.0.0.1.
  • IBKR_GATEWAY_URL defaults to https://ibkr-gateway:5000/v1/api.
  • The certificate fingerprint is pinned on first contact (IBKR_GATEWAY_PIN, set by the wizard after the owner accepts it). This replaces insecureLocal.
  • /broker/login on the app's existing Tailscale URL proxies only the allowlisted SSO paths and refuses /v1/api/*. The notification link points there.

6. Contract resolution with EU exchange preference (M), which fixes gaps 5 and 6

  • Files:
    • src/broker/ibkr.ts:45-55, 160-208, moved into a new src/broker/ibkr/contracts.ts
    • src/market/universe.ts, adding ISIN and MIC per line, or reading them from the existing /api/eu/metadata
  • Resolve by ISIN first, then by symbol through /trsrv/stocks. Then filter candidates by primary exchange (a MIC to IBKR table that replaces EXCHANGE) and currency. Confirm with /iserver/contract/{conid}/info.
  • Keep the result in a cache table with its date. Resolve only in the wizard and on an explicit "re-check contracts". Never on a panel load (fixes firm.ts:639 and broker.js:11-86).
  • Store a price unit per line (GBp or GBP) and normalise before the collar.
  • Request fields 31,84,86,6509,7741.
    • Treat C/H-prefixed values as not-a-live-price.
    • During market hours, refuse the collar on 6509 N, O, Z or Y.
    • On D, allow the collar but put "IBKR's price is 15 minutes delayed" on the ticket for the owner to see before signing.

7. What-if in the ticket (M), which fixes gap 11 and makes PRIIPs and margin visible before signing

  • Files:
    • src/broker/venue.ts, adding whatIf() to the interface
    • src/broker/paper.ts, using feeFor and impactBps to give a paper what-if
    • src/broker/ibkr.ts:247-267
    • the ticket and approval code paths
    • web/views ticket view
    • src/setup/routes.ts:113-140
  • When a live proposal is drafted, and again when the owner opens it to sign, run the what-if after a snapshot. Show, as IBKR computed them:
    • commission, with currency
    • equity and initial-margin change
    • the warn and error text verbatim
    • for a foreign-currency buy, the ledger's cash in that currency, and whether the order would take it negative
  • The signed digest includes the what-if's hash and its time. An error, or any warning on the refusal list from item 3, blocks signing. A stale what-if (more than 2 minutes old) is re-run.
  • The setup dry run uses the same classifier, so 21/…market data is no longer "ok".

8. Multi-currency cash and an explicit FX leg (L), which fixes gap 4

  • Files:
    • src/broker/ibkr.ts:232-239, adding ledger() alongside available()
    • src/gateway/gateway.ts:105-119, 161-176
    • the proposal model, adding an optional paired FX leg
    • src/broker/paper.ts
    • web/views ticket view
  • The no-margin check reads that currency's cashbalance from /ledger, not base availablefunds.
  • If cash is short, the ticket offers a separate FX leg: isCcyConv on the pair's conid.
    • The owner signs both legs, and the FX leg's what-if shows its commission.
    • It never converts on its own, and never silently borrows.
  • Reconcile also checks cash per currency against the Record. Fees are booked in their own currency.
  • IBKR's exchange rate is transcribed from ledger.exchangerate. The fund never computes one.

9. Connection wizard (M)

  • Files:
    • src/setup/routes.ts:34-73
    • src/setup/doctor.ts:135-144
    • src/setup/readiness.ts:47-52
    • web/views/broker.js
    • docs/operating.md
  • Steps, each with a plain pass or fail and the owner's next action:
    1. Gateway reachable. Show and pin the certificate.
    2. Log in on the phone through /broker/login.
    3. Paper detected (DU, isPaper). The wizard refuses to continue on a live login until paper has passed.
    4. Account and base currency. Entity [from account data, if exposed; otherwise the owner confirms it].
    5. Market-data check: a 6509 snapshot of one contract per exchange in the universe, listing which exchanges come back R, D, N or O.
    6. Resolve contracts (item 6) and show currency, exchange and unit per line for the owner to confirm.
    7. Test what-if on one small order, with no send.
    8. Paper round trip: place, see it as Submitted, cancel, and see Cancelled.
    9. Flex token and query check (item 10).
    10. Only then offer the live login and the signed go-live terms, recording the paper/live flag and the entity.

10. Daily Flex reconciliation, discontinuities and corporate actions (L), which fixes gap 10

  • Files:
    • new src/broker/ibkr/flex.ts (fetch, parse, pacing and error codes from section 5)
    • new src/recon/flex-recon.ts
    • src/record/schemas.ts:98-100, reusing existing event types
    • src/notify/watch.ts:16
    • the scheduler
    • .env.example (IBKR_FLEX_TOKEN, IBKR_FLEX_QUERY, and the token expiry)
  • The daily pull runs after 07:00 CET for the previous day. Match against the Record:
    • executions by order_ref / execution_id
    • commissions with currency
    • dividends and withholding
    • interest and fees
    • cash per currency
    • positions
  • Any difference is recorded as recon.discontinuity with both numbers and a notification. Never auto-fixed.
  • Corporate actions (splits, spin-offs, mergers, symbol or conid changes) in the Flex CorporateActions section produce corpaction.recorded, flagged for the owner. They are never applied without the owner's decision.
    • Until the owner decides, the reconcile excludes that instrument, so the recon halt does not fire on a known corporate action.
  • The live reconcile (firm.ts:694-702) calls positions/invalidate first and requires the difference to persist across two reads at least 2 minutes apart, which avoids the post-fill cache race.
  • Remind the owner 30 days before the token expires. Error 1012 goes to the owner as a plain message.

11. Remaining status polish (S), which fixes gaps 13, 17 and 18

  • Map the order states properly: Inactive becomes pending until a reject reason exists; PendingCancel and PreCancelled become cancelling.
  • Make one trades?days=7 call per tick, shared across working orders.
  • Fetch positions page by page.
  • Add modify (the full order body) only when the owner asks for it. The owner signs the new terms.

Order, with dependencies

#ItemEffortDepends on
1Call layer, pacing, error taxonomy, ambiguous-send, pre-send save, two-step lookupMnone
2Recorded-fixture fake gatewayM1
3Reply-chain allowlistS1, 2
4Session supervisor with a push login link and paper/live detectionM1
5Gateway container, pinned TLS, login-path proxy over TailscaleM4
6Contract resolution (ISIN, EU exchange, currency, unit, 6509)M1, 2
7What-if in the ticket, bound to the signatureM3, 6
8Multi-currency cash and a signed FX legL7
9Connection wizard (paper first)M4, 5, 6, 7
10Flex daily reconciliation and corporate-action flagsL1; independent of 3 to 9
11Status polishS1

Total: about 15 to 22 developer-days.

Go-live gate:

  • Items 1 to 7 and 9 must be done and green on paper.
  • Item 8 must be done before the first non-EUR trade. Until then, restrict live trading to EUR-denominated lines.
  • Item 10 must be done within the first live week.

Still to confirm on the paper account

  • Login paths: which paths the phone login loads through the proxy.
  • ISIN search: whether secdef/search accepts an ISIN for every universe line.
  • FX pairs: the FX pair conids.
  • LSE units: the LSE price unit at IBKR.
  • PRIIPs refusal: how a PRIIPs refusal looks on a US ETF.
  • Order statuses: whether Inactive appears for a DAY order sent outside hours.
  • Flex: the exact names of the Flex query sections.
  • Fees: current market-data and FX fees.