【MQL5 Paradise Episode 7】Let's Talk with the Indicator! Read Moving Average Values to Determine the Trend ~ Introduction to MQL5
Hello everyone! This is Pineapple.
In the previous Episode 6, we learned about the heart of an EA“OnTick”— the mechanism that runs the program every time the price ticks. With this, the foundation of a 24/7 automated trading robot was finally built, right?
However, our current EA can only look at the “current price.” In actual trading, we analyze the market with indicators such as the “Moving Average” (MA), which reads trends from past price averages, and the “RSI” which determines overbought/oversold conditions, right?Indicators
By giving the EA a “new eye” called an indicator, it can evolve from a mere price watcher to a capable trader that analyzes the market.
A few new concepts will appear, but we will explain slowly and clearly, so relax with a cup of coffee and keep reading.
MQL5 indicators are like “restaurant reservations”
If you have previously programmed in MT4 (MQL4), you might feel a bit puzzled here. In MT4, when you needed an indicator value, you could write a function like “tell me the current MA value now!” and you’d get it immediately.
However, things are a little different in MQL5. Getting an indicator in MQL5 follows a two-step rule like a “restaurant reservation.”Two-step reservation
“speed and lightness”.
If you recomputed the indicator from scratch on every Tick (price movement), your computer would overload.
Thus, in MQL5, you first declare which indicator you will use (reserve) and create a calculation path, and then, each time the value updates, you receive only the latest result from that path, in a highly efficient system.
Thanks to this, MQL5 backtesting is dramatically faster than MT4. This is the secret of a truly “paradise” development environment.
Remember the two steps
- Reserve (obtain a handle)First, tell MT5 that you will use the 14-period Moving Average, andreserve ticket (handle), you will receive.
- Receive values (copy to buffer)Each time the price moves, you present that reservation ticket and ask for the latest numbers, and have them placed into a prepared buffer.
Finish the reservation with the new framework “OnInit”
Just like making a restaurant reservation before dining, you shouldn’t wait until just before the meal. In a program, waiting to reserve on every price change (OnTick) would be too late. You want to reserve once when the EA is attached to the chart.
Enter the framework calledOnInit (OnInitialize). (Init stands for Initialization.)
When you create a new EA file in MetaEditor, above OnTick, there is already a block called OnInit prepared. Here you write the “one-time setup you want the EA to do when it is first attached to the chart.” It’s the perfect place to reserve indicators.
Prepare a column of boxes (an array) to hold multiple data
There is one more thing to prepare. Indicator values exist for several past candles: the current candle, one candle ago, two candles ago, and so on.
To receive these, a single variable box that could hold only one value (as learned in Episode 3) isn’t enough. You need a row of boxes arranged side by side called a“array (array of boxes)”.
In MQL5, you create this “row of boxes” simply by adding [] after the variable name.double ma_values[];
By writing this, you have prepared a small column of boxes to hold many MA values.
Now write a program to actually read the indicator
The explanation has become long, but seeing actual code is best. This time we will create an EA that determines whether the current price is above or below the period-14 Simple Moving Average (SMA) and outputs the result.
Please insert the following code.
//+------------------------------------------------------------------+
//| My_MA_Cross.mq5 |
//+------------------------------------------------------------------+
// 1. Prepare the “boxes” and the row of boxes used throughout
int ma_handle; // an integer box to store the reservation handle
double ma_values[]; // a column of boxes to receive MA values (array)
//+------------------------------------------------------------------+
//| Preparation when the EA enters the chart (executed once) |
//+------------------------------------------------------------------+
int OnInit()
{
// 2. Obtain a reservation ticket for the moving average (SMA, period 14)
ma_handle = iMA(_Symbol, PERIOD_CURRENT, 14, 0, MODE_SMA, PRICE_CLOSE);
// 3. Arrange the box column in new order (newest from right to left)
ArraySetAsSeries(ma_values, true);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Heartbeat called on every price movement (tick) |
//+------------------------------------------------------------------+
void OnTick()
{
// 4. Using the ticket, receive the latest 3 MA values (now, 1 ago, 2 ago)
if(CopyBuffer(ma_handle, 0, 0, 3, ma_values) <= 0) return;
// 5. Get the current price (Bid)
double current_price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
// 6. Compare current price with MA (ma_values[0] is the latest)
if(current_price > ma_values[0])
{
Print("Current price (", current_price, ") is above MA (", ma_values[0], "). Bullish!");
}
else if(current_price < ma_values[0])
{
Print("Current price (", current_price, ") is below MA (", ma_values[0], "). Bearish!");
}
}
How to read the sample code
How about it? If we go step by step, it’s not too difficult.
- Step 2: Obtain the reservation ticket (iMA function)
iMAThis uses a function to reserve. Inside the parentheses you pass the currency pair, timeframe, period (14), display shift, calculation method (SMA), and applied price (close). The items are the same settings we usually use when adding MA to a chart. - Step 3: The array magic (ArraySetAsSeries)This is a very important MQL5-specific “magic.” Normally, program arrays fill from oldest data. But what we want is the newest data. By setting
ArraySetAsSeriestotrue, the order of the boxes is reversed, so that“ma_values[0] is the newest current candle”, “ma_values[1] is one candle ago”— an intuitive and easy-to-understand order. - Step 4: Receiving values (CopyBuffer)
OnTickHere we useCopyBufferto obtain data. We request from the reservation ticket (ma_handle) the newest values (index 0) for 3 items and place them into ma_values.
Then, as learned two lessons ago, we use anif statement. Compare the latest price (current_price) with the latest MA value (ma_values[0]) and print whether it is bullish or bearish.
Compile and attach to a chart, then check the Expert Log. Each price movement will narrate the market by comparing MA values and current price!
Simplicity makes discernment powerful
Once you can obtain indicators via a program, many people want to combine many indicators at once (MA, RSI, MACD, Bollinger Bands, etc.).
I understand the feeling well. In the past I too created EAs that filled the chart with indicators, obscuring the candles, and enjoyed it (laughs).
But the more indicators you add, the stricter the conditions become, and the fewer entries you’ll have. You end up with an over-optimized EA that only captures miracles when all conditions align over the past decade (curve fitting).
Future markets do not follow exactly the same patterns as the past.Aim for simple, robust tradingIf you want that, strongly recommend starting with a simple trend-following approach using just one Moving Average.
The simple fact we incorporated this time—whether price is above or below the MA—is one of the strongest truths in the market (the trend). Rather than twisting complex formulas, I believe respecting these staple discernments forms the foundation of a long-lived system.
First, listen carefully to the voice of a single indicator.
In Conclusion
This time, using OnInit and CopyBuffer, we learned how to obtain the Moving Average value and determine market trends.
Current price retrieval, if conditional checks, and analysis by indicators. With these in place, your EA’s “brain” already has the capabilities of a competent trader.
What’s missing is just one more thing. Yes,“to actually place orders (enter a trade)”.
Next time, we will finally press MT5’s order button on the EA we built. Although placing orders in MQL5 is often said to be difficult, don’t worry. I’ll clearly explain how to use the powerful helper “CTrade,” which lets even beginners place orders safely and easily.
The moment your program places a position of its own, is within sight!
Until then, I look forward to meeting you again in the next “MQL5 Paradise.” May your EA analysis capture wonderful trends. This is Pineapple!