MQL|Basic Programming

Variables and Data Types

When starting programming, the first thing to understand is variables and data types. In MQL4 and MQL5, variables are named areas for storing data. By using variables, you can manipulate and retain values within a program.

Variable Declaration

Before using a variable, it must first be declared. Declarations specify the variable name and data type. For example:

int number; // Declare an integer variable
double price; // Declare a double variable
string name; // Declare a string variable

Data Types

The main data types used in MQL4 and MQL5 include:

  • int: Integer (e.g., 1, 100, -50)
  • double: Floating-point number (e.g., 1.23, -0.456)
  • bool: Boolean value (e.g., true, false)
  • string: String (e.g., “Hello”, “MQL”)

Basic Syntax

Understanding basic structures like conditionals and loops is essential for programming. These structures enable you to implement complex logic.

Conditionals

Conditionals are used to execute different actions based on certain conditions. The most common conditional is the if statement.

int number = 10;
if (number > 5) {
    Print("Number is greater than 5");
} else {
    Print("Number is 5 or less");
}

Loops

Loops are used to repeatedly execute the same process. Common loops are for and while loops.

// Example of a for loop
for (int i = 0; i < 10; i++) {
    Print("Iteration: " i);
}

// Example of a while loop
int j = 0;
while (j < 10) {
    Print("Iteration: " j);
    j++;
}

Defining and Using Functions

Functions are blocks of code that perform specific tasks. By using functions, you can enhance code reusability and organization.

Defining Functions

Functions are defined by specifying the function name, parameters (optional), and return type.

// Function without parameters and return value
void MyFunction() {
    Print("Hello from MyFunction");
}

// Function with parameters and return value
int Add(int a, int b) {
    return a + b;
}

Using Functions

Defined functions can be used by calling their names.

// Calling a function
MyFunction();

// Calling a function with a return value
int result = Add(5, 3);
Print("Result of Add: " result);