Indicator Loop Problem

 

Hello,

Normally, I use the following code to perform my looping within an indicator:

   int lookback = 15;
   int limit = Bars - 1 - MathMax(lookback, prev_calculated);

   for(int i = limit; i >= 0 && !IsStopped(); --i)
     {
        // my code
     }  
   return rates_total-1;

However, I want to limit the number for loops the indicator performs to 100. When I try this code my indicator doesn't work:

   int lookback = 15;
   int limit = 100 - 1 - MathMax(lookback, prev_calculated);

   for(int i = limit; i >= 0 && !IsStopped(); --i)
     {
        // my code
     }  
   return rates_total-1;

It seems that prev_calculated is a large number and making limit negative. Any ideas on how I limit my loop to the last 100 candles please?

 

Yes

Rates total , is the total bars 

Prev calculated , is the bars the indicator has reached up to

So if the chart has 1000 bars , on the first call the prev calculated will be 0 .

On the second call - before a new bar comes - the prev calculated will be 1000 (because it has read all the bars)

If a new bar comes Rates total will receive one more bar so  rates total will be 1001 and prev calculated will be 1000 so you know there is one bar unread

So , what you can detect is if there is a need to reload by subtracting the prev calculated from the rates total

int from=rates_total-prev_calculated

Then if your from value is bigger than your limit , just start from the limit , but you can check that with finding the mininum

int from=rates_total-prev_calculated;
//the bars_custom_limit is your 100 bars 
//so
from=(int)MathMin(from,bars_custom_limit);
//loop
for(int i= from ;i >= 0 && !IsStopped(); --i)
{
}
 
Lorentzos Roussos #:

Yes

Rates total , is the total bars 

Prev calculated , is the bars the indicator has reached up to

So if the chart has 1000 bars , on the first call the prev calculated will be 0 .

On the second call - before a new bar comes - the prev calculated will be 1000 (because it has read all the bars)

If a new bar comes Rates total will receive one more bar so  rates total will be 1001 and prev calculated will be 1000 so you know there is one bar unread

So , what you can detect is if there is a need to reload by subtracting the prev calculated from the rates total

Then if your from value is bigger than your limit , just start from the limit , but you can check that with finding the mininum

Thanks very much