# Runbook: onboard a Charles Schwab account Schwab's Trader API is not a token you paste. It is an OAuth app, a browser consent, and a refresh token that dies after about seven days. This runbook is the whole operator path, written so that the weekly re-consent is a five-minute routine rather than an incident. Everything here is against the **developer portal** () and the `api.schwabapi.com` endpoints. There is no paper account: the only way to prove an order is a one-share limit order far below the market on a live account, which is the last step and is not done by this runbook. ## 0. What you need | Thing | Why | |---|---| | A Schwab **brokerage account** | The Trader API requires one; an individual developer role is granted against it | | An individual developer account on the portal | One app maximum per individual developer | | The app approved (`Ready for Use`, not `Approved - Pending`) | Approval is manual and takes days | | A machine that can listen on `127.0.0.1:8182` | The consent callback is loopback HTTPS | | `openssl` | To generate the self-signed certificate the loopback listener needs | Do not start this on the day you need to trade. The app approval is the long pole. ## 1. Create the app 1. Sign in at and choose the individual developer role. 2. **Apps → Create App**. 3. **API product:** the Accounts and Trading product (the one that includes the Trader API). The portal may call it "Accounts and Trading Production"; select the product that grants the Trader API, not a data-aggregation product. 4. **Callback URL:** `https://127.0.0.1:8182` — no trailing slash, no path. It must match what you pass to the command **exactly**; a trailing-slash difference fails as a security error that looks like a bad client id. - The portal enforces HTTPS for this product. A self-signed certificate is expected and normal; the browser will warn once. - If the portal refuses `127.0.0.1`, register `https://localhost:8182` and use that string everywhere, including in `--redirect-uri`. 5. **Order limit:** 120 per minute per account. The documented range is 0–120 and it covers new, replaced and cancelled orders. A lower value throttles the desk; 120 is the ceiling. 6. Submit. The app shows `Approved - Pending`. **It is not usable yet.** Wait for `Ready for Use`; the client id and secret are issued with approval. 7. Copy the **Client ID** and **Client Secret** into the environment, never into a file in the repository: ```bash export SCHWAB_CLIENT_ID='...' export SCHWAB_CLIENT_SECRET='...' export DATABASE_URL='postgresql://...' # the desk's database ``` The secret is read from the environment by the consent command. It is never a command-line argument, so it does not appear in `ps` or shell history. ## 2. Make the loopback certificate The callback must be HTTPS, so the listener needs a certificate. Generate one once, outside the repository: ```bash mkdir -p ~/.config/tapebook/schwab && chmod 700 ~/.config/tapebook/schwab cd ~/.config/tapebook/schwab openssl req -x509 -newkey rsa:2048 -nodes -days 825 \ -keyout key.pem -out cert.pem \ -subj '/CN=127.0.0.1' -addext 'subjectAltName=IP:127.0.0.1' chmod 600 key.pem cert.pem ``` This is a self-signed certificate for a loopback listener only. It is not a secret in the credential sense, but keep it out of the repository anyway. ## 3. Run consent The consent flow is library code; this snippet is the command that wires it to the token store. Save it nowhere — paste it into a shell whose environment has `SCHWAB_CLIENT_ID`, `SCHWAB_CLIENT_SECRET` and `DATABASE_URL`: ```bash uv run python - <<'PY' import asyncio, os from pathlib import Path import httpx, psycopg from tapebook.adapters.brokers.schwab_auth import ( SchwabConfig, SchwabSession, new_state, run_consent_listener, ) from tapebook.adapters.persistence.tokens import PostgresTokenStore async def main() -> None: config = SchwabConfig( client_id=os.environ["SCHWAB_CLIENT_ID"], client_secret=os.environ["SCHWAB_CLIENT_SECRET"], redirect_uri="https://127.0.0.1:8182", ) state = new_state() async with await psycopg.AsyncConnection.connect(os.environ["DATABASE_URL"]) as conn: async with httpx.AsyncClient(timeout=30.0) as http: session = SchwabSession(config=config, client=http, store=PostgresTokenStore(conn)) print("Open this URL and approve the app:\n") print(session.authorization_url(state=state)) tokens = await run_consent_listener( session, expected_state=state, certfile=Path.home() / ".config/tapebook/schwab/cert.pem", keyfile=Path.home() / ".config/tapebook/schwab/key.pem", ) print(f"Refresh token expires at {tokens.refresh_expires_at.isoformat()}") asyncio.run(main()) PY ``` The snippet prints an authorisation URL. Open it in a browser, sign in to Schwab, and approve the app. The browser is redirected to `https://127.0.0.1:8182/?code=...&state=...`; the local listener answers with "Consent received" and the snippet exchanges the code. **What you paste, and where.** With the listener, **nothing** — the code arrives on loopback and is exchanged immediately. If you cannot run the listener (a headless box with no browser), skip `run_consent_listener` and use the manual path in the same snippet: ```python from tapebook.adapters.brokers.schwab_auth import parse_redirect_url line = input("Paste the full redirect URL: ").strip() code, pasted_state = parse_redirect_url(line) tokens = await session.complete_consent(code=code, state=pasted_state, expected_state=state) ``` Complete the consent on any machine whose browser can reach the app, then paste the **full redirect URL from the address bar** into the prompt. Paste it once, into the process's stdin. Never put it in a file, a chat message, a commit, or a shell argument: it contains a single-use authorisation code. The snippet exchanges it immediately; the code is dead afterwards. The `state` value is generated per attempt and compared before the exchange. A callback with the wrong state is discarded and nothing is exchanged. ## 4. Where the token lands Two rows in the existing `broker_tokens` table, under the same upsert discipline as INDstocks: the table is not encrypted at rest; protect the database, not a second store. | `broker` | `token` | `expires_at` | |---|---|---| | `schwab:access` | the bearer access token | about 30 minutes after issue | | `schwab:refresh` | the refresh token | **consent + 7 days**, and never extended by a refresh | Everything that runs later reads these rows; nothing mints a token except the consent command. The refresh row's deadline is written once, at consent. A refresh rotates the secret if Schwab returns a new one but leaves the deadline alone, on purpose. ## 5. When it expires | Expiry | What happens | Who fixes it | |---|---|---| | Access token (~30 min) | `SchwabSession.access_token()` refreshes it, five minutes before expiry, one attempt | automatic | | Refresh token (~7 days) | `ReauthorisationRequired`, raised before any request, carrying the deadline | **a human re-runs §3** | The adapter will not retry a dead grant. Once `ReauthorisationRequired` is raised in a process it is cached, so a loop around `access_token()` cannot hammer the token endpoint. A scheduler should call `next_access_refresh_at()` for the routine refresh and `consent_due_at()` (deadline minus 24 hours) to remind a human. A 401 at order time is too late: it means a cycle already lost. When the deadline passes, re-run §3. It overwrites both rows; no cleanup is needed. ## 6. Revoke Any one of these ends access: - **Portal:** deactivate the app (Apps → the app → Deactivate). This stops the client id entirely and requires a new app or re-approval to trade again. - **Schwab account:** revoke the third-party app's access in Schwab's own consent/security settings. The next refresh then fails with `invalid_client`, which the adapter classifies as `ReauthorisationRequired`. - **Local:** delete the two `broker_tokens` rows. This only removes the local copy; it does not revoke anything on Schwab's side, so do one of the above as well. Revocation is irreversible. Getting back in means a fresh consent (§3), and possibly a fresh app approval if the app was deactivated. ## 7. What this does not prove - No live read has been made: there is no app credential in this repository and access to `api.schwabapi.com` returns 401 without one. - No order has been placed. `SUPPORTED` stays `False` until a live account read **and** one one-share limit order far below the market has been placed, read back, and cancelled (GAP-162). - The order/account field names come from the published models and the reference client, not from a captured payload, because the portal's endpoint reference is login-gated. The fake in `tests/conformance/broker/fakes.py` is marked synthetic; it proves parsing, not the wire. - Market-data entitlements (delayed vs real-time) are not established. Do not have a strategy claim real-time prices on this account until the entitlement is checked in the Schwab UI. ## 8. Stock plans (RSUs) are not this brokerage account The same Schwab login can show an employer stock plan. **It is not a trading account.** The Trader API documents no stock-plan surface: the developer portal's product catalogue has no stock-plan product, its guides never mention plans or blackouts, and plan servicing lives on a separate platform — the Equity Award Center () with a separate third-party authorisation form. Treat `GET /trader/v1/accounts/accountNumbers` as brokerage-only. If a plan account ever does appear there, **do not select it**. Put its hash in `SchwabBroker(plan_account_hashes=...)`; `authenticate()` refuses it. Otherwise the plan's shares would flow through `BrokerPort`, be counted in sleeve equity, and be sold by a whole-book rebalance. ### What you export by hand From the Equity Award Center (or the plan's statements), one row per grant tranche: | Field | Meaning | |---|---| | `grant_id` | the award identifier the plan uses; stays on every inflow and sale | | `vest_date` | the date the tranche vests (`YYYY-MM-DD`) | | `quantity` | shares in the tranche, exact decimal | | `fmv_per_share` | **FMV on the vest date**, for vested tranches only; blank for future tranches | | `forfeited` | `true` if the tranche was forfeited (otherwise omitted) | Plus, separately: - **sell-to-cover / sale confirmations:** date, quantity, sale price, and the plan's basis for those shares. The basis is FMV at vest; never enter zero. - **blackout calendar:** start date, end date (inclusive), and the plan's own reason. Copy the dates from the plan's trading-window notice, not from memory. - The **current vested share balance**, so it can be reconciled against the sum of vested tranches. ESPP purchases are a different instrument (discounted purchase price, not FMV) and are out of scope until modelled separately. ### Where it goes `domain/stock_plan.py`, not the holdings importer. The importer (`tape import-holdings`) books `OpeningPosition` rows into the sleeve; `plan_orders` then counts them in sleeve equity and sells anything the target weights do not cover — during a blackout, if the calendar says so. That is the one place an RSU would be mistaken for tradeable capital. Reconciliation compares the plan's own statement to `StockPlanAccount.vested_quantity(as_of)`. A disagreement means a missing or duplicated tranche/sale. It is never reconciled against the brokerage cash balance, and an empty plan is an empty plan — not a balance of zero. ### What is wired The CLI and API read the same payload, and **neither stores plans in the database**: this version has no stock-plan table, and inventing a migration number another lane may take would be worse than a named limitation. The CLI keeps a JSON plan document per plan id under `$TAPEBOOK_PLANS_DIR` (default `~/.config/tapebook/plans/`); the API keeps imported plans in the API process's memory, so a restart clears them and the plan must be re-imported. **CSV columns.** The grant-tranche export is exactly the five documented fields, one row per tranche, with any header case: | Column | Meaning | |---|---| | `grant_id` | the award id; rows with the same id become one grant | | `vest_date` | `YYYY-MM-DD` | | `quantity` | exact decimal shares, e.g. `100` or `0.5` | | `fmv_per_share` | FMV on the vest date; blank for a future tranche | | `forfeited` | `true` or blank/`false`; a forfeited row may not carry an FMV | Sales and blackouts are **not** in this CSV; the API payload below carries them. The CLI prints the plan's exposure without those two (concentration still needs `--price` and `--other-net-worth`). ```bash tape plan import acme-rsu.csv --plan-id PLAN-1 --sponsor 'Employer Inc.' \ --symbol ACME --venue NASDAQ --currency USD tape plan show PLAN-1 --as-of 2026-11-30 --price ACME=150.25 --other-net-worth 90150 ``` `plan import` prints vested/unvested/basis and the upcoming inflows, then writes `~/.config/tapebook/plans/PLAN-1.json`. `plan show` reads that file through the same payload parser; `--price` is `PRICE` or `SYMBOL=PRICE`, and a price for another symbol is refused rather than used. `POST /api/stock-plans/PLAN-1/import` takes the same shape. It is the **only mutating route** on the API and requires the approval bearer token exactly as move approvals do: without `TAPEBOOK_API_TOKEN` configured it is `503`, with a token configured but absent/wrong it is `401`. The response is the exposure below with `"stored": true`. ```json { "sponsor": "Employer Inc.", "instrument": {"symbol": "ACME", "venue": "NASDAQ", "currency": "USD"}, "custody_account_hash": null, "grants": [ {"grant_id": "G-2025", "tranches": [ {"quantity": "100", "vests_on": "2025-11-30", "fmv_per_share": "150.25"}, {"quantity": "50", "vests_on": "2027-11-30"} ]} ], "blackouts": [ {"starts_on": "2026-11-25", "ends_on": "2026-12-05", "reason": "quarter-end window"} ], "sales": [ {"on": "2025-11-30", "quantity": "40", "sale_price": "180.00", "basis": "6010.00", "reason": "SELL_TO_COVER"} ] } ``` `GET /api/stock-plans/PLAN-1?as_of=2026-11-30&price=150.25&other_net_worth=90150` returns the exposure, the vest inflows, and the concentration, each tagged so it cannot be read as strategy performance. `price` accepts a bare amount or `ACME=150.25`; `other_net_worth` is the denominator and must already exclude the plan. ```json { "plan_id": "PLAN-1", "instrument": "ACME@NASDAQ", "vested": "100", "unvested": "50", "vested_basis": "USD 15025.00", "market_value": "USD 22537.50", "single_name_share_of_net_worth": "0.2", "attribution": "STOCK_PLAN", "in_forward_record": false, "upcoming_inflows": [{"on": "2027-11-30", "quantity": "50"}] } ``` `market_value` is null without a price and `single_name_share_of_net_worth` is null without `other_net_worth`; neither is invented. The ratio is displayed to six decimal places, with trailing zeros removed. The sleeve report keeps its own number; the plan is a disclosure beside it. A rising ACME price moves `single_name_share_of_net_worth`, not the sleeve's return. The CLI file and the API memory are both **not** the source of truth. The plan statement is. When a stock-plan table lands, the payload parser here is the one the store should use, so the CSV, the API and the table cannot disagree about a tranche. ## 9. Verification you can run without a credential ```bash uv run pytest tests/adapters/test_schwab_auth.py tests/adapters/test_schwab.py \ tests/conformance -o addopts="" -q ``` No live call is made by any of these, and none of them needs a Schwab account.