Lesson 123 min read

Build a Futures Algo: A Trend System, End to End

November 05, 2026

// TL;DR

The capstone assembles the course into one loop: FETCH OHLC + the active contract; check the SIGNAL (e.g. 20-MA crosses 50-MA); run a RISK CHECK (size by risk and stop distance, confirm margin and spare buffer); place the ORDER with a stop attached; then MANAGE (trail the stop, watch MTM/margin, and ROLL a few days before expiry) — looping each bar, with a KILL-SWITCH that flattens everything on any error. The signal is the easy, small part; the discipline is everything else — size by RISK not margin (8x is rope), assume a gap can slip past the stop, keep spare margin for daily MTM debits and margin hikes, roll early, and account for fees/STT/CTT/slippage/roll yield honestly. Backtest on a back-adjusted continuous series, paper-trade forward, then go live with one lot. Boring, well-margined and small beats clever and big, every time.

The capstone. We take the whole course — the linear payoff, cost of carry, margin and MTM, rollover, risk — and assemble it into one small, disciplined, end-to-end trend-following futures algo. Not a money printer; a careful system that does the boring things perfectly.

The architecture

A simple futures algo end to end, a trend-following loop that respects margin, mark-to-market and the roll. Five steps. One, fetch: OHLC plus the active contract. Two, signal: trend or breakout, for example 20-MA greater than 50-MA. Three, risk check: size by risk, margin, stop distance. Four, order: enter with a stop-loss attached. Five, manage and roll: trail the stop, watch mark-to-market, roll before expiry. Run each bar, roll a few days before expiry, with a kill-switch that flattens on any error. The realities that separate a demo from a live futures algo: the signal, a moving-average crossover or breakout, is the easy small part; the discipline is everything else — size by risk not margin because 8 times leverage is rope to hang yourself, attach a stop but size assuming a gap can jump past it, keep spare margin for daily mark-to-market debits and volatility-driven margin hikes, roll a few days before expiry not on the day, square off or manage overnight risk deliberately because commodities move on global sessions while you sleep, and have a kill-switch that flattens every position on any error; account for fees, STT or CTT and slippage honestly.

Every systematic futures strategy runs the same loop:

  1. Fetch — OHLC data and the currently active contract (the one you trade; roll as expiry nears).
  2. Signal — does your rule fire? (e.g. the 20-period MA crosses above the 50-period MA → go long.)
  3. Risk check — size the position by risk and stop distance (Lesson 10), confirm margin and a spare buffer. This gate can veto the trade.
  4. Order — enter, with a stop-loss already attached.
  5. Manage + roll — trail the stop, watch MTM and margin, and roll a few days before expiry (Lesson 6).

…looping each bar, wrapped in a kill-switch that flattens everything the instant anything looks wrong.

A runnable skeleton

def run_once(broker, cfg):
    bars   = broker.history(cfg.active_contract, cfg.timeframe)
    signal = ma_crossover_signal(bars.close, cfg.fast, cfg.slow)   # Lesson 7

    # roll first if expiry is near (Lesson 6)
    if days_to_expiry(cfg.active_contract) <= cfg.roll_days:
        roll_position(broker, cfg)       # close near, open next month
        cfg.active_contract = next_contract(cfg.active_contract)

    if signal == "flat":
        return "no signal"

    # RISK CHECK (veto gate) — size by risk, not margin
    stop = compute_stop(bars, signal, cfg)
    lots = position_size(cfg.capital, cfg.risk_pct, bars.close[-1], stop, cfg.point_value)
    if lots < 1:
        return "skip — risk too large for one lot"
    if broker.free_margin() < required_margin(lots, cfg) * cfg.margin_buffer:
        return "skip — insufficient spare margin"

    # ORDER — enter with stop attached
    broker.enter(cfg.active_contract, signal, lots, stop=stop)
    return f"entered {signal} {lots} lot(s), stop {stop}"

# main loop
while market_open():
    try:
        log(run_once(broker, cfg))
        manage_positions(broker, cfg)        # trail stops, check MTM & margin
    except Exception as e:
        kill_switch(broker)                  # flatten everything, stop
        alert(f"KILLED: {e}")
        break
    sleep(cfg.bar_seconds)

Notice, as in the other courses, how little of this is “clever”. The signal is one line (the strategy articles have the real thing). The vast majority is rolling, risk checks, stops, margin monitoring and the kill-switch — and that is exactly right. In a live futures algo, the discipline is the strategy.

The realities that make or break it

  • Size by RISK, not margin. The ~8× the exchange allows is rope to hang yourself. Size by your rupee risk if the stop hits (Lesson 10).
  • Assume a gap can slip the stop. Stops don’t fill through a gap. Size so a worse-than-stop fill is survivable, especially in energy and over weekends.
  • Keep spare margin. Daily MTM debits and volatility-driven margin hikes will come. A buffer prevents a forced liquidation at the low.
  • Roll early and deliberately. A few days before expiry, not on the day — and account for the roll yield (contango bleed).
  • Manage overnight risk. MCX commodities move on global sessions and news while you sleep; decide whether to hold, hedge or square off.
  • Count every cost. Fees, STT/CTT, slippage and roll yield — model them, because leverage magnifies their drag.
  • Backtest honestly, then paper-trade. On a back-adjusted continuous series (Lesson 11), with costs. Then forward paper-trade for weeks, then one lot.

The course in one line

A future is a simple, linear, leveraged bet with no premium — so the payoff is easy to model, and the real skill is the mechanics: cost of carry, margin and daily mark-to-market, and rollover’s quiet cost. Automate the boring parts like the programmer you are, size by risk (not by the ~8× margin allows), respect the gap and the margin call, roll early, and make survival the strategy.

You now have the foundations — futures mechanics, pricing, the commodity universe, margin, rollover, strategies, spreads, hedging, risk, and the tooling to build. Go and backtest honestly and paper-trade, patiently.

For more, see the companion Options Trading and Crypto Options & Algo Trading courses, the Low-Latency Trading Systems course, and the strategy articles on trend following, mean reversion and position sizing with Kelly.