← Back to Dashboard

Options Scalper
System Documentation

A multi-layered algorithmic trading system for BANKNIFTY/NIFTY options + 15 equity stocks. Four signal layers for options, three for equity intraday (long + short), comprehensive validation, and strict risk management — all running autonomously.

4 Signal Layers
6 Validation Filters
~500ms Fastest Signal
12+ Risk Guards

System Architecture

The system processes market data through a pipeline of detection, validation, and execution stages. Each signal layer operates independently at different speeds, from tick-level (~500ms) to AI analysis (~60s).

Zerodha WebSocket (954 tokens: 2 indices + 937 options + 15 stocks) │ ├─ on_tick() ← Every ~500ms │ ├─ Update candle aggregator (1min, 5min, 15min) │ ├─ Update options chain (Greeks, OI, LTP) │ ├─ Update equity chains (LTP, bid/ask, volume) │ ├─ Update volume profile (POC, VAH, VAL) │ ├─ Update S/R detector │ └─ Manage equity positions (SL/target + MIS squareoff at 15:15) │ ├─ on_candle_close() ← Every 1 minute │ │ │ ├─ ── OPTIONS PATH (NIFTY/BANKNIFTY) ── │ │ ├─ Supertrend Fast-Path ← LAYER 1 │ │ ├─ Mean Reversion ← LAYER 2 (if no fast-path) │ │ ├─ Pivot Bounce/Break ← LAYER 3 (if no MR) │ │ └─ Gemini AI Analysis ← LAYER 4 (every 60s) │ │ │ └─ ── EQUITY PATH (15 stocks) ── │ ├─ Equity Fast-Path ← Real volume + VWAP │ ├─ Equity Mean Reversion ← BB + RSI + Pivots │ └─ Equity Pivot Bounce/Break ← Real volume BREAK │ └─ manage_positions() ← Every tick ├─ SL / Target monitoring ├─ Trailing SL updates └─ Credit spread management
Cascade Logic: Rule-based layers (1–4) are checked in order on each candle close. If a faster layer triggers a trade, slower layers are skipped for that candle. Gemini AI runs independently on a 60-second rate limit.

Daily Timeline

The system follows a structured schedule aligned with NSE market hours.

09:00

System Boot

Load config, connect to Zerodha, subscribe tokens, warm up historical candles (1min/5min/15min), calculate pivot levels from previous day OHLC, seed volume profile from futures data.

09:15

Market Open — Engine Starts

Engine state → RUNNING. WebSocket ticks start flowing. Session memory reset for new day. All daily counters reset (fast-path, OF, MR, pivot trades).

09:20

Order Flow Active

Order flow imbalance detection begins (skips first 5 min to avoid opening auction noise). Needs 5+ ticks of history before first signal possible.

09:25

All Layers Active

Fast-Path, Mean Reversion, and Pivot Bounce/Break activate. Indicators need ~15 candles warm-up. Gemini AI starts analyzing.

15:10

Credit Spread Auto-Exit

All open credit spreads auto-exit at 15:10 (20 min before close). Open positions trigger close-to-market-close restriction.

15:15

No New Trades

"Too close to market close" — risk manager blocks all new entries. Only exit management continues.

15:30

Market Close

WebSocket disconnects. System remains running for next-day reconnect.

Signal → Execution Flow

Every signal (from any layer) follows this pipeline before becoming a trade.

Signal Generated Detect

One of 5 layers detects a trade opportunity. Signal object created with type, strike, confidence, SL, target.

Direction Block Check Guard

If 3+ consecutive losses in same direction (CE or PE), that direction is blocked. Opposite direction still allowed.

Duplicate Position Check Guard

Won't open same option type (CE/PE) for same underlying if one is already open.

Risk Manager Risk

Checks daily PnL limits, max open positions, consecutive losses, trade count, VIX range, market hours.

Validation Chain Validate

Greeks validator (IV, delta, theta) → Pivot rules → Volume Profile → MTF alignment → Diversity check. Some hard-reject, some soft-penalty.

Execute Entry Trade

ATM strike selected → Best contract found (min 2 DTE) → Order placed (paper/live) → Position tracked → Performance recorded → Dashboard updated.

