本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
////////////////////////////////////////////////////////////
// Copyright by HPotter v2.0 13/10/2014
// Average True Range Trailing Stops Strategy, by Sylvain Vervoort
// The related article is copyrighted material from Stocks & Commodities Jun 2009
// Modified by River to add Bands, and change color of Trailing Stop and add Wick Protection
////////////////////////////////////////////////////////////
study(title="ATR Trailing Stop Bands [R] ", overlay = true)
nATRPeriod = input(5)
nATRMultip = input(4)
length = input(30, "#Periods of Wick Protection", minval=2, type=integer)
bType = input(0, "Max [1] or Avg Wick Protection [0]", minval=0, maxval=1, type=integer)
avgupperwick = sma(close[1] <= open[1] ? high[1] - open[1] : high[1] - close[1], length)
maxupperwick = highest(close[1] <= open[1] ? high[1] - open[1] : high[1] - close[1], length)
avglowerwick = sma(close[1] > open[1] ? open[1] - low[1] : close[1] - low[1], length)
maxlowerwick = highest(close[1] > open[1] ? open[1] - low[1] : close[1] - low[1], length)
upperwick = bType == 0 ? avgupperwick : maxupperwick
lowerwick = bType == 0 ? avglowerwick : maxlowerwick
xATR = atr(nATRPeriod)
nLoss = nATRMultip * xATR
upperband = iff(high < nz(upperband[1], 0) and high[1] < nz(upperband[1], 0), min(nz(upperband[1]), high + nLoss + upperwick), high + nLoss + upperwick)
lowerband = iff(low > nz(lowerband[1], 0) and low[1] > nz(lowerband[1], 0), max(nz(lowerband[1]), low - nLoss - lowerwick), low - nLoss - lowerwick)
xATRTrailingStop = iff(low > nz(xATRTrailingStop[1], 0) and low[1] > nz(xATRTrailingStop[1], 0), max(nz(xATRTrailingStop[1]), low - nLoss - lowerwick),
iff(high < nz(xATRTrailingStop[1], 0) and high[1] < nz(xATRTrailingStop[1], 0), min(nz(xATRTrailingStop[1]), high + nLoss + upperwick),
// iff(low <= nz(xATRTrailingStop[1], 0) and close[1] > nz(xATRTrailingStop[1], 0), high + nLoss + upperwick, iff(high >= nz(xATRTrailingStop[1], 0) and close[1] < nz(xATRTrailingStop[1], 0), low - nLoss - lowerwick,0))))
iff(low <= nz(xATRTrailingStop[1], 0) and close[1] > nz(xATRTrailingStop[1], 0), upperband[1], iff(high >= nz(xATRTrailingStop[1], 0) and close[1] < nz(xATRTrailingStop[1], 0), lowerband[1],0))))
pos = iff(close[1] > nz(xATRTrailingStop[1], 0) and low <= nz(xATRTrailingStop[1], 0), 1,
iff(close[1] < nz(xATRTrailingStop[1], 0) and high >= nz(xATRTrailingStop[1], 0), -1, nz(pos[1], 0)))
color = pos == 1 ? red: pos == -1 ? green : blue
plot(upperband, color=red, title="ATR Upper")
plot(xATRTrailingStop, color=color, title="ATR Trailing Stop", linewidth=2)
plot(lowerband, color=green, title="ATR Lower")