Mastering MQL5: Variables and Arithmetic Operations in MT5 - Day 2

Learn MQL5 variables and arithmetic operations for building successful Expert Advisors (EAs) in MetaTrader 5. Explore data types, variable declaration, arithmetic operations, and more.

Mastering MQL5: Variables and Arithmetic Operations in MT5 - Day 2
avatar
Stormie
2 min read·
--
Comments
No comment yet!

In this blog post, we'll cover the basics of MQL5, focusing on variables and arithmetic operations.

Whether you're new to coding or an experienced developer, this guide will help you grasp the essentials and take your first steps in the exciting realm of algorithmic trading.


Understanding Data Types in MQL5


In MQL5, data types determine the nature of the information your program handles. Let's look at examples of different data types:

Example:

int age = 30; // Integer variable to store age
double price = 1.2345; // Floating-point variable to store price
char grade = 'A'; // Character variable to store grade
bool isActive = true; // Boolean variable to store true/false


Flow the step in Day 1, create newScript then paste the example code to it.

The IDE will format the code for us and make it a little bit easier to read.



Declaring Variables and Constants


Variables store data temporarily, while constants maintain fixed values. Here's how you declare and use them:

Example:

void OnStart()
{
  int quantity; // Variable declaration
  const double pi = 3.14159265359; // Constant declaration

  quantity = 10; // Assigning a value to the variable
  double result = quantity * pi; // Using the constant in a calculation
  Print("The result is: ", result);
}


Now, to print out something, we use built-in function OnStart()

Paste it to Example code to your script, hit "F5" (Start real-time debug), then check the "Experts" tap in MT5.

The Print() function is valuable for debugging and displaying information.




Performing Arithmetic Operations


Arithmetic operations are vital for trading strategies. Let's perform some basic operations:

Example:

void OnStart()
{
    int num1 = 10;
    int num2 = 5;

    int sum = num1 + num2; // Addition
    int difference = num1 - num2; // Subtraction
    int product = num1 * num2; // Multiplication
    double quotient = (double)num1 / num2; // Division with casting for accurate result

    Print("Sum: ", sum);
    Print("Difference: ", difference);
    Print("Product: ", product);
    Print("Quotient: ", quotient);
}


With the basic Arithmetic Operations, we know calculate something.

Remember, event calculate the speed of light started with basic plus and subtract.

To "Clear" the output you printed before, in "MT5" > "Experts" tab > "Right click" > "Clear".




Conclusion

Congratulations! You've learned the basics of MQL5 programming. You can now use variables to store data and perform arithmetic operations to build your own EAs. Stay tuned for more exciting topics in our MQL5 series!