Speed of full market data fetch

I am trying to fetch live data from Websocket API, I am using a example code given on Github Repository of upstox. But, while fetching data I am observing that the data is not fetched accurately. I am getting data after every 3 4 seconds.

Please help me with this. If I am doing anything wrong in the code or I should modify the code for better speed, please suggest changes.

I am attaching the code file I am using.

# Import necessary modules
import asyncio
import json
import ssl
import upstox_client
import websockets
from google.protobuf.json_format import MessageToDict

import MarketDataFeed_pb2 as pb


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

    # 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 = "eyJ0eXAiOiJKV1QiLCJrZXlfaWQiOiJza192MS4wIiwiYWxnIjoiSFMyNTYifQ.eyJzdWIiOiIyRENTRVkiLCJqdGkiOiI2NzE3MzkxMTU1YTc4MTQxNmMwYjU5YTMiLCJpc011bHRpQ2xpZW50IjpmYWxzZSwiaWF0IjoxNzI5NTc1MTg1LCJpc3MiOiJ1ZGFwaS1nYXRld2F5LXNlcnZpY2UiLCJleHAiOjE3Mjk2MzQ0MDB9.KE38b-xRO5CWp4eclDvdaLiAUgL1MX7rxcpOzjfC2QM"

    # 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": ["NSE_FO|50971", "NSE_FO|50972", "NSE_FO|59382", "NSE_FO|46080"]
            }
        }

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

            # Print the dictionary representation
            with open("/mnt/7A42C8D342C894F3/programming/personal/marketAnalysis/trade/upStox/upStox_1.jsonl", "a") as js:
                json.dump(data_dict, js)
                js.write("\n")
            print(json.dumps(data_dict))


# Execute the function to fetch market data
asyncio.run(fetch_market_data())

Hi @Anant_Patankar
The instruments you are subscribing to have a December expiry (like NSE_FO|50971 which is NIFTY 27000 CE 24 DEC 25) and have lower volatility.

You may consider subscribing to more active trade instruments such as NSE_FO|54775, which corresponds to NIFTY 25000 PE 31 OCT 24 to test web scokets.

Our websockets provide updates based on trades executed on the exchange. For instruments with fewer trades, there may be a 3-4 second gap between updates.

Also for easier implementation of websockets do refer to streamer functionalities provided in various languages.

1 Like

Thank you @Ketan
I will certainly check these functionalities.

1 Like