Daily trend filter, 15-minute entries, no look-ahead
Trades AAPL's opening-range breakout on 15-minute bars, only on days the daily trend is up. The trend is read from the daily bars that had CLOSED by the moment each 15-minute bar closed, so the filter never sees the day it is trading. Entries fill at the next bar's open; a bracket stop and target are tested bar by bar, and anything still open exits at the session's last close.
Trades AAPL's opening-range breakout on 15-minute bars, only on days the daily trend is up. The trend is read from the daily bars that had CLOSED by the moment each 15-minute bar closed, so the filter never sees the day it is trading. Entries fill at the next bar's open; a bracket stop and target are tested bar by bar, and anything still open exits at the session's last close.
Shows: two timeframes in one backtest, closed_by() for look-ahead-free reads, backtest.sessions() and Session.regular, backtest.exit_fill() / first_exit(), same_bar="stop_first", product="intraday", the daily answer read but not sealed (data= names only the 15m answer).
"""Daily trend filter, 15-minute entries, no look-ahead
Trades AAPL's opening-range breakout on 15-minute bars, only on days the
daily trend is up. The trend is read from the daily bars that had CLOSED by
the moment each 15-minute bar closed, so the filter never sees the day it is
trading. Entries fill at the next bar's open; a bracket stop and target are
tested bar by bar, and anything still open exits at the session's last close.
Shows: two timeframes in one backtest, closed_by() for look-ahead-free reads, backtest.sessions() and Session.regular, backtest.exit_fill() / first_exit(), same_bar="stop_first", product="intraday", the daily answer read but not sealed (data= names only the 15m answer).
"""
import bisect
from decimal import Decimal
import while25
from while25 import App, backtest, ui
from while25.backtest import Slippage
KEY = "EQ:US:AAPL"
DAILY_FROM, START, END = "2023-06-01", "2024-01-02", "2025-06-30"
STEP_MS = {"1m": 60_000, "5m": 300_000, "15m": 900_000, "30m": 1_800_000,
"1h": 3_600_000, "1D": 86_400_000}
ui.panel("bt_daily_15m", "AAPL trend + 15m breakout backtest")
ui.layout(ui.view("main"))
def closed_by(bars, interval, t_ms):
"""The bars of one line that had ended by t_ms, oldest first."""
ends = [b["time"] + STEP_MS[interval] for b in bars]
return bars[:bisect.bisect_right(ends, t_ms)]
def trend_up(daily_known, n=50):
"""True when the last known daily close is above its n-day average."""
if len(daily_known) < n:
return None
return daily_known[-1]["close"] > sum(b["close"] for b in daily_known[-n:]) / n
def session_trades(day_bars, daily, inst, a, *, range_bars=2, reward=2.0, qty=50):
"""At most one trade in one session's regular bars."""
if len(day_bars) <= range_bars + 1:
return []
high = max(b["high"] for b in day_bars[:range_bars])
low = min(b["low"] for b in day_bars[:range_bars])
for i in range(range_bars, len(day_bars) - 1):
bar = day_bars[i]
decided_at = bar["time"] + STEP_MS["15m"] # this bar has just closed
if bar["close"] <= high or not trend_up(closed_by(daily, "1D", decided_at)):
continue
entry = backtest.fill(day_bars[i + 1], "buy", "open", instrument=inst, assume=a)
stop = inst.snap(low, mode="down")
target = inst.snap(entry.price + Decimal(str(reward)) * (entry.price - stop), mode="up")
if stop >= entry.price:
return [] # opened under the range: no trade
for later in day_bars[i + 1:]:
out = backtest.exit_fill(later, "buy", instrument=inst, stop=stop, target=target, assume=a)
if out is not None:
break
else:
out = backtest.fill(day_bars[-1], "sell", "close", instrument=inst, assume=a)
return [backtest.trade(inst, "buy", qty, entry, out, product="intraday", assume=a)]
return []
def all_trades(answer_15m, daily, inst, a, **kw):
trades = []
for s in backtest.sessions(answer_15m):
bars = s.regular if s.regular is not None else s.bars
trades += session_trades(bars, daily, inst, a, **kw)
return trades
class DailyTrend15m(App):
id = "bt_daily_trend_15m"
label = "AAPL trend + 15m breakout backtest"
def run(self, ctx):
daily = while25.history_span(KEY, "1D", DAILY_FROM, END)["bars"]
m15 = while25.history_span(KEY, "15m", START, END)
inst = while25.data.instrument(KEY)
a = backtest.assume(costs="real", slippage=Slippage.ticks(1), same_bar="stop_first")
trades = all_trades(m15, daily, inst, a)
while25.ui.push("main", {"blocks": [ui.backtest_block(
trades, data=[m15["id"]], capital=50_000, assume=a,
title="AAPL 30-minute range breakout, daily trend up",
logic={"Filter": "last CLOSED daily close above its 50-day average",
"Entry": "a 15m close above the first 30 minutes' high; fill at the next open",
"Exit": "stop at the range low, target 2R, else the session's last close",
"Same bar": "stop and target both touched: the stop first"},
notes="The daily line is read for the filter only and is not named in data.")]})One strategy, two fill assumptions, side by side
A dip-buying limit order on AAPL (buy 1% under the previous close, sell at that day's close) is very sensitive to whether a limit fills when the price merely touches it or only when it trades through. This runs the same logic under both and pushes the two sealed results into one panel, so the gap between them is the first thing you see.
SPY / QQQ pair: two instruments in one backtest
Trades the spread between SPY and QQQ: when the log price ratio is more than two standard deviations from its 60-day mean, sells the rich one and buys the cheap one in equal dollar amounts, and closes both when the ratio is back within half a deviation. Both legs fill at the next day's open. Costs are a flat custom figure per order, stated in the block.