[MQL5 Paradise Episode 4] Let EA Make the "Decision" — Use if statements to navigate market turning points
Hello everyone! This is Pineapple.
In the previous third installment, we talked about the magical box that stores data, called a "variable."int(integer) anddouble(floating point) are like boxes to hold prices and lot sizes. Did your experiment of rewriting numbers yourself and displaying them with the Print function go well?
Now that we’ve learned to store data in boxes, the program is still just a “recorder” at this stage. For an EA (expert advisor) to trade the market on your behalf, it needs a brain that can “judge the situation and make decisions” based on that data. “a brain to assess the situation and make decisions”is necessary.
This time, we finally challenge the greatest thrill of programming“conditional branching (if statements)”. Once you master this, your program will take its first step toward riding the waves of the market with its own will (based on the rules you provide). Sit back with a coffee and read on at your own pace.
Teach the program “if this then that”
This“If X, then Y”logic is what we’ll teach in MT5’s syntax this time. The English “if (if you) … then” is so intuitive and easy to understand.
The basic way to write this in MQL5 looks like this.
if (条件式)
{
// 条件を満たしたときに、実行したい処理をここに書く
}
It’s very simple, isn’t it.()You write the “condition” inside the parentheses, and only when that condition is satisfied,{}the code inside the braces is executed. If the condition isn’t met, the content inside the braces is ignored.
Learn the comparison operators
To create a “condition expression,” you need symbols to compare two numbers. Imagine the less-than/greater-than signs you learned in elementary math. The six comparison operators commonly used in MQL5 are mainly below.
A > B: A is greaterA < B: A is lessA >= B: A is greater or equal (same or greater)A <= B: A is less or equal (same or smaller)A == B: A and B are exactly the same (Note: Equal signs are written twice)A != B: A and B are different (not equal)
Here is a point where programming beginners often stumble. It’sthe rule that when expressing “equal,” you write=twice as==..
Last time, when we inserted data into a variable, we wrotedouble my_lot = 0.1;. In programming, a single=means “put the right-hand thing into the left box (assignment)”.
Therefore, when you compare left and right for equality, you must write it with two equals signs as a rule to distinguish. Please keep this in mind.
Let’s write a script using if statements in practice
Now, let’s combine the “variable” from last time and the “if statements” learned this time to write a practical script.
This time we will compare the current price with the moving average price to determine whether the outlook is buy or sell, and have MT5 decide. (Note: we haven’t learned how to obtain real-time prices yet, so we’ll test by putting dummy numbers in the variables.)
Open MetaEditor, create a new script, and paste the following code.
void OnStart()
{
// 1. Put a dummy price into a variable
double current_price = 150.50; // current price (dummy)
double ma_price = 150.00; // moving average price (dummy)
Print("【Starting market environment determination】");
// 2. If the current price is higher than the moving average
if (current_price > ma_price)
{
Print("Current price (", current_price, ") is above the moving average.");
Print("Uptrend. Consider buying.");
}
// 3. Otherwise, if the current price is lower than the moving average
else if (current_price < ma_price)
{
Print("Current price (", current_price, ") is below the moving average.");
Print("Downtrend. Consider selling.");
}
// 4. If neither (they are exactly the same)
else
{
Print("Price and moving average are exactly the same. Wait and see.");
}
}
Explanation of the sample code
How does it look? The code is a bit long, but what it does is very simple.
First, in the first half,current_price (current price) is150.50,ma_price (moving average) is150.00.
Then the middle part is where the if statement comes in. Here a new keyword「else(エルス)」appears. This means “everything else.”
if (current_price > ma_price)The first threshold. 150.50 is greater than 150.00, so this condition is true. Therefore, the print inside the braces runs: “Uptrend. Consider buying.”else if (current_price < ma_price)The second threshold for what to do if the first condition isn’t met. Since the first condition was met, this is ignored.elseThe last fallback to execute if none of the above conditions apply.
If you compile and run in MT5, the expert tab in the toolbox should display “Consider buying.”
Try changing the value of the variablecurrent_price to149.00 and recompile and run. This time it should display “Consider selling.”
The Pitfalls of Overusing if Statements: Curve Fitting
Once you learn if statements, you can make the program perform more complex judgments. However, many developers fall into a frightening trap: excessive use of if statements leading to curve fitting (over-optimization).“Curve fitting (over-optimizing) due to too many if statements”.
During backtesting (testing with past data), you’ll inevitably encounter situations where you’re losing a lot. With if statements, you can easily erase those losses from the record.
“If it’s Tuesday at 3 PM, don’t trade” “If the last candle’s wick is 15 pips or more, skip entry” “If RSI is in the tricky zone between 55 and 60, take a break”
Continuing to attach if statements to past charts to avoid unfavorable parts makes the backtest graph rise to a perfect straight line. However, the resulting code becomes a spaghetti of nested if statements (spaghetti code).
When you move that past-perfect spaghetti EA to a future market, it may suddenly stop working and burn through capital, because the market never repeats exactly the same way as in the past.
“Simple and robust trading”This is my creed.
Really strong systems use surprisingly few if statements. “Buy if MA is rising” “Take profit when price moves by a certain amount.” These simple, widely known conditions (if statements) make for EAs that adapt to market changes and survive longer in the long run, in my view.
If statements are very useful, but be careful not to overuse them. When adding a condition to your code, pause and ask yourself: is this condition truly capturing the market’s essence, or is it just a projection onto the past?
In closing
This time we learned about if statements that make programs decide. By comparing variable values and executing different actions based on the results, you’ve built the brain behind an automated trading system.
However, in this sample code, we manually hard-coded price data into the variables. For real automated trading, you’ll need to obtain real-time prices from MT5 as they move moment by moment.
Next time, we will learn“How to obtain the current price (Bid/Ask) from MT5”. This is the moment your program connects to the real market. Getting the real-time rate now and using it for if statement decisions will greatly increase the realism of EA development!
Take your time, enjoy each step. I look forward to seeing you in the next “MQL5 Paradise.” May wonderful decisions come to your trading life. This was Pineapple!