Introduction
Welcome back! In the last lesson, you made your Expert Advisor (EA) come to life by using the Print() function to send a message to the Experts log. Your EA now diligently reports every new tick it receives.
However, the message "A new tick has arrived!" is static—it never changes. To build a trading robot, we need to work with information that is constantly changing: prices, profit/loss, indicator values, and the state of our trading logic. We need a way to store and manage this data.
This is where variables come in. They are the fundamental building blocks for storing information in any program.
In this lesson, you will learn how to declare and initialize variables for the four most common data types in MQL5: int, double, string, and bool. Mastering variables is the next crucial step toward giving your EA the ability to think and make decisions.
What is a Variable?
Think of a variable as a labeled box where you can store a piece of information.
- You give the box a name (an identifier).
- You decide what type of information it can hold (e.g., only whole numbers, or only text).
- You can then put a value into the box, look at the value, or change it later.
In programming, this process involves two key actions:
- Declaration: Creating the "box" by specifying its data type and giving it a name. This reserves a small piece of the computer's memory.
- Initialization: Giving the variable its first, or initial, value.
To start, let's get a clear definition of what variables are and why they are so essential.
MQL5 Variables... Building Blocks Of Programs
This brief article from MT4Gadgets clearly explains the concept of a variable as a named container for data and why it's crucial for creating flexible code.
Read the sections 'What are MQL5 Variables?' and 'Why Do We Need Variables in MQL5?'.
This distinction between declaring a variable (creating the container) and initializing it (putting something inside) is very important. The following video explains this separation very clearly.
MT5 Programming Tutorial - Variables - Part 2
In this video, René Balke gives an excellent explanation of the difference between declaring a variable (reserving memory) and initializing it (assigning a value).
Watch the segment from 05:37 to 10:11. Pay close attention to the visual explanation of how the computer reserves memory for the counter variable and then assigns values to it.
The Four Basic Data Types
MQL5 has many data types, but for now, we will focus on the four you'll use most often. Let's watch a video that introduces them, and then we'll break them down.
MQL5 Programming Tutorial 1.03 - Core Building Blocks Part 2 - Functions
This video from the 'Toolkit for Traders' channel provides a fantastic overview of the four essential data types. The presenter gives practical, trading-related examples for each one.
Watch the segment from 07:46 to 11:46. The video covers double, int, string, and bool in sequence.
Let's review these four types with their MQL5 keywords and syntax.
1. Integer (int)
An integer is a whole number without any decimal places. It can be positive, negative, or zero.
- Use in Trading: Counting things, like the number of open trades, the number of bars on a chart, or trade ticket numbers.
- Syntax:
int variableName = value; - Example:
int numberOfTrades = 3;
2. Double (double)
A double is a number that includes a decimal point. This is also known as a floating-point number.
- Use in Trading: Storing prices (like Ask or Bid), indicator values (like a Moving Average), stop-loss levels, and lot sizes. This will be one of the most common types in your EAs.
- Syntax:
double variableName = value; - Example:
double audusdPrice = 0.66547;
3. String (string)
A string is a sequence of characters, or simply, text. The value must be enclosed in double quotes (").
- Use in Trading: Storing the name of a currency pair (
"EURUSD"), error messages, or text you want to display on the chart. - Syntax:
string variableName = "value"; - Example:
string tradingSymbol = "GBPUSD";
4. Boolean (bool)
A boolean can only hold one of two possible values: true or false.
- Use in Trading: Acting as a switch or a flag. For example, a boolean variable could track whether it's okay to open a new trade (
isTradeAllowed) or if a specific condition has been met. - Syntax:
bool variableName = value; - Example:
bool isTrendingUp = true;
Here's a summary table for quick reference:
| Data Type | MQL5 Keyword | Description | Trading Example |
|---|---|---|---|
| Integer | int |
Whole numbers | int magicNumber = 12345; |
| Real Number | double |
Numbers with decimals | double stopLossPrice = 1.07250; |
| Text | string |
Text in double quotes | string accountHolder = "John Doe"; |
| Logical | bool |
true or false |
bool allowTrading = false; |
Hands-On: Using Variables in Your EA
Now, let's put this into practice. We are going to modify your MyHeikinAshiEA.mq5 file. Instead of printing a fixed message, you will declare one variable of each type and then print their values to the Experts log.
1. Open Your Project
- In MetaEditor, open
MyHeikinAshiEA.mq5.
2. Modify the OnTick() Function
-
Find the
OnTick()function. -
Delete the old
Print("A new tick has arrived!");line. -
In its place, type or copy the following code. We are declaring and initializing four variables, one for each data type.
//+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { // 1. Declare and initialize our variables string strategyName = "My Heikin Ashi EA"; int magicNumber = 202401; double targetProfit = 150.50; bool isTradingActive = true; // 2. Print the values of the variables to the log Print("Strategy Name: ", strategyName); Print("Magic Number: ", magicNumber); Print("Target Profit ($): ", targetProfit); Print("Is Trading Active? ", isTradingActive); } //+------------------------------------------------------------------+
*Notice how the `Print()` function can accept multiple items separated by commas. It will automatically combine them into a single line of text for the log.*

3. Compile and Run
- Press
F7or click Compile. Make sure you have0 error(s). - Go to your MT5 terminal. If the EA is already on a chart, the changes will apply automatically. If not, drag it onto a chart.
- Open the Experts tab in the Toolbox (
Ctrl+T).
You will now see the values of your variables being printed on every new tick. This demonstrates that you have successfully stored different types of data and can access it.
A Note on Naming Variables
As you write more code, giving your variables clear, descriptive names is incredibly important. A name like stopLossPrice is much better than slp or x.
MQL5 has a few rules for names (which are called identifiers):
- They must consist of letters, numbers, and the underscore character (
_). - They cannot start with a number.
- They are case-sensitive (
myVariableis different fromMyVariable). - They cannot be one of MQL5's reserved words (like
intordouble).
It's a common convention to use "camelCase" for variable names, where the first word is lowercase and subsequent words are capitalized, like myFirstVariable. This makes them easy to read.
Conclusion
Excellent work! You've just mastered one of the most fundamental concepts in all of programming. By learning to store data in variables, you've unlocked the ability to make your programs dynamic and responsive.
Key Takeaways:
- A variable is a named container for storing a piece of data.
- Declaration is creating the variable with a specific type and name.
- Initialization is giving the variable its first value.
- The four basic data types are:
intfor whole numbers.doublefor numbers with decimal points (like prices).stringfor text.boolfortrue/falsevalues.
- You can use
Print()to output the values of variables to help you see what your program is doing.
Preview of the Next Lesson:
Now that you can store data in variables, the next logical step is to do something with that data. In our next lesson, we will explore operators. You'll learn how to perform arithmetic (like + and -), make comparisons (like > and ==), and use logical operators to combine conditions, which are the essential skills for building trading logic.