本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © GideonMetre
//@version=5
indicator("ATR Trailing Stop", overlay=true)
// Inputs for ATR parameters and smoothing method
atrPeriod = input.int(title="ATR Period", defval=14, minval=1)
multiplier = input.float(title="ATR Multiplier", defval=3.0, minval=0.1, step=0.1)
useEMA = input.bool(title="Use EMA for ATR", defval=false)
// Calculate True Range (TR)
tr = math.max(high - low, math.max(math.abs(high - nz(close[1])), math.abs(low - nz(close[1]))))
// Compute ATR using either EMA or SMA based on user selection
atrValue = useEMA ? ta.ema(tr, atrPeriod) : ta.sma(tr, atrPeriod)
// Calculate potential stop levels for uptrend and downtrend
stopUp = close - multiplier * atrValue
stopDown = close + multiplier * atrValue
// Persistent variables to store trailing stop and trend direction
var float trailStop = na
var string trend = "up"
// Initialization for the first bar
if bar_index == 0
trailStop := stopUp
trend := "up"
else
// If in an uptrend, update the trailing stop upwards and check for reversal
if trend == "up"
newTrailStop = math.max(stopUp, nz(trailStop))
if close < newTrailStop
trend := "down"
trailStop := stopDown
else
trailStop := newTrailStop
// If in a downtrend, update the trailing stop downwards and check for reversal
else
newTrailStop = math.min(stopDown, nz(trailStop))
if close > newTrailStop
trend := "up"
trailStop := stopUp
else
trailStop := newTrailStop
// Plot the trailing stop line on the chart, using green for uptrend and red for downtrend
plot(trailStop, title="ATR Trailing Stop", color=(trend == "up" ? color.green : color.red), linewidth=2)