video

In this video we take a look at the While Loop. It counts up to 500.000 up here and only then our test starts down here. And we want to take a look at how the While command can be used to execute certain things in a loop. To do this we click on this little button here in the Metatrader or press the F4 key. This will bring up the Meta Editor. And here we click on File, New, Expert Advisor from template, Next. I’ll give the name SimpleWhileLoop here once. Click on Next, Next and Finish. Now we can delete everything above the OnTick function, even the two comment lines can be removed. We start by creating an integer variable for a delay counter up here. This variable will be assigned the value one. We use an integer variable, because we don’t need decimal places. We do the same again here. This should be our minimum value. Up to 500.000 our While loop should count up before our program continues. Again, an integer value is sufficient for us. And within our OnTick function we now want to check if our delay counter is even smaller than the minimum value for the start. And everything within the two curly brackets here is executed as long as the expression above is true. In this simple example we would like to use the Comment command to print the text DelayCounter followed by the current value of our counter. And then the counter is incremented by one. This can be done with the command DelayCounter= DelayCounter+1. That’s it. And when we have everything, we click on Compile up here or press the F7 key. That should work here without any errors. And in this case we can click up here or press the F4 key to return to the Metatrader. And in the Metatrader we click on View, Strategy Tester or press the key combination Ctrl+R. Here we now select the new file SimpleWhileLoop.ex5, mark the option for visualization and start our test. Our counter starts counting up here. And as soon as a value of 500,000 is reached, we continue here. So far so good, but unfortunately the While Loop has a catch. Let’s take this up count, cut it out and paste it outside the While Loop. Recompile our code here. And run a new test. Then nothing happens here at all. Whether we change the speed or not. The counter will not increment. That’s because we’ve created an infinite loop here. Since the value inside the loop never increments, this condition is always true here. And our program would never leave the While Loop again. You could also exchange the While Loop here for if. Recompile. And now our counter would run all the time. So if you use While in your program, make sure that there is a change within the While loop that makes sure that the expression queried above is not true at some point. Only then will the loop work as intended. Otherwise it would block your program forever. In this short video you have learned how to use the While loop. And you programmed it yourself with these few lines here in MQL5.

Hide picture