Data Fetching Issue Through Websocket

fetching the live market price through upstox api all work smooth finally reach the label :white_check_mark: Subscribed to HDFC Equity
:hourglass_not_done: No message received in 10 seconds… how can i resolve this issue

Hi @MITHLESH_1873239 Please refer to the WebSocket implementation here.

If you’re still encountering the same issue, kindly share your code so we can assist you further.

import asyncio
import json
import websockets
import ssl
import certifi
import gspread
from google.oauth2.service_account import Credentials

=== Google Sheets Setup ===

SERVICE_ACCOUNT_FILE = ‘upstoxoptionchain-6ce257f0bde0.json’
SHEET_ID = ‘1-mDbPEJ9m1-_YMhleVFYJWujHMKaRMAyOp7HG56m_XA’

Authorize Google Sheets

scope = [‘https://spreadsheets.google.com/feeds’, ‘https://www.googleapis.com/auth/drive’]
creds = Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=scope)
client = gspread.authorize(creds)

Worksheets

api_sheet = client.open_by_key(SHEET_ID).worksheet(‘API’)
hdfc_sheet = client.open_by_key(SHEET_ID).worksheet(‘HDFC’)

WebSocket URL from cell B3

ws_url = api_sheet.acell(“B3”).value.strip()

Instrument tokens

HDFC_EQUITY = “NSE_EQ|INE040A01034”
HDFC_FUTURE = “NSE_FO|HDFC24JUNFUT” # Update this monthly
NIFTY50_INDEX = “NSE_INDEX|Nifty 50”

Map symbols to rows

symbol_to_row = {
HDFC_EQUITY: “2”,
HDFC_FUTURE: “3”,
NIFTY50_INDEX: “4”
}

Update row in sheet

def update_sheet(symbol, data):
values = [
data.get(“ltp”, “”),
data.get(“open”, “”),
data.get(“high”, “”),
data.get(“low”, “”),
data.get(“prev_close”, “”)
]
row = symbol_to_row.get(symbol)
if row:
hdfc_sheet.update(f"B{row}:F{row}“, [values])
print(f":white_check_mark: Updated Row {row} for {symbol}”)
else:
print(“:warning: Unknown symbol received:”, symbol)

Connect to WebSocket

async def connect_upstox_ws():
ssl_context = ssl.create_default_context(cafile=certifi.where())
async with websockets.connect(ws_url, ssl=ssl_context) as ws:
subscribe_msg = {
“guid”: “auto123”,
“method”: “sub”,
“data”: {
“mode”: “full”,
“instrumentKeys”: [HDFC_EQUITY, HDFC_FUTURE, NIFTY50_INDEX]
}
}
await ws.send(json.dumps(subscribe_msg))
print(“:satellite_antenna: Subscribed to WebSocket”)

    while True:
        try:
            msg = await asyncio.wait_for(ws.recv(), timeout=10)
            data = json.loads(msg)

            if data.get("type") == "full":
                for item in data.get("data", []):
                    symbol = item.get("instrument")
                    update_sheet(symbol, item)
            else:
                print("ℹ️ Received other data type:", data.get("type"))

        except asyncio.TimeoutError:
            print("⏳ No message received in 10 seconds...")
        except Exception as e:
            print("❌ Error:", e)

Run

asyncio.run(connect_upstox_ws())

@MITHLESH_1873239 It seems you are requesting for wrong instrument_key format

Please refer to the Instrument JSON file for the correct instrument_key