import json
import websocket
import MarketDataFeed_pb2 as mdf
Load your access token
with open(“upstox_token.json”) as f:
token = json.load(f)[“access_token”]
WebSocket URL (V3 feed)
WS_URL = f"wss://api-v2.upstox.com/feed/market-data-feed/v3?access_token={token}"
Instrument keys (add more as needed, e.g. full Nifty50)
nifty50 = [
“NSE_EQ|INE002A01018”, # RELIANCE
“NSE_EQ|INE467B01029”, # TCS
]
def on_open(ws):
print(“
Connected to Upstox V3 WebSocket”)
# Subscribe message
sub_req = {
"guid": "abc123",
"method": "sub",
"data": {
"mode": "full",
"instrumentKeys": nifty50
}
}
ws.send(json.dumps(sub_req))
print("📡 Subscription request sent")
def on_message(ws, message):
try:
feed = mdf.FeedResponse()
feed.ParseFromString(message)
for key, data in feed.feeds.items():
if data.marketFull.ltp:
print(f"
{key} | LTP: {data.marketFull.ltp} | Volume: {data.marketFull.vol}")
except Exception as e:
print(“
Decode error:”, e)
def on_error(ws, error):
print(“
Error:”, error)
def on_close(ws, close_status_code, close_msg):
print(“
Connection closed”)
if name == “main”:
print(“
Connecting to V3 WebSocket…”)
ws = websocket.WebSocketApp(
WS_URL,
on_open=on_open,
on_message=on_message,
on_error=on_error,
on_close=on_close
)
On running this python code this error are coming again and again . i done all the necessary step login and generating access token
ws.run_forever()
Connecting to V3 WebSocket…
Error: Handshake status 401 Unauthorized -±± {‘date’: ‘Sun, 07 Sep 2025 05:33:00 GMT’, ‘content-type’: ‘application/json’, ‘transfer-encoding’: ‘chunked’, ‘connection’: ‘keep-alive’, ‘reqid’: ‘382ff59a-07c8-49d7-a4a8-af1d86c5f01a’, ‘x-content-type-options’: ‘nosniff’, ‘x-xss-protection’: ‘0’, ‘pragma’: ‘no-cache’, ‘strict-transport-security’: ‘max-age=0; includeSubDomains’, ‘x-frame-options’: ‘DENY’, ‘cache-control’: ‘must-revalidate,no-cache,no-store’, ‘vary’: ‘Access-Control-Request-Headers’, ‘message’: ‘request failed’, ‘cf-cache-status’: ‘DYNAMIC’, ‘set-cookie’: ‘__cf_bm=1p5_y5jEsP5nbgEWuzuqHI6kmepIVS6F3EJBRz1FBo0-1757223180-1.0.1.1-cDTf2t.2q3rOJ7JveZCoPeR9KmMBo6o1CJWxWWuBGIEF5J_ljwuLJrlCAh2olX0n; path=/; expires=Sun, 07-Sep-25 06:03:00 GMT; domain=.upstox.com; HttpOnly; Secure; _cfuvid=8F7rs2mgkMycRIgXfzuOL4.SGzgXIfki0jMYN9iIqD8-1757223180638-0.0.1.1-604800000; path=/; domain=.upstox.com; HttpOnly; Secure; SameSite=None’, ‘server’: ‘cloudflare’, ‘cf-ray’: ‘97b3d42ce9a821dd-CCU’, ‘alt-svc’: ‘h3=“:443”; ma=86400’} -±± None
Connection closed
Process finished with exit code 0