Skip to Content
While25SDK docs
ExamplesStrategies

Index futures trend with a manual roll

Trades one S&P 500 or Nasdaq-100 futures contract (ES, MES, NQ or MNQ) with the hourly trend: long above the 20-hour average, flat below, always with a bracket stop a few average true ranges away. `future()` names the contract the chart's continuous line is on now; when that moves to the next month, the strategy closes the old contract and opens the new one itself. A redeploy picks its bracket back up from `my_positions()`.

Trades one S&P 500 or Nasdaq-100 futures contract (ES, MES, NQ or MNQ) with the hourly trend: long above the 20-hour average, flat below, always with a bracket stop a few average true ranges away. future() names the contract the chart's continuous line is on now; when that moves to the next month, the strategy closes the old contract and opens the new one itself. A redeploy picks its bracket back up from my_positions().

Shows: future(root, "front"), tradeable / untradeable_reason, lot_size, Enum input, historical(), bracket with stop_loss=, orders.square_off(), my_positions() brackets, on_start resume.

View on GitHub

strategies/index_futures_trend.py
"""Index futures trend with a manual roll

Trades one S&P 500 or Nasdaq-100 futures contract (ES, MES, NQ or MNQ) with
the hourly trend: long above the 20-hour average, flat below, always with a
bracket stop a few average true ranges away. `future()` names the contract the
chart's continuous line is on now; when that moves to the next month, the
strategy closes the old contract and opens the new one itself. A redeploy
picks its bracket back up from `my_positions()`.

Shows: future(root, "front"), tradeable / untradeable_reason, lot_size, Enum input, historical(), bracket with stop_loss=, orders.square_off(), my_positions() brackets, on_start resume.
"""
from datetime import date, timedelta

import while25
from while25 import Strategy, on
from while25.inputs import Enum, Float, Int

TAG = "fut_trend"


def sma(values, n):
    return None if len(values) < n else sum(values[-n:]) / n


def atr(bars, n):
    tr = [max(b["high"] - b["low"], abs(b["high"] - a["close"]), abs(b["low"] - a["close"]))
          for a, b in zip(bars, bars[1:])]
    return None if len(tr) < n else sum(tr[-n:]) / n


def wanted(bars, length):
    """"long" while the last close is above its `length`-bar average, "flat"
    below it, None while there are too few bars."""
    avg = sma([b["close"] for b in bars], length)
    if avg is None:
        return None
    return "long" if bars[-1]["close"] > avg else "flat"


def needs_roll(held_key, front_key):
    return held_key is not None and held_key != front_key


class IndexFuturesTrend(Strategy):
    id = "index_futures_trend"
    label = "Index futures trend"
    inputs = [Enum("root", choices=["MES", "ES", "MNQ", "NQ"], default="MES"),
              Int("contracts", default=1, minimum=1, maximum=20),
              Int("length", default=20, minimum=5, maximum=200),
              Float("atr_mult", default=2.0, minimum=0.5, maximum=10.0, step=0.5)]

    def on_start(self, ctx):
        # Deployed again under the same id: its bracket is still its own.
        self.held_key, self.bracket_id = None, None
        root = "FUT:US:" + while25.params["root"] + ":"
        for pos in while25.portfolio.my_positions():
            if pos["instrument_key"].startswith(root) and pos["brackets"]:
                self.held_key = pos["instrument_key"]
                self.bracket_id = pos["brackets"][0]["bracket_id"]
                while25.log(f"resuming bracket {self.bracket_id} on {pos['symbol']}")

    @on.schedule(every="15m")
    def step(self, ctx):
        p = while25.params
        front = while25.future(p["root"])
        if not front["tradeable"]:
            while25.log(f"{front['symbol']}: {front['untradeable_reason']}", "warn")
            return
        if needs_roll(self.held_key, front["instrument_key"]) and self.bracket_id:
            while25.log(f"rolling {self.held_key} -> {front['symbol']}")
            self.close()

        start = (date.today() - timedelta(days=20)).isoformat()
        bars = list(while25.historical(front["instrument_key"], "1h", start=start))
        state = wanted(bars, p["length"])
        if state == "flat" and self.bracket_id:
            self.close()
        elif state == "long" and not self.bracket_id:
            self.open(front, bars)

    def open(self, contract, bars):
        p = while25.params
        a = atr(bars, 14)
        if a is None:
            return
        inst = while25.data.instrument(contract["instrument_key"])
        stop = inst.snap(bars[-1]["close"] - p["atr_mult"] * a, mode="down")
        qty = (contract["lot_size"] or 1) * p["contracts"]       # None: the venue states no lot
        res = while25.buy(contract["instrument_key"], qty, stop_loss=stop, tag=TAG)
        self.held_key, self.bracket_id = contract["instrument_key"], res["order_id"]
        while25.log(f"long {qty} {contract['symbol']} ({contract['month']}), stop {stop}")

    def close(self):
        try:
            while25.orders.square_off(self.bracket_id)
        except while25.While25Error as e:
            if e.code == "NOTHING_HELD":        # the entry never filled
                while25.orders.cancel(self.bracket_id)
            elif e.code != "NO_BRACKET":        # NO_BRACKET: its stop already closed it
                raise
        self.held_key, self.bracket_id = None, None

    @on.order(tag=TAG)
    def on_order(self, ctx, ev):
        if ev["event"] == "FILL" and ev["order_id"] == (self.bracket_id or "") + "-SL":
            while25.log(f"stopped out at {ev['average_price']}")
            self.held_key, self.bracket_id = None, None
        elif ev["event"] == "POSITION_SQUARED_OFF":
            self.held_key, self.bracket_id = None, None