while statement

 

I'm using the 'while' statement with great success for some recovery work. Embedded is a counter (for # of tries) and after such # of tries there are checks/balances before looping back to the counter such to ensure things don't take too long and take a loss will be taken if things get out of hand.

However - when my EA is in such while loop, if it is impossible to terminate the EA w/o crashing the MT4 instance. Is that typical for while statements?

I found this out 'while' (pun intended) testing.

 
You must return from OnTick within several seconds when the terminal wants the EA to exit. Check IsStopped - MQL4 Documentation and stop the loop. Alternatively, don't loop; process the tick and return.
 

Thanks IsStopped() seems indeed the winner - i didn't find the Documentation useful at all BUT after some experimenting it seems that adding:

 if(IsStopped()==true){ExpertRemove();}

 In every while loop and after every Sleep() does the trick, well it ofter does at least... 

If my while-loops and sleeps in functions outside of OnTick(), so it still doesn't work every and all time...

Ie. i have to keep looking :-( 

 

Ok so here is the solution:

if you have a while loop OUTSIDE of the normal OnTick() routine, ie in some outside function like MyFunction(), make sure you insert:

if(IsStopped()==true){return(0);}
Sleep(1000);
if(IsStopped()==true){return(0);}

 

Maybe 1x  if(IsStopped()==true){return(0);} will suffice, but i do two just to be safe. And have some Sleep() in there such to make you CPU not go to 100%. Even if it is only for 50ms or so.

With this inserted my EA and MT4 never hangs anymore. Apparantly the Return(0) is necessary to bring the EA back to OnTick() as per WHRoeder and Return() does the trick.