I am trying to make a trailingstop multiple of the ATR, since a buy or sell signal has occured. Naturally I try the barssince(long) function, to determine the amount of bars since the buy signal. Then I use the highest function to find the highest ATR value since my buy signal. My code is:

atr = atr(input(defval=14, title="ATR"))
Multip = input(0.2, minval = 0)
lower = low - atr * Multip
upper = high + atr * Multip


barssincelong = barssince(long)
barssinceshort = barssince(short)
islong = barssincelong < barssinceshort


plotlower= highest(lower, barssincelong)
plotupper= lowest(upper, barssinceshort)


stoplossline = islong ? plotlower : plotupper


plot(stoplossline)

"long" and "short" are defined in the code above that, but that is irrelevant.

For some odd reason, this script gives a Study Error that says:

"Invalid value of the 'length' argument (0) in the 'highest' function. It must be > 0.

Can someone help me with this problem?

3

There are 3 best solutions below

0
On

I met the same error and have a solution like this

barssincelong = barssince(long)
if na(barssincelong ) or barssincelong ==0
    barssincelong := 1
1
On

The function barssince returns the value na if no bar with the specified conditions is found. This situation is possible on the very first bars. For the functions highest and lowest the argument length greater than zero must be specified. You need to define in the script how to handle such situations.

0
On

you can use the following code , here nz() is used to avoid errors due to returning of na when ta.barssince() used and math.max() used to get rid of 0 returning from ta.barssince(). Hence you will not send 0 as length in the ta.highest() or ta.lowest() function.

pine script version 5 used :

//@version=5
indicator("My script")

atr = ta.atr(input(defval=14, title="ATR"))
Multip = input.float(0.2, minval = 0)
lower = low - atr * Multip
upper = high + atr * Multip

ema=ta.ema(close,20)
long=ta.crossover(close,ema)
short=ta.crossunder(close,ema)

barssincelong = nz(ta.barssince(long))
barssinceshort =  nz(ta.barssince(short))

islong = barssincelong < barssinceshort
plotlower= ta.highest(lower, int(math.max(1,barssincelong)))
plotupper= ta.lowest(upper,  int(math.max(1,barssinceshort)))
stoplossline = islong ? plotlower : plotupper


plot(stoplossline)