All 4 Signal Detection Layers

Each layer operates independently with its own detection logic, confidence level, daily limits, and cooldowns.

Layer 1 — Supertrend Fast-Path

1-min Candle Conf: 0.80

Detects Supertrend direction flips with 2-candle confirmation — requires the flip to persist for 2 consecutive candles before firing (prevents whipsaw losses). Confirms with VWAP position. Volume gate for stocks; auto-bypassed for indices.

  • BUY CE: Supertrend flips DOWN→UP (2 candle confirm) + price above VWAP
  • BUY PE: Supertrend flips UP→DOWN (2 candle confirm) + price below VWAP
  • Volume gate: 1.5x SMA for stocks/futures; auto-bypassed for indices (no volume on spot)
  • ATR-scaled SL: Dynamic 12-30% based on 2x ATR / entry_price (adapts to volatility)
  • Target: 1.5x the SL distance (dynamic R:R)
  • VWAP fallback: daily pivot used as proxy for indices (zero volume on spot candles)
  • Supertrend parameters: period=10, multiplier=3
Max 1/day/underlying 2-candle confirm ATR-scaled SL VWAP direction

Layer 2 — Mean Reversion

1-min Candle Conf: 0.72

Fades overextended moves when price stretches beyond Bollinger Bands + RSI confirms extreme + near a pivot S/R level. Triple trend filter: 5min Supertrend + 1min Supertrend + VWAP distance.

  • BUY CE (Oversold): price < BB lower + RSI < 40 + near support level (within 0.3%)
  • BUY PE (Overbought): price > BB upper + RSI > 60 + near resistance level (within 0.3%)
  • Confidence scaling: RSI < 25: +0.05 | RSI < 30: +0.02 | RSI 30-40: baseline
  • 5min ST filter: Hard block if 5min Supertrend confirms counter-trend
  • 1min ST filter: Hard block if 1min Supertrend is counter-trend (catches fast moves)
  • VWAP distance: Hard block if spot >0.3% away from VWAP against signal direction
  • SL: 15% (tighter) | Target: 20% (to VWAP/BB mid)
Max 2/day/underlying 10-min cooldown 5min + 1min ST filter VWAP distance gate

Layer 3 — Pivot Bounce / Break

1-min Candle Conf: 0.68–0.81

Trades directly off Pivot Boss levels. Detects 6 patterns: BOUNCE, RECLAIM, REJECT, BREAK. 5min Supertrend + CPR bias filters block counter-trend bounce signals. BREAK signals work on indices via 2-candle momentum proxy.

  • BOUNCE at Support: prev candle pierced level + current bullish + closed above level
  • BOUNCE at Resistance: prev candle tested level + current bearish + closed below level
  • RECLAIM Support: price was below support, current candle reclaims above (bullish reversal)
  • REJECT Resistance: price was above resistance, current candle drops back below
  • BREAK above/below: strong body (>0.5 ATR) + VWAP alignment + momentum confirmation
  • BREAK momentum: Stocks: volume >1.3x SMA | Indices: 2 consecutive directional candles (no volume on index spot)
  • Proximity: 0.25% for key levels (PDH/PDL/R1/S1) | 0.15% for others
  • Trend filter: 5min Supertrend bullish → blocks PE bounces | bearish → blocks CE bounces
  • CPR filter: spot > TC → blocks PE bounces | spot < BC → blocks CE bounces
  • BREAK signals are never blocked by trend filters (they go WITH the trend)
Max 2/day/underlying 30-min per-level cooldown 5min Supertrend filter Index momentum proxy

Layer 4 — Gemini AI Analysis

~60s Rate Limit Conf: Dynamic

Full market state analysis by Google Gemini 2.0 Flash. Receives candle data, all pivot levels (Standard, Camarilla, Fibonacci, CPR), Greeks, volume profile, open positions, session memory, and recent trade history.

  • Pre-filter triggers: price near pivot (0.15%), EMA 9/21 crossover, RSI extreme (<30/>70), significant move (>0.3%), near VP levels
  • Returns: signal_type, strike, option_type, confidence, stop_loss, target, reasoning
  • Session memory: remembers previous signals, outcomes, and level tests across the day
  • Handles both entries and exits (AI exit decisions for open positions)
  • Diversity check: if last 5 signals all same direction → confidence penalty -0.15
