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

PineScript - ATR % Stoploss


I want to add ATR stoploss when strategy placed/detected an entry. so far I came up with this script:

@version=4    
// Stop Loss inputs atr     
longLossPerc = input(title="Long Stop Loss (%)",type=input.float, minval=0.0, step=0.1, defval=1) * 0.01    
atrLength = input(title="ATR Length", type=input.integer, defval=6, minval=1)
userStructure = input(title="Use Structure", type=input.bool, defval=true)    
lookback = input(title="How far to look back for High/Low",type=input.integer, defval=7, minval=1)    
atrStopMultiplier = input(title="ATR x ? ", type=input.float, defval=1.0, minval=0.1)    
longStopPrice = strategy.position_avg_price * (1 - longLossPerc)

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

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

My problem is, I don't know how can I relate/connect this script to my script argument. Do I have to make a new variable, and then insert it in my strategy.close?

strategy.entry("LongA", strategy.long,1, when= x and y)    
strategy.close("LongA", when= z or t )

Note: x,y,z,t are predefined variables.


Solution

  • You want to use strategy.exit() function. It has stop and loss parameters.

    loss (series int/float) An optional parameter. Stop loss (specified in ticks). If it is specified, a stop order is placed to exit market position when the specified amount of loss (in ticks) is reached. The default value is 'NaN'.

    stop (series int/float) An optional parameter. Stop loss (requires a specific price). If it is specified, a stop order is placed to exit market position at the specified price (or worse). Priority of the parameter 'stop' is higher than priority of the parameter 'loss' ('stop' is used instead of 'loss', if its value is not 'NaN'). The default value is 'NaN'.

    strategy.entry("LongA", strategy.long,1, when= x and y)
    strategy.exit("Long Exit", "LongA", loss=longStop)