/algo-trading-skills:upstox-oauth-refresh-token-rotationfrom algo-trading-skills
Manages the Upstox API v2/v3 daily access token lifecycle, deriving expiry from the fixed 03:30 IST deadline and handling single-flight re-authentication with atomic persistence.
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 whenever a bot holds an Upstox access token across time — order placement, market-data streaming, or any process that outlives a single request.
Read this first, because the skill's own slug is misleading. Upstox does not issue refresh tokens and publishes no grant_type=refresh_token exchange. Upstox staff state it plainly: "We do not support refresh tokens. Our access token is valid until 3:30 AM and expires after that." The Get Token API documents authorization_code as the only grant, and its response contains no refresh_token field. This skill retains the historical slug for cross-reference stability; what it actually covers is the daily access-token lifecycle.
The two facts that drive every design decision here:
| Fact | Consequence |
|---|---|
The token expires at a fixed wall-clock instant — 03:30 IST the following day — regardless of when it was issued, and the response carries no expires_in | Expiry must be derived from the 03:30 IST rule. A now + 86400 model overstates validity by up to ~24h |
| There is no refresh credential; every re-acquisition path costs a human interaction or a console action | Re-auth must be single-flighted and the result persisted atomically, or you wake the user N times |
The three documented ways to obtain a token:
| Path | Endpoint / mechanism | Unattended? | Can place orders? |
|---|---|---|---|
| Authorization code | Browser dialog → POST https://api.upstox.com/v2/login/authorization/token, grant_type=authorization_code | No — a human completes the dialog daily | Yes |
| Access Token Request | POST https://api.upstox.com/v3/login/auth/token/request/{client_id} → user approves an in-app/WhatsApp prompt → token delivered to your registered notifier_url | Near-unattended: no browser, but the user taps approve. Individual accounts only | Yes |
| Analytics Token | Generated from the Developer Apps console; 1-year validity, one active per account | Yes | No — GET only; order APIs return 403 UDAPI100067 |
headless-broker-auth-patterns.API_KEY (client_id), API_SECRET (client_secret), and a registered redirect_uri.notifier_url webhook and an individual (not corporate) account.threading.Lock/asyncio.Lock if more than one worker reads the token.Load persisted token state. Read access_token, expires_at, source, and read_only. Treat an unreadable or schema-invalid file as no token — never as a usable one. Refuse to load a record with no expires_at rather than substituting a default; the default is how the 24-hour-validity bug gets back in.
Decide expiry against the real boundary, not a duration. Compute the next 03:30 IST instant strictly after issuance. Upstox's own examples: issued 20:00 IST Tuesday → expires 03:30 IST Wednesday (~7.5h); issued 02:30 IST Wednesday → expires 03:30 IST that same Wednesday (~1h). Where the broker supplies an authoritative expires_at (the notifier webhook does), prefer it over the derived value — but parse it as epoch milliseconds, delivered as a string.
Apply a buffer before starting work, not to "refresh early". Treat the token as expiring if it dies within ~900s. There is nothing to refresh; the buffer exists so a strategy never begins a cycle on a token that will die between an order submission and its status poll.
Single-flight the re-authentication. Acquire the lock, then re-check expiry inside it. Without the recheck the lock serialises the prompts instead of collapsing them, and ten workers waking at 03:30 IST still send ten approval pushes to the user's phone. Exactly one re-auth call must escape.
Choose the re-acquisition path deliberately. The authorization-code exchange body is form-urlencoded (Content-Type: application/x-www-form-urlencoded); the v3 Access Token Request body is JSON. Do not generalise one to the other. The authorization code is single-use — a failed exchange needs a fresh code, never a replay.
Validate what re-auth returned before trusting it. Reject an empty token, and reject one whose expires_at is already in the past. An already-dead token is nearly always a seconds/milliseconds mix-up, and accepting it produces a hot re-auth loop that spams the user with approval prompts.
Persist atomically, then publish, then release. Write to a temp file opened 0600 and os.replace it into position, all before assigning to in-memory state and before releasing the lock. Let persistence failures propagate. A token that exists only in RAM works until the next restart, at which point an unattended bot simply cannot start.
Gate write operations on the token's capability. At order-placement call sites, require a non-read-only token and fail locally. Discovering that your credential is read-only from a rejected order — 403 UDAPI100067 — is the expensive way to learn it.
Classify failures by Upstox's own error code, not by message text. UDAPI100050 (invalid/expired token) means re-authenticate. UDAPI100016 (invalid credentials) and UDAPI100073 (inactive client_id) are configuration faults that re-authentication will never fix — retrying them just burns login attempts.
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.
grant_type=refresh_token and no https://api.upstox.com/v2/login/auth/token endpoint. Any code, library, or generated snippet offering Upstox "refresh token rotation" is targeting an API surface that does not exist. (The similarly-spelled real endpoint, /v3/login/auth/token/request/{client_id}, is the user-approval flow — a different mechanism entirely.)now + expires_in, or now + 86400. The response has no expires_in, and validity is a fixed instant, not a duration. A token minted at 20:00 IST under this model is believed valid until 20:00 the next day — roughly 16.5 hours past its real death, spanning the entire next trading session. The bot reports itself authenticated while every call returns 401 UDAPI100050 from market open onward.expires_at from the notifier webhook as seconds. "1731448800000" interpreted as seconds dates the token to the year 56000 and silently disables every expiry check downstream. It is also a string, so a naive numeric comparison against time.time() raises rather than compares.{"status": "error", "errors": [{"error_code": ..., "message": ...}]}. Decode and inspect the envelope; note that the errorCode camelCase spelling is deprecated in favour of error_code, and both still appear in the wild.0600 from the start rather than chmod-ing after, which leaves a window where it is world-readable.extended_token or Analytics Token for order flow. Both are read-only; order APIs reject them with 403 UDAPI100067. The extended_token arrives in the same Get Token response as the real access token, which makes it easy to bind the wrong one.UDAPI100016 or UDAPI100073 as if they were expiry. Bad credentials and an inactive client_id are not transient; a retry loop against them accomplishes nothing and can trip login throttles.issued + 86400, and that the next session's 09:15 IST market open falls after the real expiry — this is the regression the fixed-duration model failed."1731448800000" resolves to 2024-11-13 03:30:00 IST; confirm a seconds-valued timestamp is rejected rather than accepted.UDAPI100067, before any order is sent.0600, contains no refresh_token field, and leaves no .tmp file behind.python -m unittest discover -s skills/upstox-oauth-refresh-token-rotation/scripts and confirm all tests pass.headless-broker-auth-patternstoken-lifecycle-live-probingmulti-broker-rate-limit-handlingsecrets-rotation-without-bot-downtimeindia-sebi-algo-trading-tagging-requirementswebhook-based-order-fill-notificationsWhat 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