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)