Search code examples
pine-scriptpine-script-v5tradingtradingview-api

PineScript 'ta.lowest' and 'ta.highest' shows wrong value when in 'if' condition


I have the following PineScript to check if the RSI value of 2 or more consecutive candles lie within range specified in the if condition

//@version=5
indicator("RSICondition", overlay=true, max_bars_back = 20)

RSI = ta.rsi(close, 14)

varip int ToPlot = 0                            //0 means nothing to plot, 1 means to plot RED-BOX
varip int left = 0                              //Pointer for the left edge of the box
varip float highestHigh = na                    //Declaring Global Variable
varip float lowestLow = na                      //Declaring Global Variable

if (RSI >= 58 and RSI <= 62)
    left := left + 1
    if (left > 1)                               //If we have consecutive candles within 58 & 62, eg. lets take 3 consecutive candles
        highestHigh := ta.highest(high, left)   //Calculating the Highest High from the 3 candles
        lowestLow := ta.lowest(low, left)       //Calculating the Lowest Low from the 3 candles
        ToPlot := 1                             //Specifying RED color box to plot

else
    if (ToPlot == 1)                            //When the candle after 3 consecutive candles within specified range comes, time to plot RED box for those 3 candles
        box.new(bar_index[left], highestHigh, bar_index[1], lowestLow, border_color=color.red, bgcolor=color.new(color.red, 80))
    ToPlot := 0                                 //Reset ToPlot to 0 after plotting specifying there is nothing to plot now
    left := 0                                   //Reset the pointer after box plotted

The compiler shows the following warnings for both ta.lowest and ta.highest : The function '<function_name>' should be called on each calculation for consistency. It is recommended to extract the call from this scope and also the boxes created show the incorrect values for the highestHigh and lowestLow variables since they are specified for top and bottom edge of the box respectively.

I could specify these functions outside the if statement but sometimes the value of left variable becomes 0 as well where there error throws length for ta.highest and ta.lowest cannot be 0.


Solution

  • You must evaluate ta.highest() outside of an if conditional.

    highestHighTmp = ta.highest(high, math.max(1, left)) // should "left" be 0 you don't use it anyway
    lowestLowTmp = ta.lowest(low, math.max(1, left))
    if (RSI >= 58 and RSI <= 62)
        left := left + 1
        if (left > 1)
            highestHigh := highestHighTmp
            lowestLow := lowestLowTmp
            ToPlot := 1                     
    ...