Search code examples
updatesalgorithmic-tradingtradingpine-script

Need help in updating Pinescript version 1 to version 4


//@version=1
study(title="ATR Stops", overlay = true)

nATRPeriod = input(20, title = "ATR Period")
nATRMultip = input(2, title = "ATR Multiplier")

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

color = pos == -1 ? red: pos == 1 ? green : blue 

plot(xATRTrailingStop, color=color, title="ATR Trailing Stop")

Solution

  • //@version=4
    study(title="ATR Stops", overlay=true)
    
    nATRPeriod = input(20, title="ATR Period")
    nATRMultip = input(2, title="ATR Multiplier")
    
    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)))
    
    clr = pos == -1 ? color.red : pos == 1 ? color.green : color.blue
    
    plot(xATRTrailingStop, color=clr, title="ATR Trailing Stop")