Risk Controls
| Control | Where | Value | Effect |
|---|---|---|---|
| Kill switch | check_kill_switch() | −₹10,000 / day | Halts ALL new trades |
| Risk envelope | RiskEnvelope.check_envelope() | Daily −₹10k · weekly −₹25k · monthly −₹50k · lifetime −₹1L | Runs after exits/reconciliation and before new-entry scanners; non-HEALTHY status skips all new entries. Closed live trade P&L updates risk_envelope_state; dry-run closes do not, so paper losses never pause or halt scans. Weekly totals reset on the ISO week and monthly totals on the calendar month of the close. (Before 2026-11-02 every update crashed on the NULL last_close_date, so the envelope had never counted a close.) |
| Loss-streak pause | risk_envelope_state.loss_streak_count | 3 losing days | Pauses new entries until the operator resumes with /resume_envelope confirm. |
| Lot lock | RiskEnvelope.lot_size_lock() | 30 days and ₹50k profit | Keeps promoted live strategies at 1 lot until both time and profit unlock conditions are met. |
| Max open positions | can_trade() | 10 | No new trades if 10 open |
| Max daily orders | can_trade() | 10 | Counts every order incl. reversals |
| Low balance | preflight() | < ₹1,20,000 | No new trades until topped up |
| Broker Health Guard | BrokerHealthMonitor + run_scan_cycle() | HEALTHY/DEGRADED/UNSTABLE/DOWN | Samples Dhan token, market feed, option-chain, order, position, and margin APIs each cycle. DEGRADED/UNSTABLE force dry-run entries; DOWN blocks new entries. |
| Portfolio Greeks gate | _portfolio_greeks_guard() | Δ/Gamma/Theta/Vega caps | Blocks new SHADOW/LIVE option entries when candidate Greeks would push portfolio exposure beyond configured absolute limits; dry-run entries proceed by default but record a safety event. |
| Strategy slots | ExecutionEngine._slot_guard() | dc_family = 2 | Allows one controlled scale-in while blocking a third DC-family entry. Occupancy is persisted in runtime_state.strategy_slots. |
| MDC scale-in gate | MasterDCScanner + validate_mdc_scale_in_anchor() | 90 min · max(200 pts, 50% straddle) · anchor P&L > −10% risk | Uses the newest remaining MDC position as anchor. Missing time, movement fields, live P&L, risk basis, or healthy OPEN state fails closed. |
| Exact option-leg duplicate guard | ExecutionEngine._exact_leg_duplicate_guard() | Complete security-ID set | Blocks identical DC-family broker exposure across base and MDC_* names before slot checks, dry-run persistence, or live orders. Malformed candidate or open-trade identity fails closed. |
| Min profit filter | BoxSpreadScanner | NIFTY ₹300 / BANKNIFTY ₹450 | Per-underlying threshold after all charges |
| Max margin / trade | BoxSpreadScanner | ₹80,000 | Skip capital-heavy boxes |
| DC margin cap | execute_double_calendar() | ₹1,50,000 | Skip if net debit × lot exceeds cap |
| DCS margin cap | execute_stretched_double_calendar() | ₹2,50,000 | Skip if 8-leg net debit × lot exceeds cap |
| AI_MARKET dry-run lock | execute_ai_market() | Phase 2 | Stores simulated single-leg trades only; confirmation-stage entries use live spot to pick the ATM strike and index-based exits. No broker orders are sent for AI decisions. |
| AI_MARKET trading-day gate | AutonomousMarketAnalyst | 09:05 / 09:20 / 15:25 IST | Skips weekends, cached NSE holidays, missing API key, disabled config, and duplicate same-stage same-day runs. The premarket thesis, live confirmation, and scoring jobs all wake through scheduler jobs. |
| AI_MARKET rerun OTP | /rerun_ai_market | Operator OTP | Manual same-day reruns require a short-lived Telegram OTP and preserve multiple analysis copies for the date. |
| AI_MARKET margin cap | Config.AI_MARKET_MAX_MARGIN | ₹1,00,000 | Caps planned simulated exposure for the AI strategy. |
| AI_MARKET daily budget | Config.AI_MARKET_DAILY_BUDGET_USD | $0.50 | Pre-call spend guard for the premarket + confirmation calls combined; the bot fails closed before starting another call once recorded spend reaches the budget. A call already in progress can finish slightly above the threshold. |
| Go-live confidence gate | GoLiveManager.check_confidence() | ≥30 closed dry-run trades over the last 60 trading days (only those on/after the strategy epoch), expectancy > 0 and profit factor ≥ 1.3 (CONFIDENCE_MIN_TRADES, CONFIDENCE_MIN_PROFIT_FACTOR) | /shadow is rejected until the strategy shows an edge after costs. Win rate is reported but no longer gates: MDC_DCS won 53% of 32 trades and lost ₹64k. Epochs for DC/DCS/SDCS/MDC are 2026-11-01 (db/109_strategy_epochs_exit_retune.sql), the PR #280 exit retune, so older trades taken under different rules do not count. A profit factor with no losing trade is reported as n/a and passes. |
| AI_MARKET promotion gate | load_ai_market_promotion_report() | AI dry-run performance + clean error log + forecast score | /shadow AI_MARKET and /promote AI_MARKET are rejected unless the AI usefulness report passes. |
| Live margin buffer | GoLiveManager.margin_ok() | Strategy max margin × 1.10 | Blocks SHADOW/LIVE entries when available balance lacks 10% headroom |
| Manual promotion | /promote <strategy> | SHADOW → LIVE only | No automatic go-live after the confidence gate; operator decides after shadow comparison |
| IOC + auto-reverse | _place_legs_ioc() | — | Never leaves partial box open |
| Startup reconciliation | reconcile_positions() | On startup | Alerts on orphaned positions and preserves existing broker safety checks |
| Position reconciliation auto-healer | ReconciliationService.run_cycle() | Every scan cycle | Removes tracked-flat trades only after 2 consecutive flat audits, adopts known orphan strategy shapes, and logs every action to SQLite. |
| Mismatch confirmation block | _recon_guard() + /confirm_recon | Per strategy before scan | Blocks new entries for a strategy while broker quantity mismatches are pending; operator acknowledgement clears the block. |
| Same-cycle re-entry guard | run_scan_cycle() | Per cycle | Blocks same-strategy re-entry after a real-order strategy closes in the same 30s window |
| Market event guard | EventCalendar.get_event_risk() | 7-day lookahead per strategy before scan | Blocks new DC/DCS/DCS_SKEW/DDC/MDC/IC entries ahead of seeded or fetched high-risk events; warning-only events set EVENT_RISK regime without blocking. |
| Event fetch isolation | run_market_event_fetch_job() | Source by source | One failing official source is logged and isolated; other sources and the seed file still update SQLite. |
| Operator risk view | /risk | On demand | Shows DC, DCS, DCS_SKEW, DDC, IC, and AI_MARKET risk fields with live P&L when available |
| Operator safety view | /safety | On demand | Shows live exposure, per-strategy live P&L, portfolio Greeks, kill switch, balance, and stale/drift indicators |
| Operator envelope view | /envelope | On demand | Shows envelope status, pause reason/until, current drawdown counters, and loss-streak count. Dashboard uses /api/envelope/state. |
| Signal explanation | /explain_signal dc|dcs|dcs_skew|sdcs|ddc|ic | Latest scan | Reports why each active option scanner signaled or skipped: DTE, chain, strike, IV, premium, duplicate, range, or margin context |
| Position audit | /audit_positions | On demand | Read-only comparison of open_trades against Dhan positions; reports flat/missing legs, quantity mismatches, and broker orphans |
| Reconciliation log | Dashboard /api/reconciliation/log | On demand | Shows removal, adoption, mismatch-pending, mismatch-confirmed, and orphan-alert rows from reconciliation_audit. |
| Portfolio Greeks panel | Dashboard /api/safety/portfolio-greeks | On demand | Shows total Greeks, configured limits, breach status, and strategy-wise contribution. |
| Broker health API | Dashboard /api/broker/health | On demand | Shows latest Broker Health Guard status, reasons, component latencies, and recent persisted samples. |
WS Protocol Extension (M2)
The Option Cockpit speaks the v2 WebSocket protocol at/ws/live?protocol_version=options_cockpit_ws_v2. The legacy/dashboard client remains on the immediate-tick legacy path. Failure to validate protocol_version, mode, andepoch on every inbound frame would let pre-ack legacy frames contaminate the cockpit; the v2 client must ignore any frame missing any of these three fields. Reconnect on close code 1008 fast-fails.