top of page

Get auto trading tips and tricks from our experts. Join our newsletter now

Thanks for submitting!

ES Put Ratio Spread Trading Bot: Complete Strategy Breakdown, Pseudocode Walkthrough, and How to Build It on a Professional Trading Bot Framework


Introduction: Why This Automated Trading Bot Deserves Your Attention


If you've spent any time researching algorithmic trading strategies, you already know that most retail trading bots are embarrassingly simple. A moving average crossover here, an RSI threshold there — and almost never any real risk management, volatility awareness, or options integration. The script we're dissecting today is the opposite of that. It's a sophisticated, multi-layered automated trading bot that combines three instruments into one coherent strategy: ES futures (E-mini S&P 500), a put ratio spread on ES options, and a VIX hedge using long calls on volatility.


This is the kind of architecture you'd expect to see inside a proprietary trading desk's research notebook — a volatility-aware options trading bot with its own Black-76 pricing model, dynamic position sizing, delta hedging logic, trailing stops, session-based loss limits, and a circuit breaker system that flattens everything when risk thresholds are breached.


In this article, we're going to do four things:


  1. Explain the complete trading logic behind this ES put ratio spread + VIX hedge bot in plain English.

  2. Walk through the full pseudocode of the script — no code samples, just clean, language-agnostic algorithmic steps you can implement in any programming language or platform.

  3. Show you how to use a professional trading bot framework as a base — specifically the IBKR Trading Bot Hub from hftcode.com — so you can port this pseudocode into a production-ready, multi-strategy automated trading system.

  4. Give you an important heads-up on pricing — because the price of that framework is going up soon, and the reasons why are worth understanding.


Whether you're a quant developer, a Python trading bot enthusiast, or someone preparing for a career in systematic trading, this breakdown will give you a reusable blueprint. Let's get into it.




What Is the ES Put Ratio Spread Trading Bot + VIX Hedge Bot?


At its core, this automated trading bot trades the E-mini S&P 500 futures contract (symbol ESM6 on the CME) with a long bias, but it doesn't just buy and hold futures. Every time it opens a futures position, it simultaneously constructs an options overlay designed to reshape the risk profile of the trade.


The options overlay has three components:


1. The Put Ratio Spread (the income engine). The bot buys one out-of-the-money put (roughly 5% below spot) and sells two puts closer to the money (roughly 2% below spot). This 1x2 put ratio spread collects premium from the short puts while the long put provides partial downside protection. In high implied volatility environments — when IV percentile is elevated — selling that extra put collects meaningfully more premium, which is exactly when this strategy wants to be active.

2. The Disaster Wing (the tail-risk guard). Because a naked 1x2 put ratio spread carries theoretically unlimited downside risk below the short strikes, the bot buys an additional deep out-of-the-money "disaster put" — pushed further away by a gap of roughly 6.7% of spot price. This converts the open-ended tail risk into a defined-risk structure. It's the difference between a strategy that survives a flash crash and one that doesn't.

3. The VIX Hedge (the volatility shock absorber). Finally, the bot buys out-of-the-money VIX calls — one or two contracts depending on signal strength. If the market sells off violently, volatility spikes, and these long VIX calls pay off precisely when the rest of the book is under stress. This is a classic cross-asset hedge used by institutional volatility traders.



On top of this structure, the bot runs a delta hedging engine that continuously measures the portfolio's total delta (futures delta plus options delta) and rebalances the futures position to keep directional exposure near a dynamically computed target. Add in historical volatility estimation, an implied volatility percentile rank, a VIX proxy, regime classification, adaptive position sizing, and a layered circuit breaker — and you have one of the more complete retail-accessible algorithmic trading strategies you'll find in a single file.


It's also explicitly a paper trading bot: it simulates fills, tracks cumulative, session, and weekly PnL, and logs everything as structured JSON events — which makes it a perfect candidate to port onto a real execution framework.




The Trading Logic, Explained Layer by Layer


Before we get to the pseudocode, let's understand the conceptual machinery. This options trading bot operates through five cooperating subsystems.


1. The Volatility Engine


Everything in this ES put ratio spread trading



es put ration spread trading bot

