本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// Preserved copyright below
// modified by optictropic 2019/09/16
//
////////////////////////////////////////////////////////////
// Copyright by HPotter v1.0 16/09/2014
// Average True Range Trailing Stops, by Sylvain Vervoort
// The related article is copyrighted material from Stocks & Commodities Jun 2009
////////////////////////////////////////////////////////////
// TODO
// toggle independent timeframe -- either static or same as chart
study(title="Average True Range Trailing Stops TF", shorttitle='ATR Stops', overlay = true)
timeframe = input(title='Timeframe', type=resolution, defval='1D')
nATRPeriod = input(title='ATR lookback', type=integer, defval=9)
nATRMultip = input(title='Multiplier', type=float, defval=3.5)
_high = security(tickerid, timeframe, high[0])
_low = security(tickerid, timeframe, low[0])
_close = security(tickerid, timeframe, close[1])
_atr() =>
_tr = max(_high - _low, max(abs(_high - _close), abs(_low - _close)))
ema(_tr, nATRPeriod)
xATR = _atr()
nLoss = nATRMultip * xATR
xATRTrailingStop = close > nz(xATRTrailingStop[1], 0) and close[1] > nz(xATRTrailingStop[1], 0) ? max(nz(xATRTrailingStop[1]), close - nLoss) : close < nz(xATRTrailingStop[1], 0) and close[1] < nz(xATRTrailingStop[1], 0) ? min(nz(xATRTrailingStop[1], 0), close + nLoss) : close > nz(xATRTrailingStop[1], 0) ? close - nLoss : close + nLoss
plot(xATRTrailingStop, color=red, transp=0, title='ATR Trailing Stop')