WebSocket Error: Handshake status 403 Forbidden -±± {‘date’: ‘Mon, 10 Feb 2025 08:55:28 GMT’, ‘transfer-encoding’: ‘chunked’, ‘connection’: ‘keep-alive’} -±± None
WebSocket Connection Closed
Hi @Nithya_Om,
We are checking this and will get back to you soon. Thanks.
THIS IS MY CODE.
import pandas as pd
import requests
import websocket
import json
import time
=== STEP 1: Read Access Token from Excel ===
EXCEL_FILE = r"C:\TEST\token.xlsx" # Ensure correct file path
try:
df = pd.read_excel(EXCEL_FILE) # Read Excel normally
ACCESS_TOKEN = str(df.iloc[0, 0]).strip() if “access_token” not in df.iloc[0, 0] else str(df.iloc[1, 0]).strip()
print(f" Read Access Token from Excel: {ACCESS_TOKEN.encode()}“) # Debugging
except Exception as e:
print(f" Error reading Excel file: {e}”)
exit(1)
=== STEP 2: Get WebSocket URL ===
def get_websocket_url():
url = “https://api.upstox.com/v3/feed/market-data-feed/authorize”
headers = {
“Authorization”: f"Bearer {ACCESS_TOKEN}",
“Accept”: “application/json”,
}
try:
response = requests.get(url, headers=headers)
response_json = response.json()
if response_json.get("status") == "success":
ws_url = response_json["data"]["authorized_redirect_uri"]
print(f"✅ Fresh WebSocket URL: {ws_url}")
return ws_url
else:
print(f"❌ Failed to fetch WebSocket URL: {json.dumps(response_json, indent=2)}")
exit(1)
except Exception as e:
print(f"❌ Request Error: {e}")
exit(1)
Get WebSocket URL
WEBSOCKET_URL = get_websocket_url()
=== STEP 3: WebSocket Connection ===
def on_message(ws, message):
“”" Handles incoming WebSocket messages “”"
print(f" Market Data: {message}")
def on_error(ws, error):
“”" Handles WebSocket errors “”"
print(f" WebSocket Error: {error}")
def on_close(ws, close_status_code, close_msg):
“”" Handles WebSocket closure “”"
print(“ WebSocket Connection Closed”)
def on_open(ws):
“”" Subscribes to market data upon WebSocket connection “”"
print(“ WebSocket Connection Opened”)
subscription_message = {
“type”: “subscribe”,
“tokens”: [“NSE_EQ|2885”, “NSE_EQ|1594”] # Modify with required stock symbols
}
ws.send(json.dumps(subscription_message))
print(“ Subscription Request Sent”)
Connect WebSocket
ws = websocket.WebSocketApp(
WEBSOCKET_URL,
header=[f"Authorization: Bearer {ACCESS_TOKEN}"],
on_message=on_message,
on_error=on_error,
on_close=on_close
)
ws.on_open = on_open
=== STEP 4: Run WebSocket Listener ===
print(“ Connecting to WebSocket…”)
ws.run_forever()
Hi @Nithya_Om
The new v3 WebSocket supports only a single connection. If you attempt to establish multiple connections, you will receive a 403 Forbidden error.
For more details, please refer to the v3 WebSocket documentation.
Kindly try again with a single WebSocket connection and let us know if you face any issues.
Thank you!