60s rate limit Confidence threshold Diversity penalty Session memory

Validation Chain

Every signal passes through multiple validation filters. Some hard-reject (block the trade), others soft-penalize (reduce confidence). Confidence must remain above threshold to execute.

1

Greeks Validator

Checks IV rank, delta range, theta decay. Rejects if IV too low or Greeks unfavorable.

Hard Reject
2

Pivot Boss Rules

Validates signal against CPR type, pivot bias, and trade setup. Can hard-reject or adjust confidence.

Hard / Soft
3

Volume Profile

Checks position relative to POC, VAH, VAL. LONG above VAH or SHORT below VAL → confidence penalty -0.10. Extreme distance (>0.3%) triggers penalty.

Soft -0.10
4

MTF (Multi-Timeframe) Alignment

Checks if 5min/15min timeframes align with the signal direction. Misalignment → confidence penalty -0.10. Alignment → confidence boost.

Soft -0.10
5

Correlation Check

Prevents correlated positions (e.g., both NIFTY CE and BANKNIFTY CE). Blocks if same directional exposure exists across indices.

Hard Reject
6

Index Direction Alignment

Checks if trade direction aligns with overall market bias (derived from both NIFTY and BANKNIFTY). Prevents counter-trend entries.

Hard Reject
Confidence Threshold: After all soft adjustments, the final confidence must remain above the configured threshold (default 0.60) for the trade to execute. Multiple small penalties can compound to reject a signal.

Risk Management

Multiple layers of risk protection ensure capital preservation.

■ Kill Switch

Auto-activates on max daily loss.
Closes all positions immediately.
Blocks all new trades for the day.
Sends Telegram alert.

■ Daily Trade Limit

Maximum trades per day (configurable).
Separate counters per signal layer.
Prevents overtrading.

■ Position Limits

Max open positions enforced.
No duplicate same-direction same-underlying.
Correlation check across indices.

■ Direction Blocking

3 consecutive CE losses → CE blocked.
3 consecutive PE losses → PE blocked.
Opposite direction still allowed.
Win resets the streak.

■ VIX Filter

Monitors India VIX in real-time.
Can block trades in extreme volatility.
Credit spreads: VIX 13-22 range only.

■ Market Hours Guard

No trades before 09:15 (market open).
No new entries after 15:15.
Credit spreads auto-exit at 15:10.

■ Stop Loss / Target

Every trade has SL + target set at entry.
Monitored on every tick.
AI can trail SL for winning trades.
Auto-exit on SL hit.

■ Consecutive Loss Guard

3 losses → 30-min cooldown.
4+ losses → 60-min cooldown.
Progressive tracking prevents infinite re-trigger.
Per-strike 30-min cooldown after loss.

■ Smart AI Exit

Rule-based trades: 10-min hold + AI exit only if loss >10%.
AI trades: 5-min minimum hold.
Winners (+5%) → trail SL, never exit.
SL only ratchets up, never down.

■ Progressive Trailing SL

+3%→12% trail (breathe).
+7%→8% trail (lock some).
+12%→6% trail (protect bulk).
+20%→4% trail (squeeze last bit).

SL / Target by Signal Layer

LayerStop LossTargetRisk:Reward
Supertrend Fast-PathATR-scaled 12-30%1.5x SL dist1:1.5 (dynamic)
Mean Reversion-15%+20%1:1.33
Pivot Bounce-15%+25%1:1.67
Pivot Break-20%+30%1:1.5
Credit Spread50% max loss50% max profitDefined risk
Gemini AIDynamicDynamicAI-determined

Credit Spreads

Defined-risk premium collection strategy. Sells an OTM option and buys a further OTM option as hedge.

ParameterValue
TypesBULL_PUT (bullish) and BEAR_CALL (bearish)
Width100 points between strikes
VIX Range13 – 22 (only enter when VIX is in range)
Profit Target50% of premium collected
Stop Loss50% of max profit lost (tightened from 100%)
Max LossWidth – Premium = defined max risk
Auto-Exit15:10 (20 min before market close)
Signal SourceGemini AI (returns SpreadSignal type)
How it works: When Gemini detects a range-bound market with moderate VIX, it can suggest a credit spread instead of a directional trade. The system sells the near strike, buys the far strike for protection, and collects the net premium. Profit is realized when the spread decays in value.

