Market Data Feed WebSocket v3 – 401/403 issue, permission required

Hello Upstox Team,

I have successfully created an Upstox developer app and generated access token.
I am able to get authorizedRedirectUri from
/v3/feed/market-data-feed/authorize endpoint.

However, when I try to connect to the WebSocket URL, I consistently receive
401 Unauthorized / 403 Forbidden handshake errors.

I believe my account or app does not yet have Market Data Feed (WebSocket v3)
permission enabled.

Request you to please enable Market Data Feed WebSocket v3 access
for my developer account.

Use case: Algo trading (BANKNIFTY / INDEX live LTP)

Thank you.

@Daksha_52810511

The 401/403 WebSocket handshake errors indicate that either:

  1. Your access token lacks WebSocket market data feed permissions
  2. The authorizedRedirectUri is invalid or expired
  3. 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

  1. Log in to Upstox Developer Console
  2. Navigate to your app settings
  3. Check under “Permissions” or “API Access”
  4. Look for:
    • “Market Data WebSocket Feed” or “WebSocket v3” permission
    • Should show “Enabled” or “Active”
  5. 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

:cross_mark: Token Expired: authorizedRedirectUri tokens expire in ~30 seconds

  • Solution: Fetch a fresh authorizedRedirectUri immediately before WebSocket connection

:cross_mark: Wrong Instrument Format: Invalid instrument keys in subscription

  • Solution: Use exact format like “NSE_FO|BANKNIFTY25FEB24C51000”

:cross_mark: WebSocket Permission Not Enabled: Most common cause

  • Solution: Request from Upstox support (see Step 3)

:cross_mark: 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:

  1. Check your app settings (2 min) - Verify WebSocket permission status
  2. Send request to Upstox (if not enabled) - Include app ID and use case
  3. Debug token expiry - Fetch fresh authorizedRedirectUri immediately before connecting
  4. 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

Hello Team,

Thank you for the detailed explanation.

I confirm that:

  • My REST APIs are working fine
  • Access token is valid
  • authorizedRedirectUri is being generated successfully

However, in my developer console, I do not see Market Data WebSocket v3
permission enabled for my app.

Request you to please enable WebSocket v3 Market Data Feed access
for my developer account.

Use case:
Algo trading – Live LTP for BANKNIFTY / Index instruments.

If any app-specific details are required (App ID, etc.),
I can share them via private message or email.

Thank you for your support.