Code a complete Pine Script v6 strategy() with [1]-offset 20-day breakout entries, a 50-SMA trend filter, locked ATR stops, and 1R fixed-fractional sizing mapped onto real AMEX:SPY daily data. Combining the 20-day breakout structure from Lesson 277 and Lesson 314 with the 1R sizing math in Lesson 276, Lesson 311, and Lesson 615, we now build a complete runnable strategy() engine in Pine Script v6.
While Lesson 608's indicator() merely paints visuals, strategy() tracks live virtual equity (strategy.equity), executes entries and stops, and populates TradingView's Strategy Tester.
1. strategy() setup, transaction costs, and duplicate-entry control
Embed realistic trading friction directly inside your strategy() header from day one rather than fitting zero-cost curves first (Lesson 585):
initial_capital=100000: Benchmarks equity growth from a clean$100,000starting account.commission_type=strategy.commission.percent, commission_value=0.05: Deducts0.05%per side (0.10%round-trip) automatically.slippage=2: Penalizes market fills by2price ticks per execution.pyramiding=0andstrategy.position_size == 0: Blocks consecutive breakout closes from stacking duplicate long entries.
2. The [1] breakout offset tested on real AMEX:SPY (20/50 SMA)
The #1 beginner coding bug in Pine breakout systems is writing close > ta.highest(high, 20). Because ta.highest(high, 20) includes the current bar's high and close <= high holds on every candle, that expression is mathematically impossible—producing zero trades across history.
Appending the [1] prior-bar offset—highest_20 = ta.highest(high, 20)[1]—compares today's close strictly against the highest high across the preceding 20 completed sessions. Paired with close > ta.sma(close, 50), trace how those exact rules behave across the real AMEX:SPY daily chart (207 trading days from 2023-09-01 through 2024-06-28) in Figure 2:
| Verified SPY Bar Date | OHLC Chart Print | 20 / 50 SMA Context | Strategy Rule Outcome |
|---|---|---|---|
| 2023-10-27 | Low $409.21 · Close $410.68 | Below both declining 20 & 50 SMA | close > sma50 false → blocks catching falling knives |
| 2023-12-13 | High $470.76 · Close $470.50 | Strong close above rising 20 & 50 SMA | Clears prior 20D high + trend filter → clean long trigger |
| 2024-04-18 | Low $498.56 · Close $499.52 | Pullback below 20 SMA testing 50 SMA | Live test of fixed 2×ATR stop vs. 10D low trail |
| 2024-06-28 | High $550.28 · Close $544.22 | Right-axis 20 SMA 539.84 / 50 SMA 525.84 | Trend resumes to fresh highs · trail moves upward |
Notice how the 50 SMA filter kept the system safely flat during the October 2023 drop down to $409.21 (2023-10-27). When SPY surged and closed at $470.50 on 2023-12-13 above both rising SMAs and prior 20-day highs, the rule triggered on confirmation. Later, during the April 2024 pullback (2024-04-18 low $498.56, close $499.52), price dipped under the 20 SMA into the rising 50 SMA zone—demonstrating why stop distance (2×ATR or a trailing 10-day low) dictates whether a system rides through routine pullbacks to the $550.28 high (2024-06-28, right-axis 20 SMA 539.84, 50 SMA 525.84) or exits systematically.
3. 1R fixed-fractional sizing and var float ATR stop locking
Translating the 1R sizing framework (Lesson 283, Lesson 311) into Pine divides 1% of current strategy equity by twice the 14-day ATR and floors down to whole shares:
qty = math.floor((strategy.equity * 0.01) / (2 * atr))
Add two production safeguards before deploying:
- Cash ceiling guard: During ultra-quiet volatility regimes, a tiny
2 * atrdenominator can calculate notional size exceeding100%of cash equity. Bounding withmath.min(riskQty, math.floor((strategy.equity * 0.95) / close))prevents unintended margin leverage. - State persistence with
var float stopPrice: Variables declared withvarpersist across bars rather than resetting on every candle. Withoutvar, feeding a liveclose - 2 * atrdirectly intostrategy.exit()drops the stop level lower every time price falls or ATR spikes—destroying your 1R risk cap.
4. Complete runnable Pine Script v6 strategy() code
Setting stopPrice on the signal bar and keeping strategy.exit() armed whenever not na(stopPrice) guarantees that your protective stop is already active on the very next bar's opening fill:
//@version=6
strategy(
"SPY 20D Breakout + 50 SMA + 1R ATR Sizing",
shorttitle="HR 1R Breakout",
overlay=true,
initial_capital=100000,
commission_type=strategy.commission.percent,
commission_value=0.05,
slippage=2,
pyramiding=0
)
// 1. Strategy and risk inputs
breakLen = input.int(20, "Breakout High Length", minval=5)
trendLen = input.int(50, "Trend Filter SMA", minval=10)
trailLen = input.int(10, "Trailing Low Exit Length", minval=3)
atrLen = input.int(14, "ATR Length", minval=1)
atrMult = input.float(2.0, "Stop ATR Multiple", minval=0.5, step=0.25)
riskPct = input.float(1.0, "Risk Per Trade (% Equity)", minval=0.1, maxval=5.0, step=0.1)
// 2. Core series indicators with crucial [1] prior-bar offset
sma20 = ta.sma(close, breakLen)
sma50 = ta.sma(close, trendLen)
atrVal = ta.atr(atrLen)
highest20 = ta.highest(high, breakLen)[1]
lowest10 = ta.lowest(low, trailLen)[1]
// 3. Trend filter and bar-close confirmed breakout entry
trendOK = close > sma50 and sma20 > sma50
longSignal = close > highest20 and trendOK and barstate.isconfirmed
canEnter = strategy.position_size == 0 and longSignal and not na(atrVal) and atrVal > 0
// 4. Locked entry ATR stop (var float) and 1R position sizing
var float stopPrice = na
if strategy.position_size == 0 and not canEnter
stopPrice := na
if canEnter
float riskBudget = strategy.equity * (riskPct / 100.0)
float stopDist = atrMult * atrVal
float riskQty = math.floor(riskBudget / stopDist)
float cashCapQty = math.floor((strategy.equity * 0.95) / close)
float qty = math.min(riskQty, cashCapQty)
if qty > 0
stopPrice := close - stopDist
strategy.entry("Long", strategy.long, qty=qty)
// 5. Hard initial ATR stop and 10-day low trailing exit
if not na(stopPrice)
strategy.exit("ATR Stop", from_entry="Long", stop=stopPrice)
if strategy.position_size > 0 and close < lowest10 and barstate.isconfirmed
strategy.close("Long", comment="10D Low Trail")
// 6. Visual overlays
plot(sma20, "20 SMA", color=color.teal, linewidth=2)
plot(sma50, "50 SMA", color=color.blue, linewidth=2)
plot(highest20, "Prior 20D High", color=color.new(color.green, 50), linewidth=1)
plot(strategy.position_size > 0 ? stopPrice : na, "Fixed 2xATR Stop", color=color.red, linewidth=2)
Running this script populates TradingView's Strategy Tester panel. In Lesson 610, we audit those metrics line by line and eliminate backtest traps—especially multi-timeframe repainting.
Try it yourself
- The highest high over the prior 20 sessions is
$469.50, while today's bar printshigh = $471.00andclose = $470.50. Evaluate bothclose > ta.highest(high, 20)andclose > ta.highest(high, 20)[1]astrueorfalse. - Using SPY's verified
2023-12-13breakout close of$470.50from Figure 2,strategy.equity = $100,000,1%risk budget ($1,000), and an illustrativeATR(14) = $4.50, computeqty = math.floor((strategy.equity * 0.01) / (2 * atr)), the lockedstopPrice, and whether the95%cash cap binds. - If a script omits
varand computesstop = close - 2 * atrdynamically after entering at$470.50(ATR = $4.50), what happens to the stop price the next day if price drops to$458.00andATRexpands to$6.00?
Answers
ta.highest(high, 20)includes today's$471.00high, making$470.50 > $471.00evaluate tofalse. With the[1]offset,ta.highest(high, 20)[1] = $469.50, so$470.50 > $469.50cleanly returnstrue.- Risk budget equals
$100,000 × 0.01 = $1,000and stop distance is2 × $4.50 = $9.00. Thusqty = math.floor(1000 ÷ 9.00) = 111 shares, lockedstopPrice = $470.50 − $9.00 = $461.50, and total notional111 × $470.50 = $52,225.50sits well below the$95,000cash cap (201shares max). - Instead of remaining fixed at
$461.50, the unanchored stop drifts downward to$458.00 − (2 × $6.00) = $446.00—widening potential loss by an extra$15.50per share and breaking the 1R budget.
Related lessons
- Lesson 276. Setting entry price, stop-loss, weight and quantity together
- Lesson 277. Turning breakout entries into order rules
- Lesson 311. Rules common to every method: 1R, position size and losing streaks
- Lesson 608. Pine Script Fundamentals: Writing Custom Moving-Average, ATR & Relative-Strength Indicators
- Lesson 610. Auditing Strategy Tester Reports: Commissions, Slippage & Preventing request.security() Repainting

![Pine Script strategy() execution flow diagram: [1]-offset breakout signal and 50 SMA filter leading to 1% equity 1R budget, 2xATR stop distance, math.floor qty sizing with cash cap, and var float stopPrice locked into strategy.exit.](/en/courses/overseas-stocks/609/figure_01.png)