bot is downstream of volatility. On every market data tick, the bot:


  • Appends the latest price to rolling windows of prices, highs, lows, closes, and volume.

  • Computes log-style simple returns from consecutive closes and stores them in a returns window.

  • Computes the true range (the max of high-minus-low, absolute high-minus-previous-close, and absolute low-minus-previous-close) and maintains an Average True Range (ATR).

  • Derives historical volatility (HV) by taking the standard deviation of returns and annualizing it with the square root of 252.

  • Pulls implied volatility (IV) from the data feed if available; otherwise, it synthesizes an IV estimate from HV (floored at 8%) so the options pricing model always has a volatility input.

  • Maintains a 252-observation IV history and computes an IV percentile — the percentage of historical IV readings at or below the current reading. This single number drives strike selection, expiry targeting, risk percentage, credit requirements, and hedge ratios.

  • Builds a VIX proxy: if the feed provides a real VIX value, use it; otherwise clamp IV × 100 between 10 and 60.


The bot then classifies the environment into one of four volatility regimes: LOW_VOL, MID_VOL, HIGH_VOL, or EXTREME_VOL. Regime classification influences signal strength, risk scaling, and position size multipliers. This is what separates a serious volatility trading strategy from a static one — the bot literally trades differently depending on the volatility weather.


2. Dynamic Risk Management


The risk system is where this ES put ratio spread trading bot really earns its keep. Rather than fixed stop losses and fixed sizes, everything adapts:


  • Dynamic risk percentage: Base risk per trade starts at 2% of the $250,000 simulated account, decays as IV percentile rises, and is then multiplied by a VIX-based adjustment factor (1.0 in calm markets down to 0.25 when the VIX proxy exceeds 35). The result is clamped between 1% and 2%.

  • Dynamic ATR multiplier: Stop distances widen as volatility expands — between 2x and 3x the volatility measure, scaled by both IV percentile and the VIX proxy.

  • Dynamic reward-to-risk ratio: The bot computes a rolling win rate and a Sharpe-like proxy from its last 50 simulated trades. The required reward-to-risk ratio is 1 + win rate + max(0, Sharpe proxy), floored at 1.2. Critically, entries are blocked entirely if the computed ratio falls below 2.0 — the bot refuses to take trades where the math doesn't justify the risk.

  • Position sizing: Risk capital (account × dynamic risk %) is divided by the stop distance in dollars (stop distance × $50 point value), then scaled down by the VIX adjustment and an additional 25% haircut when IV percentile exceeds 80. The result is clamped between 1 and 4 contracts.


3. Loss Limits and the Circuit Breaker


This is institutional-grade behavior rarely seen in retail bots:


  • Daily loss limit: Calculated as the negative of (volatility measure × contracts × point value × a session risk multiplier that grows with IV percentile and VIX). Breach it and the bot flattens everything.

  • Weekly loss limit: The lesser (in absolute terms) of 2x the daily limit or 10% of total account capital.

  • Consecutive loss kill switch: Five losing trades in a row trips the breaker.

  • Session resets: Daily PnL, consecutive losses, and the circuit breaker reset each new UTC date; weekly PnL resets each Monday.

  • CME maintenance window awareness: The bot knows the CME's daily settlement/maintenance window (5 PM ET Monday–Thursday, 4 PM ET Friday, using a fixed UTC-4 offset) and refuses to hold exposure through it — it flattens and stands down.


4. Signal Generation and Entry Logic


The bot is flat by default and only enters long when a composite signal strength score clears a volatility-scaled threshold. The signal combines:


  • Trend: A fast moving average (10% of the price window) minus a slow moving average (30% of the window), normalized by the slow MA.

  • VWAP deviation: How far price sits from a volume-weighted average price computed over the rolling window, weighted at 0.5.

  • IV–HV edge: The spread between implied and historical volatility, weighted at −0.2 (rich implied vol dampens the long signal).

  • Recession bias: A constant 0.1 boost, doubled in HIGH_VOL and EXTREME_VOL regimes — the bot leans into fear because that's when the put ratio spread collects the most premium.


The entry threshold itself is dynamic: the average absolute return plus one-tenth of HV. In quiet markets the bar is low; in chaotic markets the bar rises. Entries also require the bid-ask spread check to pass (spread must be under a dynamically tightened 0.35% ceiling that narrows further as IV percentile rises) and the reward-to-risk gate of 2.0.


5. Trade and Structure Management


Once in a position, the bot manages two things in parallel: the futures trade and the options structure.


For the futures leg, it maintains a trailing stop that ratchets in the trade's favor (trail distance shrinks as the rolling win rate improves), a hard base stop at entry minus/plus the stop distance, and a profit target at entry plus stop distance × reward-to-risk ratio. Hitting either boundary flattens the entire book — futures and options together.


