Back to home
Market Feed Angel One WebSocket MultiStrategyEngine Stochastic Cross Pullback-in-Trend Supertrend Flip VWAP Bias RSI conf=72 BUY RiskEngine 9 gates Kill Switch EXECUTE DELTAFORGE TRADING SYSTEM Slack Alerts | iMessage | Telegram | FastAPI Dashboard | SQLite Performance DB | Live Equity Curve
Build Log Jul 4, 2026 | 14 min read

DeltaForge: Building an Autonomous Options Trading System

Your strategy deserves better than a spreadsheet and a prayer.

Trading Systems Options Nifty 50 Risk Management Python Quantitative Finance
IK

Mohammed Imran Khan

Senior ML Engineer at Red Hat | Ex-Mercedes-Benz R&D

01 // Why I Built This

I trade Nifty 50 options intraday. Like most retail traders, I had a strategy that backtested beautifully but bled money in production. The problem was never the strategy. It was me. Late entries because I was in a meeting. Emotional exits because a candle looked scary. Position sizing that fluctuated with confidence rather than math.

The tools available were either overpriced terminals (₹2K-15K/month) that couldn't be customized, or fragile scripts taped together with cron jobs and prayers. I wanted something different: a production-grade system where I define the rules once, and the machine executes them with zero emotion, every single session. So I built one.

The Retail Trader's Problem

