Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

Simple Live Nifty Options Open Interest Monitoring Tool – Python Tutorial

2 min read

Plotting live open interest charts is a powerful tool to visualize this data in real-time, helping to make informed decisions. This tutorial will guide you through creating a live open interest chart for NIFTY options using Python, Plotly, and data from the NSE India website.

Prerequisites

  • Python 3.x
  • requests library: to fetch data from the NSE API
  • plotly library: for interactive plotting

 Install Python Libraries

pip install plotly

This code is designed to fetch, process, and visualize the open interest data of NIFTY options from the National Stock Exchange of India (NSE) website.

Complete Python Code to Fetch Open Interest Data from Nseindia Portal

import requests
import plotly.graph_objects as go

# Placeholder variables
symbol = "NIFTY"
selected_expiry_date = "29-Feb-2024"  # Replace with your desired expiry date
lot_size = 50  # Replace with your desired lot size

# The general URL for fetching NIFTY options data
url = f"https://www.nseindia.com/api/option-chain-indices?symbol={symbol}"

# Create a session object
with requests.Session() as session:
    session.headers.update({
        'Connection': 'keep-alive',
        'Cache-Control': 'max-age=0',
        'DNT': '1',
        'Upgrade-Insecure-Requests': '1',
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
        "Accept-Language": "en-US,en;q=0.9,kn;q=0.8",
        "Accept-Encoding": "gzip, deflate, br",
        'Sec-Fetch-User': '?1',
        'Sec-Fetch-Site': 'none',
        'Sec-Fetch-Mode': 'navigate'
    })

# First request to get session cookies
session.get("https://www.nseindia.com")

# Now make your API request
response = session.get(url)

# Initialize lists to store the parsed data
strike_prices = []
ce_open_interests = []
pe_open_interests = []

if response.status_code == 200:
    data = response.json()  # Parse the JSON data from the response
    # Filter the required data for the specific expiry date
    for record in data['records']['data']:
        if record['expiryDate'] == selected_expiry_date:
            strike_prices.append(record['strikePrice'])
            # Check if CE and PE data is available and multiply by lot size
            if 'CE' in record:
                ce_open_interests.append((record['CE']['openInterest'] * lot_size) / 1e6)  # Convert to millions
            else:
                ce_open_interests.append(0)
            if 'PE' in record:
                pe_open_interests.append((record['PE']['openInterest'] * lot_size) / 1e6)  # Convert to millions
            else:
                pe_open_interests.append(0)
else:
    print("Failed to retrieve data:", response.status_code)

# Creating traces for the Plotly graph
trace1 = go.Bar(
    x=strike_prices,
    y=ce_open_interests,
    name='CE Open Interest'
)
trace2 = go.Bar(
    x=strike_prices,
    y=pe_open_interests,
    name='PE Open Interest'
)

# Creating the layout for the Plotly graph with increased size
layout = go.Layout(
    title=f'NIFTY Call and Put Open Interest for {selected_expiry_date} (Lot Size: {lot_size})',
    xaxis=dict(
        title='Strike Price',
        tickmode='array',
        tickvals=strike_prices[::5]  # Show every 5th strike price for readability
    ),
    yaxis=dict(
        title='Open Interest (in millions)'
    ),
    barmode='group',
    width=1200,  # Width of the figure in pixels
    height=800   # Height of the figure in pixels
)

# Creating the figure with the data and layout
fig = go.Figure(data=[trace1, trace2], layout=layout)

# Display the plot
fig.show()

Here’s an overview of what each part does:


  1. Import Libraries
    :
    • requests: Used for making HTTP requests to fetch data from the NSE API.
    • plotly.graph_objects: Used for creating interactive plots to visualize data.
  2. Setup Variables:
    • selected_expiry_date: The expiry date for the options you’re interested in.
    • lot_size: The number of shares per option contract.
    • url: The NSE API endpoint for NIFTY option chain data.
  3. Setup Headers:
    • A set of HTTP headers to mimic a browser request
  4. Fetch Data:
    • Makes an HTTP GET request to the NSE API using the requests library and the provided headers.
    • Checks the response status to ensure the request was successful.
  5. Parse and Filter Data:
    • If the request is successful, it parses the JSON response.
    • Filters the options data for the specified expiry date.
    • Extracts the strike prices, Call (CE) open interests, and Put (PE) open interests.
    • Converts the open interests to millions and multiplies them by the lot size for a more readable scale.
  6. Prepare Data for Visualization:
    • Prepares two bar traces with Plotly: one for CE open interest and another for PE open interest against the strike prices.
  7. Configure Plot Layout:
    • Sets up the graph layout with titles, axis labels, and dimensions.
    • Adjusts the x-axis to display every 5th strike price for better readability.
  8. Create and Display the Plot:
    • Creates a Plotly figure with the prepared data and layout.
    • Displays the interactive plot, which shows the distribution of open interests across different strike prices for Calls and Puts.

The code effectively gives a visual overview of market sentiment by showing where traders are placing their bets on future price movements of the NIFTY index. The open interest levels at different strike prices can indicate potential support and resistance levels or points of market interest.

Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

Understanding Object-Oriented Programming (OOP) Concepts in Python for Traders…

For traders and investors, having well-structured code can greatly improve the efficiency and manageability of trading applications. Object-Oriented Programming (OOP) in Python offers a...
Rajandran R
3 min read

Liquidation Breakout Failure in Nifty Futures – Sign of…

The Indian stock market has been buzzing with activity, and the recent performance of the Nifty index has caught the eye of investors and...
Rajandran R
49 sec read

How I Built a Trader-Friendly Stock Market Dashboard using…

As both a developer and an avid market watcher, I set out to create a tool that could give traders and investors a clear,...
Rajandran R
2 min read

20 Replies to “Simple Live Nifty Options Open Interest Monitoring Tool –…”

  1. please do provide the backtested results
    as per
    how many times it hit T2 or T1 etc after giving arrow signal
    in each month / intra day / btst / week.
    in livesignals chart
    of nifty, banknifty, sbin, lt, tamo.

  2. Hi Rajandran

    Can this excel be tweaked to get similar presentation for stocks which are traded in Options?

    Thanks

  3. Wow! Can you please add similar Excel for SBIN, LT ? I am zero coding/programming and excel. It’d be a great help!

    Thanks!

  4. hi Rajandran

    its really nice work on excel if you could provide me the password for protected sheet input2 then i think i could make such excel for other Index option too like banknifty and so liquid stock option.. I would appreciate.. it you can share that..

  5. hi raj,,,,,,,,,,

    its kalpesh from mumbai, nallasopara……

    m want to know how could we get such an access about live stock future open interest as we have this nifty live open interest………………
    plz favour for this……………………..

  6. I have modified connection query string to get the data for option stocks but some how it is not working, what other changes I need to do ?

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More