本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This indicator implements a Consistent ATR (Average True Range) Trailing Stop that maintains uniform behavior across various chart timeframes. It's designed to provide traders with a reliable tool for setting dynamic stop-loss levels that adapt to market volatility while remaining consistent regardless of the chosen chart interval.
//@version=5
indicator("Consistent ATR Trailing Stop (ATR, 1m based) [nn1]", overlay=true)
// Inputs
atr_length = input.int(14, "ATR Length (1m base)", minval=1)
atr_multiplier = input.float(3.0, "ATR Multiplier", minval=0.1, step=0.1)
// Function to get data from 1-minute timeframe
get_1m_data(src) =>
request.security(syminfo.tickerid, "1", src)
// Calculate True Range on 1-minute data
tr_1m = get_1m_data(ta.tr)
// Calculate ATR using 1-minute true range data
atr = ta.sma(tr_1m, atr_length)
// Initialize variables
var float long_stop = na
var float short_stop = na
var int trend = 0
// Initialize position on the first bar
if barstate.isfirst
trend := close > (high + low) / 2 ? 1 : -1
if trend > 0
long_stop := low
else
short_stop := high
if trend >= 0
long_stop := math.max(high - atr * atr_multiplier, nz(long_stop[1], high))
else
short_stop := math.min(low + atr * atr_multiplier, nz(short_stop[1], low))
if trend > 0 and close < long_stop
trend := -1
short_stop := high
else if trend < 0 and close > short_stop
trend := 1
long_stop := low
// Determine color based on trend and trend change
color_transition = color.new(color.yellow, 0)
stop_color = if trend != trend[1]
color_transition
else if trend > 0
color.green
else
color.red
// Plot trailing stop
plot(trend > 0 ? long_stop : short_stop, color=stop_color, title="Trailing Stop", linewidth=1)
// Display info
var label info_label = na
label.delete(info_label)
info_label := label.new(bar_index, high, text="ATR: " + str.tostring(atr, "#.####") + "\nTrend: " + (trend > 0 ? "Up" : "Down"), color=color.navy, textcolor=color.white, style=label.style_label_down)