for-looppine-scriptpine-script-v5pine-script-v4candlestick-chart

how to check a condition for all candles between two bars in pine script?


hi in the pine script below a_index is the bar_index of a candle that already is saved with this code a_index:= bar_index and i want to check a condition for all candles between this one and the current one. however i dont know how many candles are in between because it might vary. i used this block however the code keeps giving the candle history limit error. despite that i know based on my conditions there shouldnot be lots of candles between the two. i would be very happy if you guys could help me thanks.

// Check all candles from a_index to current candle to verify conditions
allssma = false
for i = a_index to bar_index
    if (close[i] > open[i])
    allssma := true

// Check all candles from a_index to current candle to verify conditions
allssma = false
if (bar_index - a_index <= maxHistory)  // Limit range
    for i = math.max(a_index, bar_index - maxHistory) to bar_index
        if (close[i] > open[i])
            allssma := true

i tried the second block to but i still get the same error.


Solution

  • You can use ta.barssince() to figure out when your condition was true.

    ta.barssince()

    Counts the number of bars since the last time the condition was true.

    Once you get that, and if you know a_index, you can simply check if your condition was true in between, like below:

    bs_my_condition = ta.barssince(my_condition)
    was_my_condition_true = (bs_my_condition <= (bar_index - a_index))