Building a Production-Ready OAuth2 Automation SDK for Upstox
[STATUS: PUBLISHED OPEN SOURCE LIBRARY]
upstox-auth-pro (v1.1.3) is published on PyPI. It automates Upstox OAuth2 authentication, Playwright TOTP 2FA, token persistence, and retry diagnostics.
1. The Problem: Daily Interactive Authentication Breakage
Financial regulations mandate daily OAuth2 token expiry for trading APIs. Automated trading systems require fresh authorization codes every morning before market open (09:15 IST). Requiring manual browser logins every 24 hours breaks automated scheduling.
2. OAuth2 Automation Sequence Architecture
Upstox Auth Pro Automation Sequence
sequenceDiagram
autonumber
participant App as Client Application
participant SDK as UpstoxAuthPro SDK
participant Browser as Playwright Headless Engine
participant Upstox as Upstox Auth Server
participant Storage as Pluggable Token Store
App->>SDK: get_valid_token()
SDK->>Storage: Read Cached Token
alt Token Cached & Valid (< 24h IST)
Storage-->>SDK: Active Access Token
SDK-->>App: Return Access Token
else Token Expired / Missing
SDK->>Browser: Launch Headless Chromium Session
Browser->>Upstox: Navigate OAuth Login URL
Upstox-->>Browser: Prompt Mobile / PIN
Browser->>Upstox: Input Mobile & PIN
SDK->>SDK: Calculate TOTP 2FA via pyotp
Browser->>Upstox: Submit 6-digit TOTP
Upstox-->>Browser: Redirect with Auth Code
Browser-->>SDK: Extract Authorization Code
SDK->>Upstox: Exchange Code for Access Token
Upstox-->>SDK: Return Token Payload & Expiry
SDK->>Storage: Save Token & IST Expiry Metadata
SDK-->>App: Return Valid Access Token
end
Diagram 1: Interactive sequence flow during automated daily OAuth2 token acquisition.
3. SDK Usage & Installation
pip install upstox-auth-pro
from upstox_auth_pro import UpstoxAuthManager, JSONTokenStorage
storage = JSONTokenStorage("tokens.json")
auth_manager = UpstoxAuthManager(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
redirect_uri="https://127.0.0.1:5000/callback",
mobile_no="YOUR_MOBILE",
pin="YOUR_PIN",
totp_secret="YOUR_TOTP_SECRET",
storage=storage
)
# Returns active cached token or executes automated login if expired
access_token = auth_manager.get_valid_token()
print(f"Active Token: {access_token[:10]}...")
4. Engineering Decisions & Tradeoffs
| Decision | Rationale | Tradeoff |
|---|---|---|
| Playwright Headless Browser | Automates full browser JS rendering and TOTP form submit. | Requires headless browser binary installation (~150MB). |
| Pluggable Storage Strategy | Abstract interface supporting JSON file, Redis, or DB token persistence. | Requires explicit storage class injection during initialization. |
| Stealth Mode & Retries | Masks `navigator.webdriver` and captures diagnostic screenshots on fail. | Slightly increases authentication execution time by 500ms. |
Related Engineering Articles
- Designing a Real-Time Market Data Pipeline for Algorithmic Trading
- Designing an AI Trading System Without Letting the Model Control Everything