Equity Intraday Trading

Direct stock BUY + SHORT SELL using the same signal detection layers as options, but with real volume, VWAP, and order flow data. Runs in parallel alongside index options. MIS (intraday) orders auto-squareoff at 15:15.

Why equity? Index spot candles have zero volume — VWAP is approximated, volume BREAK signals use momentum proxy, order flow is dead. Stocks have real volume data, making every signal layer more accurate. Equity and options complement each other: options for leveraged moves, stocks for steady trend-following.

Stocks Traded (15 F&O Stocks)

RELIANCE HDFCBANK ICICIBANK INFY TCS SBIN AXISBANK KOTAKBANK BHARTIARTL LT TATASTEEL BAJFINANCE ITC MARUTI WIPRO

Signal Layers (Same 3 Layers, Adapted for Stocks)

LayerTriggerDirectionSL / Target
Equity Fast-Path Supertrend flip (2-candle confirm) + VWAP + real volume surge (1.5x SMA) BUY or SHORT SELL 2x ATR / 3x ATR
Equity Mean Reversion BB extreme + RSI <40/>60 + pivot level + triple trend filter BUY or SHORT SELL 1.5x ATR / 2.5x ATR
Equity Pivot Bounce/Break 6 patterns at S/R levels + real volume confirmation for BREAK BUY or SHORT SELL 1.5-2x ATR / 2.5-3x ATR

Key Advantages Over Index Options

FeatureIndex OptionsEquity Stocks
Volume dataAlways 0 (index spot)Real volume
VWAPApproximated from pivotCalculated correctly
BREAK confirmation2-candle momentum proxyReal volume surge (1.3x)
Order flowDead (no order book)buy/sell qty available
Theta decayEats position every minuteNo decay
IV crush riskCan kill profitable tradeNo IV risk
LeverageHigh (option premium)Low (full capital)

Risk Parameters

ParameterValue
Capital Pool₹2,00,000 (separate from options)
Risk per Trade1.5% of equity capital
Max Open Positions5 stocks simultaneously
Max Trades/Day10 across all stocks
No New Trades After14:45
MIS Auto-Squareoff15:15 (Zerodha MIS requirement)
Product TypeMIS (intraday only, no overnight)
ExchangeNSE
Short SellingSupported (MIS allows intraday short on all F&O stocks)
Position Sizingrisk_amount / (entry - SL) = number of shares

Execution Flow

Candle close for RELIANCE (token=738561) ↓ _check_equity_signals("RELIANCE", equity_chain) ├─ Risk check: equity positions < 5, trades < 10, time < 14:45 ├─ Layer 1: Equity Fast-Path (Supertrend flip + real VWAP + volume) ├─ Layer 2: Equity Mean Reversion (BB + RSI + pivots + trend filters) └─ Layer 3: Equity Pivot Bounce/Break (real volume BREAK!) ↓ Signal → Validate (R:R, RSI, spread) → execute_equity_entry() ↓ BUY or SHORT SELL on NSE (MIS) + broker SL order

Pivot Levels Reference

All pivot levels are calculated from previous day's OHLC data at system boot.

LevelFormulaUsed By
Pivot (P)(H + L + C) / 3All layers, Gemini, Pre-filter
TC (Top CPR)(P - BC) + PPivot Bounce/Break, Gemini
BC (Bottom CPR)(H + L) / 2Pivot Bounce/Break, Gemini
R1(2 × P) - LPivot Bounce/Break, Pre-filter, Gemini
R2P + (H - L)Pivot Bounce/Break, Gemini
R3R1 + (H - L)Gemini
S1(2 × P) - HPivot Bounce/Break, Pre-filter, Gemini
S2P - (H - L)Pivot Bounce/Break, Gemini
S3S1 - (H - L)Gemini
Cam H3C + (H-L) × 1.1/4Pivot Bounce/Break, Mean Reversion
Cam L3C - (H-L) × 1.1/4Pivot Bounce/Break, Mean Reversion
PDHPrevious Day HighPivot Bounce/Break, Gemini (strongest)
PDLPrevious Day LowPivot Bounce/Break, Gemini (strongest)
Weekly P/R1/S1Weekly OHLC pivotsGemini