For the options structure, it marks every leg to market each tick using its internal Black-76 model, aggregates the portfolio Greeks, and enforces a DTE exit: when days-to-expiry falls to a small threshold (the greater of 5 days or 5% of the minimum target DTE), the options are closed regardless of PnL. The delta of the options feeds the delta hedging engine, which we'll cover next.




The Black-76 Pricing and Delta Hedging Engine


Most retail trading bot source code you'll find online treats options as an afterthought. This bot does the opposite: it ships with a self-contained implementation of the Black-76 model — the standard for pricing options on futures — including a hand-rolled exponential function, a Newton-Raphson natural logarithm, a normal probability density function, and the classic Abramowitz-Stegun rational approximation for the normal cumulative distribution function. No external math libraries required.


For each option leg, the model computes:


  • Price (discounted expected payoff under a lognormal forward distribution)

  • Delta (sensitivity to the underlying forward price)

  • Gamma (rate of change of delta)

  • Theta (time decay, including the carry term)

  • Vega (sensitivity to implied volatility)

  • Rho (interest rate sensitivity)


A fixed 3% risk-free rate is used for discounting. VIX legs are priced with a 15% IV markup over the ES implied vol, floored at historical vol — a pragmatic proxy for the vol-of-vol premium you see in real VIX options markets.


The delta hedging loop then works like this: the bot computes a hedge ratio equal to 1 minus half the IV percentile (clamped between 0.5 and 1.0). The target delta is the futures position size multiplied by that hedge ratio. The portfolio delta is futures position plus aggregate options delta. If the delta error exceeds 10% of the target (or 0.1 in absolute terms), the bot buys or sells futures — in whole contracts, capped at 4 — to pull the portfolio back toward neutral-ish exposure. As implied volatility rises, the hedge ratio drops toward 0.5, meaning the bot deliberately runs less directional exposure exactly when markets are most dangerous. That's thoughtful, professional design.




The Complete Pseudocode Walkthrough


Here is the entire bot expressed as pseudocode — language-agnostic, implementation-ready, and free of any actual code samples. Use this as your blueprint.


Section 1 — Initialization


ALGORITHM: Initialize Bot


SET bot identity:

    name        ← "S&P 500 (ES) Put Ratio Spread + VIX Hedge"

    symbol      ← "ESM6"

    exchange    ← "CME"

    strategy    ← "ES 1x2 Put Ratio Spread + Long VIX Calls (Paper)"

    direction   ← LONG

    max futures contracts ← 4


SET market state:

    last price, best bid, best ask ← 0

    daily loss limit, weekly loss limit ← 0


SET simulated futures account:

    position ← 0 (flat)

    average entry price ← none

    entry timestamp ← none

    trade history ← empty list

    cumulative PnL ← 0

    account capital ← 250,000

    point value ← 50 dollars per index point


SET risk controls:

    consecutive losses ← 0

    circuit breaker ← OFF


CREATE rolling data windows:

    prices (600), highs/lows/closes (120), returns (240)

    true ranges (60), IV history (252), HV history (252)

    spread history (240), volume history (240)


SET volatility state:

    current IV ← 0, current HV ← 0

    IV percentile ← 50

    volatility regime ← "MID_VOL"

    VIX proxy ← 22


SET options/Greeks state:

    portfolio delta, gamma, theta, vega, rho ← 0

    hedge ratio ← 1.0, target delta ← 0

    max allowed futures spread ← 0.35% of mid


SET trade management state:

    trailing stop, stop price, target price ← none

    entry reward-to-risk ← 0

    last signal ← "FLAT"


SET options position:

    inactive, no legs, no expiry, zero entry premium


SET session anchors:

    current session date ← none

    current week anchor ← none

    session realized PnL ← 0

    week realized PnL ← 0


SET logging timers:

    diagnostics, unrealized PnL, metrics ← one poll interval in the past

    last tick timestamp ← none


CONNECT to message bus (Redis) for market data events

LOG "STRATEGY_INIT" event



Section 2 — Mathematical Helpers


FUNCTION normal_pdf(x):

    RETURN (1 / sqrt(2π)) × exp(−x² / 2)


