Skip to main content

Welcome to a Grasp lesson

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

Lesson 7

Logical Operators: AND and OR

Recommended resources

In our last lesson, you took a significant step by learning to use if-else statements, giving your code the ability to make decisions. This is the foundation of all intelligent trading logic. However, real-world trading decisions rarely hinge on a single condition. A good strategy often requires several conditions to be met simultaneously.

This lesson builds directly on that foundation. We will explore how to combine multiple conditions using logical operators. You'll learn how to tell your Expert Advisor to act only when, for example, "the price is above a moving average AND a momentum indicator shows oversold conditions," or to send an alert if "the spread is too high OR the connection is lost." Mastering this will allow you to translate more sophisticated and robust trading ideas into code.

By the end of this lesson, you will be able to combine multiple conditions in your MQL5 code using the logical && (AND) and || (OR) operators to create more complex and realistic decision-making logic.

When Everything Must Align: The && (AND) Operator

Often in trading, a signal is only valid if several criteria are met at the same time. You don't just buy because the price went up; you might buy if the price went up, the trend is strong, and there's good volume.

This is where the logical AND operator, written as &&, comes in. It connects two or more conditions, and the entire expression is only true if all of the individual conditions are true. If even one condition is false, the whole thing becomes false.

Think of it like a checklist before launching a rocket:

  1. Is the weather clear?
  2. Is the fuel tank full?
  3. Are all systems nominal?

You only launch if the answer to all three questions is "yes".

The video "MQL5 Programming Tutorial 1.05" provides an excellent explanation of both the && (AND) and || (OR) operators.

MQL5 Programming Tutorial 1.05 - Logic If/Else Operators and Expressions

This segment clearly breaks down how && and || work. Pay close attention to the examples showing when the combined expression evaluates to true or false. This is the core concept for this lesson.

Watch the instructor's explanation of combining expressions from this timestamp.

As you saw in the video, the structure for a buy signal that requires both a low RSI and a price above a moving average would look like this:

if (rsi < 30 && price > movingAverage)
{
  // Both conditions are true, so it's a valid buy signal.
  // Execute buy order...
}

The article "MQL5 If Then and Conditional Operators" gives a great, practical code example of this exact scenario.

MQL5 If Then and Conditional Operators - MT4Gadgets

This article provides a concise guide to conditional logic in MQL5. The section on combining logical operators is particularly relevant to our current topic.

Find the heading Best Practices. Read the subsection titled Combine Logical Operators and study the code example that follows. It shows how to check if the RSI is low AND the price is above a moving average before sending an order.


When Just One Condition is Enough: The || (OR) Operator

Sometimes, you want your program to act if any one of several conditions is met. For example, you might want to close a trade if the price hits your stop loss OR if it hits your take profit target. You don't need both to happen, just one of them.

For this, we use the logical OR operator, written as ||. It connects two or more conditions, and the entire expression is true if at least one of the individual conditions is true. The only way for an || expression to be false is if all of the conditions are false.

A simple analogy: a movie theater might offer a discount if you are a student OR a senior citizen. You don't need to be both; meeting just one criterion is enough to get the discount.

In MQL5, you could use this to create a flexible alert system:

if (spread > maxAcceptableSpread || isNewsTime == true)
{
  // At least one of these is true.
  // Send an alert and avoid trading.
}

Truth Tables: A Quick Reference

To make it crystal clear, here's how these operators work. In programming, true can be thought of as 1 and false as 0.

AND (&&) Operator (Result is true only if A AND B are both true)

Condition A Condition B A && B
false false false
false true false
true false false
true true true

OR (||) Operator (Result is true if A OR B is true)

Condition A Condition B A || B
false false false
false true true
true false true
true true true

This summary is also clearly laid out in the MQL5 article you can refer to.

Introduction to MQL5 (Part 2): Navigating Predefined Variables ...

This article from the official MQL5 site covers several fundamental topics. We are interested in its clear definition of logical operators.

Scroll down to the section 3.2. Logical Operations. The table here provides a perfect, quick reference for the || (OR) and && (AND) operators.


Practical Exercise: Building a Two-Factor Signal Checker

Let's apply this. We will write a simple Expert Advisor that checks two mock conditions. This will help solidify how && and || work in practice.

  1. Open MetaEditor.
  2. Create a new Expert Advisor named SignalChecker.
  3. Replace the default template with the code below.
//--- Expert Advisor settings



#property copyright "Copyright 2024, Your Name"
#property link      "https://www.mql5.com"
#property version   "1.00"

//--- Input parameters that we can change from the chart
input bool condition1 = true;
input bool condition2 = false;

//--- This function runs on every new tick (price change)
void OnTick()
{
  // --- Check using the AND operator ---
  if (condition1 && condition2)
  {
    // This block only runs if BOTH condition1 AND condition2 are true
    Comment("AND check: TRUE. \nSignal is valid.");
  }
  else
  {
    // This block runs if one or both are false
    Comment("AND check: FALSE. \nSignal is NOT valid.");
  }

  // You can uncomment the section below to test the OR operator
  /*
  // --- Check using the OR operator ---
  if (condition1 || condition2)
  {
    // This block runs if AT LEAST ONE is true
    Comment("OR check: TRUE. \nSignal is valid.");
  }
  else
  {
    // This block runs only if BOTH are false
    Comment("OR check: FALSE. \nSignal is NOT valid.");
  }
  */
}

Your Task:

  1. Compile and Run: Compile the code and attach the SignalChecker EA to any chart. You will see a comment in the top-left corner.
  2. Test the && Operator:
    • With the default settings (condition1 = true, condition2 = false), what does the comment say? Why?
    • Open the EA's Properties (F7 key). Go to the Inputs tab.
    • Change condition2 to true. What happens to the comment on the chart?
    • Try all four combinations of true/false for the two inputs and observe the result. Does it match the AND truth table?
  3. Test the || Operator:
    • Go back to the code. Comment out the AND check block by putting /* before it and */ after it.
    • Uncomment the OR check block by removing the /* and */.
    • Re-compile the code. The EA on your chart will update automatically.
    • Repeat the process of changing the input values in the EA's Properties and observe the results. Does the behavior match the OR truth table?

This exercise gives you direct, hands-on experience with how MQL5 evaluates these logical operators.


A Quick Word on Complexity

What happens when you have more than two conditions, like A || B && C? Does the || or && get evaluated first? While there are rules for this (operator precedence), the best practice is to not rely on them.

Always use parentheses () to group your conditions and make your logic explicit and easy to read.

  • if ((A || B) && C) is clear: "Is A or B true? If so, is C also true?"
  • if (A || (B && C)) is also clear: "Are B and C both true? If not, is A true?"

This simple habit will save you from many future headaches and hard-to-find bugs.


Conclusion

You've now added another crucial tool to your programming toolkit. By combining simple true/false checks with && and ||, you can build sophisticated logic that mirrors a real trading strategy. Your programs are no longer limited to single, simple questions; they can now evaluate a complex market environment.

Key Takeaways:

  • The && (AND) operator combines conditions and evaluates to true only if all individual conditions are true.
  • The || (OR) operator combines conditions and evaluates to true if at least one individual condition is true.
  • These operators are essential for building realistic trading rules that depend on multiple factors.
  • Use parentheses () to group complex conditions to ensure your code is clear and does what you intend.

We've learned how to make our code execute different paths based on complex conditions. But what if we need to repeat an action many times? For instance, what if we want to analyze the last 100 price bars? Doing this with if statements would be impossible. In our next lesson, we'll dive into loops, which give us the power to repeat blocks of code as many times as we need.