You can't cut the branch you are sitting on, was: Unexpected infinite loop

Hi

I'm trying to programatically zoom to the range where a bearish candle is found and export the chart. Here's the code:

AW = AB.ActiveWindow;
exportPath = "C:\\Program Files (x86)\\AmiBroker\\ExportedImages\\";
// bearishEngulfing = ...
dt = DateTime();
for (i = 0; i < BarCount; i++) {
	if (bearishEngulfing[i] > 0) {
		fromDate = DateTimeToStr(dt[i-10],1);
		toDate = DateTimeToStr(dt[i+10],1);
		AW.ZoomToRange(fromDate, toDate);
        // AW.ExportImage( exportPath + Name() + ".png"); 
        // Somehow sleep for 5 seconds?

	}
}

Firstly, is there a way to sleep in AFL? Secondly, the loop above continues to loop infinitely. If the ExportImage line was uncommented, the entire application freezes. Does anyone know what's going on?

Hi,
You should change your approach.
This is like sawing-off the tree branch that you are sitting on.

Run the For loop without doing any operations and accumulate the dates in a static variable.
Then later you can read the variable, perform operations like zoom to range/export etc and remove this Date from variable.
Continue doing so until the static variable has no more dates.

Also add error checking code and boundaries, like number of dates should be less than 50 etc. You dont want 100000 images being piled up because of bad coding practices.

All this causes freezes, and its not only software(AB) or OS fault etc, it is hardware limitation among other things as well.

There is ThreadSleep() for sleep but it should be used and not abused.

You can't run this code to export the chart that is using this code because as @nsm explained to you you are creating infinite loop as each export/zoom causes re-execution of this very same formula that in turns causes it again and again.

What you should do is to control AmiBroker from EXTERNAL JScript (write a text with .JS extension and you can run it from Windows using WSH). Then it would be safe. Ask ChatGPT for details how to do that :slight_smile:

@kerf, in addition to the previous observations, if you you use this kind of code in a loop from 0 to Barcount-1 you may get a:
Error 10: Array subscript out of range. You must not access array elements outside 0..(BarCount-1) range.

You need to make sure that each call using the bracket operator [] to access a single element of an array (in your case dt) is in the allowed range and, if necessary (ie. a pattern is found within the first or last 10 bars), change the range of bars to zoom by consequence.

1 Like