The websocket gives me the live data perfectly for this instrumnet key but as soon as I put in other keys from the csv mentioned above the socket returns nothing.
Please help us out with this
Could you provide a list of instrument keys sent to the WebSocket for further investigation? Additionally, sharing the code snippet youâre using would be beneficial.
import asyncio
import json
import ssl
import upstox_client
import websockets
from google.protobuf.json_format import MessageToDict
from threading import Thread
import MarketDataFeed_pb2 as pb
from time import sleep
import time
import datetime
from auto_generate_access_token import getAccessToken
# hi my name is mandar
access = getAccessToken('708316')
access_token = access['access_token']
# filename =f"access_token.txt"
# with open(filename,"r") as file:
# access_token = file.read()
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(symbol):
global data_dict
"""Fetch market data using WebSocket and print it."""
# 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)
# 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": [symbol]
}
}
# Convert data to binary and send over WebSocket
binary_data = json.dumps(data).encode('utf-8')
await websocket.send(binary_data)
# Continuously receive and decode data from WebSocket
while True:
message = await websocket.recv()
decoded_data = decode_protobuf(message)
# Convert the decoded data to a dictionary
data_dict = MessageToDict(decoded_data)
# current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
# Print the dictionary representation
value = data_dict.get('feeds', {}).get(symbol, {}).get('ff', {}).get('indexFF', {}).get('ltpc', {}).get('ltp')
if value:
print(value, datetime.datetime.now())
def run_websocket():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(fetch_market_data())
# Execute the function to fetch market data
symbol = "NSE_INDEX|Nifty Bank"
asyncio.run(fetch_market_data(symbol))
# Start the WebSocket connection in a separate thread
websocket_thread = Thread(target=run_websocket)
websocket_thread.start()
@mskasan30 Thank you for contacting us. Take a look at the latest websocket implementation offered by Upstox for user convenience, available in the Python Upstox SDK (websocket). You can be confident that the code below has been tested and functions correctly with the specified instrument key NSE_FO|67516.
Why there are two ways of fetching the market data? I donât know which one to use when since there is no mention of their relative utilities.
From your statement âthe latest websocket implementation offered by Upstox for user convenienceâ, I have the feeling that MarketDataStreamer is a wrapper that abstracts away the low level details of the other (WebsocketApi) method. So, if the dev wishes finer control, the dev can use the WebsocketApi version.
Is my understanding correct? Or there is something more important that I am missing?
Also, does the same rate limit hold in both the cases?
@sbiswas, youâre correct. The MarketDataStreamer serves as a wrapper that hides the complexities of the Websocket API. Developers can choose to directly utilize the WebsocketApi for more precise control, or they can opt for the convenience of the wrapper to access data from the Websocket.
And yes both have same rate limiting as MarketDataStreamer is a wrapper around WebsoketApi