Im facing issue while fetching live feed for nifty option data

Below code snippet which i have used to live feed nifty options.
Output is comming till
“Waiting for data…”
OUTPUT:
hi
success
Connection established
Waiting for data…
State.OPEN

next to that control is not moving next line to statement
message = await websocket.recv()

as per my understanding no data is being received into websocket object and kept inhold in this line. below is the output for your reference. can you help , what i need to change in this?.

from threading import Thread
import asyncio
import json
import ssl
import upstox_client
import websockets
from google.protobuf.json_format import MessageToDict
import MarketDataFeed_pb2 as pb

async def fetch_market_data():
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
configuration = upstox_client.Configuration()
api_version = ‘2.0’
configuration.access_token = ‘’ # Replace with your actual access token
api_instance = upstox_client.WebsocketApi(upstox_client.ApiClient(configuration))
response = api_instance.get_market_data_feed_authorize(api_version)
#response = get_market_data_feed_authorize(api_version, configuration)
print(response.status)

async with websockets.connect(response.data.authorized_redirect_uri, ssl=ssl_context) as websocket:
    print('Connection established')
    await asyncio.sleep(1)  # Wait for 1 second

    data = {
        "guid": 'NOV2323B19700CE',
        "method": "sub",
        "data": {
            "mode": "ltpc",
            "instrumentKeys": 'NSE_FO|48289',
        }
    }

    binary_data = json.dumps(data).encode('utf-8')
    await websocket.send(binary_data)
    try:
        print('Waiting for data...')
        print(websocket.state)
        message = await websocket.recv()
        print('Received raw data:', message)

        feed_response = pb.FeedResponse()
        decoded_data = feed_response.ParseFromString(message)
        data_dict = MessageToDict(decoded_data)

        print('Decoded data:', data_dict)
    except Exception as e:
        print(f"Error in fetch_market_data: {e}")
    finally:
        websocket = websocket.close()
        print(websocket.id)
        print(websocket.state)

print(“hi”)
asyncio.run(fetch_market_data())

@balukarella

We have compiled a Python example demonstrating the use of websockets. You can check it out at this link for reference: https://github.com/upstox/upstox-python/tree/master/examples/websocket/market_data. Consider reviewing this example to see if any adjustments to your code are needed. This particular code example has been thoroughly tested and is confirmed to be functional.

Thank you!

@balukarella

Upon a quick check, it seems that instrumentKeys should be an array. I recommend starting by making this modification.

Thanks!

I got it… it is working… thank you

1 Like