Websocket is not returning data for all the instrument keys

Hi,
I wanted Banknifty option chain data for every minute. As its streaming data so as suggested I tried websocket. I passed 80 options instrument key but I am getting response for very few, sometime 10, sometime 5 sometimes 60. Shouldn’t it always return data for all 80 instruments?
Please help me .

Below is the code:

def get_market_data_feed_authorize(api_version, configuration):
“”“Get authorization for market data feed.”“”
api_instance = upstox_client.WebsocketApi(
upstox_client.ApiClient(configuration))
api_response = api_instance.get_market_data_feed_authorize(api_version)
return api_response

def decode_protobuf(buffer):
“”“Decode protobuf message.”“”
feed_response = pb.FeedResponse()
feed_response.ParseFromString(buffer)
return feed_response

async def fetch_market_data():
“”“Fetch market data using WebSocket and print it.”“”
global data_dict
print(“Creating SSL context…”)
# Create default SSL context
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE

# Configure OAuth2 access token for authorization
configuration = upstox_client.Configuration()

api_version = '2.0'
configuration.access_token = access_token

# Get market data feed authorization
response = get_market_data_feed_authorize(api_version, configuration)

print("Connecting to WebSocket...")
# Connect to the WebSocket with SSL context
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 to be sent over the WebSocket
    data = {
        "guid": "someguid",
        "method": "sub",
        "data": {
            "mode": "full",
            "instrumentKeys": instrument_keys  #instrument_keys will contain 80 instrument keys of CE & PE
        }
    }

    # Convert data to binary and send over WebSocket
    binary_data = json.dumps(data).encode('utf-8')
    #print("Sending subscription message...")
    await websocket.send(binary_data)

    # Continuously receive and decode data from WebSocket
    while True:
        #print("Waiting to receive message...")
        message = await websocket.recv()
        #print("Message received, decoding...")
        decoded_data = decode_protobuf(message)

        # Convert the decoded data to a dictionary
        data_dict = MessageToDict(decoded_data)
        print("Inside len: ",len(data_dict['feeds'].keys()))
        # Print the dictionary representation
        #print("Decoded message:", json.dumps(data_dict))

def run_websocket():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(fetch_market_data())

websocket_thread = Thread(target=run_websocket)
websocket_thread.start()

Check if an event loop is already running

time.sleep(5)
while True:

#print(data_dict)
print(len(data_dict['feeds'].keys()))
print("Sleeping for 5 s")
time.sleep(5)

@Pradeep_Jaiswar can you please help on this?

Ideally ticks would be received when there is any trading activity. There will be lot of options strikes where there is no trading activity each second so no ticks would be received. Usually thats how websocket would work.

Hi @Chetan_Suri ,
If that’s the case then how can i get option chain data through websocket as I can’t fill the missing Strike Prices? I wanted to poll option chain every 1 minute and for frequent polling websocket was recommended in the documentation.

do you need 1 min OHLC data as well ? if not you could just use https://upstox.com/developer/api-documentation/get-pc-option-chain this api and get snapshot every minute of all strike price. if you would need OHLC , you can code and make 1 min candlestick from the websocket data.
Depending on how you are processing data, you can store ticks data and just fetch last data of ticks which would give you latest price even if tick is maybe few seconds older.
hope this helps

Hi @Chetan_Suri
If we post process the received ticks from websocket for any option contracts I have noticed that it does not represent the ohlc data in app.
Eg.
9.30.00 - 100
9.30.00 - 102
9.30.01 - 101
9.30.01 - 110

9.30.59 - 115
9.31.00 - 116
In this case, there are two ticks recieved at 9.30.00. So which one do you consider for open price? I noticed in app sometime it would be 100 and someother time it would be 102.

@Pradeep_Jaiswar Can you please help here if possible?

Thanks,
Shiva

upstox team can guide more.
but in my opinion, whatever tick comes first should be considered as open price.