pine-scriptpine-script-v5thinkscript

Thinkscript to Pine Script recursive bool assignment to initialize array


I'm trying to convert the following code from thinkscript to Pine Script.

def highestVolEv = if volume>highestVolEv[1] then volume else highestVolEv[1];

This is supposed to create the array highestVolEv in pine script. I tried to do:

var highestVolEv = array.new_int()
highestVolEv = if volume>highestVolEv[1] 
    volume 
else 
    highestVolEv[1]

but then I get get the error: Compilation error. Line 62: Cannot call 'operator >' with argument 'expr1'='call 'operator SQBR' (int[])'. An argument of 'int[]' type was used but a 'simple float' is expected lines 62:66: Return type of one of the 'if' or 'switch' blocks is not compatible with return type of other block(s) (series float; int[])

What is the proper way to do this in Pine Script?

Expected result: Array of volumes: Prior highest volume if current bar volume is less than prior highest volume. Current volume if it's higher than prior highest volume.


Solution

  • // store highest vol in a variable and keep updating
    var highestVol = volume
    if highestVol < volume
        highestVol := volume
    

    or

    // get highest volume in the last n bars
    length = 5
    ta.highest(volume, length)
    

    The solution with the arrays is probably not the best way to do it. The problem with it is:

    1. volume is a float so array.new()
    2. to calculate with an array value use: array.get(myArray, idx)
    3. to add to an array use eg.: array.push(myArray, value) Further reference to array usage.