Manual Trading

  • You click buttons all day
  • "I'll stop at 5% loss" (you won't)
  • Fixed lots, guesswork sizing
  • Copy-paste into Excel

Paid Terminals

  • Alerts, but you still click
  • Basic SL/target
  • Separate backtest logic
  • ₹2,000–₹15,000/mo

DeltaForge

  • Fully autonomous execution
  • 9-gate risk + kill switch
  • Same engine: backtest = live
  • Free, open source

"Stop watching charts. Start trading systems."

02 // System Architecture

DeltaForge is a pipeline, not unlike a CI/CD system, but for money. Market data flows in from the left, passes through strategy evaluation, risk filtering, and position management, then exits as either an executed trade or a rejected signal.

Data Flow: Tick → Signal → Risk → Execute

WebSocket tick stream Nifty + MCX Candle Builder tick→OHLCV Strategy Engine 5 strategies Risk Engine 9 gates pass reject Position Mgr skip Kill Switch CapitalTracker

Market Data

market_feed.py - SmartWebSocketV2 real-time ticks

candle_builder.py - Tick to OHLCV aggregation

indicators_extended.py - HTF (15m) indicators

Signal Generation

multi_strategy_engine.py - 5 parallel strategies

premium_model.py - Black-Scholes delta/theta

strike_selector.py - ATM strike selection

Risk & Execution

risk_engine.py - 9-gate pre-trade filter

capital_tracker.py - Equity + compound sizing

position_manager.py - Lifecycle + trailing SL

Infrastructure

broker.py - Angel One SmartAPI wrapper

alerts/ - Slack, iMessage, Telegram

dashboard/ - FastAPI + WebSocket UI

03 // Multi-Strategy Engine

A single strategy is brittle. Markets are regime-dependent: what works in trending days fails on mean-reversion days. DeltaForge runs five strategies in parallel, each generating a signal with a confidence score. The engine picks the highest-confidence signal above threshold.

01

Stochastic Cross

%K crosses back from extreme zone (<25 or >75). EMA(9) vs EMA(21) confirms direction. HTF RSI boosts confidence when aligned.

02

Pullback-in-Trend

15-minute RSI confirms trend (|RSI-50| ≥ 10). Four LTF oscillators (RSI, Stochastic, CCI, Williams %R) detect pullback exhaustion.

03

Supertrend Flip

Supertrend(10,3) direction change with EMA + ADX confirmation. Fast Supertrend(7,2) boosts when both agree. ADX ≥ 15 required.

04

VWAP Bias

Intraday VWAP with daily reset. Signals aligned with VWAP position get +5 confidence boost. Acts as a conviction multiplier.

05

RSI Mean Reversion

Buy oversold dips (RSI < 38) in uptrends, sell overbought (> 62) in downtrends. Requires HTF confirmation and EMA20 alignment.

multi_strategy_engine.py
class MultiStrategyEngine:
    strategies = [
        StochasticCross(),
        PullbackInTrend(),
        SupertrendFlip(),
        VWAPBias(),
        RSIMeanReversion(),
    ]

    def evaluate(self, candle: OHLCV) -> Signal | None:
        # Run all strategies in parallel, pick highest confidence
        signals = [s.check(candle) for s in self.strategies]
        valid = [s for s in signals if s and s.confidence >= 50]
        return max(valid, key=lambda s: s.confidence, default=None)
Category Indicators
TrendEMA(9, 20, 21, 50), Supertrend(10,3), Supertrend(7,2)
MomentumRSI(14), Stochastic(14,3), CCI(20), Williams %R(14)
VolumeVWAP (intraday), Volume SMA(20)
VolatilityATR(14), Bollinger Bands %B
Multi-TF15-minute RSI via candle resampling

Walk-Forward Backtest (100+ days, Nifty 5m data, realistic costs)

~76%

Win Rate

2.62

Profit Factor

100+

Days Tested

Includes brokerage, STT, stamp duty, and slippage. Past performance does not guarantee future results.

04 // The 9-Gate Risk Model

This is the part that actually matters. A strategy that's 55% accurate with rigorous risk management will outperform a 75% strategy with none. Every signal must pass through all nine gates sequentially. A single failure means the trade is either rejected (signal skipped) or the system halts entirely.

9-Gate Risk Filter: Signal → Validation → Execute or Reject

Signal conf=72 G0 G1 G2 G3 G4 G5 G5.5 G6 G7 G8 GO HALT G1-G5 fail REJECT G5.5-G8 fail halt? cap daily week streak DD VIX exp time conf
Gate Check On Fail
0System not haltedReject
1Capital ≥ ₹3,000HALT
2Daily loss < 25% of day-start capitalHALT
3Weekly loss < 50% of starting capitalHALT
4Consecutive losses < 5HALT
5Drawdown < 35% from peakHALT
5.5India VIX ≤ 18Reject
6Not Nifty expiry dayReject
7Within entry window (9:20-14:30)Reject
8Signal confidence ≥ 50Reject

The key distinction: Reject means the signal is skipped but trading continues. HALT means the system stops for the entire session. Gates 1-5 trigger halts because they indicate something structurally wrong: you're losing too much money and need to stop.

risk_engine.py
class RiskEngine:
    # 9 gates - every signal must pass ALL before execution

    def check_gates(self, signal: Signal) -> GateResult:
        gates = [
            self._gate_system_active,       # 0: not halted
            self._gate_min_capital,          # 1: capital >= ₹3,000
            self._gate_daily_loss,           # 2: daily loss < 25%
            self._gate_weekly_loss,          # 3: weekly loss < 50%
            self._gate_consecutive_losses,   # 4: streak < 5
            self._gate_drawdown,             # 5: drawdown < 35%
            self._gate_vix,                  # 5.5: VIX ≤ 18
            self._gate_expiry_day,           # 6: not expiry
            self._gate_entry_window,         # 7: within hours
            self._gate_confidence,           # 8: conf ≥ 50
        ]
        for gate in gates:
            result = gate(signal)
            if not result.passed:
                return result  # REJECT or HALT
        return GateResult(passed=True)
05 // Compound Position Sizing

Fixed lot sizing leaves money on the table when you're winning and amplifies losses when you're not. DeltaForge uses compound position sizing that scales with your equity curve, but throttles aggressively during drawdowns.

Drawdown < 20%

Full Size

1 lot per ₹3,000 deployable capital. Maximum 50 lots.

Drawdown 20-35%

Half Size

Reduce exposure. Protect capital. Wait for recovery signal.

Drawdown ≥ 35%

HALT

No trades. System stops. Manual review required.

Deploy ratio: 60% of total capital is deployable

Lot sizing: 1 lot per ₹3,000 of deployable capital (configurable)

Atomic state: capital.json written via tmp + rename (crash-safe)

Options model: Black-Scholes delta≈0.70, slightly ITM, 15% SL, 2hr max hold

06 // Paper-Live Parity

Most trading systems have a dirty secret: the backtest code and the live code are different. Different indicator calculations, different order logic, different assumptions. You validate a strategy in backtest, deploy it live, and it behaves differently. DeltaForge eliminates this by using the exact same engine across all modes.

Backtest

Historical replay

same engine

Paper

Simulated fills

same engine

Live

Real execution

same engine

Signal generation • Risk gates • Position sizing • Indicators — ALL identical

The only difference between modes is what happens after the position manager decides to trade: paper mode simulates the fill with a realistic premium model (brokerage ₹20/order + STT + stamp duty + ₹1.5 slippage), while live mode hits the Angel One SmartAPI.

terminal - df trade
$ df trade

[09:15:01] Engine started in PAPER mode
[09:15:02] WebSocket connected - streaming Nifty ticks
[09:22:15] SIGNAL  Stochastic Cross  BUY  conf=72
[09:22:15] RISK    9/9 gates passed
[09:22:16] ENTRY   NIFTY 24500 CE @ ₹185.40  qty=50
[10:14:33] EXIT    ₹213.20  P&L +₹1,390  (+15.0%)
[15:30:00] EOD     3 trades | Net P&L +₹3,820 | Capital ₹13,820
07 // The Kill Switch

An autonomous trading system without a kill switch is a ticking bomb. DeltaForge's kill switch is an independent watchdog process, completely separate from the main trading engine. If the engine hangs, crashes, or enters an infinite loop, the kill switch still works.

Kill Switch: Independent Watchdog via File-Based Signaling

Main Process Engine RiskEngine halt file read Watchdog (independent) KillSwitch write df halt Dashboard Auto (breach)

Why file-based? Because it works even when the main process is hung. No IPC, no shared memory, no sockets. Just a file on disk. If the file exists, trading stops. Period. The risk engine checks it before every gate evaluation.

1

Automatic: Drawdown or consecutive loss breach triggers automatic halt

2

CLI: df halt - instant stop from terminal

3

Dashboard: Toggle in the web UI at localhost:8900

4

Manual: Create the halt file on disk. Works even if everything else is broken

08 // Lessons Learned

Building DeltaForge taught me things no blog post or course ever could. Here's what I'd tell anyone building a similar system:

1

Risk management is the product

The strategy is the easy part. Risk management (drawdown tiers, position sizing, circuit breakers) is what keeps you in the game long enough for your edge to compound.

2

Paper-live parity is non-negotiable

If your backtest uses different code than your live engine, you're not backtesting. You're writing fiction. One engine, three modes, zero divergence.

3

Your kill switch must be independent

If the kill switch runs in the same process as the trading engine, it dies with the engine. File-based signaling survives hangs, crashes, and infinite loops.

4

Alerts are your eyes when you're away

Instant Slack/iMessage/Telegram for every entry, exit, error, and EOD summary. You should know what your system did before you check it.

5

Multiple strategies beat single-strategy optimization

Markets are regime-dependent. A trending strategy fails on range days. Running five strategies with confidence scoring adapts to whatever the market throws at you.

$ echo "TL;DR"

DeltaForge is what happens when you stop treating trading as a hobby and start treating it as a systems engineering problem. Define your rules. Let the machine execute. Sleep well.

// What's Next

DeltaForge is shipped and trading, but the roadmap is far from done:

Shipped

  • Multi-strategy engine
  • Multi-asset (MCX + CDS)
  • Adaptive risk system
  • Walk-forward backtest
  • Automated scheduling

Next

  • BankNifty support
  • ML-based regime detection
  • Strategy marketplace

Future

  • Mobile companion alerts
  • Cloud sync
  • Broker-agnostic execution
  • Community strategies

Disclaimer

DeltaForge is educational software, not financial advice. Options trading involves substantial risk of loss and is not suitable for all investors. Past performance (backtested or otherwise) does not guarantee future results. The author is not a registered financial advisor. Use at your own risk. See the full disclaimer.

IK

Mohammed Imran Khan

Senior ML Engineer at Red Hat. Ex-Principal ML Engineer at Mercedes-Benz R&D Center. PhD Scholar. Building autonomous trading systems and agentic AI platforms.

-- views