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 APIplotly
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:
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.
- 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.
- Setup Headers:
- A set of HTTP headers to mimic a browser request
- 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.
- Makes an HTTP GET request to the NSE API using the
- 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.
- 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.
- 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.
- 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.
HAPPY BONVOYAGE SIR
What is password for you option oi software ?
Thanks.
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.
Sir, your previous photo was a good person sir.
WHY Live Nifty Option page is not getting loaded..???
WHY Live Nifty Option page is not getting uploaded..???
Due to changes in nseindia unable to fetch the data automatically from nseindia. Looking for alternative arrangements.
thank you bro …
wasnt working the last time
Thanks. ok.
Hi Rajandran
Can this excel be tweaked to get similar presentation for stocks which are traded in Options?
Thanks
yes it can be done
Wow! Can you please add similar Excel for SBIN, LT ? I am zero coding/programming and excel. It’d be a great help!
Thanks!
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..
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……………………..
Sir its NOT Updating
Hi Shiraj,
Now the tool is ported online you can watch Live OI for Nifty options here
what is most imp tool to predict nifty movement ????
As a human being we cant use math tools to predict the market. Prediction is really tough here.
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 ?