FUNCTION normal_cdf(x):

    // Abramowitz–Stegun rational approximation

    k ← 1 / (1 + 0.2316419 × |x|)

    polynomial ← (((((1.330274429×k − 1.821255978)×k + 1.781477937)×k

                    − 0.356563782)×k + 0.319381530)×k)

    estimate ← 1 − normal_pdf(|x|) × polynomial

    RETURN estimate IF x ≥ 0 ELSE 1 − estimate


FUNCTION black76_price_and_greeks(forward, strike, time_years, iv, is_call, quantity):

    IF forward ≤ 0 OR strike ≤ 0 OR time_years ≤ 0 OR iv ≤ 0:

        RETURN all zeros

    rate ← 3%

    vol_time ← iv × sqrt(time_years)

    d1 ← (ln(forward/strike) + 0.5 × iv² × time_years) / vol_time

    d2 ← d1 − vol_time

    discount ← exp(−rate × time_years)


    IF is_call:

        price ← discount × (forward×N(d1) − strike×N(d2))

        delta ← discount × N(d1)

        theta ← −discount×forward×pdf(d1)×iv / (2×sqrt(t))

                 + rate × price

    ELSE:

        price ← discount × (strike×N(−d2) − forward×N(−d1))

        delta ← −discount × N(−d1)

        theta ← −discount×forward×pdf(d1)×iv / (2×sqrt(t))

                 + rate × price


    gamma ← discount × pdf(d1) / (forward × iv × sqrt(t))

    vega  ← discount × forward × pdf(d1) × sqrt(t)

    rho   ← −time_years × price


    RETURN price, delta, gamma, theta, vega, rho — each × quantity




Section 3 — Volatility and Regime Measurement


FUNCTION compute_historical_volatility:

    IF fewer than 10 returns: RETURN 0

    mean ← average of returns

    variance ← average of squared deviations from mean

    RETURN max(sqrt(variance) × sqrt(252), 0.0001)


FUNCTION compute_average_true_range:

    RETURN average of true range window (0 if empty)


FUNCTION compute_iv_percentile(current_iv):

    IF fewer than 20 IV observations: RETURN 50

    count ← number of historical IV values ≤ current IV

    RETURN (count / history length) × 100


FUNCTION classify_volatility_regime:

    IF IV percentile ≥ 80 OR VIX proxy ≥ 35: RETURN "EXTREME_VOL"

    IF IV percentile ≥ 70 OR VIX proxy ≥ 25: RETURN "HIGH_VOL"

    IF IV percentile ≤ 30 OR VIX proxy < 15:  RETURN "LOW_VOL"

    RETURN "MID_VOL"



Section 4 — Dynamic Risk and Sizing


FUNCTION dynamic_risk_percent:

    base ← 2% − (IV percentile / 100) × 1%

    adjustment ← 1.0  if VIX < 15

                 0.75 if VIX < 25

                 0.50 if VIX < 35

                 0.25 otherwise

    RETURN clamp(base × adjustment, min 1%, max 2%)


FUNCTION dynamic_atr_multiplier:

    mult ← 2.0 + IV percentile/100 + VIX proxy/100

    RETURN clamp(mult, min 2.0, max 3.0)


FUNCTION rolling_win_rate:

    IF no trades: RETURN 0.5

    RETURN winning trades / total trades


FUNCTION sharpe_proxy:

    IF fewer than 5 trades: RETURN 0

    pnls ← last 50 trade PnLs

    RETURN mean(pnls) / stddev(pnls), or 0 if stddev is 0


FUNCTION dynamic_reward_to_risk:

    rr ← 1 + rolling_win_rate + max(0, sharpe_proxy)

    RETURN max(rr, 1.2)


FUNCTION update_loss_limits(volatility_measure):

    contracts ← max(1, |position| if positioned else max contracts)

    session multiplier ← 1 + IV percentile/100 + VIX proxy/100

    daily loss limit ← −(volatility_measure × contracts × point value × session multiplier)

    weekly loss limit ← the more conservative of

                        (2 × daily limit) and (−10% of account capital)


FUNCTION compute_position_size(stop_distance):

    risk capital ← account capital × dynamic_risk_percent

    raw size ← risk capital / (stop_distance × point value)

    apply VIX adjustment (same ladder as above)

    IF IV percentile > 80: apply additional 25% reduction

    RETURN clamp(integer size, min 1, max 4)


