Automated intraday Nifty options trading system with Greek-aware risk management, tiered firefighting adjustments, and real-time web dashboard. v7 scoring architecture.
nifty_trader/ โโโ agents/ # Market analysis agents โ โโโ global_macro.py # 31 global instruments, FII/DII, GIFT Nifty โ โโโ technical_analysis.py # RSI, MACD, BB, VWAP, SuperTrend, OI chain โ โโโ news_sentiment.py # RSS feeds, headline sentiment scoring โ โโโ market_intelligence.py # Participant OI analysis โ โโโ risk_manager.py # Portfolio-level risk assessment โ โโโ ai_advisor.py # Claude AI advisory (optional) โ โโโ strategy_engine.py # Strategy proposal generation โโโ core/ # Core trading logic โ โโโ orchestrator.py # Main workflow conductor โ โโโ strategy_scorer.py # v7 FMS + VIX multiplier scoring โ โโโ firefighter.py # 3-tier adjustment decision engine โ โโโ position_manager.py # Live position monitoring & exits โ โโโ risk_engine.py # Dynamic SL/trailing/rupee floors โ โโโ greeks.py # Black-Scholes delta calculator โ โโโ models.py # Data models (Position, Leg, OptionsChain) โ โโโ trend_analyzer.py # Multi-timeframe trend analysis โ โโโ expiry_selector.py # Weekly/monthly expiry logic โ โโโ margin_calculator.py # Per-strategy margin estimation โ โโโ learning_engine.py # Post-trade pattern learning โ โโโ parameter_tuner.py # Dynamic parameter optimization โโโ execution/ # Order execution layer โ โโโ trading_engine.py # Unified paper/live engine (WebSocket, monitoring) โ โโโ broker.py # Zerodha Kite API wrapper โ โโโ order_manager.py # Order placement & tracking โ โโโ kite_auth.py # Authentication (auto + manual) โ โโโ paper_trader.py # Paper trading simulation โโโ strategies/ # Strategy implementations โ โโโ base.py # Base class (strike selection, payoff calc) โ โโโ short_straddle.py # ATM CE+PE sell โ โโโ short_strangle.py # OTM CE+PE sell โ โโโ iron_condor.py # Credit spread both sides + wings โ โโโ bull_call_spread.py # Debit CE spread (bullish) โ โโโ bear_put_spread.py # Debit PE spread (bearish) โโโ dashboard/ # Web UI โ โโโ api_server.py # FastAPI backend (~4800 lines) โ โโโ index.html # Single-page dashboard (~3300 lines) โโโ data/ # Persistence โ โโโ trade_store.py # SQLite trade history + AI logs โ โโโ journal.py # Trade journaling โ โโโ market_feeds.py # Data feed helpers โโโ config/settings.py # All configuration โโโ tests/ # Comprehensive test suite
Sell ATM CE + ATM PE. Maximum premium collection. Best in neutral, low-VIX environments. FMS zone: -1 to +1.
Edge: Highest theta. Risk: Unlimited on both sides.
Sell OTM CE + OTM PE (200pts from ATM). Wider breakevens, lower premium. FMS zone: ยฑ1 to ยฑ2.
Edge: Higher win rate. Risk: Unlimited, lower premium cushion.
Short strangle + protective wings (300pts OTM). Last seller standing in mild trends. FMS zone: ยฑ3 to ยฑ5.
Edge: Capped risk. Risk: Lower credit, defined max loss.
Buy ATM CE + Sell OTM CE. Directional bullish. Needs FMS โฅ +3 (bullish trend confirmed).
Edge: Profits from rally. Risk: Net debit paid.
Buy ATM PE + Sell OTM PE. Directional bearish. Needs FMS โค -3 (bearish trend confirmed).
Edge: Profits from decline. Risk: Net debit paid.
Four-stage pipeline. No single indicator dominates โ all signals are fused into a single score.
FMS ranges from -10 (extreme bearish) to +10 (extreme bullish). Purely directional โ no VIX influence.
| Component | Weight | Source |
|---|---|---|
| Trend direction | 35% | EMA/SuperTrend/ADX from technical agent |
| MACD | 15% | Signal crossover strength + histogram direction |
| RSI | 15% | Overbought/oversold with momentum |
| Global Macro | 20% | 31 instruments: indices, futures, GIFT Nifty, FII/DII |
| Intraday Bias | 15% | VWAP position + 5min candle structure |
Each strategy has a score curve mapping FMS to a base score (0-100):
| FMS Zone | Straddle | Strangle | IC | BCS | BPS |
|---|---|---|---|---|---|
| -2 to +2 (neutral) | Highest | High | Medium | Low | Low |
| ยฑ3 to ยฑ5 (mild trend) | Drops off | Moderate | Peak | Rising | Rising |
| ยฑ6+ (strong trend) | Zero | Low | Low | Peak | Peak |
VIX level ร VIX direction creates a multiplier that scales base scores:
Sellers: VIX falling = boost (theta friendly). VIX rising + high = penalize (vol expansion risk).
Buyers: VIX rising = boost (movement helps). VIX falling = penalize (IV crush).
Hostility = composite of VIX level + trend strength + regime volatility. High hostility penalizes unlimited-risk sellers more than defined-risk strategies. IV Rank >60 boosts sellers (rich premiums), <30 boosts buyers.
Score = FMS_Base ร VIX_Mult ร Hostility_Mult ร IV_Rank_Mod
Threshold: 55%. Strategies scoring below are not recommended. Highest scorer gets SELECTED.
execution/trading_engine.py โ Unified engine for both paper and live trading.
WebSocket data: Live ticks for spot + all loaded option instruments via Kite WebSocket. Builds real-time OptionsChain with LTP, OI, volume, Greeks.
LTP-only pricing: All fills use last traded price (market orders). No bid/ask dependency.
Position monitoring: Every tick updates P&L, checks SL/trailing/time exit, computes loss severity for firefighter tier triggers.
Paper/Live unified: Same engine code. Paper mode simulates fills locally. Live mode places MARKET orders via Kite API.
| Parameter | Sellers | Buyers |
|---|---|---|
| Base SL | 30% of premium | 20% of debit |
| SL Floor | 20% (never wider) | 15% (never wider) |
| Trail Activation | 25-30% profit | 30% profit |
| Trail Floor | 70% of peak profit | 80% of peak profit |
| Rupee Floor | 30% of premium in โน | 20% of debit in โน |
| Time Exit | 3:00 PM | 3:00 PM |
SL tightens (never widens) based on: VIX rising, high VIX regime, short DTE, strong trend, low entry confidence, late session.
Called by Position Manager when loss severity reaches tier thresholds. Analyzes market context (bias, OI, macro, delta drift) and recommends the optimal adjustment.
| Tier | Severity | Straddle/Strangle | Iron Condor | BCS/BPS |
|---|---|---|---|---|
| TIER 1 | 30% of SL | Roll untested side (surge threshold) | Roll untested side | Narrow spread (roll short closer) |
| TIER 2 | 50% of SL | Roll untested (lower threshold) | Roll untested | Add ~25% extra short lots |
| TIER 3 | 70% of SL | Roll or tighten SL if max rolls | Roll or hold (defined risk) | Scenario: add shorts (drift) or longs (reversal) |
Special triggers:
Delta Tier: Independent of SL tiers. Fires when position delta drifts โฅ0.25 from entry. Unlimited rolls. Restores delta neutrality by rolling profitable side.
VIX Wing Buy: VIX spikes โฅ1.5% from entry โ buy both CE+PE wings immediately (straddle/strangle only). Converts to defined risk. Highest priority override.
Range Breach: After wings bought, if spot breaches wing strike โ guaranteed loser, exit immediately.
Max rolls: 1 at T1, 2 at T2, 3 at T3. When exhausted โ tighten SL for controlled exit.
Each adjustment's threshold is adjusted by a [-5, +5] urgency modifier based on: intraday bias confirming tested side (+3), OI sentiment (+2), OI momentum (+2), macro direction (+2), regime (trending +2, rangebound -2), trend duration, delta drift, VIX spike.
Fetches and scores 31 instruments across 6 categories: global indices (S&P 500, Nasdaq, Nikkei, Hang Seng, DAX, FTSE, Shanghai), US futures (ES, NQ, YM), GIFT Nifty, commodities (Gold, Crude, VIX), forex (DXY, USD/INR), and bonds (US 10Y, India 10Y).
FII/DII participant positioning from NSE with daily change analysis. 15-second refresh rate. Parallel fetching (10 workers).
Multi-timeframe analysis: RSI, MACD, Bollinger Bands (width %), VWAP, SuperTrend, ADX. Support/resistance via pivot points + previous day H/L. Options chain: PCR, max pain, IV percentile, OI buildup by strike.
RSS feeds from Economic Times, Moneycontrol, LiveMint. Headline-based sentiment scoring with market-impact keywords. Parallel fetching for speed.
Participant-level OI analysis: FII vs DII net long/short positioning. Change-based OI momentum (strong bullish โ strong bearish). Feeds into urgency modifier and FMS.
Single-page web app served by FastAPI. Real-time data via polling (30s scores, 5s positions). No external dependencies โ all charting via Chart.js.
| Tab | Content |
|---|---|
| ๐ Tech Overview | Spot, VIX, technicals, global macro grid (31 instruments), OI analysis, news feed |
| ๐ฏ Strategy Scores | v7 scoring breakdown, planned strikes, payoff diagram (BS with calibrated IV), adjustment plan |
| ๐ผ Positions | Live positions with P&L, firefighter status, mini payoff charts, activity logs |
| โ๏ธ Trading | Kite connection, engine start/stop, manual trade entry, paper/live toggle |
| ๐ History | Trade history from SQLite, win rate, strategy breakdown |
| ๐ง Learnings | AI-generated post-trade analysis, pattern observations, parameter suggestions |
| ๐ค AI Advisor | Claude AI interaction logs, advisory opinions on adjustments |
| ๐ Logs | Live system logs, filterable by level |
1. SCORING (every 30s during market hours)
Agents collect: macro score, technicals, OI, news sentiment
โ compute_fms() โ FMS score (-10 to +10)
โ FMS lookup โ base score per strategy
โ VIX multiplier โ hostility โ IV rank โ final score
โ Highest scorer above 55% threshold โ SELECTED
2. ENTRY
Selected strategy proposes strikes (ATM/OTM based on strategy)
โ Verify liquidity (LTP available for all legs)
โ Calculate risk_engine exit levels (dynamic SL, trail, rupee floor)
โ Place MARKET orders (paper: LTP fill, live: Kite MARKET)
โ Initialize position tracking (net premium, Greeks, base delta)
3. MONITORING (every tick, ~1-5s)
Update leg LTPs from WebSocket โ compute unrealized P&L
โ Check priority order:
a. TIME EXIT (3:00 PM) โ close all
b. RANGE BREACH (post-wings) โ close all
c. HARD SL (rupee floor or % SL) โ close all
d. TRAILING STOP (70/80% of peak) โ close all
e. ADJUSTMENT ZONE (30-100% of SL severity):
โ Build FirefighterContext (bias, OI, macro, delta, surge)
โ Firefighter.analyze() โ recommendation
โ Execute: roll untested / buy wings / add lots / tighten SL
f. NORMAL โ continue monitoring
4. EXIT
Close all legs via MARKET orders
โ Compute final P&L (realized + unrealized)
โ Store to SQLite with full market snapshot
โ AI post-trade analysis (optional)
โ Update learning engine patterns
| Component | Technology |
|---|---|
| Language | Python 3.11+ |
| Broker API | Zerodha Kite Connect (kiteconnect SDK) |
| Market Data | Kite WebSocket (live), yfinance (macro/fallback) |
| Web Server | FastAPI + Uvicorn |
| Dashboard | Vanilla HTML/JS + Chart.js (no framework) |
| Database | SQLite (trade_history.db) |
| AI (optional) | Claude API via LLM provider |
| Deployment | GCP VM (Ubuntu) or local Windows |