Backtest a breakout strategy
Inspect a previous-high breakout example with persistent state and a scripted closing rule.
Before you start
The current bundled Pine breakout enters when the close exceeds the previous 20-bar high. Its persistent peak tracks closes, not intrabar highs: every breakout resets it to the current close, and a later higher close updates it. A close-based scripted exit is not the same as an intrabar stop order.
Follow the workflow
- Read how the example excludes the current bar from the breakout lookback. Otherwise a condition can accidentally compare a price with a range that already includes that price.
- Follow every assignment to peak, including repeated breakouts during a position. The example does not explicitly clear this variable when it exits.
- Inspect the 3% threshold below that recorded close and the next queued closing fill. Compare this with price-based protective fills.
- Record data, timeframe, size and costs before changing the lookback or trailing percentage.
Worked example
Open the actual bundled persistent-state example. Its code and recommended timeframe are shared with the workbench.
//@version=6
strategy("Trailing high stop (var)", initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.1)
len = input.int(20, "Breakout length", minval=2)
stopPct = input.float(3.0, "Trail, %") * 0.01
var float peak = na
breakout = close > ta.highest(high, len)[1]
if breakout
peak := close
if close > peak
peak := close
if breakout
strategy.entry("Long", strategy.long)
if close < peak * (1 - stopPct)
strategy.close("Long")
Limits and interpretation
The strategy uses a scripted close condition; do not describe it as an exchange-side protective order. A gap, a candle path assumption and a next-bar market fill can produce different prices from another trailing-stop design. Test alternative rules separately and do not hide failed variants when evaluating the result.