OI Analysis
Added 2026-10-03. A port of the old Tkinter OI sheet (oldTradeEntry/PyFutureEntry/Main.py), which polled
NSE's live option chain every 3 minutes, for NIFTY and BANKNIFTY. The page has two modes that share
one response shape, so every chart works in both:
| Mode | Source | Module |
|---|---|---|
| Historical | 1-minute option bars in the IEOD Parquet store (from Jun 2016), any past date | backend/nseieod/oi_analysis.py |
| Live | NSE option chain, fetched every 3 min in market hours, stored in a temp folder (today only) | backend/nseieod/oi_live.py |
Files
| File | Purpose |
|---|---|
backend/nseieod/oi_analysis.py | Historical replay, expiry selection, shared build_result() (Max Pain, PCR, decay ...) |
backend/nseieod/oi_live.py | NSE client, 3-minute collector, temp storage, analyse_live() |
backend/app/api/oi_analysis.py | REST endpoints (/api/oi-analysis/*), developer-gated router |
backend/nseieod/nseIEOD.py | Con_Price_Getter.get_prices_by_masids() - a whole chain in one DuckDB scan |
frontend/src/pages/OIAnalysis.jsx | Page: mode switch, filters, Chart / Strikes tabs |
frontend/src/pages/OIBasketDecay.jsx | Basket Decay tab + computeBasket() |
frontend/src/pages/OITimeNav.jsx | Time navigator |
frontend/src/pages/oiAnalysisUi.jsx | Shared colours, Panel, Stat, formatters |
Definitions
All match the old app and NSE's option chain.
| Value | Definition |
|---|---|
| Change in OI | OI now − OI at the previous trading day's close |
| Premium change | LTP now − previous day's close |
| PCR | total PE OI / total CE OI |
| Max Pain | strike where option writers pay out least at expiry: argmin_K Σ OI_CE·max(K−s,0) + Σ OI_PE·max(s−K,0) |
| Max CE / PE strike | strike with the highest OI |
| Call / Put decay | mean premium change of the 5 highest-OI CEs / PEs (_top_mean) |
| Strikes used | only strikes listed for both CE and PE (old app's inner join) |
OI is carried in shares; the response has meta.lot_size and the page divides by it when "Contracts" is chosen
(NSE's chain shows contracts).
Expiry selection — select_expiries()
Same rule as the old app's SelectedExpiry(): the 2 nearest weekly expiries, the 2 nearest monthly expiries, then
the next June and December monthly (NIFTY (1, 1), BANKNIFTY (0, 0)). A monthly expiry is the last one of its
month. One fix over the old code: the June/December rule only picks monthly expiries (the old code could pick a far
June weekly).
Historical — oi_analysis.py
from nseieod import oi_analysis as oa
oa.expiries("NIFTY", "2025-01-15") # ['2025-01-16', '2025-01-23', '2025-01-30', ...]
r = oa.analyse("NIFTY", "2025-01-15", "2025-01-16", interval=3) # interval: 1, 3, 5, 15
oa.latest_date("NIFTY") # newest day with 1-minute F&O bars
oa.adjacent_trading_day("2026-10-02", -1) # 2026-10-01 (NSE holiday calendar)
How analyse() builds a day (_day(), cached with lru_cache(16), so changing the interval is instant):
- Contracts of the expiry from
scr_master(typ >= 5).scr_mastercan hold duplicate masids for one strike/type/edate (expiry mismatch, seenseieodCLAUDE.md rule 11 - 169 such groups for NIFTY/BANKNIFTY); the one with the most OI on the date wins, else the one with the most EOD history. - Bars for all contracts in one scan:
Con_Price_Getter(symbol).get_prices_by_masids(masids, d, d), plus the index spot bars. - Previous close per contract (OI, close) from
scr_nsefo_eod; spot previous close fromeq_storeon the previous NSE trading day (prev_trading_day(), holiday calendar) - never an older day's close. - Pivot to a minute grid (
MarketOpeningTime.. close − 1 min, labelled by bar start; GDFL bars end at:59), forward-fill. A contract with no bar yet carries its previous close / OI (as NSE's chain would show). - Sample every
intervalminutes plus the last minute, thenbuild_result().
build_result() — shared by both modes
build_result(meta, times, strikes,
ce_oi, pe_oi, ce_ltp, pe_ltp, # [snapshot][strike]
ce_prev_oi, pe_prev_oi, # [strike], NaN = unknown
ce_prev_close, pe_prev_close,
under, prev_spot)
Response shape (also returned by analyse_live):
{
"meta": {"mode": "historical", "symbol": "NIFTY", "date": "...", "expiry": "...", "prev_date": "...",
"interval": 3, "lot_size": 75, "top_n": 5, "prev_spot_close": 23176.05},
"times": ["09:15", "09:18", "..."],
"summary": [{"time": "09:15", "underlying": 23240.9, "max_pain": 23250, "pcr": 0.773,
"call_decay": 0.01, "put_decay": -4.01, "max_ce_strike": 24000, "max_pe_strike": 23000,
"call_oi_change": 2597775, "put_oi_change": 1906950, "max_ce_oichange": 23300,
"max_pe_oichange": 23250, "ce_oi": 185263950, "pe_oi": 143187450}],
"strikes": [22000, 22050, "..."],
"ce": {"oi": [[...]], "chg_oi": [[...]], "ltp": [[...]], "chg": [[...]], "prev_oi": [...], "prev_close": [...]},
"pe": {"...": "same keys"}
}
Size: about 1 MB at 3-minute interval, 1.7 MB at 1-minute (no gzip in the app).
Live — oi_live.py
NSE API (2025+)
The old /api/option-chain-indices endpoint used by the Tkinter app now returns 404. Used instead:
| Endpoint | Gives |
|---|---|
/api/option-chain-contract-info?symbol=NIFTY | expiry list (DD-Mon-YYYY) |
/api/option-chain-v3?type=Indices&symbol=NIFTY&expiry=06-Oct-2026 | one expiry's chain: OI (contracts), change in OI, LTP, change, IV, volume, records.timestamp |
/api/allIndices | index previousClose - the live spot % baseline (no dependency on the Bhav download) |
The session warms up on https://www.nseindia.com/option-chain (browser headers, cookies) and re-warms on 401/403,
same pattern as nseeod/corp_actions.py. One fetch of both symbols is about 10 requests and 5 seconds.
Collector
run_collector() is started by app/main.py's startup event. On NSE trading days (get_nse_working_days) it
fetches at every 3-minute mark from the open - 09:15, 09:18 ... 15:30 - plus 5 seconds; outside market hours it
sleeps until the next session. OI_LIVE_COLLECT=0 in backend/.env turns it off.
fetch_once() (also POST /api/oi-analysis/live/fetch, the page's Fetch now button) fetches and stores one
snapshot of every symbol.
Storage
backend/tmp/oi_live/ ← Config.OI_LIVE_PATH (LOCAL_/VPS_OI_LIVE_PATH), git-ignored
└── 2026-10-01/
├── NIFTY.jsonl ← one JSON line per snapshot
└── BANKNIFTY.jsonl
- The folder date and the
HH:MMlabel come from NSE's timestamp, so a fetch outside market hours stores the last session, not a fake "today". - Today only: writing a new day deletes the other day folders.
- A snapshot whose NSE timestamp has not moved is skipped (old app's duplicate check). On read, a later write for the same minute wins.
- Each row:
[strike, CE openInterest, changeinOpenInterest, lastPrice, change, impliedVolatility, totalTradedVolume, PE ...same]. IV is stored but not charted yet.
analyse_live(symbol, expiry=None)
Reads the latest day folder, pivots the snapshots per strike, multiplies OI by the lot size
(scr_nsefo_eod, near-month future), derives previous OI = OI − change in OI and previous close = LTP − change, and
calls build_result(). meta adds mode: "live", last_nse_time and snapshots.
API — /api/oi-analysis
Registered in app/main.py with the developer gate (_dev).
| Method | Path | Purpose |
|---|---|---|
| GET | /symbols | symbols, intervals, latest date with 1-minute data per symbol |
| GET | /expiries?symbol&date | expiry dropdown (404 on a holiday / no data) |
| GET | /adjacent-day?date&step | previous / next NSE trading day (navigator) |
| GET | /analysis?symbol&date&expiry&interval | historical replay |
| GET | /live/status | collector state, next fetch, stored day, snapshots + expiries per symbol |
| GET | /live/analysis?symbol&expiry | live snapshots, same shape as /analysis |
| POST | /live/fetch | fetch one snapshot now |
Frontend
Charts — relative movement, each series on its own scale
Charts show actual values, and where several series share a chart each one is auto-scaled to its own range, so every series' movement fills the chart height (relative movement). On one shared % scale the index looked flat next to option premium; with bars along the bottom, change in OI barely moved - both rejected by the user.
| Chart | Series and axes |
|---|---|
Max CE / Max PE strike, Strikes drill-down (StrikeChart) | option price (left axis, Rs) · underlying (right axis, points, dashed) · change in OI (blue line, hidden auto axis; values in the tooltip and title) |
| Change in OI | CE / PE change in OI (left) · underlying (right) - the old app's toiplt |
| Premium Decay | CE / PE mean premium change of the top-5-OI strikes (Rs) only - the old app's chart, no underlying |
| Max Pain | Max CE strike, Max Pain, Max PE strike, spot (index points) |
| OI Change / Total OI | CE vs PE bars at the as-of time |
The old app (main.py) drew the strike charts as price + change in OI (ceplt / peplt with twinx); the strike
chart here adds the underlying as a third, independently scaled series.
Basket Decay tab — OIBasketDecay.jsx
A cleaner decay test than the old top-5-OI average, whose strike set changes during the day (on 10-07-2026 the PE line jumped from −38 to −112 mostly because near-ATM puts entered the top 5).
- Basket: the 5 strikes nearest spot at the base time (default 09:20 → first snapshot at or after it), the same strikes for CE and PE, fixed all day.
- Opening range (ORB): spot high / low of the first N minutes (default 30), from snapshot closes - exact only at 1-minute interval.
- Chart: underlying on its own left axis (points) with the ORB band, so its movement fills the chart; CE / PE / combined basket as % from the base on the right axis, with the base line (0 %) and decay line (default −4 %).
- Regime at the as-of time:
| Regime | Rule |
|---|---|
| Range-bound (theta harvest) | spot inside ORB and combined basket ≤ decay line |
| Range, decay building | spot inside ORB, decay line not reached |
| Trend up confirmed | spot > ORB high and combined ≥ base (CE gain beats PE decay) |
| Trend down confirmed | spot < ORB low and combined ≥ base |
| Breakout, not confirmed | spot outside ORB but combined < base |
| Forming | before the base time or the ORB end |
Base time, ORB length and decay % are editable on the tab. A table lists each basket strike's CE / PE price at base and now.
Time navigator — OITimeNav.jsx
▶ « Day SOD -2h -30m -15m -5m -1m [Thu, Oct 1, 2026] [hour] [minute] 1m+ 5m+ 15m+ 30m+ 2h+ EOD Day »
- Backward steps land on the last snapshot at or before the target, forward steps on the first at or after it, so
1m+still moves at a 3-minute interval. « Day/Day »call/adjacent-dayand keep the same time of day.- Buttons that cannot move are disabled; Live mode disables the date and day buttons (today only).
- In Historical mode the navigator stays visible on a date without data, so the user can leave it.
Live mode on the page
Polls /live/status and /live/analysis every 60 s; stays on the newest snapshot unless the user moved back in
time. The status line shows collector on/off, next fetch, stored day, snapshot count, NSE time and the last error.
Operations
- Deploy:
./pull.shon the VPS rebuilds the frontend and restarts the backend; the restart starts the collector. - Disable live collection:
OI_LIVE_COLLECT=0inbackend/.env, restart. - NSE blocked / rate-limited: the error appears on the Live status line and in the JSON log
(
oi_live fetch failed); the collector keeps running and retries at the next mark. - Several backends running (e.g. a local dev copy next to the real one): both write the same files; the duplicate check and "later write wins" keep the data consistent.
Known gaps
- Duplicate
scr_mastercontracts are worked around, not fixed - runexpiry_mismatch.pyto clean them. - IV is stored in live snapshots but not charted; historical bars have no IV.
- The Basket Decay ORB is approximate above 1-minute interval.