๐Ÿ—๏ธ Nifty Trader โ€” System Architecture

Automated intraday Nifty options trading system with Greek-aware risk management, tiered firefighting adjustments, and real-time web dashboard. v7 scoring architecture.

System Overview

๐Ÿ“ก Kite WebSocket
Live ticks, OI, Greeks
โ†’
๐Ÿ”ฌ Analysis Agents
Macro, Tech, News, OI
โ†’
๐Ÿ“Š Strategy Scorer v7
FMS โ†’ Score โ†’ Select
โ†’
โšก Trading Engine
Entry, Monitor, Adjust
โ†’
๐Ÿš’ Firefighter
3-tier adjustments
โ†’
๐Ÿ’พ Trade Store
SQLite + Learnings

Directory Structure

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

5 Strategies

๐Ÿ”ด Short Straddle SELL ยท Unlimited Risk

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.

๐ŸŸ  Short Strangle SELL ยท Unlimited Risk

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.

๐ŸŸก Iron Condor SELL ยท Defined Risk

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.

๐ŸŸข Bull Call Spread BUY ยท Defined Risk

Buy ATM CE + Sell OTM CE. Directional bullish. Needs FMS โ‰ฅ +3 (bullish trend confirmed).

Edge: Profits from rally. Risk: Net debit paid.

๐Ÿ”ต Bear Put Spread BUY ยท Defined Risk

Buy ATM PE + Sell OTM PE. Directional bearish. Needs FMS โ‰ค -3 (bearish trend confirmed).

Edge: Profits from decline. Risk: Net debit paid.

Strategy Scoring โ€” v7 Architecture

Four-stage pipeline. No single indicator dominates โ€” all signals are fused into a single score.

Stage 1: Compute FMS (Final Market Sentiment)

FMS ranges from -10 (extreme bearish) to +10 (extreme bullish). Purely directional โ€” no VIX influence.

ComponentWeightSource
Trend direction35%EMA/SuperTrend/ADX from technical agent
MACD15%Signal crossover strength + histogram direction
RSI15%Overbought/oversold with momentum
Global Macro20%31 instruments: indices, futures, GIFT Nifty, FII/DII
Intraday Bias15%VWAP position + 5min candle structure

Stage 2: FMS โ†’ Base Score Lookup

Each strategy has a score curve mapping FMS to a base score (0-100):

FMS ZoneStraddleStrangleICBCSBPS
-2 to +2 (neutral)HighestHighMediumLowLow
ยฑ3 to ยฑ5 (mild trend)Drops offModeratePeakRisingRising
ยฑ6+ (strong trend)ZeroLowLowPeakPeak

Stage 3: VIX Multiplier

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).

Stage 4: Hostility ร— IV Rank

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.

Final Score

Score = FMS_Base ร— VIX_Mult ร— Hostility_Mult ร— IV_Rank_Mod

Threshold: 55%. Strategies scoring below are not recommended. Highest scorer gets SELECTED.

Trading Engine

execution/trading_engine.py โ€” Unified engine for both paper and live trading.

Lifecycle

๐Ÿ”Œ Start
Kite auth + WebSocket
โ†’
๐Ÿ“ฅ Load Instruments
NFO options chain
โ†’
๐Ÿ“Š Score Loop
Every 30s during market
โ†’
โšก Entry
Market orders, LTP fill
โ†’
๐Ÿ‘๏ธ Monitor
5s tick โ†’ P&L, Greeks
โ†’
๐Ÿš’ Adjust / Exit
SL, Trail, Firefighter

Key Features

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.

Risk Management

Dynamic Exit Levels (risk_engine.py)

ParameterSellersBuyers
Base SL30% of premium20% of debit
SL Floor20% (never wider)15% (never wider)
Trail Activation25-30% profit30% profit
Trail Floor70% of peak profit80% of peak profit
Rupee Floor30% of premium in โ‚น20% of debit in โ‚น
Time Exit3:00 PM3:00 PM

SL tightens (never widens) based on: VIX rising, high VIX regime, short DTE, strong trend, low entry confidence, late session.

Firefighter โ€” 3-Tier Adjustment Engine (firefighter.py)

Called by Position Manager when loss severity reaches tier thresholds. Analyzes market context (bias, OI, macro, delta drift) and recommends the optimal adjustment.

TierSeverityStraddle/StrangleIron CondorBCS/BPS
TIER 130% of SLRoll untested side (surge threshold)Roll untested sideNarrow spread (roll short closer)
TIER 250% of SLRoll untested (lower threshold)Roll untestedAdd ~25% extra short lots
TIER 370% of SLRoll or tighten SL if max rollsRoll 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.

Urgency Modifier

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.

Analysis Agents

๐ŸŒ Global Macro agents/global_macro.py

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).

๐Ÿ“ˆ Technical Analysis agents/technical_analysis.py

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.

๐Ÿ“ฐ News Sentiment agents/news_sentiment.py

RSS feeds from Economic Times, Moneycontrol, LiveMint. Headline-based sentiment scoring with market-impact keywords. Parallel fetching for speed.

๐Ÿ” Market Intelligence agents/market_intelligence.py

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.

Dashboard

Single-page web app served by FastAPI. Real-time data via polling (30s scores, 5s positions). No external dependencies โ€” all charting via Chart.js.

Tabs

TabContent
๐Ÿ“Š Tech OverviewSpot, VIX, technicals, global macro grid (31 instruments), OI analysis, news feed
๐ŸŽฏ Strategy Scoresv7 scoring breakdown, planned strikes, payoff diagram (BS with calibrated IV), adjustment plan
๐Ÿ’ผ PositionsLive positions with P&L, firefighter status, mini payoff charts, activity logs
โš™๏ธ TradingKite connection, engine start/stop, manual trade entry, paper/live toggle
๐Ÿ“ˆ HistoryTrade history from SQLite, win rate, strategy breakdown
๐Ÿง  LearningsAI-generated post-trade analysis, pattern observations, parameter suggestions
๐Ÿค– AI AdvisorClaude AI interaction logs, advisory opinions on adjustments
๐Ÿ“‹ LogsLive system logs, filterable by level

Data Flow โ€” Entry to Exit

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

Technology Stack

ComponentTechnology
LanguagePython 3.11+
Broker APIZerodha Kite Connect (kiteconnect SDK)
Market DataKite WebSocket (live), yfinance (macro/fallback)
Web ServerFastAPI + Uvicorn
DashboardVanilla HTML/JS + Chart.js (no framework)
DatabaseSQLite (trade_history.db)
AI (optional)Claude API via LLM provider
DeploymentGCP VM (Ubuntu) or local Windows