Hi @RAJA_NAGA_5275531,
Excellent questions - these are fundamental architectural decisions. I’ll address each based on Upstox API design and SEBI compliance requirements.
QUESTION 1: Multi-User OAuth Onboarding
YES - Single app CAN manage multiple Upstox accounts
Upstox OAuth2.0 supports this model:
Architecture:
- One app = One
client_id + client_secret + One redirect URI
- Multiple users = Multiple OAuth flows through the same redirect URI
- Each user gets their own
auth_code after consent
- Each auth_code exchanges for that user’s unique
access_token
Implementation Pattern:
User A → Redirect to Upstox OAuth → User A grants permission → auth_code_A → access_token_A
User B → Redirect to Upstox OAuth → User B grants permission → auth_code_B → access_token_B
User C → Redirect to Upstox OAuth → User C grants permission → auth_code_C → access_token_C
Your Redirect URI handles all three flows - Upstox passes state parameter to identify which user is completing OAuth.
Best Practice:
# Store state mapping
state_to_user_mapping = {
"unique_state_123": "user_a_id",
"unique_state_456": "user_b_id",
}
# In OAuth callback
user_id = state_to_user_mapping.get(request.args.get('state'))
auth_code = request.args.get('code')
access_token = upstox_client.exchange_code_for_token(auth_code) # User-specific
save_user_token(user_id, access_token) # Database
QUESTION 2: Unique Access Tokens Per User
YES - Each user gets unique token; backend can store multiple tokens
Token Architecture:
- Each
access_token is user-specific - bound to that Upstox account
- Tokens are short-lived (typically 24 hours at Upstox)
- Refresh tokens are long-lived (multiple months) - enable silent re-authentication
Storage Pattern (SECURE):
# Database schema
class UserTokens(db.Model):
user_id = db.Column(db.String, primary_key=True)
access_token = db.Column(db.String) # Encrypted
refresh_token = db.Column(db.String) # Encrypted (AES-256)
token_expiry = db.Column(db.DateTime)
encrypted_at = db.Column(db.DateTime)
# Encryption in production
from cryptography.fernet import Fernet
cipher = Fernet(encryption_key)
encrypted_token = cipher.encrypt(access_token.encode())
# Store encrypted
user_token = UserTokens(
user_id="user_123",
access_token=encrypted_token,
refresh_token=cipher.encrypt(refresh_token.encode()),
token_expiry=datetime.utcnow() + timedelta(hours=24)
)
db.session.add(user_token)
db.session.commit()
Token Refresh Logic:
def get_valid_token(user_id):
token_record = UserTokens.query.filter_by(user_id=user_id).first()
# Check if expired
if datetime.utcnow() > token_record.token_expiry:
# Refresh using refresh_token
new_token = upstox_client.refresh_access_token(
refresh_token=cipher.decrypt(token_record.refresh_token.encode())
)
token_record.access_token = cipher.encrypt(new_token['access_token'].encode())
token_record.token_expiry = datetime.utcnow() + timedelta(hours=24)
db.session.commit()
return cipher.decrypt(token_record.access_token.encode()).decode()
QUESTION 3: Multi-User Order Placement from Single Backend
YES - Allowed IF correct user’s token is used per request
How It Works:
- Each order request requires:
Authorization: Bearer <user_specific_token>
- Upstox API validates token matches the order context
- Order is placed in that user’s account only
- Cannot place orders “for” another user (cross-trading prohibited)
Compliant Order Execution Pattern:
def place_order_for_user(user_id, order_params):
# Get user's token
access_token = get_valid_token(user_id)
# Set correct authorization
headers = {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json"
}
# Place order - ONLY in user_id's account
response = requests.post(
"https://api.upstox.com/v2/order/place",
headers=headers,
json={
"quantity": order_params['qty'],
"price": order_params['price'],
"instrument_token": order_params['token'],
"order_type": order_params['type'],
"validity": "DAY",
}
)
if response.status_code == 200:
order_id = response.json()['data']['order_id']
log_order(user_id, order_id) # Audit trail
return order_id
else:
raise Exception(f"Order failed for {user_id}: {response.text}")
# Batch placement for multiple users
users_to_trade = ['user_1', 'user_2', 'user_3']
for user_id in users_to_trade:
try:
order_id = place_order_for_user(user_id, order_params)
print(f"✓ Order {order_id} placed for {user_id}")
except Exception as e:
print(f"✗ Failed for {user_id}: {e}")
# CRITICAL: Log failure for compliance audit
Critical Compliance Point:
- Each order must have audit trail: who placed it, when, token used, outcome
- SEBI requires this for algo trading platforms
QUESTION 4: API Rate Limits for Multi-User Orders
NEEDS OFFICIAL CONFIRMATION - This is critical
Likely Rate Limits (based on broker patterns):
- Per-user: ~10 orders/second
- Per-app: ~100 orders/second (aggregate)
- Daily order volume limits: May apply
What You MUST Verify with Upstox:
- Are rate limits enforced per user-token or per app?
- What happens when rate limit exceeded? (Response code)
- Is there a burst allowance or strict enforcement?
- Any throttling for multi-user scenarios?
Recommended Rate Limiting Implementation:
from redis import Redis
from time import time
redis_client = Redis()
def check_rate_limit(user_id, max_orders_per_second=10):
key = f"rate_limit:{user_id}"
current_count = redis_client.incr(key)
if current_count == 1:
redis_client.expire(key, 1) # Reset every second
if current_count > max_orders_per_second:
raise RateLimitError(f"User {user_id} exceeded {max_orders_per_second} orders/sec")
return True
def place_order_rate_limited(user_id, order_params):
check_rate_limit(user_id)
return place_order_for_user(user_id, order_params)
ACTION REQUIRED: Contact Upstox support with your use case to get specific rate limits.
QUESTION 5: Algo Vendor Registration Requirement
LIKELY YES - Required for multi-client automated trading
When Algo Vendor Registration IS Required:
You’re building a platform for multiple external clients
Clients pay you for algorithmic trading services
You place orders programmatically for non-proprietary trading
You provide trading automation as a service
When Algo Vendor Registration IS NOT Required:
Single individual managing own multiple accounts
Proprietary trading (trading with your own capital only)
Internal company algo (employees only, not external clients)
Your Use Case Analysis:
Based on “multiple clients” + “automated execution,” you likely need Algo Vendor Registration.
SEBI Compliance Framework for Algo Vendors:
-
Entity Requirements:
- Must be a registered entity (individual with DP code, or company)
- Must have SEBI Algo Trader Registration (if applicable tier)
- PAN + KYC verification required
- Audited financials (for companies)
-
Technical Controls Required:
- Order execution audit trails (timestamp, price, qty, user)
- Real-time risk monitoring
- Kill switches for each client
- Order rejection system for safety limits
- Network security (SSL/TLS, IP whitelisting)
-
Operational Controls:
- Client segregation (no cross-trading)
- Margin availability checks before order
- Daily settlement reconciliation
- Monthly compliance reports
Upstox Algo Vendor Registration Process (Typical - VERIFY):
Step 1: Entity Setup
- Register as Algo Trader with SEBI (if required tier)
- Open individual DP account or company trading account at Upstox
- Ensure PAN + KYC complete
Step 2: Application to Upstox
- Email: developer@upstox.com (or use developer portal)
- Subject: "Algo Vendor Registration Request"
- Include:
* Business description
* Number of clients you'll serve
* Trading strategies (brief)
* Technical architecture doc
* SEBI registration documents (if applicable)
* Risk management policies
* Compliance officer contact
Step 3: Review & Approval
- Upstox reviews compliance requirements
- May request technical documentation
- May request live trading demo
- Approval or rejection within 15-30 days
Step 4: Activated Access
- Higher API rate limits
- Multi-user token support
- Batch order endpoints (if available)
- Direct support contact
Critical Actions BEFORE Integration:
-
Contact Upstox Support:
Subject: "Multi-client Algo Execution - Compliance Check"
Questions:
- Do we need Algo Vendor registration for multi-user automated trading?
- What are the current rate limits for multi-user scenarios?
- What documentation is required?
- What is the approval timeline?
-
Consult SEBI Guidelines:
- Reference: “SEBI Algo Trading Regulations”
- Key: Client segregation + Audit trails
- Review: Risk management framework requirements
-
Legal Review:
- Ensure TOS with your clients mention algo trading
- Include disclaimers about execution risks
- Document consent from clients for API integration
SUMMARY TABLE
| Question |
Answer |
Action Required |
| Q1: Multi-user OAuth |
YES |
Implement state management |
| Q2: Unique tokens |
YES |
Secure encryption for storage |
| Q3: Multi-user orders |
YES* |
Contact Upstox for compliance |
| Q4: Rate limits |
UNKNOWN |
CRITICAL: Get official limits |
| Q5: Algo Vendor Reg |
LIKELY YES |
CRITICAL: Verify with Upstox |
IMMEDIATE NEXT STEPS
-
Email Upstox Support with:
- Clarification on Q4 rate limits
- Confirmation on Q5 Algo Vendor requirement
- Your specific client count + order volume estimates
-
Implement Secure Token Storage (don’t wait for approval)
- AES-256 encryption for tokens
- Separate key management (HSM if possible)
- Access logs for all token usage
-
Build Audit Trail System:
- Log every order: timestamp, user_id, token_hash, order_params, result
- Store in tamper-proof database
- Monthly compliance reports
-
Get Legal Clearance:
- Review client agreements
- Ensure compliance documentation
- SEBI algo trading rules
Key Takeaway: Your architecture is fundamentally sound and OAuth + multi-token approach is the right pattern. The blockers are regulatory (Algo Vendor status + rate limits), not technical. Get official clarification on those two items before going live.
Happy to discuss implementation details for any of these questions.
-VENKATA