Skip to Content
While25SDK docs
ExamplesStrategies

Daily breakout with a trailing-stop exit

Buys AAPL when a daily bar closes above the highest high of the bars before it, and on the fill puts a trailing stop under the position, a few average true ranges away. The stop can be held by While25 or, where the broker holds trailing stops (IBKR), by the broker, so it works while the computer sleeps.

Buys AAPL when a daily bar closes above the highest high of the bars before it, and on the fill puts a trailing stop under the position, a few average true ranges away. The stop can be held by While25 or, where the broker holds trailing stops (IBKR), by the broker, so it works while the computer sleeps.

Shows: Bars on "1D", @on.fill, order_type="TRAIL", trail_amount=, reduce_only=, held_by="broker", validity="gtc", Bool input, Instrument.snap(mode="up").

View on GitHub

strategies/trailing_stop_exit.py
"""Daily breakout with a trailing-stop exit

Buys AAPL when a daily bar closes above the highest high of the bars before
it, and on the fill puts a trailing stop under the position, a few average
true ranges away. The stop can be held by While25 or, where the broker holds
trailing stops (IBKR), by the broker, so it works while the computer sleeps.

Shows: Bars on "1D", @on.fill, order_type="TRAIL", trail_amount=, reduce_only=, held_by="broker", validity="gtc", Bool input, Instrument.snap(mode="up").
"""
from decimal import Decimal

import while25
from while25 import Bars, Strategy, on
from while25.inputs import Bool, Float, Int

KEY = "EQ:US:AAPL"
TAG = "aapl_trail"


def true_ranges(bars):
    """Each bar's true range after the first: the widest of high-low and the
    gaps from the previous close."""
    return [max(b["high"] - b["low"], abs(b["high"] - a["close"]), abs(b["low"] - a["close"]))
            for a, b in zip(bars, bars[1:])]


def atr(bars, n):
    """The mean true range of the last n bars, or None with too few bars."""
    tr = true_ranges(bars)
    return None if len(tr) < n else sum(tr[-n:]) / n


def breaks_out(bars, lookback):
    """True when the last bar closed above the highest high of the
    `lookback` bars before it."""
    if len(bars) < lookback + 1:
        return False
    return bars[-1]["close"] > max(b["high"] for b in bars[-lookback - 1:-1])


def trail_distance(inst, atr_value, mult):
    """The trail as a price distance on the tick grid, rounded up so the
    stop is never tighter than asked."""
    return inst.snap(atr_value * mult, mode="up")


class TrailingBreakout(Strategy):
    id = "aapl_trailing_breakout"
    label = "AAPL breakout, trailing exit"
    inputs = [Int("lookback", default=20, minimum=5, maximum=200),
              Int("atr_length", default=14, minimum=2, maximum=100),
              Float("atr_mult", default=3.0, minimum=0.5, maximum=10.0, step=0.5),
              Int("shares", default=10, minimum=1, maximum=10_000),
              Bool("broker_held", default=False, label="Let the broker hold the trailing stop")]

    daily = Bars(KEY, "1D", keep=250)

    def on_start(self, ctx):
        self.inst = while25.data.instrument(KEY)

    @on.bar(daily)
    def on_day(self, ctx, bar):
        p = while25.params
        mine = while25.portfolio.my_position(KEY)
        if mine and mine["quantity"] != 0:
            return                              # in a trade: the trail is the exit
        if any(o["tag"] == TAG for o in while25.orders.mine(KEY)):
            return                              # an entry is already working
        if breaks_out(self.daily.rows, p["lookback"]):
            while25.buy(KEY, p["shares"], tag=TAG)
            while25.log(f"breakout close {bar['close']}: buy {p['shares']}")

    @on.fill(tag=TAG)
    def on_fill(self, ctx, ev):
        if ev["side"] != "BUY" or ev["status"] != "COMPLETE":
            return                              # wait for the whole entry
        p = while25.params
        a = atr(self.daily.rows, p["atr_length"])
        dist = trail_distance(self.inst, a, p["atr_mult"]) if a else None
        if dist is None:
            while25.log("no ATR or no tick yet: no trailing stop placed", "error")
            return
        extra = {"held_by": "broker", "validity": "gtc"} if p["broker_held"] else {}
        while25.sell(KEY, Decimal(ev["filled_quantity"]), order_type="TRAIL",
                     trail_amount=dist, reduce_only=True, tag=TAG, **extra)
        while25.log(f"trailing stop {dist} under the high, held by "
                    f"{'the broker' if p['broker_held'] else 'While25'}")