Friends, after so many requests (literally bahut saare messages aaye the!), I'm finally back with another NSE-related Python tutorial. Aap logo ka pyaar dekhte hue, today I want to share how I created this small but powerful program that shows live NSE derivatives Top Contract data in the simplest way possible. Even if you're new to coding, you can understand this (aur haan, this time I won't disappear for months - promise!).
We all know how frustrating it is to keep refreshing the NSE website to check option prices (time waste na?). I wanted a quicker way to track top contracts without all that hassle. So I thought - "Let's make my own tracker that just works!"
How It Works (Step-by-Step)
- First It Asks You - When you run it, the program politely asks "Bhaiya, kitne contracts dikhau?" (5, 10, 15 or 20?)
- Fetches Live Data - : It quietly gets live data from NSE website (like a mini browser).
- Shows Clean Output - Displays only important columns in colorful format (Green = up, Red = down - just like trading apps!)
- Auto-Refresh - Updates every 1-2 minutes (no manual refresh needed)
The Best Parts
- No Login Needed - Unlike other apps (jo har waqt OTP mangte hain)
- Error Proof - If internet slow hai, it tries again 3 times (very patient program!)
How To Use It
Just 3 steps:
- Copy the code
- Save as nse_tracker.py
- Run
python nse_tracker.py
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
import pandas as pd
import time
import random
from datetime import datetime
from colorama import init, Fore, Back, Style
import os
init(autoreset=True)
class NSE:
def __init__(self):
self.url = "https://www.nseindia.com/api/liveEquity-derivatives?index=top20_contracts"
self.headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Accept': 'application/json, text/plain, */*',
'Accept-Language': 'en-US,en;q=0.9',
'Referer': 'https://www.nseindia.com/market-data/equity-derivatives-watch'
}
self.limit = self.get_choice()
self.session = self.setup_session()
def setup_session(self):
s = requests.Session()
retry = Retry(total=3, backoff_factor=2, status_forcelist=[401, 429, 500, 502, 503, 504])
s.mount('https://', HTTPAdapter(max_retries=retry))
return s
def get_choice(self):
print(f"{Fore.CYAN}{'='*50}")
print(f"{Fore.CYAN}{'NSE DERIVATIVES MONITOR':^50}")
print(f"{Fore.CYAN}{'='*50}")
print(f"{Fore.YELLOW}Select contracts to display:")
choices = ["5", "10", "15", "20"]
for i, c in enumerate(choices, 1):
print(f"{Fore.GREEN}{i}. Top {c} contracts")
while True:
try:
choice = input(f"\n{Fore.WHITE}Enter choice (1-4): ").strip()
if choice in ['1', '2', '3', '4']:
val = [5, 10, 15, 20][int(choice)-1]
print(f"{Fore.YELLOW}Selected: Top {val} contracts")
return val
else:
print(f"{Fore.RED}Invalid choice. Enter 1-4.")
except KeyboardInterrupt:
print(f"\n{Fore.YELLOW}Exiting...")
exit(0)
except Exception as e:
print(f"{Fore.RED}Error: {e}. Try again.")
def fetch(self):
try:
r = self.session.get(self.url, headers=self.headers, timeout=10)
r.raise_for_status()
return r.json()
except requests.RequestException as e:
print(f"{Fore.RED}Fetch error: {e}")
return None
def format(self, data):
if not data or 'data' not in data:
return None, {}
df = pd.DataFrame(data['data'])
print(f"{Fore.CYAN}API: {len(df)} contracts, showing: {self.limit}")
df = df.head(self.limit)
cols = ['underlying', 'optionType', 'strikePrice', 'lastPrice',
'change', 'pChange', 'volume', 'openInterest', 'noOfTrades']
df = df[cols].copy()
df.columns = ['Stock', 'Type', 'Strike', 'LTP', 'Change', 'Change%', 'Volume', 'OI', 'Trades']
df['LTP'] = df['LTP'].round(2)
df['Change'] = df['Change'].round(2)
df['Change%'] = df['Change%'].round(2)
df['Volume'] = df['Volume'].apply(lambda x: f"{x/1e6:.1f}M")
df['OI'] = df['OI'].apply(lambda x: f"{x/1000:.0f}K")
df['Trades'] = df['Trades'].apply(lambda x: f"{x/1000:.0f}K")
return df, data.get('marketStatus', {})
def header(self, status):
os.system('cls' if os.name == 'nt' else 'clear')
print(f"{Back.BLUE}{Fore.WHITE}{'='*80}")
print(f"{Back.BLUE}{Fore.WHITE}{'NSE DERIVATIVES LIVE DATA':^80}")
print(f"{Back.BLUE}{Fore.WHITE}{'='*80}{Style.RESET_ALL}")
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
mkt_date = status.get('marketCurrentTradingDate', 'N/A')
mkt_status = status.get('marketStatusMessage', 'N/A')
print(f"{Fore.CYAN}Time: {now}")
print(f"{Fore.CYAN}Market Date: {mkt_date}")
print(f"{Fore.CYAN}Status: {mkt_status}")
print(f"{Fore.MAGENTA}Showing: Top {self.limit}")
print(f"{Fore.YELLOW}{'-'*80}")
def color(self, row):
pct = float(row['Change%'])
if pct > 5: return f"{Back.GREEN}{Fore.BLACK}"
elif pct > 0: return f"{Fore.GREEN}"
elif pct < -5: return f"{Back.RED}{Fore.WHITE}"
elif pct < 0: return f"{Fore.RED}"
else: return f"{Fore.WHITE}"
def table(self, df):
if df is None or df.empty:
print(f"{Fore.RED}No data")
return
hdr = f"{Fore.YELLOW}{'Stock':^8} {'Type':^4} {'Strike':^7} {'LTP':^8} {'Change':^7} {'Change%':^8} {'Volume':^8} {'OI':^8} {'Trades':^8}"
print(hdr)
print(f"{Fore.YELLOW}{'-'*80}")
for _, row in df.iterrows():
c = self.color(row)
print(f"{c}{row['Stock']:^8} {row['Type']:^4} {row['Strike']:^7} "
f"{row['LTP']:^8} {row['Change']:^7} {row['Change%']:^8} "
f"{row['Volume']:^8} {row['OI']:^8} {row['Trades']:^8}{Style.RESET_ALL}")
def run(self):
print(f"\n{Fore.GREEN}Starting NSE Monitor...")
print(f"{Fore.YELLOW}Press Ctrl+C to stop")
time.sleep(2)
try:
while True:
data = self.fetch()
delay = random.uniform(60, 90)
if data:
df, status = self.format(data)
self.header(status)
self.table(df)
print(f"\n{Fore.MAGENTA}Next update: {delay:.0f}s...")
else:
print(f"{Fore.RED}Failed. Retry: {delay:.0f}s...")
time.sleep(delay)
except KeyboardInterrupt:
print(f"\n{Fore.YELLOW}Stopped by user")
except Exception as e:
print(f"{Fore.RED}Error: {e}")
def main():
nse = NSE()
nse.run()
if __name__ == "__main__":
main()
Output
Important Note About Possible Errors (Read Before Trying!)
Doston, ek choti si warning de deta hoon - sometimes when you run this script, you might see errors like:
- 401/441 Error - This means NSE is blocking our request (thoda sa strict ho gaya hai NSE)
- Max retries exceeded - Matlab program ne 3 baar try kiya, par NSE ne data nahi diya
Kyu Hota Hai Yeh?
- NSE doesn't like when too many requests come from same computer (security reasons)
- Sometimes they change their API rules without telling (typical na?)
PS: Full code upar hi diya hai - copy-paste karo aur enjoy karo! Koi doubt ho toh pooch lena.
Doston, aapke pyaar ne humesha mujhe motivate kiya hai! 😊 My previous NSE Python blogs (especially the NSE Option Chain Data using Python one) got such amazing response - 25K+ views and so many kind comments! Aap sab ka support hi hai jo mujhe aise useful scripts share karne ki himmat deta hai.
Top comments (0)