FUNCTION spread_is_acceptable:

    mid ← average of bid and ask (fallback: last price)

    IF mid ≤ 0: RETURN false

    record spread/mid into spread history

    allowed ← 0.35% × (1 − IV percentile/100 × 0.25), floored sensibly

    RETURN spread/mid ≤ allowed



Section 5 — Option Structure Construction


FUNCTION target_expiry(now, dte_min, dte_max):

    target days ← midpoint of (dte_min, dte_max), rounded

    provisional ← now + target days

    expiry ← next Friday on or after provisional

    IF expiry ≤ now: expiry ← expiry + 7 days

    RETURN expiry


FUNCTION build_option_structure(spot, now, signal_strength):

    IF IV percentile > 70: DTE range ← 30 to 45 days

    ELSE:                  DTE range ← 45 to 90 days


    expiry ← target_expiry(now, DTE range)

    time in years ← max(days to expiry, 1) / 365


    regime adjustment ← 1 + VIX proxy/100

    long put strike   ← spot × (1 − 5% × regime adjustment)

    short put strike  ← spot × (1 − 2% × regime adjustment)

    disaster strike   ← lowest of the above, extended by the put wing width,

                        then minus a gap of 6.7% × spot

    VIX call strike   ← max(VIX proxy, 1) × 1.10


    minimum option mid ← spot × 0.05%

    IV multiplier ← clamp(IV percentile / 50, 0.5, 2.0)

    premium budget ← spot × (1.5% + IV percentile/100 × 1.0%) × spot × IV multiplier

    minimum required credit ← 10% of premium budget


    IF current IV ≤ 0: current IV ← max(current HV, 12%)


    legs ← [ +1 long put, −1 short put, −1 short put (the ratio),

             +1 disaster put, +(1 or 2) VIX calls based on signal strength ]


    FOR each leg:

        underlying price ← spot for ES legs, VIX proxy for VIX legs

        leg IV ← current IV for ES; max(IV × 1.15, HV) for VIX

        greeks ← black76(underlying, strike, time, max(leg IV, 5%), type, |qty|)

        mid ← max(greeks price, minimum option mid)

        bid ← mid × (1 − (10% + IV percentile/1000))

        ask ← mid × (1 + (10% + IV percentile/1000))

        spread ratio ← (ask − bid) / mid


        REJECT structure if mid < minimum option mid

        REJECT structure if spread ratio > 35%


        accumulate signed premium (negative qty × mid = credit collected)

        record leg with name, type, qty, strike, mid, bid, ask, spread ratio


    IF IV percentile > 70 AND net credit < minimum required credit:

        REJECT structure


    RETURN active structure with legs, expiry, entry premium,

           estimated max profit (2× premium), estimated max loss (3× premium)




Section 6 — Marking, Greeks, and Delta Rebalancing


FUNCTION mark_options_and_greeks(now):

    IF no active options: RETURN 0

    time in years ← max(days to expiry, 1) / 365

    total mark, delta, gamma, theta, vega, rho ← 0

    FOR each leg:

        price the leg with black76 using current underlying and IV

        sign ← +1 if long, −1 if short

        total mark += signed price

        accumulate each Greek × sign

    STORE gamma, theta, vega, rho as current portfolio Greeks

    RETURN total mark


FUNCTION recompute_target_delta:

    hedge ratio ← clamp(1 − (IV percentile/100) × 0.5, 0.5, 1.0)

    target delta ← futures position × hedge ratio


FUNCTION rebalance_delta_if_needed:

    portfolio delta ← futures position + options delta

    allowed error ← max(10% of |target delta|, 0.1)

    error ← portfolio delta − target delta

    IF |error| ≤ allowed error: DO NOTHING, RETURN

    IF price ≤ 0: RETURN

    hedge quantity ← clamp(integer of |error|, 1, max contracts)

    IF error > 0: SELL hedge quantity of futures

    ELSE:         BUY hedge quantity of futures

    clamp resulting position to ±max contracts

    apply position change with reason "DELTA_REBALANCE"

    LOG "HEDGE_REBALANCE" event



Section 7 — Position Accounting


FUNCTION apply_position_change(new position, trade price, now, reason):

    IF new = old: RETURN


    CASE flat → positioned:

        set position, entry price, entry time

        LOG "SIM_ENTRY"


    CASE same direction (scaling in):

        IF adding contracts:

            entry price ← weighted average of old and new fills

        update position; LOG "POSITION_SCALE"


    CASE reducing or flipping:

        closed quantity ← contracts being closed

        PnL ← (exit − entry) × closed qty × point value   [if long]

              (entry − exit) × closed qty × point value   [if short]

        record trade; add PnL to cumulative, session, and weekly totals

        IF PnL < 0: consecutive losses += 1 ELSE reset to 0

        LOG "SIM_EXIT"

        IF now flat: clear entry price, stops, and targets

        IF flipped: open new position at trade price; LOG "SIM_ENTRY"


