添加跟踪ATR止损

时间:2018-11-26 09:03:13

标签: tradingview-api pine-script

添加尾随ATR止损时出现输出错误。

我的简单脚本是,当出现突破时走多头,当收盘价跌至追踪ATR以下时关闭。

我认为问题出在这一行:

如果(pos == 0且strategy.position_size> 0并关闭

//@version=2
nATRPeriod = input(14)
nATRMultip = input(3)

xATR = atr(nATRPeriod)
nLoss = nATRMultip * xATR

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 =   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))) 

if (pos == 1 and strategy.position_size == 0 and reverse == false) 
    strategy.entry("Long", strategy.long)
if (pos == 1 and strategy.position_size == 0 and reverse == true) 
    strategy.entry("Short", strategy.short)
if (pos == 0 and strategy.position_size > 0 and close < nz(xATRTrailingStop[1], 0)
    strategy.close("Long")
if (pos == 0 and strategy.position_size < 0)
    strategy.close("Short")
barcolor(strategy.position_size > 0 ? green: strategy.position_size < 0 ? red: blue)   
plotshape(pos, style=shape.triangleup, location = location.belowbar, color = green)

1 个答案:

答案 0 :(得分:0)

我已修复您代码的语法错误

//@version=3
strategy("Example")
nATRPeriod = input(14)
nATRMultip = input(3)
reverse = close > open // TODO: need reverse logic here

xATR = atr(nATRPeriod)
nLoss = nATRMultip * xATR

xATRTrailingStop = 0.0
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 = 0.0
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))) 

if (pos == 1 and strategy.position_size == 0 and reverse == false) 
    strategy.entry("Long", strategy.long)
if (pos == 1 and strategy.position_size == 0 and reverse == true) 
    strategy.entry("Short", strategy.short)
if (pos == 0 and strategy.position_size > 0 and close < nz(xATRTrailingStop[1], 0))
    strategy.close("Long")
if (pos == 0 and strategy.position_size < 0)
    strategy.close("Short")
barcolor(strategy.position_size > 0 ? green: strategy.position_size < 0 ? red: blue)   
plotshape(pos, style=shape.triangleup, location = location.belowbar, color = green)

希望这会有所帮助!