Confidence by Level Strength (Pivot Bounce/Break)

TierLevelsBounce ConfBreak Conf
HighPDH, PDL, R1, S1, R2, S20.780.81
MediumPivot, TC, BC, CamH3, CamL30.720.75
BaseOther levels0.680.71

Technical Indicators

All indicators are calculated from 1-minute candle data using the TechnicalIndicators class.

IndicatorParametersUsed By
Supertrendperiod=10, multiplier=3Fast-Path (direction flip), Mean Reversion (trend filter)
Bollinger Bandsperiod=20, std=2Mean Reversion (overextension detection)
RSIperiod=14Mean Reversion (oversold <35, overbought >65), Pre-filter (<30/>70)
VWAPVolume-weighted averageAll layers (direction confirmation)
ATRperiod=14Fast-Path (SL/target sizing), Pivot (candle body filter)
EMA 9/21span=9, span=21Pre-filter (crossover trigger for Gemini)
Volume SMAperiod=20Fast-Path (1.5x surge), Pivot Break (1.3x surge)

File Map

Key source files and their responsibilities.

FileRole
strategy/scalper.pyMain engine — all 5 signal layers, cascade logic, signal logging, performance recording
strategy/signal_validator.pyValidation chain — Greeks, Pivot Boss rules, Volume Profile, MTF filters
strategy/entry_exit.pyOrder execution — entry/exit logic, position management, spread execution
risk/risk_manager.pyRisk checks — PnL limits, trade limits, VIX, market hours, correlation
risk/kill_switch.pyEmergency stop — daily loss limit, auto-exit all positions
ai/gemini_engine.pyGemini API — prompt construction, signal parsing, session memory
ai/market_state.pyMarket state builder — aggregates candles, pivots, VP, Greeks into AI prompt
data/candle_aggregator.pyCandle construction — builds 1min/5min/15min from ticks
data/indicators.pyTechnical indicators — Supertrend, BB, RSI, VWAP, ATR, EMA
data/pivots.pyPivot calculator — Standard, Camarilla, Fibonacci, CPR, weekly
data/options_chain.pyOptions chain — track all strikes, Greeks, OI, spot price
data/volume_profile.pyVolume profile — POC, VAH, VAL, value area calculations
broker/position_tracker.pyPosition tracking — open/closed positions, PnL, spreads
web/app.pyDashboard server — FastAPI, WebSocket, REST API for exits
web/templates/dashboard.htmlDashboard UI — real-time positions, signals, chain, analytics
core/models.pyData models — Tick, Signal, SpreadSignal, Indicators, MarketState
core/config.pyConfiguration — risk params, spread config, expiry day config
main.pyEntry point — wires all components, starts WebSocket + web server

Signal Layer Summary

Layer Trigger Speed Confidence Max/Day Cooldown
Fast-Path Supertrend flip (2-candle confirm) + VWAP + volume 1 min 0.80 1
Mean Reversion BB extreme + RSI <40/>60 + pivot S/R + 5min/1min ST + VWAP distance 1 min 0.64–0.77 2 10 min
Pivot Bounce/Break 6 patterns at pivots + 5min ST filter + CPR bias + index momentum 1 min 0.68–0.81 2 30 min/level
Gemini AI Full market analysis (pre-filtered) ~60s Dynamic 60s rate

Version History

