Risk Controls

Risk Controls

ControlWhereValueEffect
Kill switchcheck_kill_switch()−₹10,000 / dayHalts ALL new trades
Risk envelopeRiskEnvelope.check_envelope()Daily −₹10k · weekly −₹25k · monthly −₹50k · lifetime −₹1LRuns 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 pauserisk_envelope_state.loss_streak_count3 losing daysPauses new entries until the operator resumes with /resume_envelope confirm.
Lot lockRiskEnvelope.lot_size_lock()30 days and ₹50k profitKeeps promoted live strategies at 1 lot until both time and profit unlock conditions are met.
Max open positionscan_trade()10No new trades if 10 open
Max daily orderscan_trade()10Counts every order incl. reversals
Low balancepreflight()< ₹1,20,000No new trades until topped up
Broker Health GuardBrokerHealthMonitor + run_scan_cycle()HEALTHY/DEGRADED/UNSTABLE/DOWNSamples 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 capsBlocks 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 slotsExecutionEngine._slot_guard()dc_family = 2Allows one controlled scale-in while blocking a third DC-family entry. Occupancy is persisted in runtime_state.strategy_slots.
MDC scale-in gateMasterDCScanner + validate_mdc_scale_in_anchor()90 min · max(200 pts, 50% straddle) · anchor P&L > −10% riskUses 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 guardExecutionEngine._exact_leg_duplicate_guard()Complete security-ID setBlocks 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 filterBoxSpreadScannerNIFTY ₹300 / BANKNIFTY ₹450Per-underlying threshold after all charges
Max margin / tradeBoxSpreadScanner₹80,000Skip capital-heavy boxes
DC margin capexecute_double_calendar()₹1,50,000Skip if net debit × lot exceeds cap
DCS margin capexecute_stretched_double_calendar()₹2,50,000Skip if 8-leg net debit × lot exceeds cap
AI_MARKET dry-run lockexecute_ai_market()Phase 2Stores 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 gateAutonomousMarketAnalyst09:05 / 09:20 / 15:25 ISTSkips 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_marketOperator OTPManual same-day reruns require a short-lived Telegram OTP and preserve multiple analysis copies for the date.
AI_MARKET margin capConfig.AI_MARKET_MAX_MARGIN₹1,00,000Caps planned simulated exposure for the AI strategy.
AI_MARKET daily budgetConfig.AI_MARKET_DAILY_BUDGET_USD$0.50Pre-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 gateGoLiveManager.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 gateload_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 bufferGoLiveManager.margin_ok()Strategy max margin × 1.10Blocks SHADOW/LIVE entries when available balance lacks 10% headroom
Manual promotion/promote <strategy>SHADOW → LIVE onlyNo automatic go-live after the confidence gate; operator decides after shadow comparison
IOC + auto-reverse_place_legs_ioc()—Never leaves partial box open
Startup reconciliationreconcile_positions()On startupAlerts on orphaned positions and preserves existing broker safety checks
Position reconciliation auto-healerReconciliationService.run_cycle()Every scan cycleRemoves 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_reconPer strategy before scanBlocks new entries for a strategy while broker quantity mismatches are pending; operator acknowledgement clears the block.
Same-cycle re-entry guardrun_scan_cycle()Per cycleBlocks same-strategy re-entry after a real-order strategy closes in the same 30s window
Market event guardEventCalendar.get_event_risk()7-day lookahead per strategy before scanBlocks 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 isolationrun_market_event_fetch_job()Source by sourceOne failing official source is logged and isolated; other sources and the seed file still update SQLite.
Operator risk view/riskOn demandShows DC, DCS, DCS_SKEW, DDC, IC, and AI_MARKET risk fields with live P&L when available
Operator safety view/safetyOn demandShows live exposure, per-strategy live P&L, portfolio Greeks, kill switch, balance, and stale/drift indicators
Operator envelope view/envelopeOn demandShows 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|icLatest scanReports why each active option scanner signaled or skipped: DTE, chain, strike, IV, premium, duplicate, range, or margin context
Position audit/audit_positionsOn demandRead-only comparison of open_trades against Dhan positions; reports flat/missing legs, quantity mismatches, and broker orphans
Reconciliation logDashboard /api/reconciliation/logOn demandShows removal, adoption, mismatch-pending, mismatch-confirmed, and orphan-alert rows from reconciliation_audit.
Portfolio Greeks panelDashboard /api/safety/portfolio-greeksOn demandShows total Greeks, configured limits, breach status, and strategy-wise contribution.
Broker health APIDashboard /api/broker/healthOn demandShows 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.