Search code examples
pine-scriptalgorithmic-tradingtradingpine-script-v4

PineScript = Adding input to atr stoploss


I want to make a new input for plotting only long atr stoploss.

atr SL script:

// Stop Loss inputs atr     
var atr_sl = "ATR Stoploss"    
longLossPerc = input(title="Long Stop Loss (%)",type=input.float, group = atr_sl,minval=0.0, step=0.1, defval=1) * 0.01    
atrLength = input(title="ATR Length", type=input.integer, group = atr_sl,defval=6, minval=1)    
userStructure = input(title="Use Structure", type=input.bool, group = atr_sl, defval=true)    
lookback = input(title="How far to look back for High/Low",type=input.integer,group = atr_sl,defval=7, minval=1)    
atrStopMultiplier = input(title="ATR x ? ", type=input.float, group = atr_sl,defval=1.0, minval=0.1)    
plotLong = input(title="Long ATR", type=input.bool, group= atr_sl, defval=false)

// calculate data atr    
longStopPrice = strategy.position_avg_price * (1 - longLossPerc)    
atr=atr(atrLength)    
longStop = (userStructure ? lowest(low, lookback) : close) - atr * atrStopMultiplier    
shortStop = (userStructure ? highest(high,lookback) : close) + atr * atrStopMultiplier

Should I use if (plotLong == true) argument to plot this script? if yes how?

// plot
plot(longStop, color=color.green, style=plot.style_linebr, title="Long Trailing Stop-ATR")

Solution

  • You cannot plot in if blocks. What you can do is, create an input to enable/disable plotting.

    plotAtrSL = input(title="On/Off", type=input.bool, defval=true)
    

    Then use this variable in plot() as a condition.

    plot(plotAtrSL ? longStop : na)
    

    If it is false, it won't plot anything due to `na.