Search code examples
pine-scriptpine-script-v5

else if structure does not return true when it should


I'm new to PineScript and I have a very weird issue with the "else-if" structure.

This code returns true, even though arePreviousBarsInUpTrend(index) is false.

isShootingStar(index) =>
    result = if (math.min(close[index], open[index]) <= low[index+1] and isCandleGreen(index))
        false
    else if (not arePreviousBarsInUpTrend(index))
        false
    else
        isLowerWickInsignificant(index) and isLongUpperWick(index)

    // Return the final result
    result

I've tried the arePreviousBarsInUpTrend(index) alone, it works fine.

As soon as I introduce the "else-if" structure, the method call is apparently ignored or overwritten.

I must be missing something.


Solution

  • After many tries I found that the arePreviousBarsInUpTrend(index) method was not consistent. Pine script is very tricky when dealing with series.

    as soon as you have a warning message like this one, you are very likely to run in some troubles:

    Warning at xxx:xx The function 'arePreviousBarsInUpTrend' should be called on each calculation for consistency. It is recommended to extract the call from the ternary operator or from the scope

    here is the explanation from the official documentation: https://www.tradingview.com/pine-script-docs/en/v4/language/Functions_and_annotations.html

    In my case, the exact same method was returning a different answer when moved up or down in the full script. I thought I was mad, but the context (series) was indeed changing. So the method would return true in a given call and would return false a bit later in the same script with the same input parameters, because the series had changed.

    Fixing the warnings fixed my weird issue.