MQL4|Using Arrays in MetaTrader 4 (MT4) MQL4 Programming

In MetaTrader 4 (MT4) MQL4 programming, arrays can be used to efficiently handle data. This article explains the basic usage of arrays in a way that beginners can understand. By using arrays, you can store multiple values in a single variable, improving the flexibility of your program.

What is an Array?

An array is a data structure that organizes values of the same data type in a sequence. By using arrays, you can handle multiple values with a single variable, making data manipulation easier. For example, the four price data (Open, High, Low, Close) are managed using arrays.

Basic Syntax of Arrays

The following sample code demonstrates the basic usage of arrays.

// Declaring an array
double values[3];

// Assigning values to the array
values[0] = 1.0;
values[1] = 2.0;
values[2] = 3.0;

// Displaying the contents of the array
for (int i = 0; i < 3; i++) {
    Print("values[" i "] = " values[i]);
}

Execution Result

When you run this sample code, the following results are output:

values[0] = 1.0
values[1] = 2.0
values[2] = 3.0

Basic Operations of Arrays

Declaring an Array

Before using an array, you need to declare it. To declare an array, specify the data type and the size of the array.

double values[3];  // Declaring an array of double type with size 3

Assigning Values to an Array

To assign values to each element of an array, use an index. The index starts from 0 and goes up to the size of the array minus one.

values[0] = 1.0;
values[1] = 2.0;
values[2] = 3.0;

Retrieving Values from an Array

When retrieving values from an array, use an index. The following code shows an example of displaying array values using a loop.

for (int i = 0; i < 3; i++) {
    Print("values[" i "] = " values[i]);
}

Pay Attention to Array Size

Since arrays use 0-based indexing, to access the last element of the array, you need to specify “array size at declaration – 1”.

Summary

By using arrays, you can efficiently manage and manipulate data within MQL4 programs. Understanding the basic usage of arrays will enable you to handle more complex programs. Beginners should first learn the basic operations of arrays and apply them to actual trading programs.