grdnryn
Pine Script Rookie
Pine Script Rookie
Posts: 3
Joined: September 26th, 2021
Contact: TradingView Profile

For loop not counting correctly

Hi all,

I have a simple for loop script that I grabbed from one of Matthew's videos to count the number of occurrences of a specific instance happening on my chart.
I also have these same instances plotted on the chart with the plotshape() function just so that I can double check the accuracy of the for loop count...and there is a big difference in the result! :concerned:

The for loop

Code: Select all

positiveBars = 0
for i = (lookback - 1) to 0
    if (high[i] < HH75 and low[i] > LL25)
        positiveBars := positiveBars + 1
positiveBarsPercent = (positiveBars / lookback) * 100
with these declared earlier in the script.

Code: Select all

length = input(5)
HH = highest(high, length)
LL = lowest(low, length)
HH75 = HH-(HH-LL)*0.25
LL25 = LL+(HH-LL)*0.25
Any ideas why I would be getting such a discrepancy?

Deep-Wave
Pine Script Master
Pine Script Master
Posts: 44
Joined: September 4th, 2020
Contact: TradingView Profile

Re: For loop not counting correctly

Hi grdnryn,

it is a bit difficult to help without seeing the entire code, I am not sure i understand exactly what you want to do.
But one thing i noticed in your code is that in your if statement you compare current values to index values, is that intentional?

Code: Select all

 if (high[i] < HH75 and low[i] > LL25)
instead of

Code: Select all

 if (high[i] < HH75[i] and low[i] > LL25[i])
Anyway, I hope this helps a bit.
Good luck with your coding :wink:

Return to “Pine Script Q&A”