本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// @version=4
// Based off of script by @garethyeo but changed by @millerrh to allow for the ability to display trailing high/low without flipping depending on whether you are long or short.
// Allows you to see what the ATR support or resistance levels are regardless of what position you are in.
study(title="Trailing ATR Stops", shorttitle="ATR Trail", overlay=true, linktoseries=true)
// ============================== GET INPUTS ==================================
atrLookback = input(defval=14,title="ATR Lookback Period",type=input.integer)
multiplier = input(defval=3,title="ATR Multiplier",type=input.float, step=0.1, minval=0.5, maxval=4)
trailMode = input(title="Trail Mode", defval="Trailing", options=["Running", "Trailing"])
trigInput = input(title="Trigger Trailing Stop On", defval="Close", options=["Close","Wick"])
showInput = input(title="Show Trailing", defval="Support", options=["Support","Resistance","Both"])
// ============================== CALCULATE ATR ==================================
atrValue = atr(atrLookback)
atrMultiplied = atrValue * multiplier
// plot the price plus or minus the ATR
atrLow = low - atrMultiplied
atrHigh = high + atrMultiplied
// Calculate both the low and high trailing ATRs every time. The low one never goes down, and the high one never goes up
// Set them to something to start with
trailAtrLow = atrLow
trailAtrHigh = atrHigh
// If the ATR Low has gone up AND it has gone above the trail, the low trailing ATR should also go up. If the ATR Low has gone up or down, but not below the trail, the ATR trail stays where it is
trailAtrLow := na(trailAtrLow[1]) ? trailAtrLow : atrLow >= trailAtrLow[1] ? atrLow : trailAtrLow[1]
// Same for the High
trailAtrHigh := na(trailAtrHigh[1]) ? trailAtrHigh : atrHigh <= trailAtrHigh[1] ? atrHigh : trailAtrHigh[1]
// Trigger stop based on candle close or High/Low
trigResistance = trigInput == "Close" ? close : trigInput == "Wick" ? high : na
trigSupport = trigInput == "Close" ? close : trigInput == "Wick" ? low : na
// Determine if price is above resistance or below support
resistanceHit = trigResistance >= trailAtrHigh
supportHit = trigSupport <= trailAtrLow
// If price is above resistance or below support, reset the trailing ATR
trailAtrLow := supportHit ? atrLow : trailAtrLow
trailAtrHigh := resistanceHit ? atrHigh : trailAtrHigh
// ============================== PLOT LINES ==================================
plotLow = showInput == "Support" ? trailAtrLow : showInput == "Both" ? trailAtrLow : na
plotHigh = showInput == "Resistance" ? trailAtrHigh : showInput == "Both" ? trailAtrHigh : na
plot(plotLow, color=color.white, style=plot.style_linebr, linewidth=2)
plot(plotHigh, color=color.white, style=plot.style_linebr, linewidth=2)