PART XIII · Chapter 108 · 609 / 660

Lesson 609. Coding Complete Trading Rules in Pine Script: Breakout Entries, ATR Stops & 1R Position Sizing

Chapter 108. TradingView Setup & Hands-On Pine Script Strategy Coding Lab

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

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.

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,000 starting account.
  • commission_type=strategy.commission.percent, commission_value=0.05: Deducts 0.05% per side (0.10% round-trip) automatically.
  • slippage=2: Penalizes market fills by 2 price ticks per execution.
  • pyramiding=0 and strategy.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)

Real TradingView daily chart of AMEX:SPY from 2023-09-01 to 2024-06-28 with 20 SMA and 50 SMA overlays, highlighting the 2023-10-27 low at $409.21, the 2023-12-13 breakout close at $470.50, the 2024-04-18 pullback low at $498.56, and the 2024-06-28 high at $550.28 (right-axis 20 SMA 539.84, 50 SMA 525.84).

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 DateOHLC Chart Print20 / 50 SMA ContextStrategy Rule Outcome
2023-10-27Low $409.21 · Close $410.68Below both declining 20 & 50 SMAclose > sma50 false → blocks catching falling knives
2023-12-13High $470.76 · Close $470.50Strong close above rising 20 & 50 SMAClears prior 20D high + trend filter → clean long trigger
2024-04-18Low $498.56 · Close $499.52Pullback below 20 SMA testing 50 SMALive test of fixed 2×ATR stop vs. 10D low trail
2024-06-28High $550.28 · Close $544.22Right-axis 20 SMA 539.84 / 50 SMA 525.84Trend 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:

  1. Cash ceiling guard: During ultra-quiet volatility regimes, a tiny 2 * atr denominator can calculate notional size exceeding 100% of cash equity. Bounding with math.min(riskQty, math.floor((strategy.equity * 0.95) / close)) prevents unintended margin leverage.
  2. State persistence with var float stopPrice: Variables declared with var persist across bars rather than resetting on every candle. Without var, feeding a live close - 2 * atr directly into strategy.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

  1. The highest high over the prior 20 sessions is $469.50, while today's bar prints high = $471.00 and close = $470.50. Evaluate both close > ta.highest(high, 20) and close > ta.highest(high, 20)[1] as true or false.
  2. Using SPY's verified 2023-12-13 breakout close of $470.50 from Figure 2, strategy.equity = $100,000, 1% risk budget ($1,000), and an illustrative ATR(14) = $4.50, compute qty = math.floor((strategy.equity * 0.01) / (2 * atr)), the locked stopPrice, and whether the 95% cash cap binds.
  3. If a script omits var and computes stop = close - 2 * atr dynamically after entering at $470.50 (ATR = $4.50), what happens to the stop price the next day if price drops to $458.00 and ATR expands to $6.00?

Answers

  1. ta.highest(high, 20) includes today's $471.00 high, making $470.50 > $471.00 evaluate to false. With the [1] offset, ta.highest(high, 20)[1] = $469.50, so $470.50 > $469.50 cleanly returns true.
  2. Risk budget equals $100,000 × 0.01 = $1,000 and stop distance is 2 × $4.50 = $9.00. Thus qty = math.floor(1000 ÷ 9.00) = 111 shares, locked stopPrice = $470.50 − $9.00 = $461.50, and total notional 111 × $470.50 = $52,225.50 sits well below the $95,000 cash cap (201 shares max).
  3. 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.50 per share and breaking the 1R budget.

Related lessons