Indicator does not enter for loops correctly when I change timeframe/asset

 
Hello everyone and thank you in advance for your help.
I wrote an indicator that, based on the opening and closing conditions of the past bars, creates rectangles in the chart.
The indicator works well most of the time and updates correctly on the chart.
The problem occurs when I try to change assets or timeframes several times: if an asset hasn't been used before, often the indicator seems not to appear on the chart (i.e. no objects are drawn) until I reload the indicator or I switch between timeframes.
I tried inserting some print to debug and when this happens, the on init is initialized correctly but the print inside the for loop that loops the bars is not printed. This leaves me thinking that the problem is in the loop.

This is how I try to cycle the bars :

 int barsToProcess = 300 ; 

int limit = MathMin (rates_total - prev_calculated, barsToProcess); 
   
   for ( int i = limit - 1 ; i >= 0 && ! IsStopped (); i--)
     {
..... // code 
     }

I've tried searching the forum, but I don't see any reason why this for loop code shouldn't work, but I don't have much experience.

 
forextastic: , but I don't see any reason why this for loop code shouldn't work, but I don't have much experience.

Use the debugger or print out your variables, including _LastError and prices and find out why. Do you really expect us to debug your code for you?
          Code debugging - Developing programs - MetaEditor Help
          Error Handling and Logging in MQL5 - MQL5 Articles (2015)
          Tracing, Debugging and Structural Analysis of Source Code - MQL5 Articles (2011)
          Introduction to MQL5: How to write simple Expert Advisor and Custom Indicator - MQL5 Articles (2010)

 
No, I don't expect that. I just asked because I've been banging my head on it for days and for several hours so if anyone has had a similar experience it can help.
As I already wrote, the problem happens in the for loop and I sent the code. If I insert a print immediately after the for when it happens the problem , the print is not executed. 
What is the point of the forum otherwise ? 😉 

 
Resolved. The problem was that I was comparing the visible bars in the chart with Mathmin in the oninit and this sometimes returned a negative value.
By removing that line, the problem does not occur.
Reason: