fetching the live market price through upstox api all work smooth finally reach the label
Subscribed to HDFC Equity
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"
Updated Row {row} for {symbol}”)
else:
print(“
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(“
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
import asyncio
import json
import ssl
import certifi
import websockets
import gspread
from google.oauth2.service_account import Credentials
=== Google Sheets Setup ===
SERVICE_ACCOUNT_FILE = ‘upstoxoptionchain-6ce257f0bde0.json’ #
Your credentials
SHEET_ID = ‘1-mDbPEJ9m1-_YMhleVFYJWujHMKaRMAyOp7HG56m_XA’ #
Your Sheet ID
Authorize and connect to 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)
api_sheet = client.open_by_key(SHEET_ID).worksheet(‘API’)
sheet = client.open_by_key(SHEET_ID).worksheet(‘HDFC’) #
You can rename this to ‘SBI’ if you want
=== Live WebSocket URL from sheet (B3)
ws_url = api_sheet.acell(“B3”).value.strip()
=== Instrument key for SBI Equity (confirmed working)
SBI_EQ = “NSE_EQ|INE062A01020”
=== Row where you want to write SBI data
row = “2” # You can put it in row 2 (A2 = SBI)
def update_sheet(symbol, data):
values = [
data.get(“ltp”, “”),
data.get(“open”, “”),
data.get(“high”, “”),
data.get(“low”, “”),
data.get(“prev_close”, “”)
]
sheet.update(f"B{row}:F{row}“, [values])
print(f"
Sheet Updated for SBI”)
# JSON Format Output
print("📦 SBI Live JSON:\n", json.dumps({
"instrument_key": symbol,
"ltp": data.get("ltp"),
"open": data.get("open"),
"high": data.get("high"),
"low": data.get("low"),
"prev_close": data.get("prev_close")
}, indent=2))
async def connect_ws():
ssl_context = ssl.create_default_context(cafile=certifi.where())
async with websockets.connect(ws_url, ssl=ssl_context) as ws:
await ws.send(json.dumps({
“guid”: “live123”,
“method”: “sub”,
“data”: {
“mode”: “ltp”, #
Use ‘ltp’ mode for faster reliable data
“instrumentKeys”: [SBI_EQ]
}
}))
print(“
Subscribed to SBI”)
while True:
try:
msg = await asyncio.wait_for(ws.recv(), timeout=10)
data = json.loads(msg)
if data.get("type") == "ltp":
for item in data.get("data", []):
symbol = item.get("instrument")
update_sheet(symbol, item)
else:
print("ℹ️ Other message:", data.get("type"))
except asyncio.TimeoutError:
print("⏳ No message in 10 seconds...")
except Exception as e:
print("❌ Error:", e)
Run the WebSocket connection
asyncio.run(connect_ws())
again i am getting same error can please share example i am very thankfull to you
Hi @MITHLESH_1873239 Which WebSocket version are you using? If you’re using the V3 WebSocket, make sure to properly encode and decode the payload. You can refer to the sample WebSocket example for guidance.
Let us know if this helps resolve the issue.