Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 8

Mastering the For Loop: Fixed Iteration

Recommended resources

Introduction

In our last lesson, you learned how to combine multiple conditions with && (AND) and || (OR), allowing your code to make nuanced decisions. This was a crucial step, but what happens when you need to perform an action not just once, but multiple times? For instance, to calculate a simple moving average, you need to sum up the closing prices of the last 20 bars. Writing 20 lines of code for this is impractical and inefficient.

This is where loops come in. This lesson introduces one of the most fundamental concepts in programming: repetition. We will focus on the for loop, a powerful tool for executing a block of code a specific number of times. Mastering this will unlock the ability to work with historical data, perform complex calculations, and automate repetitive tasks—all essential skills for building any serious trading bot.

By the end of this lesson, you will be able to implement a for loop to iterate, or repeat actions, a predefined number of times in your MQL5 code.


Why Do We Need Loops? The Concept of Repetition

Imagine you want to find the highest price of the last 50 candlesticks. With the tools you have now, you'd need to write code to check the high of the first bar, then the second, then the third, all the way to 50. It would be a nightmare to write and even worse to read.

A loop solves this problem by providing a structure to repeat a set of instructions. A for loop is ideal when you know exactly how many repetitions you need. For example:

  • "Repeat this 50 times."
  • "Count from 1 to 100."
  • "Look at each of the last 10 bars."

The Anatomy of a for Loop

The for loop might look a bit intimidating at first, but it's very logical. It consists of three parts, all contained within parentheses, that control its execution.

The general structure is:
for (initialization; condition; iteration)
{
// Code to be repeated goes here
}

Let's break down these three essential parts:

  1. Initialization: A statement executed only once when the loop begins. This is where you typically declare and initialize a counter variable. For example: int i = 0; (Start counting at 0).
  2. Condition: An expression evaluated before each loop cycle. If the condition is true, the code inside the loop's curly braces {} is executed. If it becomes false, the loop terminates. For example: i < 10; (Keep looping as long as i is less than 10).
  3. Iteration: A statement executed at the end of each loop cycle. This is where you update your counter variable, usually by incrementing it. For example: i++ (Add 1 to i).

The following video, "LEARN MQL5 TUTORIAL BASICS - 9 HOW TO USE THE FOR LOOP", provides a clear, step-by-step walkthrough of creating a basic for loop that counts upwards.

LEARN MQL5 TUTORIAL BASICS - 9 HOW TO USE THE FOR LOOP

The presenter does an excellent job of breaking down the three expressions of the for loop. Pay close attention to how the counter variable is initialized, checked, and then incremented.

Watch the section that builds the first for loop, from this timestamp.

For a written reference that reinforces this structure, you can consult the official MQL5 documentation.

Introduction to MQL5 (Part 2): Navigating Predefined Variables ...

This article explains the for loop and its advantages. Focus on its breakdown of the syntax.

Read the section titled 4.3. For loop. The Explanation part clearly maps the Initialization, Condition, and Iteration concepts to a code example.


Understanding the Execution Flow

It's crucial to understand the exact order of operations in a for loop to predict its behavior and avoid mistakes.

Here's the sequence:

  1. Initialization runs once.
  2. The Condition is checked.
    • If true, the code inside the {} runs.
    • If false, the loop stops, and the program continues with the code after the loop.
  3. The Iteration step runs.
  4. Go back to step 2.

This cycle—Condition, Code, Iteration—repeats until the condition becomes false.

The article "From Basic to Intermediate: FOR Statement" has a great flowchart that visualizes this process perfectly.

From Basic to Intermediate: FOR Statement - MQL5 Articles

This resource provides a detailed look at the for loop's mechanics. We'll focus on the flowchart that illustrates its execution path.

Find the section titled Execution Flow. Study the flowchart (Figure 04) and read the explanation. Notice how "Expression 01" (Initialization) is outside the main loop cycle. The main cycle consists of checking "Expression 02" (Condition), running the code, and then executing "Expression 03" (Iteration).


Practical Exercise: Creating a Counter EA

Let's put this into practice. We'll create a simple Expert Advisor that uses a for loop to print messages to the Experts journal.

  1. Open MetaEditor.
  2. Create a new Expert Advisor named LoopCounter.
  3. Delete the default template and replace it with this code:
//+------------------------------------------------------------------+
//|                                                  LoopCounter.mq5 |
//+------------------------------------------------------------------+



#property copyright "Copyright 2024, Your Name"
#property version   "1.00"

//--- This function runs when the EA is first started on the chart
void OnInit()
{
  // A simple loop that counts from 1 up to 10
  Print("--- Starting Upward Count ---");
  for(int i = 1; i <= 10; i++)
  {
    Print("The current count is: ", i);
  }
  Print("--- Upward Count Finished ---");
}

//--- The OnTick function is not needed for this example
void OnTick()
{
}

Your Task:

  1. Compile and Run: Compile the code (F7). Open the Strategy Tester in MetaTrader 5 (Ctrl+R). Select the LoopCounter.ex5 EA, choose any symbol/period, and click "Start".
  2. Check the Journal: Go to the "Journal" tab at the bottom of the Strategy Tester window. You should see the output of your for loop, counting from 1 to 10.
  3. Experiment:
    • Count Down: Modify the for loop in OnInit() to count down from 20 to 15. You'll need to change the initialization, condition, and iteration. (Hint: Initialize i to 20, check if i >= 15, and use i-- for the iteration.)
    • Count in Steps: Modify the loop to count from 0 to 100 in steps of 10 (0, 10, 20...). (Hint: i = i + 10 is one way to do this.)

The video you watched earlier also demonstrates how to make these exact changes.

LEARN MQL5 TUTORIAL BASICS - 9 HOW TO USE THE FOR LOOP

You can refer back to this video if you need help with the countdown and step-counting parts of the exercise.

The countdown logic is explained from this section. Changing the step size is covered from this section.


Making it Relevant: Loops in Trading

Simple counting is useful, but how does this apply to building a trading bot? The most common use of for loops in trading is to iterate over historical data like prices, volumes, or indicator values.

The video "MQL5 Programming Tutorial 1.07 - Loops and Lists" contains an excellent, practical example. It uses a for loop to get the volume of the last 5 bars.

MQL5 Programming Tutorial 1.07 - Loops and Lists

This video connects the abstract for loop to a real trading task. It introduces some new concepts like arrays and built-in functions, which we will cover in future lessons. For now, focus only on how the for loop itself is structured and used.

Watch the segment from this timestamp. Observe how the loop is set to run 5 times. Inside the loop, the counter i is used to specify which bar's volume to get (bar 0, then bar 1, then bar 2, etc.).

This example gives you a glimpse of the power you've just unlocked. The counter variable i in for(int i=0; ...) is not just a number; it becomes an index that you can use to pinpoint a specific piece of historical data. i=0 refers to the current, developing bar, i=1 refers to the most recently closed bar, i=2 is the one before that, and so on. This is the mechanism you will use to build nearly every trading strategy.


Conclusion

You have now learned how to control repetition in your programs using the for loop. This is a massive leap forward. Instead of writing code that runs once, you can now write code that systematically works through sets of data, performs calculations, and automates tasks that would be impossible to do by hand.

Key Takeaways:

  • Loops are used to execute a block of code repeatedly.
  • The for loop is best used when you know the number of iterations in advance.
  • A for loop is defined by three parts: initialization (runs once at the start), condition (checked before each run), and iteration (runs at the end of each run).
  • In trading, the for loop's counter is commonly used as an index to access historical price bars, indicator values, or other time-series data.

In this lesson, we focused on loops that run a pre-defined number of times. But what if you want a loop to run until a specific event happens, and you don't know when that will be? For example, "keep checking the price every second until it crosses above $100." For these situations, we need a different kind of loop. In our next lesson, we will explore the while loop, which continues as long as a condition remains true.