v3.1 — Mar 28, 2026 (Current) — Options Revamp

  • CRITICAL CE entries restricted — CE lost ₹81,245 on 84 trades (21% WR). Fast-Path CE only on BULLISH bias. MR CE only on extreme reversal (S2/S3 + RSI < 25)
  • CRITICAL Pivot + VP layers disabled — Pivot was 95% of losing trades; VP was buying CE on bearish days. Both net losers.
  • NEW MR PE RSI+bias override — RSI > 70 + BEARISH bias overrides 5min/1min Supertrend block for SHORT PE. Unlocks slow grind-down days.
  • NEW Hour restrictions — Block 11:00 hour (consistent loser) + after 14:30. Focus on 10:00-13:00 window (12:00 = +₹42K).
  • IMPROVED Trend Rider volume relaxed — Skip volume filter for indices (Zerodha returns 0 volume for index spot). TR can finally fire.
  • IMPROVED Timezone v4 fix — _has_datetime_index() guard prevents RangeIndex crash after mid-day restart.
  • STRATEGY PE-focused system: Fast-Path (80% WR) → MR (PE bias override) → Trend Rider (volume relaxed). 3 active layers, down from 6.

v3.0 — Mar 1, 2026

  • NEW Equity Intraday Trading — 15 F&O stocks (RELIANCE, HDFCBANK, etc.) with BUY + SHORT SELL via MIS
  • NEW 3 equity signal layers: Fast-Path, Mean Reversion, Pivot Bounce/Break — same logic, real volume/VWAP
  • NEW EquityChain class — lightweight stock data handler (LTP, bid/ask, volume, day OHLC)
  • NEW Equity risk management — separate capital pool (₹2L), 5 max positions, MIS auto-squareoff at 15:15
  • NEW Dynamic lot sizes from Zerodha API — auto-updates if NSE changes lot sizes
  • NEW Blocked signals dashboard — shows filter activity (MR 5min ST: 5, Pivot CPR: 7)
  • IMPROVED MR position size capped at 2 lots (counter-trend = conservative sizing)
  • IMPROVED Scale-out uses whole lots only (can't sell half a lot in real trading)
  • IMPROVED SWING positions survive app restarts (saved to DB, not force-closed)
  • IMPROVED Market close buffer reduced to 10 min (was 20)
  • IMPROVED RSI SHORT filter relaxed (10 from 20) — allows trend-following PE entries in crashes
  • IMPROVED R:R upper bound (>10:1 rejected) — catches Gemini pricing errors
  • IMPROVED Signal/Position models generic — Optional strike/option_type for equity compatibility

v2.2 — Feb 27, 2026

  • CRITICAL FIX Fast-Path Supertrend never executed trades — 2-candle confirmation had variable aliasing bug (prev_dir already updated before direction check)
  • CRITICAL FIX Pivot BREAK signals never fired on indices — volume gate (1.3x SMA) always blocked because index spot has zero volume. Now uses 2-candle directional momentum as proxy
  • NEW Mean Reversion 1min Supertrend hard block — blocks counter-trend entries when immediate trend confirms (catches fast moves 5min misses)
  • NEW Mean Reversion VWAP distance filter — blocks entries when spot >0.3% away from VWAP against signal direction (prevents fading strong momentum)
  • IMPROVED Rule-based trade protection: 10-min hold minimum + AI exit only if loss >10%
  • IMPROVED Mean Reversion 5min Supertrend changed from penalty to hard block
  • REMOVED Order Flow Imbalance detector — indices have no order book (buy/sell quantity always 0)

v2.1 — Feb 2026

  • 5min Supertrend trend filter for pivot bounce signals
  • CPR bias check (blocks counter-trend bounces)
  • 30-min per-level cooldown for pivot signals
  • Smart AI exit management (hold minimum, winner protection)
  • 2-candle Supertrend confirmation for fast-path
  • Progressive trailing SL from +3%: 12%→8%→6%→4%
  • ATR-scaled dynamic SL for fast-path: 12-30%
  • Mean reversion RSI thresholds: 40/60 with confidence scaling
  • VWAP fallback for indices (daily pivot as proxy)
  • FIX: Consecutive loss cooldown infinite loop
  • FIX: All 4 rule-based layers dead (VWAP=0 on index candles)

v2.0 — Feb 2026

  • Pivot Bounce/Break detector (6 patterns)
  • Credit spread trading (Bull Put / Bear Call)
  • Pre-market AI analysis with Gemini
  • Multi-timeframe analysis (1min, 5min, 15min)
  • Volume profile, expiry day rules, index correlation check

v1.0 — Initial Release

  • Gemini AI signal generation, paper trading, dashboard, kill switch, basic risk management