# Runbook: verifying an adapter against a real broker An adapter that has never reached its broker is a claim, not a feature. This is how one becomes the other. INDmoney's INDstocks API is first, because it is the Indian execution leg and the only venue where the static-IP rule binds. IBKR is the other extreme — a GUI gateway with a browser session — and has its own section (§7) because none of the token advice above applies to it. ## 1. Get the credential | Broker | Where | What you need | |---|---|---| | INDstocks | `indstocks.com/app/api-trading` → Access Tokens | an access token; TOTP enrolment if not done | | IBKR | Client Portal Gateway on `https://localhost:5000` | no API token — a logged-in **browser session** against the GUI gateway; see §7 | INDstocks tokens are minted in the **algo-trading portal**, not the consumer app — the same login, a different surface. If your account is not yet KYC- and F&O-onboarded, that takes days, so start it before you need it. ## 1b. If the runner must mint tokens itself Pasting a token works today and dies at **07:00 IST tomorrow**. For an unattended runner, enrol TOTP once at `indstocks.com/app/api-trading/access-tokens` → **Setup TOTP**, then put three values in `.env`: | Variable | What it is | Notes | |---|---|---| | `INDSTOCKS_CLIENT_ID` | dashboard Client ID | sent as `x-api-key`, **not** `Authorization` | | `INDSTOCKS_MPIN` | account MPIN | | | `INDSTOCKS_TOTP_SECRET` | base32 secret | shown **once**, at setup only | Constraints that are not negotiable, from the API's own documentation: - **One live token at a time.** A new token invalidates the previous one for Indian *and* Global stocks, so exactly one process may mint. Two processes will keep killing each other's sessions. - **60 seconds minimum between generations.** A looping client is throttled. - **5 wrong codes locks the account for 15 minutes; 3 lockouts in an hour locks it for an hour and emails you.** No retry loop exists in `app/token_refresh.py` for this reason. - **A lockout does not kill a live token.** So a failed refresh must leave the working token alone rather than treating it as invalid. - **Check the host clock.** A drift of more than about a minute fails every code while your authenticator shows a perfectly valid one. Sync with NTP before debugging anything else. ## 2. Decide about the static IP Order placement in India is refused from an address the broker has not whitelisted. **Read traffic is usually allowed from anywhere**, so verification can start before this is settled — but the moment you capture an order response, the whitelisted IP matters. Whitelist the address of the machine that will run `algo runner` (ADR-0005), not your laptop, and remember a broker allows roughly one change per week. A wrong entry is a week of not trading. ## 3. Capture ```bash cd ~/tapebook cat > .env <<'EOF' INDSTOCKS_ACCESS_TOKEN=paste_token_here EOF chmod 600 .env uv run python tools/capture_recordings.py indstocks ``` The tool tries the auth shapes INDstocks' documentation is ambiguous about — a bare token and a `Bearer` prefix — and tells you which one the API accepted. Guessing wrong presents as "expired token", which sends you to re-mint a credential that was fine. Read-only by default. Add `--place-order` only once you have confirmed the reads work: that sends one 1-share limit order far below the market, then the response is what the order parser needs. ## 4. What the output means | You see | Meaning | Do | |---|---|---| | `auth plain HTTP 200` | bare token is accepted | nothing | | `auth plain HTTP 401`, `bearer HTTP 200` | a prefix is required | corrected by the capture; `IndstocksWire.auth_prefix` follows | | `HTTP 403` naming an IP | static IP not whitelisted | whitelist it; this is not a token problem | | `HTTP 401` on both styles | token is wrong or expired | re-mint | | `HTTP 404` on a read | the path is wrong — my guess, not your account | report it; it is exactly what capture exists to find | ## 5. Promote the recordings ```bash ls tests/adapters/recordings/indstocks/*/ # read these yourself first ``` Redaction replaces credential-shaped keys and scrubs JWT-shaped strings, but redaction is a heuristic, not a proof. Read the file, then copy a minimal one into `tests/adapters/fixtures/` and build a `respx` route from it. Only `fixtures/` is committed. ## 6. Then, and only then - Correct `IndstocksWire` against what came back. Every guess is one edit away. - Flip `SUPPORTED` in `adapters/brokers/indstocks.py`. - Close GAP-030 and GAP-049 in the gap ledger, naming the date the payloads were captured. ## Not the same thing - A **200 on a read** proves the path and the auth. It does not prove order placement, fills, or rejections — hence the optional order probe. - A **green conformance suite against a fake** proves parsing and error mapping against my own assumptions. That is what GAP-049 says, and this runbook is how it stops being true. ## 7. IBKR — Client Portal Gateway IBKR is the one broker whose payloads had never been captured until 2026-12-01 (GAP-025 — the **reads** are captured now, the order lifecycle is not; see §7.7), and the one where the credential is not a token you can paste: it is a **browser session against a GUI gateway** (GAP-029). There is no headless login to script, so this section is written for a person sitting at a machine with the gateway already running. Everything below is read-only except the two order probes, which are a 1-share LIMIT order far from the market. `SUPPORTED` stays `False` until the whole section has produced fixtures. ### 7.1 Preconditions | Thing | Value | |---|---| | Gateway | IB Gateway or Client Portal Gateway, listening on `https://localhost:5000` | | Account | **paper** (`DU…`), never the live account | | Login | browser → `https://localhost:5000` → log in, complete 2FA, accept the self-signed cert | | Certificate | `curl` needs `-k`; the API is self-signed and this is expected | | Session | expires daily and after ~6 idle minutes; `/iserver/tickle` keeps it alive | Check the session before anything else: ```bash curl -sk -c /tmp/ibkr.cookies 'https://localhost:5000/v1/api/iserver/auth/status' | jq . # {"authenticated": true, "competing": false, "connected": true, ...} ``` `authenticated: false` means log in again at the gateway; the adapter calls this `GatewaySessionExpiredError` and deliberately does **not** retry it. `connected: false` with `authenticated: true` is transient (IBKR is still linking the session); retry the read. ### 7.2 Endpoints to hit, in this order Use one cookie jar for the whole run. Save each response under the name in the last column. | # | Request | Why | Save as | |---|---|---|---| | 1 | `GET /v1/api/iserver/auth/status` | baseline shape of the session probe | `auth-status.json` | | 2 | `GET /v1/api/iserver/accounts` | account ids and `selectedAccount` shape | `accounts.json` | | 3 | `GET /v1/api/portfolio/{accountId}/ledger` | per-currency `cashbalance`/`BASE` | `ledger.json` | | 4 | `GET /v1/api/portfolio/{accountId}/positions/0` | `conid`, `contractDesc`, `position` | `positions.json` | | 5 | `GET /v1/api/iserver/secdef/search?symbol=AAPL&secType=STK` | whether a symbol maps to one conid or several | `secdef-search-aapl.json` | | 6 | `POST /v1/api/iserver/tickle` | keepalive response shape | `tickle.json` | | 7 | `POST /v1/api/iserver/account/{accountId}/orders` (probe 1) | the **confirmation prompt** (a `reply` id) | `order-prompt.json` | | 8 | `POST /v1/api/iserver/reply/{replyId}` `{"confirmed": true}` | the acknowledgement after confirming | `order-confirmed.json` | | 9 | `GET /v1/api/iserver/account/order/status/{orderId}` | the lifecycle vocabulary and cumulative `filledQuantity` | `order-status-submitted.json` | | 10 | repeat #9 until terminal | a real terminal shape (`Filled`, `Cancelled`, `Inactive`) | `order-status-terminal.json` | | 11 | `POST /v1/api/iserver/account/{accountId}/orders` (probe 2), then `DELETE /v1/api/iserver/account/{accountId}/order/{orderId}` | cancel acknowledgement | `order-cancel.json` | Examples for the shapes that are easy to get wrong: ```bash ACCOUNT=DU0000000 # the value from accounts.json, not the one in this file # 3/4: reads curl -sk -b /tmp/ibkr.cookies \ "https://localhost:5000/v1/api/portfolio/$ACCOUNT/ledger" > ledger.json curl -sk -b /tmp/ibkr.cookies \ "https://localhost:5000/v1/api/portfolio/$ACCOUNT/positions/0" > positions.json # 5: resolution — the interesting case is a symbol with more than one listing curl -sk -b /tmp/ibkr.cookies \ 'https://localhost:5000/v1/api/iserver/secdef/search?symbol=AAPL&secType=STK' \ > secdef-search-aapl.json # 6: keepalive (the adapter refuses to do this more than once a minute) curl -sk -b /tmp/ibkr.cookies -X POST \ 'https://localhost:5000/v1/api/iserver/tickle' > tickle.json # 7: order probe 1 — 1 share, LIMIT 50% below the market, DAY curl -sk -b /tmp/ibkr.cookies -X POST \ -H 'Content-Type: application/json' \ "https://localhost:5000/v1/api/iserver/account/$ACCOUNT/orders" \ -d '{"conid": , "secType": ":STK", "orderType": "LIMIT", "side": "BUY", "quantity": 1, "price": 1.00, "tif": "DAY", "outsideRTH": false, "cOID": "capture-probe-1"}' > order-prompt.json # 8: confirm exactly the id from order-prompt.json curl -sk -b /tmp/ibkr.cookies -X POST \ -H 'Content-Type: application/json' \ 'https://localhost:5000/v1/api/iserver/reply/' \ -d '{"confirmed": true}' > order-confirmed.json ``` If probe 1 comes back as an **acknowledgement instead of a prompt**, that is also a capture worth keeping: it proves the account's confirmation policy is off. Record it as `order-no-prompt.json` and say so in the README. ### 7.3 Sanitisation rules Replace, do not delete, so the shape stays visible: | Field / header | Rule | |---|---| | `accountId`, `acctId`, `clientAccountID`, `accountAlias` | replace with `DU0000000` (paper-masked, same length) | | `username`, `userId`, `userName`, `displayName` | replace with `` | | `sessionId`, `sessionToken`, `X-...-Session`, cookies | **remove entirely**; never commit a cookie jar | | `Set-Cookie`, `Authorization`, `Cookie` headers | never save headers; save bodies only | | `hw_info`, `mac`, `ip`, `lastLogin`, `clientIP` | replace with `` / `0.0.0.0` | | `token`, `access_token`, `refresh_token` | replace with `` | | `conid` | keep: it is a public contract id, not an identifier of you | | `order_id`, `cOID` | keep: the adapter's recovery path keys on them, so a fake must use the same shape | Read every file before copying it. Redaction is a habit, not a proof. ### 7.4 Proving the saved capture matches the live shape A fixture that was typed from memory is worse than no fixture. Save the live probe to `tests/adapters/recordings/ibkr/` (git-ignored), then compare **key paths**, not values: ```bash uv run python - <<'PY' import json, pathlib def paths(value, prefix=""): if isinstance(value, dict): for key, child in value.items(): yield from paths(child, f"{prefix}.{key}" if prefix else key) elif isinstance(value, list) and value: yield from paths(value[0], f"{prefix}[]") else: yield prefix live_dir = pathlib.Path("tests/adapters/recordings/ibkr") fixture_dir = pathlib.Path("tests/adapters/fixtures/ibkr") for live in sorted(live_dir.glob("*.json")): fixture = fixture_dir / live.name if not fixture.exists(): print(f"missing fixture: {live.name}") continue a = set(paths(json.loads(live.read_text()))) b = set(paths(json.loads(fixture.read_text()))) print(live.name, "OK" if a == b else f"DIFF only-live={sorted(a-b)} only-fixture={sorted(b-a)}") PY ``` Only "OK" lines belong in a fixtures README. A `DIFF` line is either a stale fixture or a sanitisation that changed structure — both are fixes, not caveats. ### 7.5 What this buys, and what it still does not The fixtures exist (2026-12-01) and `tests/adapters/test_ibkr.py` parses them through `IbkrBroker` over a `MockTransport`, which moves the claim from "parses my fake" to "parses a real body". It still does not prove: fills caused by the market rather than a 1-share probe, an IP rejection (IBKR does not impose India's static-IP rule), a live order rejection reason, or a full daily re-authentication cycle. Those need a real gateway session and a real trading day, which is why GAP-029 stays open until the paper run is done end to end. ### 7.6 When the login succeeds but the API returns 401 What the gateway *says* on this path is not what it means. Everything below was established by disassembling the bytecode of the build that was run (`Build 10.50.1f`, 2026-12-01), after a session spent chasing the messages at face value. - **`Access Denied` is not IBKR's verdict on the account.** `HttpProxy.getFailedReason` returns that literal for *any* upstream **401**. A fully entitled login, a genuinely expired session and a rejected client all produce the same body from `/sso/validate`, so do not read it as "this account is not permitted to use the API". - **`Client login succeeds` in the gateway log does not mean the session validated.** The line is emitted for any 302 to `/sso/Dispatcher` without looking at `Location`, so a redirect to `/restricted/` — pending verification, an annual review, an unsigned agreement — logs exactly like a success. Check the redirect target, not the log line. - **`x-sess-uuid` is Akamai's edge cookie, not an IBKR session.** The gateway accepts only `{XYZAB, XYZAB_AM.LOGIN}` from a client, which is why copying a browser's cookie jar changes nothing and why one `curl -sk` on the same host is the supported pattern (§7.2, §7.4). - **There is no "Client Portal API" enable toggle to find.** A current account does not have one, so the missing menu is expected rather than the diagnosis. OAuth 1.0a/2.0 are not offered to UK individual accounts either, so "call the API directly instead of the gateway" is not an escape. - **`ip2loc` in `root/conf.yaml` is a client-side hint, not a region lever.** The login page is byte-identical for US, IN, GB and UK; setting it moved nothing in either direction, and it was set for the whole of a failing session. Leave it at the shipped US value — an earlier version of this section told you to set `"IN"`, which was noise. - **Port 5000 is called out by IBKR itself for macOS.** AirPlay Receiver holds it, which is why the gateway is commonly started on another port (5001 here). Pass the full URL — `https://localhost:5001/v1/api` — and expect a self-signed certificate on it. `IbkrBroker(verify=False)` is allowed only for a loopback `base_url`; anything else refuses with `UnverifiedRemoteGatewayError`. - **IBKR support's own workaround for this loop is `proxyRemoteHost: "https://1.api.ibkr.com"`** in `root/conf.yaml`. It is the one lever support offers when a gateway that starts and proxies still cannot validate a login; try it before opening a ticket. "is the gateway running?" is the wrong question once `/iserver/auth/status` has answered at all. Order to try, cheapest first: the JDK (§7.7 — it costs nothing and is the only variable that has flipped this in practice), then `proxyRemoteHost`, then the login itself. Probe it without the adapter: ```bash curl -sk 'https://localhost:5001/v1/api/sso/validate' # {"error":"Access Denied"} — the gateway labelling an upstream 401; says nothing about the account # a validation payload (RESULT/PASS) — the session itself is fine ``` ### 7.7 What the first capture actually recorded (2026-12-01) The reads in §7.2 were run against a **live** account (`U19444565`) on `https://localhost:5001`, not the paper account §7.1 asks for — the only login available was the live one, and every request was a `GET`. No order probe was run, so GAP-025 stays open for the order lifecycle half of this section. **The gateway runs on JDK 21; the authenticated call path did not behave the same on it.** The jar starts and proxies fine on 21 — this is not a jar-too-old-for-21 claim. What differed was `/sso/validate`: `Access Denied` after `Client login succeeds`, six logins in a row, with `ip2loc: "IN"` already set throughout (and, per §7.6, that setting was never a lever). Changing one variable and nothing else — the JDK to 11 — was followed by a session that validated (`authenticated: true, established: true`). One A/B does not prove a JDK bug; it does record where the first successful session came from, and it is the first thing to try because it costs nothing. Sanitised fixtures are in `tests/adapters/fixtures/ibkr/` with their substitutions listed in that directory's README: `ledger.json`, `positions.json`, `contract-1520593.json`. The raw bodies stay in `~/tapebook-captures/ibkr-2026-12-01/`. What they settled, each of which contradicted a comment in `adapters/brokers/ibkr.py`: | Question §7.2 left open | Answer in the capture | |---|---| | Does a positions row name its venue? | Yes: `listingExchange` (`NYSE`, `NASDAQ`) on all 13 rows. There is no `exchange` and no `primaryExch`, and `exchs` is `null` with `conExchMap` `[]` | | Which field of `/iserver/contract/{conid}/info` names the exchange? | **None names a listing.** `exchange` is `SMART` — the routing destination — for JPM (NYSE) and for NOW/AAPL (NASDAQ); `valid_exchanges` is every venue the contract may route to. The field is useful for `currency` and the symbol, not for the venue | | What is the ledger's base key? | `BASE`, whose own `currency` field is the literal `"BASE"`. Per-currency fields are `cashbalance` and `netliquidationvalue` — the adapter had been reading `cashbalance` correctly and `netliquidation*` not at all | | Is one symbol one conid? | No: `secdef/search` for `AAPL` returned five rows (`NASDAQ`, `TSE`, `MEXI`, `EBS` and a `BOND` row whose conid is `2147483647`), and the venue appears in `description` and in the `companyHeader` suffix | | Does the ledger carry a currency the desk cannot hold? | Yes: `GBP`. See GAP-196 — `account()` now refuses that balance by name rather than dropping it | `SUPPORTED` stays `False`: §7.4's key-path comparison is green for all three fixtures, but §7.5's "parses a real body" step has not been extended to the order probes (§7.2 items 7–11), which is what the paper run in §7.1 is for.