Websockets are not accepting the instrumentToken

I am reffeering to this web_socket implimentation. and whenever I put in the instrument keys for options, I am not able to get any data. To get the instrumentKeys I am using this : https://assets.upstox.com/market-quote/instruments/exchange/complete.csv.gz

 data = {
            "guid": "someguid",
            "method": "sub",
            "data": {
                "mode": "full",
                "instrumentKeys": ['NSE_INDEX|Nifty 50'],

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(
    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()
    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()

# Execute the function to fetch market data
symbol = "NSE_INDEX|Nifty Bank"

# Start the WebSocket connection in a separate thread
websocket_thread = Thread(target=run_websocket)

I was tring this key NSE_FO|67516

symbol = "NSE_FO|67516"

@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.

import upstox_client

def on_message(message):
def main():
    configuration = upstox_client.Configuration()
    access_token = '<ACCESS_TOKEN>'
    configuration.access_token = access_token
    streamer = upstox_client.MarketDataStreamer(
        upstox_client.ApiClient(configuration), ["NSE_FO|67516"], "full")
    streamer.on("message", on_message)

if __name__ == "__main__":

I am confused with the two examples:

  1. upstox_client.WebsocketApi
  2. upstox_client.MarketDataStreamer

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

1 Like