/algo-trading-skills:headless-broker-auth-patternsfrom algo-trading-skills
Classifies broker authentication into five archetypes for unattended bot operation. Helps select a mechanism that the broker actually supports, avoiding dead-end implementations.
Ships in algo-trading-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them; scripts run unread.
Invoke this when a bot needs to authenticate with a broker without a human present at bot-start time — nightly restarts, systemd auto-restart, or cloud deployment where no browser session exists.
Start by identifying which archetype the broker actually is. The single most expensive mistake in this area is building against a mechanism the broker does not publish. There are five, not two:
| Archetype | Mechanism | Brokers | Unattended? |
|---|---|---|---|
| C — Refresh token | One interactive OAuth login seeds a longer-lived refresh token; the bot exchanges it for daily access tokens | Fyers API v3 (refresh token valid 15 days) | Yes, until the refresh token expires — prefer this wherever it exists |
| D — Static credential | API key + secret sent as headers on every request; no login, no session, no expiry | Alpaca Trading API | Yes, trivially. The problem is key custody, not session acquisition |
| E — Supervised gateway | A long-running local gateway process holds the session; 2FA approved out-of-band | IBKR TWS/IB Gateway (via IBC / IBAutomater) | Partly — IBKR forces a periodic restart, and 2FA arrives as a push to IBKR Mobile |
| A — Scripted credential/TOTP post | Credentials + TOTP posted to a login endpoint that returns an auth code | Fyers/Zerodha unofficial internal endpoints | Technically yes; see When NOT to Use first |
| B — Browser automation | Drive the broker's human login page and intercept the redirect | ICICI Breeze (publishes no session-creation API at all) | Technically yes; see When NOT to Use first |
Archetypes C, D and E are broker-sanctioned. A and B are not: they automate a login surface the broker built for a human, and both are covered by the constraints below. Reach for A or B only after confirming C/D/E genuinely do not exist for that broker, and only where you have established that automating it is permitted.
Do not use the Archetype A or B paths to build indefinitely-unattended authentication against an Indian broker (Fyers, Zerodha Kite, ICICI Breeze, Upstox). This is a stated constraint, not a stylistic preference:
These standards are fully applicable to all stock brokers from 01-Apr-2026 (SEBI/HO/MIRSD/MIRSD-PoD/P/CIR/2025/132, 30-Sep-2025, extending SEBI/HO/MIRSD/MIRSD-PoD/P/CIR/2025/0000013, 04-Feb-2025). Outside India, and for brokers whose terms permit it, Archetypes A and B remain legitimate — the mechanics below are correct and worth implementing well. Confirm the broker's own terms of use before automating a login page; this repository is not legal or compliance advice.
Broker developer app registered (API key + secret, redirect URI configured)
A static IP registered with the broker, for Indian brokers. NSE/INVG/67858 A.1 makes this mandatory for API access, I.e requires access "only through a unique vendor client specific API key and static IP whitelisted by the broker," and A.6 permits changing the mapped IP "not more than once a calendar week." A headless bot on an ephemeral cloud IP simply will not authenticate, and you cannot chase a rotating address by re-registering daily. Budget for a static/elastic IP or a fixed-IP NAT gateway before writing any auth code.
Confirmation of which archetype the broker is (table above) — before writing an HTTP client against an endpoint that may not exist
TOTP secret provisioned for 2FA-enabled accounts, only where the scripted path is permitted (store as encrypted secret, never plaintext in repo)
For Archetype B: headless Chromium/Chrome available in the deployment environment (not just dev machine — this breaks silently in minimal Docker images missing browser deps)
A secrets store (env vars, Vault, or at minimum a .env excluded from git) — credentials must never be hardcoded
Broker developer app registered (API key + secret, redirect URI configured)
TOTP secret provisioned for 2FA-enabled accounts (store as encrypted secret, never plaintext in repo)
For Archetype B: headless Chromium/Chrome available in the deployment environment (not just dev machine — this breaks silently in minimal Docker images missing browser deps)
A secrets store (env vars, Vault, or at minimum a .env excluded from git) — credentials must never be hardcoded
fyers_refresh_token_login): grant_type=refresh_token, appIdHash, refresh_token, pin. No browser, no stored password.pyotp or equivalent) — do not assume the code is valid for more than ~30s, generate it at the moment of use.sha256(app_id + ":" + secret_key) with the auth code sent separately as code; Zerodha uses sha256(api_key + request_token + api_secret) with no separators. Never guess this shape from another broker's.{"s": "error", "code": -371, ...}), so raise_for_status() passing means nothing. Unwrap the payload and surface the broker's own code and message, or the failure resurfaces later as an opaque KeyError.token-lifecycle-live-probing skill) before triggering a fresh login — do not blindly re-login every restart, as some brokers rate-limit login attempts.sleep() calls — page load time varies and fixed sleeps cause flaky failures under CI/cron load.driver.current_url after redirect, or a network-request listener) and parse the query string properly to extract the token parameter. Confirm the exact parameter name against the broker's documentation — ICICI Breeze returns API_Session, with that capitalisation. Do not slice the URL on a literal "session_token=": when the parameter is named anything else, the slice silently yields the whole URL prefix and hands it downstream as though it were a token.breeze.generate_session(api_secret, session_token)), then close/quit the browser instance — do not leave headless Chrome processes running, they accumulate as zombie processes under systemd restarts and exhaust memory over days.Full step-by-step procedure with broker-specific detail: see
references/workflows.md. Broker/framework coverage table for this skill: seereferences/standards.md. Printable pre-flight checklist: seeassets/checklist.md.
"session_token=". Against ICICI Breeze — whose parameter is API_Session — the slice matches no separator and returns the entire URL prefix as the "token", with no exception raised. Parse the query string and fail loudly when the expected parameter is absent.-371 ("Please provide sha256 hash of appId and app secret") inside a 200 body; the resulting KeyError: 'access_token' points nowhere near the checksum that actually caused it.navigator.webdriver); test explicitly in headless mode, not just headed mode during development.token-lifecycle-live-probing for why expiry cannot be assumed from documentation alone.ps aux | grep chrome should be clean).API_Session=... for Breeze) yields the token, and a redirect carrying none of the expected parameters raises rather than returning a truncated URL.KeyError.python -m unittest discover -s skills/headless-broker-auth-patterns/scripts.token-lifecycle-live-probingmulti-broker-rate-limit-handlingsystemd-supervision-for-trading-botsupstox-oauth-refresh-token-rotationibkr-tws-gateway-headless-launchcentralized-secrets-management-vault-integrationindia-sebi-algo-trading-tagging-requirementsWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub himanshuj16/algo-trading-skills --plugin algo-trading-broker-integration36 skills in this plugin
/alpaca-paper-live-key-separationUse when a bot connects to the Alpaca Trading API and must never cross paper keys with the live endpoint; pins the base URL per environment, checks the key prefix, probes /v2/account and requires an explicit ALLOW_LIVE_TRADING flag./api-key-least-privilege-audit-toolUse before deploying a live bot, to audit existing broker API keys for scopes they do not need. Flags withdrawal, transfer and admin rights that turn a leaked execution key into theft./broker-account-margin-call-handlingUse when a bot trades a Reg T, portfolio or futures margin account and must act before the broker liquidates: tiered maintenance-margin warnings cross-checked against broker excess liquidity, initial-margin order gating and liquidity-aware de-leveraging.Other plugins' skills for the same job