Search code examples
pine-scriptpine-script-v5

How to workaround ta.highest() or ta.lowest() functions' error?


Crossings

I am investigating those crossings, see red/green dots. The goal is to validate them if a dot is preceded by a big movement but dropping crossing events when its too calm.

Just call the distance between the two plots 'X_hist'. I'd like to watch its highest value since the last crossing event.

BarsSinceCrossingUp = ta.barssince(CrossingUp)
CrossingIsValid = ta.highest(math.abs(X_hist), BarsSinceCrossingUp) > math.abs(X_hist[1]) * 5

It fails;

Error on bar 22: Invalid value of the 'length' argument (NaN) in the "highest" function. It must be > 0.

I thought the following Boolean operation will protect the ta.highest() function from 0 or NaN values:

BarsSinceCrossingUp = // wrapped for readability
     ta.barssince(CrossingUp) < 1 or // handling 0
     na(ta.barssince(CrossingUp)) ? 1 : // handling NaN
     ta.barssince(CrossingUp)

CrossingIsValid = ta.highest(math.abs(X_hist), BarsSinceCrossingUp) > math.abs(X_hist[1]) * 5

Error message remained which I don't get why though. How could I make this ta.highest() function work? Maybe this ta.barssince(CrossingUp) function isn't the proper way to retrieve the number of bars since the last CrossingUp event?


Solution

  • Instead of using those functions, you can just a var variable.

    var float highest_x = na     // Keep of highest X_hist after a cross
    
    if (CrossingUp)              // New cross, reset the variable
        highest_x := X_hist
    else
        if (X_hist > highest_x)  // Check if the current X_hist is greater than our variable
            highest_x := X_hist