本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=3
//@okadoke
////////////////////////////////////////////////////////////
// Based on Average True Range Trailing Stops Strategy by HPotter
// Average True Range Trailing Stops Strategy, by Sylvain Vervoort
// The related article is copyrighted material from Stocks & Commodities Jun 2009
////////////////////////////////////////////////////////////
strategy(title="ATR Trailing Stops Strategy", shorttitle="ATRTSS", overlay = true,
initial_capital=100000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type="percent", commission_value=0.0)
nATRPeriod = input(5, "ATR Period")
nATRMultip = input(3.5, "ATR Multiplier")
useShorts = input(false, "Test w/Shorts?")
daysBackMax = input(defval = 360, title = "Max Days Back to Test", minval = 0)
daysBackMin = input(defval = 0, title = "Min Days Back to Test", minval = 0)
msBackMax = 1000 * 60 * 60 * 24 * daysBackMax
msBackMin = 1000 * 60 * 60 * 24 * daysBackMin
xATR = atr(nATRPeriod)
nLoss = nATRMultip * xATR
xATRTrailingStop = na
xATRTrailingStop :=
iff(close > nz(xATRTrailingStop[1], 0) and close[1] > nz(xATRTrailingStop[1], 0), max(nz(xATRTrailingStop[1]), close - nLoss),
iff(close < nz(xATRTrailingStop[1], 0) and close[1] < nz(xATRTrailingStop[1], 0), min(nz(xATRTrailingStop[1]), close + nLoss),
iff(close > nz(xATRTrailingStop[1], 0), close - nLoss, close + nLoss)))
pos = na
pos :=
iff(close[1] < nz(xATRTrailingStop[1], 0) and close > nz(xATRTrailingStop[1], 0), 1,
iff(close[1] > nz(xATRTrailingStop[1], 0) and close < nz(xATRTrailingStop[1], 0), -1, nz(pos[1], 0)))
color = pos == -1 ? red: pos == 1 ? green : blue
plot(xATRTrailingStop, color=color, title="ATR Trailing Stop")
isWithinTimeBounds = (msBackMax == 0 or (time > (timenow - msBackMax))) and (msBackMin == 0 or (time < (timenow - msBackMin)))
buy = crossover(close, xATRTrailingStop)
sell = crossunder(close, xATRTrailingStop)
strategy.entry("LONG", long=true, when=buy and isWithinTimeBounds)
strategy.close("LONG", when=sell and isWithinTimeBounds)
strategy.entry("SHORT", long=false, when=useShorts and sell and isWithinTimeBounds)
strategy.close("SHORT", when=useShorts and buy and isWithinTimeBounds)