FUNCTION flatten_everything(now, reason):

    IF futures position ≠ 0 and price > 0:

        apply_position_change(0, price, now, reason)

    IF options active:

        close_options(now, reason)


FUNCTION close_options(now, reason):

    mark ← mark_options_and_greeks(now)

    PnL ← (mark − entry premium) × point value

    record trade; update PnL totals and consecutive-loss counter

    LOG "SIM_EXIT" (instrument: OPTIONS)

    reset options position to inactive



Section 8 — The Main Market Data Loop


ALGORITHM: On Every Market Data Event


1.  now ← current UTC time

2.  IF new calendar day: reset session PnL, consecutive losses, circuit breaker

    IF new week (Monday anchor): reset weekly PnL

3.  extract price from data (price / last / trade_price / close / mark)

    IF price missing or ≤ 0: DISCARD tick entirely

4.  extract bid and ask (default to price); sanitize so ask ≥ bid > 0

5.  extract volume; LOG raw tick

6.  append price to rolling windows (prices, highs, lows, closes, volume)

7.  IF at least 2 closes:

        append simple return to returns window

        append true range to true range window

8.  current HV ← compute_historical_volatility; append to HV history

9.  current IV ← feed IV if present (normalize if given in %)

                 else derive from HV, floored at 8%

    append to IV history; IV percentile ← compute_iv_percentile

10. VIX proxy ← feed VIX if present else clamp(IV × 100, 10, 60)

11. volatility regime ← classify_volatility_regime

12. ATR ← average true range

    volatility measure ← max(ATR, HV × price)

    update_loss_limits(volatility measure)

13. CIRCUIT BREAKER CHECKS:

    IF session PnL ≤ daily loss limit:    breaker ON, flatten ("DAILY_LOSS_LIMIT")

    IF weekly PnL ≤ weekly loss limit:    breaker ON, flatten ("WEEKLY_LOSS_LIMIT")

    IF consecutive losses ≥ 5:            breaker ON, flatten ("CONSECUTIVE_LOSSES")

14. IF inside CME maintenance window:

        flatten everything ("CME_MAINTENANCE_WINDOW"); STOP processing

15. options mark ← mark_options_and_greeks

    IF options active AND days-to-expiry ≤ max(5, 5% of min target DTE):

        close_options ("DTE_EXIT")

16. rebalance_delta_if_needed

17. trend ← (fast MA − slow MA) / slow MA   [fast = 10% of window, slow = 30%]

18. VWAP ← volume-weighted average of window (weight 1 if volume is 0)

    VWAP deviation ← (price − VWAP) / VWAP

    IV−HV edge ← current IV − current HV

    recession bias ← 1.0 in HIGH/EXTREME vol, else 0.5

    signal strength ← trend + 0.5×VWAP dev − 0.2×IV−HV edge + 0.1×recession bias

19. stop distance ← volatility measure × dynamic ATR multiplier

    reward-to-risk ← dynamic_reward_to_risk

20. IF positioned:

        update unrealized PnL

        ratchet trailing stop toward price (distance shrinks as win rate rises)

        stop price ← worst of base stop and trailing stop

        target price ← entry ± stop distance × reward-to-risk

        IF price breaches stop:   flatten ("STOP_HIT")

        IF price reaches target:  flatten ("TARGET_HIT")

21. once per poll interval: LOG unrealized PnL + Greeks snapshot

22. IF breaker OFF and flat:

        IF spread not acceptable:    signal ← "BLOCKED_SPREAD"

        ELSE IF reward-to-risk < 2:  signal ← "BLOCKED_RR"

        ELSE:

            threshold ← avg|returns| + HV/10

            IF signal strength > threshold:

                quantity ← compute_position_size(stop distance)

                ENTER long futures at ask

                build and open option structure

                signal ← "ENTERED_LONG"

            ELSE: signal ← "NO_ENTRY"

23. once per poll interval: LOG full diagnostics (price, spread, position,

    PnL, limits, regime, IV/HV/percentile, VIX proxy, signal, Greeks,

    options status/DTE/mark, feed staleness)

