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.
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).
Daily Timeline
The system follows a structured schedule aligned with NSE market hours.
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.
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).
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.
All Layers Active
Fast-Path, Mean Reversion, and Pivot Bounce/Break activate. Indicators need ~15 candles warm-up. Gemini AI starts analyzing.
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.
No New Trades
"Too close to market close" — risk manager blocks all new entries. Only exit management continues.
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
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
Layer 2 — Mean Reversion
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)
Layer 3 — Pivot Bounce / Break
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)
Layer 4 — Gemini AI Analysis
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
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.
Greeks Validator
Checks IV rank, delta range, theta decay. Rejects if IV too low or Greeks unfavorable.
Pivot Boss Rules
Validates signal against CPR type, pivot bias, and trade setup. Can hard-reject or adjust confidence.
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.
MTF (Multi-Timeframe) Alignment
Checks if 5min/15min timeframes align with the signal direction. Misalignment → confidence penalty -0.10. Alignment → confidence boost.
Correlation Check
Prevents correlated positions (e.g., both NIFTY CE and BANKNIFTY CE). Blocks if same directional exposure exists across indices.
Index Direction Alignment
Checks if trade direction aligns with overall market bias (derived from both NIFTY and BANKNIFTY). Prevents counter-trend entries.
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
| Layer | Stop Loss | Target | Risk:Reward |
|---|---|---|---|
| Supertrend Fast-Path | ATR-scaled 12-30% | 1.5x SL dist | 1: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 Spread | 50% max loss | 50% max profit | Defined risk |
| Gemini AI | Dynamic | Dynamic | AI-determined |
Credit Spreads
Defined-risk premium collection strategy. Sells an OTM option and buys a further OTM option as hedge.
| Parameter | Value |
|---|---|
| Types | BULL_PUT (bullish) and BEAR_CALL (bearish) |
| Width | 100 points between strikes |
| VIX Range | 13 – 22 (only enter when VIX is in range) |
| Profit Target | 50% of premium collected |
| Stop Loss | 50% of max profit lost (tightened from 100%) |
| Max Loss | Width – Premium = defined max risk |
| Auto-Exit | 15:10 (20 min before market close) |
| Signal Source | Gemini AI (returns SpreadSignal type) |
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.
Stocks Traded (15 F&O Stocks)
Signal Layers (Same 3 Layers, Adapted for Stocks)
| Layer | Trigger | Direction | SL / 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
| Feature | Index Options | Equity Stocks |
|---|---|---|
| Volume data | Always 0 (index spot) | Real volume |
| VWAP | Approximated from pivot | Calculated correctly |
| BREAK confirmation | 2-candle momentum proxy | Real volume surge (1.3x) |
| Order flow | Dead (no order book) | buy/sell qty available |
| Theta decay | Eats position every minute | No decay |
| IV crush risk | Can kill profitable trade | No IV risk |
| Leverage | High (option premium) | Low (full capital) |
Risk Parameters
| Parameter | Value |
|---|---|
| Capital Pool | ₹2,00,000 (separate from options) |
| Risk per Trade | 1.5% of equity capital |
| Max Open Positions | 5 stocks simultaneously |
| Max Trades/Day | 10 across all stocks |
| No New Trades After | 14:45 |
| MIS Auto-Squareoff | 15:15 (Zerodha MIS requirement) |
| Product Type | MIS (intraday only, no overnight) |
| Exchange | NSE |
| Short Selling | Supported (MIS allows intraday short on all F&O stocks) |
| Position Sizing | risk_amount / (entry - SL) = number of shares |
Execution Flow
Pivot Levels Reference
All pivot levels are calculated from previous day's OHLC data at system boot.
| Level | Formula | Used By |
|---|---|---|
| Pivot (P) | (H + L + C) / 3 | All layers, Gemini, Pre-filter |
| TC (Top CPR) | (P - BC) + P | Pivot Bounce/Break, Gemini |
| BC (Bottom CPR) | (H + L) / 2 | Pivot Bounce/Break, Gemini |
| R1 | (2 × P) - L | Pivot Bounce/Break, Pre-filter, Gemini |
| R2 | P + (H - L) | Pivot Bounce/Break, Gemini |
| R3 | R1 + (H - L) | Gemini |
| S1 | (2 × P) - H | Pivot Bounce/Break, Pre-filter, Gemini |
| S2 | P - (H - L) | Pivot Bounce/Break, Gemini |
| S3 | S1 - (H - L) | Gemini |
| Cam H3 | C + (H-L) × 1.1/4 | Pivot Bounce/Break, Mean Reversion |
| Cam L3 | C - (H-L) × 1.1/4 | Pivot Bounce/Break, Mean Reversion |
| PDH | Previous Day High | Pivot Bounce/Break, Gemini (strongest) |
| PDL | Previous Day Low | Pivot Bounce/Break, Gemini (strongest) |
| Weekly P/R1/S1 | Weekly OHLC pivots | Gemini |
Confidence by Level Strength (Pivot Bounce/Break)
| Tier | Levels | Bounce Conf | Break Conf |
|---|---|---|---|
| High | PDH, PDL, R1, S1, R2, S2 | 0.78 | 0.81 |
| Medium | Pivot, TC, BC, CamH3, CamL3 | 0.72 | 0.75 |
| Base | Other levels | 0.68 | 0.71 |
Technical Indicators
All indicators are calculated from 1-minute candle data using the TechnicalIndicators class.
| Indicator | Parameters | Used By |
|---|---|---|
| Supertrend | period=10, multiplier=3 | Fast-Path (direction flip), Mean Reversion (trend filter) |
| Bollinger Bands | period=20, std=2 | Mean Reversion (overextension detection) |
| RSI | period=14 | Mean Reversion (oversold <35, overbought >65), Pre-filter (<30/>70) |
| VWAP | Volume-weighted average | All layers (direction confirmation) |
| ATR | period=14 | Fast-Path (SL/target sizing), Pivot (candle body filter) |
| EMA 9/21 | span=9, span=21 | Pre-filter (crossover trigger for Gemini) |
| Volume SMA | period=20 | Fast-Path (1.5x surge), Pivot Break (1.3x surge) |
File Map
Key source files and their responsibilities.
| File | Role |
|---|---|
strategy/scalper.py | Main engine — all 5 signal layers, cascade logic, signal logging, performance recording |
strategy/signal_validator.py | Validation chain — Greeks, Pivot Boss rules, Volume Profile, MTF filters |
strategy/entry_exit.py | Order execution — entry/exit logic, position management, spread execution |
risk/risk_manager.py | Risk checks — PnL limits, trade limits, VIX, market hours, correlation |
risk/kill_switch.py | Emergency stop — daily loss limit, auto-exit all positions |
ai/gemini_engine.py | Gemini API — prompt construction, signal parsing, session memory |
ai/market_state.py | Market state builder — aggregates candles, pivots, VP, Greeks into AI prompt |
data/candle_aggregator.py | Candle construction — builds 1min/5min/15min from ticks |
data/indicators.py | Technical indicators — Supertrend, BB, RSI, VWAP, ATR, EMA |
data/pivots.py | Pivot calculator — Standard, Camarilla, Fibonacci, CPR, weekly |
data/options_chain.py | Options chain — track all strikes, Greeks, OI, spot price |
data/volume_profile.py | Volume profile — POC, VAH, VAL, value area calculations |
broker/position_tracker.py | Position tracking — open/closed positions, PnL, spreads |
web/app.py | Dashboard server — FastAPI, WebSocket, REST API for exits |
web/templates/dashboard.html | Dashboard UI — real-time positions, signals, chain, analytics |
core/models.py | Data models — Tick, Signal, SpreadSignal, Indicators, MarketState |
core/config.py | Configuration — risk params, spread config, expiry day config |
main.py | Entry 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