A lightweight Python package that simplifies Upstox API authentication by handling TOTP-based login and token generation automatically. With this library, you can securely generate and refresh access tokens required to connect to the Upstox trading platform without manual intervention.
Project description
Upstox TOTP Python SDK
A modern, lightweight Python package that simplifies Upstox API authentication by handling TOTP-based login and token generation automatically. With this library, you can securely generate and refresh access tokens required to connect to the Upstox trading platform without manual intervention.
๐ Features
- ๐ Automated TOTP Authentication โ Generate secure time-based one-time passwords (TOTP) for Upstox login
- โก Token Management โ Fetch, refresh, and store Upstox access tokens with ease
- ๐ ๏ธ Simple API โ Minimal, developer-friendly methods for quick integration
- ๐ Trading Ready โ Instantly plug into Upstox APIs for real-time market data, order placement, and portfolio management
- ๐ Pythonic Design โ Built with modern async/session handling for robust performance
- ๐ฏ CLI Tool โ Command-line interface for quick token generation
- ๐ง Environment Configuration โ Auto-configuration from environment variables
- ๐ก Helpful Error Messages โ Clear error messages with troubleshooting guidance
- ๐ Secure by Design โ Uses secure SecretStr for sensitive data handling
- ๐ Comprehensive Documentation โ Detailed guides and API reference at upstox-totp.readthedocs.io
๐ Table of Contents
- ๐ Features
- ๐ Table of Contents
- ๐ฏ Quick Start
- โ๏ธ Configuration
- ๐ง Advanced Usage
- ๐ API Reference
- ๐ Documentation
- ๐ ๏ธ CLI Commands
- ๐ Security Best Practices
- ๐จ Troubleshooting
- ๐ Integration Examples
- ๐ Examples
- ๐ค Contributing
- ๐ Requirements
- ๐ License
- โ ๏ธ Important Notes
- ๐ Acknowledgments
๐ฏ Quick Start
Requires Python 3.12 or higher
Installation
# Add as a dependency to your project
uv add upstox-totp
# Or install with pip
pip install upstox-totp
Python SDK Usage
from upstox_totp import UpstoxTOTP
# Initialize (auto-loads from environment variables or .env file)
upx = UpstoxTOTP()
# Generate access token
try:
response = upx.app_token.get_access_token()
if response.success and response.data:
print(f"โ
Access Token: {response.data.access_token}")
print(f"๐ค User: {response.data.user_name} ({response.data.user_id})")
print(f"๐ง Email: {response.data.email}")
print(f"๐ข Broker: {response.data.broker}")
print(f"๐ Products: {', '.join(response.data.products)}")
print(f"๐๏ธ Exchanges: {', '.join(response.data.exchanges)}")
# Use the token for Upstox API calls
access_token = response.data.access_token
except Exception as e:
print(f"โ Error: {e}")
CLI Tool Usage
# Check if environment is properly configured
upstox_cli check-env
# Generate access token
upstox_cli generate-token
Example CLI output:
โฏ upstox_cli generate-token
๐ Access token generated successfully!
Token Details:
Access Token: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...
User ID: BAT123
User Name: Batman
User Type: individual
Broker: UPSTOX
Email: batman@arkham.com
Products: D, I, CO, MIS
Exchanges: NSE_EQ, BSE_EQ, NSE_FO, NSE_CD, BSE_FO, BSE_CD, MCX_FO
Is Active: True
๐ก You can now use this access token to make authenticated API calls to Upstox.
โ๏ธ Configuration
Environment Variables
Create a .env file or set environment variables:
# Required - Your Upstox account credentials
UPSTOX_USERNAME=your-mobile-number # 10-digit mobile number
UPSTOX_PASSWORD=your-password # Your Upstox password
UPSTOX_PIN_CODE=your-pin # Your Upstox PIN code
# Required - TOTP secret from your Upstox app setup
UPSTOX_TOTP_SECRET=your-totp-secret # TOTP secret key
# Required - OAuth app credentials from Upstox Developer Console
UPSTOX_CLIENT_ID=your-client-id # API key from app generation
UPSTOX_CLIENT_SECRET=your-client-secret # API secret from app generation
UPSTOX_REDIRECT_URI=your-redirect-uri # Must match app settings
# Optional
UPSTOX_DEBUG=false # Enable debug logging
UPSTOX_SLEEP_TIME=1000 # Request delay in milliseconds
Python Configuration
from upstox_totp import UpstoxTOTP
from pydantic import SecretStr
# Method 1: Auto-load from environment
upx = UpstoxTOTP()
# Method 2: Load from specific .env file
upx = UpstoxTOTP.from_env_file(".env.production")
# Method 3: Manual configuration
upx = UpstoxTOTP(
username="9876543210",
password=SecretStr("your-password"),
pin_code=SecretStr("your-pin"),
totp_secret=SecretStr("your-totp-secret"),
client_id="your-client-id",
client_secret=SecretStr("your-client-secret"),
redirect_uri="https://your-app.com/callback",
debug=True
)
๐ง Advanced Usage
Context Manager
from upstox_totp import UpstoxTOTP
# Use as context manager for automatic cleanup
with UpstoxTOTP() as upx:
response = upx.app_token.get_access_token()
if response.success:
access_token = response.data.access_token
# Use token for API calls
Session Management
# Access the underlying HTTP session
upx = UpstoxTOTP()
session = upx.session
# Reset session if needed (clears cookies, headers, etc.)
upx.reset_session()
# Generate new request ID
request_id = upx.generate_request_id()
TOTP Generation
# Generate TOTP manually
upx = UpstoxTOTP()
totp_code = upx.generate_totp_secret()
print(f"Current TOTP: {totp_code}")
Error Handling
from upstox_totp import UpstoxTOTP, UpstoxError, ConfigurationError
try:
upx = UpstoxTOTP()
response = upx.app_token.get_access_token()
except ConfigurationError as e:
print(f"Configuration Error: {e}")
print("๐ก Check your environment variables in .env file")
except UpstoxError as e:
print(f"Upstox API Error: {e}")
# Error includes helpful troubleshooting tips
except Exception as e:
print(f"Unexpected Error: {e}")
๐ API Reference
Main Classes
UpstoxTOTP- Main client class for TOTP authenticationAccessTokenResponse- Response model for access token dataUpstoxError- Custom exception with helpful error messagesConfigurationError- Raised when configuration is invalid
Response Models
All API responses follow a consistent structure:
class ResponseBase:
success: bool # Whether the request was successful
data: T | None # Response data (varies by endpoint)
error: dict | None # Error details if request failed
Access Token Data
class AccessTokenData:
access_token: str # Your Upstox access token
user_id: str # Your user ID
user_name: str # Your display name
email: str # Your email address
broker: str # Broker name (UPSTOX)
user_type: str # Account type
products: list[str] # Available product types
exchanges: list[str] # Available exchanges
is_active: bool # Account status
# ... more fields
๐ Documentation
For comprehensive documentation, tutorials, and examples, visit our official documentation:
๐ upstox-totp.readthedocs.io
The documentation includes:
-
๐ User Guide
-
๐ API Reference
-
๐ก Examples & Tutorials
-
๐ก๏ธ Additional Information
๐ ๏ธ CLI Commands
Check Environment
Validate your configuration before generating tokens:
upstox_cli check-env
Generate Token
Generate access token for API usage:
upstox_cli generate-token
Help
Get help for any command:
upstox_cli --help
upstox_cli generate-token --help
๐ Security Best Practices
- Never commit secrets - Use
.envfiles and add them to.gitignore - Use SecretStr - Sensitive data is automatically protected from logs
- Environment variables - Store credentials in environment variables, not code
- Token rotation - Regenerate tokens regularly for security
- Debug mode - Disable debug mode in production to prevent credential leaks
๐จ Troubleshooting
Common Issues
Configuration Error: Missing environment variables
# Check what's missing
upstox_cli check-env
# Set required variables in .env file
echo "UPSTOX_USERNAME=9876543210" >> .env
echo "UPSTOX_PASSWORD=your-password" >> .env
# ... add other variables
Invalid Credentials Error
- Verify your username (should be 10-digit mobile number)
- Check password and PIN are correct
- Ensure TOTP secret is properly configured
Client ID / Redirect URI Error
- Verify client_id and client_secret in Upstox Developer Console
- Ensure redirect_uri exactly matches your app settings
- Check if your app is approved and active
TOTP Validation Failed
- Verify your TOTP secret is correct
- Check system time is synchronized
- Ensure TOTP secret format is valid (no spaces, correct encoding)
๐ Integration Examples
With Upstox API
import requests
from upstox_totp import UpstoxTOTP
# Get access token
upx = UpstoxTOTP()
token_response = upx.app_token.get_access_token()
access_token = token_response.data.access_token
# Use token with Upstox API
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json'
}
# Get user profile
response = requests.get(
'https://api.upstox.com/v2/user/profile',
headers=headers
)
print(response.json())
# Get positions
response = requests.get(
'https://api.upstox.com/v2/portfolio/long-term-positions',
headers=headers
)
print(response.json())
Automated Token Refresh with Caching
import time
import json
from datetime import datetime, timedelta
from upstox_totp import UpstoxTOTP
class UpstoxClient:
def __init__(self, cache_file="upstox_token.json"):
self.upx = UpstoxTOTP()
self.cache_file = cache_file
self.access_token = None
self.token_expiry = None
self.load_cached_token()
def load_cached_token(self):
"""Load token from cache if still valid"""
try:
with open(self.cache_file, 'r') as f:
data = json.load(f)
token_expiry = datetime.fromisoformat(data['expiry'])
# Check if token is still valid (with 1-hour buffer)
if token_expiry > datetime.now() + timedelta(hours=1):
self.access_token = data['token']
self.token_expiry = token_expiry
print("โ
Using cached token")
return
except (FileNotFoundError, KeyError, ValueError):
pass
# Cache miss or expired token - refresh
self.refresh_token()
def refresh_token(self):
"""Refresh access token and cache it"""
response = self.upx.app_token.get_access_token()
if response.success:
self.access_token = response.data.access_token
self.token_expiry = datetime.now() + timedelta(hours=24)
# Cache the token
with open(self.cache_file, 'w') as f:
json.dump({
'token': self.access_token,
'expiry': self.token_expiry.isoformat()
}, f)
print("โ
Token refreshed and cached successfully")
else:
raise Exception("Failed to refresh token")
def api_call(self, endpoint, **kwargs):
"""Make authenticated API call with auto-refresh"""
# Check if token needs refresh
if (self.token_expiry and
self.token_expiry < datetime.now() + timedelta(hours=1)):
print("๐ Token expiring soon, refreshing...")
self.refresh_token()
headers = kwargs.setdefault('headers', {})
headers['Authorization'] = f'Bearer {self.access_token}'
# Make your API call here
return requests.get(endpoint, **kwargs)
# Usage
client = UpstoxClient()
response = client.api_call('https://api.upstox.com/v2/user/profile')
Database Storage Example (SQLite)
import sqlite3
from datetime import datetime, timedelta
from upstox_totp import UpstoxTOTP
class UpstoxTokenManager:
def __init__(self, db_path="upstox.db"):
self.upx = UpstoxTOTP()
self.db_path = db_path
self.init_db()
def init_db(self):
"""Initialize database table"""
conn = sqlite3.connect(self.db_path)
conn.execute('''
CREATE TABLE IF NOT EXISTS tokens (
id INTEGER PRIMARY KEY,
access_token TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
expires_at TIMESTAMP NOT NULL
)
''')
conn.commit()
conn.close()
def get_valid_token(self):
"""Get valid token from DB or generate new one"""
conn = sqlite3.connect(self.db_path)
cursor = conn.execute('''
SELECT access_token, expires_at FROM tokens
WHERE expires_at > datetime('now', '+1 hour')
ORDER BY created_at DESC LIMIT 1
''')
result = cursor.fetchone()
conn.close()
if result:
print("โ
Using cached token from database")
return result[0]
# Generate new token
return self.refresh_and_store_token()
def refresh_and_store_token(self):
"""Generate new token and store in database"""
response = self.upx.app_token.get_access_token()
if not response.success:
raise Exception("Failed to generate token")
token = response.data.access_token
expires_at = datetime.now() + timedelta(hours=24)
conn = sqlite3.connect(self.db_path)
conn.execute('''
INSERT INTO tokens (access_token, expires_at)
VALUES (?, ?)
''', (token, expires_at))
conn.commit()
conn.close()
print("โ
New token generated and stored in database")
return token
# Usage
token_manager = UpstoxTokenManager()
access_token = token_manager.get_valid_token()
๐ Examples
Check out the examples/ directory for more comprehensive examples:
quickstart.py- Basic token generation- More examples coming soon!
๐ค Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Development Setup
# Clone the repository
git clone https://github.com/batpool/upstox-totp.git
cd upstox-totp
# Install dependencies with uv
uv sync
# Install development dependencies
uv sync --group dev
# Run tests
uv run pytest
# Format code
uv run black src/
uv run isort src/
๐ Requirements
- Python 3.12 or higher
- Active Upstox trading account
- Upstox Developer App (for client credentials)
- TOTP app setup (Google Authenticator, Authy, etc.)
๐ License
MIT License - see LICENSE file for details.
โ ๏ธ Important Notes
Token Management
๐ Access Token Expiry: Upstox access tokens have a 24-hour expiration time. For production applications, it's recommended to:
- Store tokens securely in a database or cache (Redis, etc.)
- Implement automatic token refresh logic
- Monitor token expiry and regenerate proactively
Disclaimer
This is an unofficial library for Upstox API authentication. Please ensure you comply with Upstox's terms of service and API usage guidelines. Use at your own risk.
๐ Acknowledgments
- Upstox for providing the trading platform and API
- Pydantic for excellent data validation
- pyOTP for TOTP implementation
- curl-cffi for HTTP client
Happy Trading! ๐
For questions or support, please open an issue on GitHub.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file upstox_totp-1.0.8.tar.gz.
File metadata
- Download URL: upstox_totp-1.0.8.tar.gz
- Upload date:
- Size: 19.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
092fccb07f000706c1b91490f434a789e4df40d63cee66f0a17b9feef8abdb56
|
|
| MD5 |
8114c103297324ba1deedc69283c45f8
|
|
| BLAKE2b-256 |
944304ed061db38f2e837a66cc2f7d7f973c45d27772725c70fff0c284c2ad18
|
Provenance
The following attestation bundles were made for upstox_totp-1.0.8.tar.gz:
Publisher:
release.yml on batpool/upstox-totp
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
upstox_totp-1.0.8.tar.gz -
Subject digest:
092fccb07f000706c1b91490f434a789e4df40d63cee66f0a17b9feef8abdb56 - Sigstore transparency entry: 549189557
- Sigstore integration time:
-
Permalink:
batpool/upstox-totp@3df2d933986e77b02ff5b3601d84aa2516202e77 -
Branch / Tag:
refs/heads/master - Owner: https://github.com/batpool
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@3df2d933986e77b02ff5b3601d84aa2516202e77 -
Trigger Event:
push
-
Statement type:
File details
Details for the file upstox_totp-1.0.8-py3-none-any.whl.
File metadata
- Download URL: upstox_totp-1.0.8-py3-none-any.whl
- Upload date:
- Size: 23.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3fa2a891ca70a1ad07f6ae59acca501ae9f074d901139bb622dafab171666bbf
|
|
| MD5 |
acc21883915654486e46134b30a6658c
|
|
| BLAKE2b-256 |
85485a50c65cd68dccc0eb93d7d300180dafa42df424d21c3c775fdd934d9b40
|
Provenance
The following attestation bundles were made for upstox_totp-1.0.8-py3-none-any.whl:
Publisher:
release.yml on batpool/upstox-totp
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
upstox_totp-1.0.8-py3-none-any.whl -
Subject digest:
3fa2a891ca70a1ad07f6ae59acca501ae9f074d901139bb622dafab171666bbf - Sigstore transparency entry: 549189586
- Sigstore integration time:
-
Permalink:
batpool/upstox-totp@3df2d933986e77b02ff5b3601d84aa2516202e77 -
Branch / Tag:
refs/heads/master - Owner: https://github.com/batpool
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@3df2d933986e77b02ff5b3601d84aa2516202e77 -
Trigger Event:
push
-
Statement type: