/algo-trading-skills:schwab-api-oauth-pkce-flowfrom algo-trading-skills
Authenticates against the Charles Schwab Trader API using the documented confidential-client authorization-code flow (not PKCE). Handles token exchange, refresh, and 7-day expiry alerting.
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.
Use this when authenticating an automated trading bot or market-data client against the Charles Schwab Trader API, including migrations off the retired TD Ameritrade API.
Start with the correction, because most Schwab "PKCE" tooling is built on a false
premise. Schwab's published Trader API documentation describes a
confidential-client authorization-code flow. The authorization URL it documents
is https://api.schwabapi.com/v1/oauth/authorize?client_id={key}&redirect_uri={cb}
— no code_challenge, no code_challenge_method — and the token endpoint
authenticates the client with Authorization: Basic base64(app_key:app_secret).
No Schwab source, and not the most widely used community client (schwab-py),
mentions PKCE anywhere. Implement the documented flow; do not send PKCE parameters
Schwab has never published support for.
And settle the operational question before writing code. Schwab's refresh token is valid for 7 days from creation, refreshing does not extend that window, and Schwab publishes no way to renew it programmatically. A Schwab-connected bot requires a human at a browser at least once a week. That is a scheduling constraint, not a bug to engineer around.
What this skill then covers: building the authorization URL without mangling it, decoding the percent-encoded callback code, exchanging it with strict response validation, persisting tokens as the credentials they are, refreshing on a buffer, and alerting before the 7-day window closes.
headless-broker-auth-patterns before designing around it.SchwabPKCEGenerator is RFC 7636-correct and
usable elsewhere, but PKCE is for public clients that cannot hold a secret.
Schwab issues an app secret, so the client is confidential by definition.0600 file. For
multi-host or multi-tenant deployments see
centralized-secrets-management-vault-integration and
secrets-rotation-without-bot-downtime.kill-switch-and-drawdown-circuit-breakers and sec-rule-15c3-5-risk-controls-us.client_id)
and App Secret.https://127.0.0.1 is
explicitly allowed), under Schwab's 255-character limit, matching byte-for-byte
what the client sends. An HTTPS loopback listener needs a self-signed certificate.http_post_fn(url, form_payload, headers) -> dict that raises
on transport failure.Confirm the weekly re-authorization is acceptable, and schedule it.
Build the authorization URL with encoded parameters and no PKCE.
redirect_uri truncates the query
string at its own ?/&; Schwab then compares a mangled callback against the
registered one and rejects the login with a security error that names nothing.code_challenge. get_authorization_url sends it
only when a caller passes one explicitly, and warns when they do, because that
behaviour is unverified against Schwab.Capture the callback and URL-decode the code.
error before looking for code. A denied
consent redirects with error; treating that as "no code yet" hangs instead of
failing.%40.
Schwab's documentation states the code "must be URL decoded prior to making the
request". The community habit of slicing between the literals code= and
%40 truncates the trailing @ or leaves the value encoded; the exchange then
fails with an opaque error. extract_code_from_callback parses the query
string properly.Exchange the code, and validate the response strictly.
POST /v1/oauth/token with Authorization: Basic base64(app_key:app_secret),
Content-Type: application/x-www-form-urlencoded, and
grant_type=authorization_code&code=…&redirect_uri=….expires_in. A client that invents a
lifetime the server did not state keeps using a dead token, and every later
call 401s for a reason nothing in the logs explains. Absent or non-numeric is
fatal. A missing refresh_token is fatal too — unattended operation is
impossible without it.SchwabAmbiguousTokenError marks this and leaves stored state
untouched.access_token, refresh_token and id_token. Echo the OAuth
error/error_description and the key names only.Persist tokens as credentials.
0600 before any secret is written, fsync,
then os.replace. A default-mode temp file is briefly world-readable; an
unsynced write can leave a truncated file that looks like corruption.SchwabTokenPersistenceError
is raised while the in-memory state is kept, so a running process can continue
trading and retry the write rather than discarding a token Schwab already issued.Refresh on a buffer, and never move the 7-day anchor.
refresh_expires_at is anchored at the original
authorization. Re-anchoring it on each refresh silences the warning entirely
and the bot dies without notice mid-week. refresh_access_token carries the
original deadline forward unchanged.refresh_token if one is returned, and
keep the existing one if not. Rotation is undocumented; this is correct either
way.invalid_client means re-authorize, not retry. That is
how Schwab rejects an over-age refresh token, and no retry can succeed.
SchwabRefreshTokenExpiredError exists so an alert binds to exactly that.Alert on the window, and gate the bearer header.
is_refresh_token_expiring_soon() hourly; at 24 hours remaining raise an
operator alert, not a log line — the remedy needs a human.get_bearer_header() refuses to build a header from a token inside the refresh
buffer, so staleness fails locally instead of as a mid-order 401.Full step-by-step procedure: see
references/workflows.md. Sourced endpoints, lifetimes and the PKCE evidence: seereferences/standards.md. Printable pre-flight checklist: seeassets/checklist.md.
?/& and the login fails with a security error.%40; slicing on code=/%40 truncates or
under-decodes it, and the exchange fails with an error that names nothing.expires_in when the response omits it. The client then believes a
dead token is live.invalid_client as a transient error and retrying. It means the
refresh window closed; only a human can fix it.repr-ing token state. One logger.debug(state) ships credentials
to the log aggregator; tokens are excluded from repr for this reason.redirect_uri
containing : and / never appears literally); no code_challenge or
code_challenge_method is present by default; both appear only when a challenge
is explicitly supplied; a padded challenge, a non-HTTPS callback, an over-length
callback and a blank app key each raise.?code=C0.abc-def%40 yields C0.abc-def@; %2B yields
+, not a space; an error parameter raises; zero, empty or duplicated code
parameters raise./v1/oauth/token with
grant_type=authorization_code, the decoded code, the callback,
Authorization: Basic base64("KEY:SECRET") and the form content type; no
code_verifier unless supplied; a colon in the app key raises before dispatch.expires_in raises and leaves state
unset; None, "soon", 0, -5, True, inf and NaN all raise; a missing
refresh_token raises.refresh_token/id_token produces a
message containing the OAuth error but neither credential; repr() of token state
shows the expiry fields and neither token.SchwabAmbiguousTokenError and leave prior state identical.grant_type/refresh_token; a rotated
token is stored and reaches disk; an absent one keeps the existing value; an
elapsed window and a missing token both raise SchwabRefreshTokenExpiredError
with zero network calls; error=invalid_client raises the same; a transport
failure preserves state.expiry - 300 s, the
refresh warning at exactly expiry - 86400 s; no state counts as expiring;
get_bearer_header() raises inside the buffer and returns the Bearer header
outside it..tmp files remain;
the file is 0600 on POSIX; a corrupt or wrongly typed file yields None state
without crashing and is left on disk for the operator; an unwritable path raises
SchwabTokenPersistenceError while the in-memory token stays usable.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk →
E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM) reproduces exactly; challenges are
43 characters and unpadded; lengths 42 and 129 raise while 43 and 128 succeed.python -m unittest discover -s skills/schwab-api-oauth-pkce-flow/scripts
and confirm all tests pass.headless-broker-auth-patternstoken-lifecycle-live-probingsecrets-rotation-without-bot-downtimecentralized-secrets-management-vault-integrationsandbox-credential-leakage-preventionbroker-agnostic-adapter-interfacemulti-broker-rate-limit-handlingstructured-logging-for-post-incident-forensicsWhat SKILL.md sets; muted values are Claude Code's defaults
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