Skip to main content

Welcome to a Grasp lesson

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

Lesson 3

Manipulating Numeric Variables

Recommended resources

In our previous lesson, we established the groundwork for giving your trading bot a memory by learning how to declare and initialize variables. You now know how to create "storage boxes" for different types of data like numbers (int, double), text (string), and logical states (bool).

This lesson takes the next logical step: we'll learn how to manipulate the data inside those variables. You can't build a trading strategy without performing calculations—determining profit targets, risk levels, or comparing indicator values. Here, we will cover the essential tools for the job: arithmetic and assignment operators. These are the fundamental verbs of programming that allow you to add, subtract, multiply, and update values, turning static data into dynamic logic.

Revisiting the Assignment Operator: =

You've already used the assignment operator, =, to initialize variables. It's the operator that puts an initial value into the storage box you create.

double price = 1.0750;

Its job doesn't end there. You can also use it to update or change the value of a variable at any point in your program.

// 1. Declare and initialize a variable
int numberOfTrades = 5;

// At a later point in the code...

// 2. Assign a new value to the same variable
numberOfTrades = 10; 

After the second line, the original value of 5 is gone, and the numberOfTrades variable now holds the value 10. This ability to change a variable's state is fundamental to making your programs responsive.

The image below from an example Expert Advisor shows several variables being declared. The lines highlighted in the red circle demonstrate the use of the = operator to initialize an int, a bool, and declare a CTrade object.

This code shows the assignment operator `=` used to give initial values to variables like `ExtHandle` and `ExtHedging`.

Performing Calculations: Arithmetic Operators

To make your variables do useful work, you need to perform calculations with them. MQL5 uses a standard set of arithmetic operators for this purpose.

Arithmetic operations - Programming fundamentals - MQL5 Programming for Traders

This resource from the official MQL5 book provides a clear table of the main arithmetic operators and explains their order of execution, which is a crucial concept.

Focus on the table and the paragraph that follows it. Pay close attention to the symbols (+, -, *, /, %) and the "P" (precedence) column.

As you saw in the reading, the main arithmetic operators are:

  • + (Addition)
  • - (Subtraction)
  • * (Multiplication)
  • / (Division)
  • % (Modulo - remainder of a division)

Operator Precedence

Just like in standard mathematics, MQL5 follows an order of operations. Multiplication and division are performed before addition and subtraction.

For example, this line of code:
double result = 10 + 5 * 2;

The result will be 20, not 30, because 5 * 2 is calculated first. If you need to control the order, you use parentheses, which always have the highest priority.

double result = (10 + 5) * 2;

Now, the result will be 30. When in doubt, use parentheses to make your intentions clear.

An Important Detail: Integer vs. Floating-Point Division

This is a common pitfall for new programmers. When you divide two integers, MQL5 performs integer division, meaning it throws away any fractional part of the result.

int a = 10;
int b = 4;
double result = a / b; // The result will be 2.0, not 2.5

Even though result is a double, the damage is already done because a and b are both integers. To get a precise decimal result, at least one of the numbers in the division must be a double (a floating-point number).

double a = 10.0; // Make 'a' a double
int b = 4;
double result = a / b; // The result will be 2.5

This is critical in trading calculations where precision is everything. This concept is explained well in the following resource.

Arithmetic operations - Programming fundamentals - MQL5 Programming for Traders

This section explains the nuances of division and introduces the modulo operator.

Read the part that begins with the explanation of integer division. Then, continue to the section on the modulo operator.


Simplifying Your Code: Compound and Increment Operators

Often, you'll need to modify a variable based on its current value. For example, to add 50 to your account balance, you might write:

balance = balance + 50.0;

This is so common that programming languages provide a shorthand.

Compound Assignment Operators

These operators combine an arithmetic operation with an assignment.

  • += (Add and assign)
  • -= (Subtract and assign)
  • *= (Multiply and assign)
  • /= (Divide and assign)

Using this shorthand, the previous example becomes much cleaner:

balance += 50.0;

This article section provides a clear explanation.

Master MQL5 from beginner to pro (Part II): Basic data types and use ...

This resource explains the various forms of the assignment operator, including the useful shorthand versions.

Read the subsections titled Assignment operator and Shorthand use of assignment.

Increment and Decrement Operators

The most common modification is adding or subtracting 1, such as when counting bars or trades. MQL5 has ultra-compact operators for this: ++ (increment) and -- (decrement).

int tradeCounter = 0;
tradeCounter++; // tradeCounter is now 1
tradeCounter++; // tradeCounter is now 2
tradeCounter--; // tradeCounter is now 1

Each ++ is equivalent to tradeCounter = tradeCounter + 1; or tradeCounter += 1;.


Practical Application: Calculating the Spread

Theory is useful, but seeing these operators in action is what solidifies understanding. Let's watch a segment from the tutorial video we used last time. The author builds a small tool to calculate the current symbol's spread, demonstrating the use of several operators.

MQL5 Programming Tutorial 1.04 - Core Building Blocks Part 1 - Variables and Comments

This video provides a practical, hands-on demonstration of using arithmetic operators to solve a real trading-related problem: calculating the spread.

First, watch how the initial, simple spread calculation is done using the subtraction operator. Pay attention to the line spread = p_ask - p_bid;. Watch the segment from the calculation. You'll notice the initial result isn't quite right. The author then refines the calculation to display the spread in points. This involves division (/) by the _Point variable. This is a perfect example of how operators are used to transform data into a more useful format. Watch the debugging and refinement process from this section.

This practical example shows you that programming is often a process of starting with a simple calculation (ask - bid) and progressively refining it ((ask - bid) / _Point) until you get the exact result you need for your strategy.


Conclusion

You've now added the essential "tools" to your programming toolkit. You started with variables (storage boxes) and now have the operators to manipulate what's inside them. This is the core of all logic in your future trading bots.

Key Takeaways:

  • The assignment operator (=) is used to both initialize and update the value of a variable.
  • The primary arithmetic operators are +, -, *, /, and %. They follow a standard order of precedence, which can be controlled with parentheses.
  • Be mindful of integer division: dividing two int variables will discard any decimal part of the answer. Ensure at least one number is a double for precise calculations.
  • Use compound operators (+=, -=) and increment/decrement operators (++, --) to write cleaner, more efficient code for common modifications.

You can now calculate new values, but how do you check if your calculations are correct? The next step is to learn how to make your program communicate with you. In our next lesson, we will cover the Print() function, an indispensable tool for displaying variable values and messages, which is crucial for testing and debugging your code.