24. once per poll interval: compute and LOG performance metrics



Section 9 — The Run Loop and Startup


ALGORITHM: Run Loop


START bot (connect to message bus and market data channels)

run strategy initialization

WHILE bot is running:

    IF last tick is older than 2 × poll interval:

        LOG "STALE_FEED_WARNING" with seconds elapsed

    sleep 1 second

ON shutdown: disconnect cleanly


ALGORITHM: Startup (main)


REGISTER bot name and symbols with the bot registry

LOAD environment variables from .env file

VERIFY required credentials exist (Rithmic user, password, system name,

    app name, server URL, FCM ID, IB ID) — abort with error if any missing

CREATE bot instance

RUN the async run loop



That pseudocode is the entire system: roughly nine cooperating algorithms covering data ingestion, volatility estimation, options pricing, structure construction, hedging, accounting, and risk supervision. Any competent developer can implement this in Python, C#, Java, or TypeScript — which brings us to the fastest path to production.




Using This Strategy as a Base on the IBKR Trading Bot Hub


Here's the honest truth about the script we just dissected: the strategy logic is excellent, but it's a paper trading simulation wired to a single data feed. There's no real order routing, no broker-side bracket orders, no portfolio margin awareness, no multi-bot orchestration, and no AI-assisted signal filtering. If you wanted to trade this live, you'd have to build all of that plumbing yourself — months of work, and months of debugging edge cases that have nothing to do with your edge.


This is exactly the gap that the IBKR Trading Bot Hub from hftcode.com fills.


The Trading Bot Hub is a production-ready Python framework built on the Interactive Brokers API with a single TWS connection that multiplexes unlimited trading bots simultaneously. It ships with four complete strategies out of the box — NVDA/BHP SMA crossover, EUR/USD RSI, and XAUUSD Bollinger — plus a Claude AI filter layer and full source code. It's enterprise architecture: the connection management, contract handling, order state machines, and multi-strategy routing are already solved.

Now think about how naturally the pseudocode above maps onto that hub:


  • The main market data loop (Section 8) becomes a new bot module subscribed to ES futures market data through the hub's shared TWS connection — no Redis polling, no feed-staleness hacks, just real tick events from Interactive Brokers.

  • The option structure builder (Section 5) plugs into IBKR's options chains: instead of synthetically estimating mids with a slippage band, you request real bid/ask quotes for the ES option strikes the algorithm selects, and the existing spread-ratio and minimum-credit gates become genuine execution-quality checks.

  • The Black-76 engine (Sections 2 and 6) stays almost exactly as-is — it becomes your pre-trade pricing sanity layer, comparing theoretical values against live market quotes before any order is sent. You can also cross-check against IBKR's model Greeks.

  • The delta hedging loop (Section 6) becomes a scheduled rebalance task inside the hub, adjusting the ES futures leg while the hub's order manager handles the actual order placement and fill tracking.

  • The circuit breaker system (Section 4) upgrades from simulated PnL to real account PnL from the IBKR account summary — daily loss limits, weekly limits, and consecutive-loss kill switches enforced against real money.

  • The Claude AI filter adds something the original script doesn't have at all: an AI gate on the composite signal from Section 8. Before entering the put ratio spread, Claude can evaluate regime context, upcoming macro events, and signal quality — an extra discretionary-style filter on top of the quantitative one.


In other words, this script is the brain, and the Trading Bot Hub is the nervous system. You keep every clever idea — the 1x2 put ratio spread, the disaster wing, the VIX call hedge, the IV-percentile-driven adaptivity — and you drop it into infrastructure that's already battle-tested for live execution, multi-strategy concurrency, and AI-assisted decision-making. It's also an outstanding portfolio piece if you're building toward a quant career: "I ported a volatility-targeted put ratio spread bot with Black-76 pricing and dynamic delta hedging onto a multi-strategy Interactive Brokers framework" is a sentence that gets interviews.




Important: The Price Is Going Up — Here's Why


Fair warning, because the window matters: the price of the IBKR Trading Bot Hub is increasing. This isn't artificial urgency — it's the result of a formal pricing evaluation on the hftcode.com product line, and the reasoning is worth understanding because it tells you exactly what you're buying.


