How to Fetch option Chain in WebSocket ! HERE IS THE ANSWER

import asyncio
import json
import ssl
import upstox_client
import websockets
from google.protobuf.json_format import MessageToDict
import requests
import pandas as pd
import MarketDataFeed_pb2 as pb
access_token =‘YOUR ACCESS_TOKEN’

Define a list to store received data

received_data =

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()
configuration.access_token = access_token

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

async with websockets.connect(response.data.authorized_redirect_uri, ssl=ssl_context) as websocket:
    print('Connection established')

    await asyncio.sleep(0)  # Wait for 1 second

    # Fetch live option chain data using the API
    url = "https://api.upstox.com/v2/option/chain"
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': f'Bearer {access_token}',  # Replace with your access token
    }
    params = {
        'instrument_key': 'NSE_INDEX|Nifty Bank',
        'expiry_date': '2024-02-29'  # Replace with the desired expiry date
    }
    response = requests.get(url, headers=headers, params=params)
    if response.status_code == 200:
        data = json.loads(response.text)
        option_chain = data['data']
        # Extract instrument keys from the option chain data
        instrument_keys = [option['call_options']['instrument_key'] for option in option_chain]
        instrument_keys += [option['put_options']['instrument_key'] for option in option_chain]

        # Subscribe to instrument keys in the WebSocket feed
        for instrument_key in instrument_keys:
            data = {
                "guid": "someguid",
                "method": "sub",
                "data": {
                    "mode": "full",
                    "instrumentKeys": [instrument_key]
                }
            }
            binary_data = json.dumps(data).encode('utf-8')
            await websocket.send(binary_data)

        print('Subscription request sent')  # Add this line

        # Continuously receive and process data from WebSocket
        while True:
            message = await websocket.recv()
            decoded_data = decode_protobuf(message)
            data_dict = MessageToDict(decoded_data)
            print(json.dumps(data_dict, indent=4))  # Print received data

    else:
        print("Failed to fetch option chain data. Status code:", response.status_code)

Run the fetch_market_data function in an asyncio event loop

asyncio.run(fetch_market_data())

1 Like

@Davinci_Code, thank you for your contributions to the Upstox community. Your support helps in the community’s growth.

Hii @Davinci_Code

Can you also post about how to do authentication and get access token for the API to run ? I didn’t understand why a redirect uri is required to fetch the access token.

The Upstox API adheres to the OAuth specification, necessitating the provision of a one-time authorization code on the redirected URL following a successful login. This authorization code is solely for single-use to acquire the access token.

For further information, please consult the authentication documentation at Authentication | Upstox Developer API.

Replace “mode”: “full” with “mode”: “option_chain” in below code to get only option chain data.

for instrument_key in instrument_keys:
data = {
“guid”: “someguid”,
“method”: “sub”,
“data”: {
“mode”: “full”,
“instrumentKeys”: [instrument_key]
}
}

Thank you for your assistance, @tekchandg

We have updated the documentation for the option_chain mode as well. You can find it here:

I am having similar issue. I am using node express for connecting upstox market feed data api through websockets, but the issue is that websockets is connected successfully but api is not returning any data.I have connected during the market is open but then also please help me out to solve this issue.

Code link: GitHub - hetpatel4902/upstox