// This Pine Script® code is licensed under Apache-2.0
// SPDX-License-Identifier: Apache-2.0
// © PineForge contributors 2026
//
// PF probe 13 — ATR-trailing-stop with var-state direction
// Purpose: parity test for ta.atr() driven trailing stop and `var float trailStop`
// / `var bool isLong` state-machine progression on EMA crossovers.
//
//@version=6
strategy("ATR Trailing Stop", overlay=true, initial_capital=1000000, process_orders_on_close=false, pyramiding=1, commission_type=strategy.commission.percent, commission_value=0, slippage=0, default_qty_type=strategy.fixed, default_qty_value=1)
// === Inputs ===
atrLen = input.int(14, "ATR Length", minval=1)
atrMult = input.float(2.0, "ATR Multiplier", step=0.1)
maLen = input.int(20, "MA Length", minval=5)
// === Indicators ===
atrVal = ta.atr(atrLen)
maVal = ta.ema(close, maLen)
// === Trailing stop logic with var ===
var float trailStop = na
var bool isLong = false
// === Entry signals ===
longEntry = ta.crossover(close, maVal)
shortEntry = ta.crossunder(close, maVal)
if longEntry
strategy.entry("Long", strategy.long)
isLong := true
trailStop := close - atrVal * atrMult
if shortEntry
strategy.entry("Short", strategy.short)
isLong := false
trailStop := close + atrVal * atrMult
// === Update trailing stop ===
if isLong and strategy.position_size > 0
newStop = close - atrVal * atrMult
if not na(trailStop)
trailStop := math.max(trailStop, newStop)
else
trailStop := newStop
if close < trailStop
strategy.close("Long")
isLong := false
if not isLong and strategy.position_size < 0
newStop = close + atrVal * atrMult
if not na(trailStop)
trailStop := math.min(trailStop, newStop)
else
trailStop := newStop
if close > trailStop
strategy.close("Short")
plot(trailStop, "Trail Stop", color=isLong ? color.green : color.red, style=plot.style_stepline)
plot(maVal, "MA", color=color.blue)