Mastering MQL5: Control Structures and Looping - Day 4

Let's explore conditional statements, looping structures, and control statements in MetaTrader 5. Elevate your Expert Advisor coding skills with real-life examples for strategic decision-making and iterative tasks.

Mastering MQL5: Control Structures and Looping - Day 4
4 min read·
No comment yet!


Welcome to Day 4 of our MQL5 programming challenge! Today, we're taking a deep dive into the fascinating world of control structures and looping. These essential programming constructs empower your Expert Advisors (EAs) to make intelligent decisions, repeat actions, and adapt seamlessly to the ever-changing dynamics of the financial markets.

Ok, let's start.

Conditional Statements (if, if-else, else-if)

Conditional statements are the bedrock of decision-making in programming.

  • if Statement: Execute a block of code if a condition is true.
  • if-else Statement: Execute one block if the condition is true, and another block if false.
  • else-if Statement: Check multiple conditions sequentially and execute the first true condition.

The syntax of a full-form IF conditions is as bellow.

  if (condition1)
    { // Code block to execute if condition1 is true }
  else if (condition2)
    { // Code block to execute if condition2 is true }
    { // Code block to execute if none of the conditions are true }

Example 1 - Check the trend:

void OnInit()
    // Define the period for the two moving averages
    int fastMAPeriod = 10; // Fast moving average period
    int slowMAPeriod = 20; // Slow moving average period
    int ShiftEMA = -2;

    // Calculate the moving averages
    double fastMA = iMA(_Symbol, _Period, fastMAPeriod, ShiftEMA, 
    double slowMA = iMA(_Symbol, _Period, slowMAPeriod, ShiftEMA, 

    // Check for a crossover condition
    if (fastMA > slowMA)
      Print("UP trend -- " + fastMA + " -- " + slowMA);  
    else if (fastMA < slowMA)
      Print("DOWN trend -- " + fastMA + " -- " + slowMA);  

Run the code above and we get something write down to the "Expert" tab.

Hummm, the code run ok, but I don't think the logic is right.

Anyway, the logic is for later, current let's only focus on the idea of using IF statements

Looping Structures (for, while, do-while)

Looping structures allow your program to repeat a block of code multiple times. I come from Python + Javascript stack, so this is all the same with other language.

  • for Loop: Iterate a block of code a specific number of times.
  • while Loop: Repeat a block of code while a condition is true.
  • do-while Loop: Repeat a block of code at least once and then while a condition is true.

Example 2 - Calculating Moving Average:

void OnTick() {
   int period = 14; // Number of periods for moving average
   double sum = 0;
   for (int i = 0; i < period; i++)
       sum += iClose(_Symbol, 0, i);
   double movingAverage = sum / period;
   Print("Simple Moving Average: ", movingAverage);

Run the example and we got some output like this.

Every time the chart get new data, it will also calculate the MA for us. We created a loop

Using OnTick() build-in function is the main source of place order in MQL5.

Break and Continue Statements

Learn how to control the flow within loops using the break and continue statements:

  • break Statement: Exit a loop prematurely.
  • continue Statement: Skip the rest of the loop iteration and move to the next.

Example 3 - Early Exit from Loop:

void OnInit() {
   for (int i = 0; i < 10; i++)
       if (i == 5)
           Print("Loop terminated at i = 5.");
           break; // Exit the loop
       Print("Loop iteration: ", i);

The origin loop will be stop when i =10, but here it was broken when i = 5.

If we have a take profit order but only wait for 10 minute, we will use "break" to break the waiting logic and take what ever profit we has at that moment.


Congratulations on completing Day 4 of our MQL5 programming challenge! You've mastered conditional statements, looping structures, and control statements, enabling your EAs to make informed decisions and perform repetitive tasks. Keep practicing and stay tuned for more exciting challenges as we continue to build your MQL5 programming expertise!