For the standalone Trading Bot Hub, the evaluation landed on a recommended price of $197 (with a fair-value band of $147–$297). The analysis was blunt: as a developer tool, even one with enterprise-grade architecture, a single TWS connection multiplexing unlimited bots, four included strategies, and a Claude AI filter, the market caps out quickly above $300 for cold traffic. At $197, it sits at the top of the impulse-friendly range while still filtering for serious buyers. If the current listed price is below that, it won't be for long.


For the Trading Bot Hub + AI Interview Prep bundle, the math changes completely — because it's not selling a tool, it's selling a career outcome. The bundle adds 500+ codebase-grounded interview questions, firm-specific modules for Citadel, Two Sigma, Renaissance Technologies, Jump, and top crypto funds, resume and compensation intelligence ($250k–$400k junior packages up to $5M+ at principal level), and a structured 4-week prep plan. When the product is a path to a $250k+ quant offer, the recommended price is $697 (fair-value band $497–$997) — deliberately kept under the $1,000 psychological barrier while still signaling premium. There's even headroom to $997 if mock interview review or community access gets added later.


So the trajectory is clear: standalone toward $197, bundle toward $697 or higher. If you've been on the fence, the economically rational move is to lock in current pricing before the ad rates go live:



Every strategy concept in this article — the put ratio spread mechanics, the VIX hedge, the Black-76 Greeks, the circuit breakers — becomes dramatically more valuable the moment it's running on real infrastructure. That infrastructure is about to cost more.




Frequently Asked Questions


What is a put ratio spread, and why does this bot use a 1x2 structure? A put ratio spread involves buying puts at one strike and selling a larger number of puts at a different strike. This bot buys one put ~5% out-of-the-money and sells two puts ~2% out-of-the-money. The short puts generate income (especially rich when IV percentile is high), while the long put and the additional disaster wing define the downside. It's an income-and-protection structure designed for high implied volatility environments.


Why hedge with VIX calls instead of just more ES puts? VIX calls are a volatility hedge rather than a price hedge. In a sharp selloff, implied volatility typically spikes — meaning VIX calls can pay off convexly exactly when the short puts in the ratio spread are under maximum stress. It's a cross-instrument hedge that diversifies the source of protection.


What is the Black-76 model and why not Black-Scholes? Black-76 is the standard model for pricing options on futures contracts. Since ES options are options on ES futures, Black-76 is the theoretically correct choice — it prices off the forward price directly rather than a spot price with cost-of-carry adjustments.


How does the delta hedging engine work? The bot sums the delta of the futures position and all option legs, compares it to a target delta (futures position × a hedge ratio that shrinks as IV percentile rises), and trades futures to close the gap whenever the error exceeds a tolerance band. Higher implied volatility → lower target hedge ratio → less directional exposure.


What triggers the circuit breaker? Three conditions: session realized PnL breaching the dynamically computed daily loss limit, weekly realized PnL breaching the weekly limit (capped at 10% of account capital), or five consecutive losing trades. Any of them flattens all futures and options positions immediately.


Can I run this strategy live through Interactive Brokers? Not with the script as-is — it's a paper trading simulation. But the pseudocode in this article maps cleanly onto the IBKR Trading Bot Hub, which provides the live connection, order management, and multi-bot orchestration you'd need for real execution.


Why is the Trading Bot Hub price increasing? A formal pricing evaluation recommended $197 for the standalone hub (enterprise architecture, four strategies, Claude AI filter, full source) and $697 for the bundle with AI interview prep, which is priced as a career-outcome product targeting $250k+ quant roles. Current prices are below those targets and will rise toward them.




Conclusion


The ES Put Ratio Spread + VIX Hedge bot is a masterclass in what a serious automated trading bot looks like: a volatility-aware signal engine, a multi-leg options structure with defined tail risk, a self-contained Black-76 pricing model, dynamic delta hedging, adaptive position sizing, and a multi-layer circuit breaker — all wrapped in clean, event-driven pseudocode you can now implement anywhere.


But a brilliant strategy on simulated infrastructure is still a simulation. Pairing this logic with the IBKR Trading Bot Hub gives you the live execution layer, the Claude AI signal filter, and the multi-strategy architecture to run it alongside other bots on a single Interactive Brokers connection — and pairing it with the interview prep bundle turns the whole project into a quant career asset. With prices moving to $197 and $697 respectively, the best time to build on this base is before the increase takes effect.


Educational purposes only — not investment advice. Options and futures trading involves substantial risk of loss. Seek professional financial advice if needed.



Comments


bottom of page