Search code examples
pine-scriptpine-script-v5pine-script-v4

finding nearest value in a array in pinescript v5


i am trying to code a strategy based on fibretracement. i have added the fib values as an array. i want for trail my target and stoploss basis the fib levels. if close of the candle is between fib levels say 0.5 and 1, the trail target i want to fix as fib level of 1 and stoploss at 0.5. then if close moves to 1.25 of fib level, then the target to be moved to the 1.618 and tsl at 1. hence i am looking to get a positioning of close[1] in respect to the array index say between index position 3 and 4 or say 5 and 6 and out put to be the value of the respective index iteratively. i have made this work thru a if loop

if target > fiblevel1
t1 := fiblevel2
sl  := fiblevel1
    if target > fiblevel2
        t1:=fiblevel3
        sl:= fiblevel2

and so on. i am trying to do the same thru array manipulation if possible can some body help me


Solution

  • var float[] array_fibos = array.new_float()
    var bool level_reached = false
    
    // fill the array with fibo levels
    array.push(array_fibos, fiblevel1)
    array.push(array_fibos, fiblevel2)
    array.push(array_fibos, fiblevel3)
    ...
    
    // sort the array
    // for longs, ascending order
    // for shorts, descending order
    
    // use array.sort function
    
    // browse the array and exit when high is higher
    
    if array.size(array_fibos) > 0
    
        for i = 0 to(array.size(array_fibos) == 0  ? na : array.size(array_fibos) - 1)
    
            if high >= array.get(array_fibos, i)
                 level_reached := true
                 break