@Daksha_52810511
The 401/403 WebSocket handshake errors indicate that either:
- Your access token lacks WebSocket market data feed permissions
- The authorizedRedirectUri is invalid or expired
- Your account/app hasn’t been approved for WebSocket feeds yet
DIAGNOSIS CHECKLIST:
Step 1: Verify Your Access Token Has WebSocket Permissions
Your access token might work for REST APIs but NOT for WebSocket. Check the token’s scopes:
import requests
import json
# Decode your JWT token at jwt.io to check claims
# Or make a test REST API call to verify it works
headers = {"Authorization": f"Bearer {your_access_token}"}
response = requests.get(
"https://api.upstox.com/v2/user/profile",
headers=headers
)
print(response.json())
# If this works, your token is valid for REST APIs
# But it might NOT have WebSocket permissions
Step 2: Verify WebSocket Permissions Are Enabled
- Log in to Upstox Developer Console
- Navigate to your app settings
- Check under “Permissions” or “API Access”
- Look for:
- “Market Data WebSocket Feed” or “WebSocket v3” permission
- Should show “Enabled” or “Active”
- If NOT enabled, you need to request it
Step 3: Request WebSocket v3 Permission
Email Upstox Developer Support:
-
To: developer-support@upstox.com
-
Subject: Enable WebSocket v3 Market Data Feed - [Your App Name]
-
Provide:
App Name: [Your app name]
App ID: [Your app ID from dashboard]
Use Case: Algo trading (BANKNIFTY / INDEX live LTP)
Required Instruments:
- NSE_FO|BANKNIFTY (options/futures)
- NSE_EQ|NIFTY50 (spot index)
Reason: Real-time market data feed for algorithmic trading
Step 4: Debugging the Handshake Error
Before you connect to WebSocket, verify the authorizedRedirectUri:
# 1. Get authorizedRedirectUri
response = api_instance.get_market_data_feed_authorize()
auth_uri = response['data']['authorizedRedirectUri']
print(f"Auth URI: {auth_uri}")
# 2. Extract the token from URI
# The token should be embedded in the URI
# Example: wss://..?token=<JWT_TOKEN>
# 3. Try connecting immediately
# The token might expire within 30 seconds
import asyncio
import websockets
async def test_websocket():
try:
# Use the authorizedRedirectUri directly from the API response
async with websockets.connect(auth_uri) as websocket:
print("WebSocket connection successful!")
# Subscribe to data
subscribe_msg = {
"guid": "someguid",
"method": "sub",
"data": {
"mode": "ltpc", # LTP + Close
"instrumentKeys": [
"NSE_FO|BANKNIFTY25FEB24C51000"
]
}
}
await websocket.send(json.dumps(subscribe_msg))
print(await websocket.recv())
except Exception as e:
print(f"Connection error: {e}")
print(f"Status code in error: {e}")
asyncio.run(test_websocket())
Step 5: Common Causes of 401/403
Token Expired: authorizedRedirectUri tokens expire in ~30 seconds
- Solution: Fetch a fresh authorizedRedirectUri immediately before WebSocket connection
Wrong Instrument Format: Invalid instrument keys in subscription
- Solution: Use exact format like “NSE_FO|BANKNIFTY25FEB24C51000”
WebSocket Permission Not Enabled: Most common cause
- Solution: Request from Upstox support (see Step 3)
Account/KYC Restrictions: Your account might not have F&O clearance
- Solution: Check your trading account permissions on Upstox app
Step 6: Once Permissions Are Enabled
Test with this minimal working example:
import asyncio
import json
import websockets
from upstox_client.rest import ApiClient, Configuration
async def websocket_market_data():
# Initialize Upstox API
config = Configuration()
config.api_key['Authorization'] = 'Bearer ' + YOUR_ACCESS_TOKEN
api_client = ApiClient(config)
# Get fresh authorizedRedirectUri
from upstox_client.apis.websocket_api import WebsocketApi
ws_api = WebsocketApi(api_client)
response = ws_api.get_market_data_feed_authorize()
auth_uri = response['data']['authorizedRedirectUri']
print(f"Connecting to: {auth_uri}")
try:
async with websockets.connect(auth_uri, ping_interval=None) as websocket:
print("✓ WebSocket connected successfully!")
# Subscribe to BANKNIFTY options
subscribe = {
"guid": "web-1",
"method": "sub",
"data": {
"mode": "ltpc",
"instrumentKeys": [
"NSE_FO|BANKNIFTY25FEB24C51000", # Sample option
"NSE_EQ|NIFTY50" # Index
]
}
}
await websocket.send(json.dumps(subscribe))
# Receive data
while True:
msg = await websocket.recv()
data = json.loads(msg)
print(f"Received: {data}")
except Exception as e:
print(f"✗ Error: {e}")
if __name__ == '__main__':
asyncio.run(websocket_market_data())
IMMEDIATE ACTION:
- Check your app settings (2 min) - Verify WebSocket permission status
- Send request to Upstox (if not enabled) - Include app ID and use case
- Debug token expiry - Fetch fresh authorizedRedirectUri immediately before connecting
- Test with sample code above once permissions are confirmed
The 401/403 errors are almost always due to missing WebSocket v3 permissions, which require explicit approval from Upstox. Your REST APIs work because they’re enabled by default, but WebSocket feed is separately gated.
Let me know once you get permission approval and I can help with implementation issues!
-VENKATA