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 withbin/run.sh root/conf.yaml) that listens onhttps://localhost:5000with 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,/oauthand/oauth2paths are not served by it. [doc] - A
User-Agentheader 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 /tickleabout once a minute./tickleitself 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, callPOST /iserver/auth/ssodh/init?publish=true&compete=true. - Wait about 2 seconds, then
GET /iserver/accountsand 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/reauthenticateis 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:trueappears. - 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 withU./portfolio/accountsreturnsisPaperper account. [doc] - So the fund can tell paper from live. The claim in
docs/operating.md:286that it cannot is wrong.
2. Order flow
Placing
POST /iserver/account/{acct}/orderswith body{"orders":[{...}]}. [doc]- Fields:
conid,orderType,side,tif,quantity,price,cOID,listingExchange,outsideRTH,cashQty. - For currency conversion:
isCcyConvandfxQty.
- Fields:
- 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/resetundoes it. Suppression also changes what the what-if returns. [doc]- Suppressible ids that matter here:
| id | What it warns about |
|---|---|
| o163 | price is a percentage away from market |
| o354 | no market data |
| o382 | tick size |
| o383 | size limit |
| o403 | will fill immediately |
| o451 | total value limit |
| o10151 | market order risk |
| o10153 | mandatory cap price |
| o10164, o10223 | cash quantity |
| o10336 | limited liquidity |
| p12 | price-management algorithm |
What-if
POST /iserver/account/{acct}/orders/whatiftakes the same body. [doc]- It returns
amount{amount,commission,total},equity{current,change,after},initial{current,change,after},maintenance{...},position{...},warnanderror. - It needs a market-data snapshot for the contract first. A warning like
21/You are trying to submit an order without having market dataarrives inwarn, not inerror.
Modify and cancel
- Modify is
POST /iserver/account/{acct}/order/{orderId}with the full original order as a single object. [doc] - Cancel is
DELETEon the same path. It answers{"msg":"Request was submitted"}, which "does not [mean] the order ticket itself has been canceled". [doc] PendingCancelandPreCancelledcan still fill. [doc]
Monitoring
GET /iserver/account/orderslists 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=trueclears the cache, and "Submission will appear as a blank array". You must call again to get data.- Filtering the list stops the websocket
sortopic until the nextforce=true.
- The fund's client order id comes back as
GET /iserver/account/trades?days=Nreturns today plus up to six earlier days. It includesexecution_id,order_ref,commission(no currency field),net_amountandtrade_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,CancelledandWarnState. [doc]Inactivealso means "created, not yet transmitted". It is not only a reject.
- Websocket topics (
wss://localhost:5000/v1/api/ws):sorfor orders,strfor trades,splfor P&L,ssdfor account summary,sldfor 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:Cmeans the value is the prior close,Hmeans halted. [doc] - Field
6509is availability. [doc]market-data-availability.md- The first character is the timeline:
Rreal-timeDdelayed 15 to 20 minutesZfrozenYfrozen delayedNnot subscribedOmeans the annual Market Data API Acknowledgement has not been signed
- The second character is
P(snapshot) orp(consolidated). The third is alwaysB.
- The first character is the timeline:
- Useful fields: 31 last, 84 bid, 86 ask, 7295 open, 7741 prior close, 6509 availability, and 55 symbol. [doc]
- Streaming:
smd+CONID+{"fields":[...]}subscribes andumd+CONID+{}unsubscribes. [doc] - EU exchanges need paid subscriptions per username. Without one, the snapshot comes back delayed
(
D) orN. [doc] [unverified: exact bundle names for Euronext, Xetra, LSE and SIX]
4. Portfolio and ledger
- Call
GET /portfolio/accountsbefore any other/portfoliocall. 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, andPOST /portfolio/{acct}/positions/invalidateclears the cache./portfolio2/{acct}/positionsis the newer, less-cached endpoint. [doc]GET /portfolio/{acct}/ledgeris cash by currency:cashbalance,settledcash,exchangerate,interest,netliquidationvalue, and aBASErow. [doc]- This is the only way to see that a USD buy left a negative USD balance.
GET /portfolio/{acct}/summaryreturnsavailablefunds,excessliquidityand 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
GET https://ndcdyn.interactivebrokers.com/AccountManagement/FlexWebService/SendRequest?t={token}&q={queryId}&v=3returns<Status>Success</Status><ReferenceCode>. [doc]- Optional parameters:
p(period), orfdandtd(date range, sent together).
- Optional parameters:
GET .../GetStatement?t={token}&q={ReferenceCode}&v=3returns the XML statement. [doc]- Poll while it answers
1019(generation in progress).
- Poll while it answers
- Pacing is 1 request per second and 10 per minute per token. Error
1018means too many requests. [doc]
Error codes to map
| Code | Meaning |
|---|---|
| 1001, 1004, 1009, 1021 | try again shortly |
| 1005 | settlement data not ready |
| 1003 | statement not available |
| 1012 | token expired |
| 1013 | IP restriction |
| 1014 | query invalid |
| 1015 | token invalid |
| 1018 | pacing |
| 1019 | generation 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,
1005is 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.
- The universe benchmark is
- 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.
summaryandledgerBASE 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.
- LSE prices on some data sources are in pence (GBp). The repo's market data is Yahoo
- 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]:
| Endpoint | Limit |
|---|---|
/iserver/marketdata/snapshot | 10 per second |
/iserver/account/orders | 1 per 5 seconds |
/iserver/account/trades | 1 per 5 seconds |
/iserver/account/pnl/partitioned | 1 per 5 seconds |
/portfolio/accounts | 1 per 5 seconds |
/tickle | 1 per second |
/sso/validate | 1 per minute |
/pa/* | 1 per 15 minutes |
Failure modes the fund must name to the owner
| Signal | Meaning | What the owner should see |
|---|---|---|
| TLS error on connect | self-signed certificate, not pinned | "The broker connection's certificate changed. Nothing was sent." |
| connection refused | gateway process down | "The broker gateway is not running." |
401 | no brokerage session (idle, reset, or a restart) | "IBKR needs you to log in. [Log in]" |
authenticated:false, connected:true | SSO alive, brokerage session gone | handled by ssodh/init; the owner is told only if it fails |
competing:true | same 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 /iserver | backend bridge not up after login, or maintenance | "IBKR is still starting the session" (retry for about 30 seconds), then "IBKR is in maintenance" |
429 | pacing | never shown. Back off; after two in a row, stop polling for 60 seconds. |
200 {error} on order | business reject | IBKR's text, quoted, plus which rule it resembles |
reply o354 | no market data | block; 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 withname=true. [doc]- Passing an ISIN as
symbolis widely reported to work for stocks. [community, unverified] GET /trsrv/stocks?symbols=ASMLlists every contract for a symbol withconid,exchangeandisUS, "typically differentiated based on currency of the primary exchange". [doc]- Then
GET /iserver/contract/{conid}/infogives currency, exchange andvalidExchanges. [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
listingExchangeon 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/ibeamis maintained and wraps the CP Gateway, but its purpose is injecting stored credentials. Rejected under the constraints. [community]gnzsnz/ib-gatewayand 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-jreplusclientportal.gw.zipfromdownload2.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.allowcovers127.0.0.1and 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 plus127.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
- 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_ordersbefore acceptance (ibkr.ts:355-358).
- Every socket error, including the 15-second timeout that fires after the order POST or
the reply confirm was written, becomes
- 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.
- What happens:
- The duplicate check reads an array that is always blank (
broker/ibkr.ts:296).- What happens:
lookup()calls/iserver/account/orders?force=trueonce and trusts the result.- IBKR documents that
force=truemakes 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 duplicatecOIDis 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.
- What happens:
- 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.
- What happens: up to five replies are confirmed with no allowlist. That includes
- The "no margin" check ignores currency (
broker/ibkr.ts:327-332,gateway/gateway.ts:161-176).- What happens:
available()is base-currencyavailablefundsfrom/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.
- What happens:
- The collar can price off stale data (
broker/ibkr.ts:66-70, 198-208).- What happens:
num()strips theC(prior close) andH(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
o354auto-confirmed.
- What happens:
- The contract is not verified (
broker/ibkr.ts:160-183).- What happens:
- Mapping is
secdef/search?symbol=matched on adescriptionstring equal to the IBKR exchange code. - No ISIN, no currency check, no
contract/infoconfirmation. - Yahoo's
.Lpence and IBKR's price units are never reconciled.
- Mapping is
- 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.
- What happens:
B: fragility that halts or confuses live trading
- 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, nocompetingorestablishedhandling (ibkr.ts:118-133), and no notification to the owner when the session drops (notify/notify.ts:10has no login kind).
- The heartbeat returns early unless
- Why it matters: the session dies silently and nobody is told.
- What happens:
- The portfolio primer never re-runs (
broker/ibkr.ts:212-217).- What happens:
portfolioPrimedstays true for the life of the process, but IBKR needs/portfolio/accountsagain after each new session. - Why it matters: after the daily re-login,
/portfoliocalls can fail or return stale data until a restart.
- What happens:
- Pacing violations are built in.
- Each
submit()makes about five calls toauth/statusand/iserver/accounts(account()atibkr.ts:141-147is called from lookup, submit, positions and available). refresh()calls/iserver/account/trades?days=7once per working order every minute (ibkr.ts:368). That endpoint allows 1 call per 5 seconds and IBKR advises once per session.liveTerms()runsmapUniverse()(sequentialsecdef/searchfor the whole universe) on every broker panel load (firm/firm.ts:639), and the panel reloads wheneverlivechanges (web/views/broker.js:11-86).- There is no
429handling anywhere. - Why it matters: the result is a 10-minute penalty box at the worst moment.
- Each
- 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/0with noinvalidate. - 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.
- Positions come from the cached
- Note: the schema already has
corpaction.recorded,corpaction.appliedandrecon.discontinuity(record/schemas.ts:98-100), but no broker source feeds them.
- What happens:
- 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 a21/…without market datawarning passes.
- What happens:
- Paper and live look the same (
docs/operating.md:286,broker/ibkr.ts:118-133).isPaperand theDUprefix are ignored. The go-live terms don't record which kind of login was checked.
- Status handling is wrong in places (
broker/ibkr.ts:365-397).Inactiveis mapped to rejected (:385), but it also means "not yet transmitted".- Cancel is treated as done when the
DELETEanswers (:391-397).PendingCancelandPreCancelledcan still fill. - Fill
feehas no currency (:376); it is booked in the order currency atgateway/gateway.ts:105-119. - There is no modify.
- 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=1can't work with the self-signed certificate, so in practice everyone runs unverified.
- 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.allowfor the Docker bridge is undocumented, and the troubleshooting row (docs/operating.md:574) doesn't mention it.
- The gateway is a manual Java process on the host (
- Errors reach the owner raw (
broker/ibkr.ts:106,firm/assist.ts:94-95).401becomesIbkrErrorwithHTTP 401, whichgateway.executedoes not catch as venue-down.- A 200
{error}is only recognised insidesubmit.
C: polish
positions/0reads only the first page (fine up to 100 positions).lookup()misses orders from earlier days. Usetrades?days=7or Flex for recovery.- The
Venueinterface (broker/venue.ts) has nowhatIf,session,cashormodify, so the paper venue cannot rehearse any of them. - 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,401orcompeting - no 6509 or
Cprefix - 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 ofibkr.ts:88-114 - new
src/broker/ibkr/errors.ts src/broker/venue.tssrc/gateway/gateway.ts:84-102
- new
- Token-bucket pacing: 8 requests per second globally, plus per-endpoint buckets taken from the table in section 7.
429handling: 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 replacesaccount()callingstatus()on every use. - Classify every outcome into:
unreachable | tls | unauthenticated | competing | bridge | paced | rejected | ambiguous.ambiguousmeans 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.ambiguousand 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_orderswith statesendingbefore the POST. - Two-step
lookup: callforce=true, wait, call again, and also checktrades?days=7. Only treat an order as unknown after both come back empty. - Cancel semantics:
cancelenterscancelling, and becomescancelledonly on aCancelledstatus.
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 (
o163theno354) 429401in the middle of a sequencecompeting:true- a timeout after the order is written
C/Hprefixes and 6509 =D,NandOPendingCancelthenFilled- a partially filled order
- GBp versus GBP
- blank pre-flight on snapshots and on
- 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 newsrc/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) ando403(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 returningrejectedwith IBKR's words.
- Auto-confirm only warnings already covered by what the owner signed:
- 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-702src/main.ts:76-78src/notify/notify.ts:10, adding kindsbroker_loginandbroker_sessionweb/views/broker.js
- new
- 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: callssodh/init?publish=true&compete=true, wait 2 seconds, verify/iserver/accounts, re-prime/portfolio/accounts, then clearportfolioPrimedand the session cache. - On
competingor 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
isPaperand 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-42docs/operating.md:244-343, 574
- An
ibkr-gatewayservice 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.yamlips.allowlists exactly that subnet plus127.0.0.1.
IBKR_GATEWAY_URLdefaults tohttps://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 replacesinsecureLocal. /broker/loginon 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 newsrc/broker/ibkr/contracts.tssrc/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 replacesEXCHANGE) 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:639andbroker.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,ZorY. - On
D, allow the collar but put "IBKR's price is 15 minutes delayed" on the ticket for the owner to see before signing.
- Treat
7. What-if in the ticket (M), which fixes gap 11 and makes PRIIPs and margin visible before signing
- Files:
src/broker/venue.ts, addingwhatIf()to the interfacesrc/broker/paper.ts, usingfeeForandimpactBpsto give a paper what-ifsrc/broker/ibkr.ts:247-267- the ticket and approval code paths
web/viewsticket viewsrc/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
warnanderrortext 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 datais no longer "ok".
8. Multi-currency cash and an explicit FX leg (L), which fixes gap 4
- Files:
src/broker/ibkr.ts:232-239, addingledger()alongsideavailable()src/gateway/gateway.ts:105-119, 161-176- the proposal model, adding an optional paired FX leg
src/broker/paper.tsweb/viewsticket view
- The no-margin check reads that currency's
cashbalancefrom/ledger, not baseavailablefunds. - If cash is short, the ticket offers a separate FX leg:
isCcyConvon 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-73src/setup/doctor.ts:135-144src/setup/readiness.ts:47-52web/views/broker.jsdocs/operating.md
- Steps, each with a plain pass or fail and the owner's next action:
- Gateway reachable. Show and pin the certificate.
- Log in on the phone through
/broker/login. - Paper detected (
DU,isPaper). The wizard refuses to continue on a live login until paper has passed. - Account and base currency. Entity [from account data, if exposed; otherwise the owner confirms it].
- Market-data check: a 6509 snapshot of one contract per exchange in the universe, listing
which exchanges come back
R,D,NorO. - Resolve contracts (item 6) and show currency, exchange and unit per line for the owner to confirm.
- Test what-if on one small order, with no send.
- Paper round trip: place, see it as
Submitted, cancel, and seeCancelled. - Flex token and query check (item 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 typessrc/notify/watch.ts:16- the scheduler
.env.example(IBKR_FLEX_TOKEN,IBKR_FLEX_QUERY, and the token expiry)
- new
- 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
- executions by
- Any difference is recorded as
recon.discontinuitywith both numbers and a notification. Never auto-fixed. - Corporate actions (splits, spin-offs, mergers, symbol or conid changes) in the Flex
CorporateActionssection producecorpaction.recorded, flagged for the owner. They are neverappliedwithout 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) callspositions/invalidatefirst 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:
Inactivebecomespendinguntil a reject reason exists;PendingCancelandPreCancelledbecomecancelling. - Make one
trades?days=7call 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
| # | Item | Effort | Depends on |
|---|---|---|---|
| 1 | Call layer, pacing, error taxonomy, ambiguous-send, pre-send save, two-step lookup | M | none |
| 2 | Recorded-fixture fake gateway | M | 1 |
| 3 | Reply-chain allowlist | S | 1, 2 |
| 4 | Session supervisor with a push login link and paper/live detection | M | 1 |
| 5 | Gateway container, pinned TLS, login-path proxy over Tailscale | M | 4 |
| 6 | Contract resolution (ISIN, EU exchange, currency, unit, 6509) | M | 1, 2 |
| 7 | What-if in the ticket, bound to the signature | M | 3, 6 |
| 8 | Multi-currency cash and a signed FX leg | L | 7 |
| 9 | Connection wizard (paper first) | M | 4, 5, 6, 7 |
| 10 | Flex daily reconciliation and corporate-action flags | L | 1; independent of 3 to 9 |
| 11 | Status polish | S | 1 |
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/searchaccepts 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
Inactiveappears for a DAY order sent outside hours. - Flex: the exact names of the Flex query sections.
- Fees: current market-data and FX fees.