Lesson 2: EMA MT5 Function to Identify Market Trends – A Detailed Programming Guide

Want to code an EMA MT5 function to identify market trends for automated forex trading on MetaTrader 5? This guide offers a clear, step-by-step tutorial for beginners and experienced traders to create an Expert Advisor (EA) that uses the Exponential Moving Average (EMA) to detect market trends. With MQL5 code examples, you’ll be able to build an effective trading robot.

EMA MT5 Function to Identify Market Trends - A Detailed Programming Guide

What Is EMA and Why Is It Important?

The Exponential Moving Average (EMA) is a popular technical indicator in forex, used to identify market trends by giving more weight to recent price data compared to the Simple Moving Average (SMA). Benefits of using EMA include:

  • Quick Response to Price Changes: EMA reacts faster to recent price movements, helping detect trends early.
  • Trend Identification: Short-term and long-term EMAs can signal bullish or bearish trends.
  • Easy Integration into EAs: EMA is a foundation for automated trading strategies, such as EMA crossovers or combinations with other indicators.

By coding an EMA function on MT5, you can automate market trend analysis, saving time and improving accuracy.

Guide to Coding an EMA MT5 Function for Trend Identification

1. Set Up Your Programming Environment

To get started, you need:

  • MetaTrader 5 and MetaEditor (the built-in MQL5 code editor).
  • Open MetaEditor from MT5 (press F4 or go to Tools > MetaQuotes Language Editor).
  • Create a new EA file: In MetaEditor, select File > New > Expert Advisor.

2. Structure of the EMA Trend Function

The EMA function will calculate two EMAs (fast and slow) and identify trends based on their crossover. For example, a fast EMA crossing above a slow EMA from below signals a bullish trend, while the opposite indicates a bearish trend.

#property copyright "Copyright 2023, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"

#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>  
CSymbolInfo    m_symbol;                     // symbol info object
CTrade trade;


input string               rem7                 = "======  EMA ======";
input bool UseEMA = true; // On/Off EMA
input int                  MA1_Period       =            12;  // MA1 Period
input int                  MA2_Period       =            26;  // MA2 Period
input ENUM_MA_METHOD       MA_Method       =      MODE_SMA;  // Method
input ENUM_APPLIED_PRICE   MA_Price =   PRICE_CLOSE;  // Apply To
input ENUM_TIMEFRAMES      MA_Time = PERIOD_CURRENT; // Time Frames   
//+------------------------------------------------------------------+


// Function to identify trend based on EMA
double EMAGet(int MA_period,const int index)
  {
   int handle_iMA=iMA(m_symbol.Name(),MA_Time,MA_period,0,MA_Method,MA_Price);
   double MA[1];
   ResetLastError();
   if(CopyBuffer(handle_iMA,0,index,1,MA)<0)
     {PrintFormat("Failed to copy data from the iMA indicator, error code %d",GetLastError());
      return(0.0);
     }
   return(MA[0]);
  }
//+------------------------------------------------------------------+

void OnTick() 
{
   double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
   double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
   
   double Ema1 = EMAGet(MA1_Period,1);// 14 Cây Nến , Giá ở Nến 1
   double Ema2 = EMAGet(MA2_Period,1);
   
   if(Ema1>Ema2) {
      trade.Buy(0.1, _Symbol, ask, bid - 50 * _Point, bid + 50 * _Point, "Buy Order");
   }
   if(Ema1<Ema2) {
      trade.Sell(0.1, _Symbol, bid, ask + 50 * _Point, ask - 50 * _Point, "Sell Order");
   }
}

3. Code Explanation

  • getTrend(): Calculates a fast EMA (12 periods) and a slow EMA (26 periods), comparing current and previous values to detect bullish (1), bearish (-1), or neutral (0) trends.
  • placeOrder(): Places a Buy order for a bullish trend and a Sell order for a bearish trend, with stop loss and take profit set at 50 pips.
  • OnTick(): Calls the placeOrder() function on each new price tick.
  • CTrade: Uses the Trade.mqh library for simplified trade management.

4. Testing and Optimization

  • Backtesting: Use MT5’s Strategy Tester to test your EA on historical data.
  • Optimization: Adjust parameters like EMA periods (12, 26) or stop loss/take profit distances.
  • Demo Testing: Run the EA on a demo account to evaluate real-time performance.

Tips for Beginners

  • Learn MQL5 Basics: Start with MetaQuotes’ official documentation or online MQL5 courses.
  • Customize EMA Periods: Experiment with different EMA periods (e.g., 9, 21 or 50, 200) to suit your strategy.
  • Implement Risk Management: Always include stop loss and take profit to protect your capital.
  • Join the Community: Find resources and code examples on the MQL5 Community or forex forums.

Why Code an EMA MT5 Function?

  • Accurate Trend Detection: EMA helps identify market trends quickly and reliably.
  • Custom Strategies: Integrate EMA into EAs to match your trading style.
  • Time-Saving: Automate trend analysis, eliminating manual chart monitoring.

Start Coding Your EMA MT5 Function Today!

Ready to create an EMA MT5 function to identify market trends? Try the code above in MetaEditor. If you need professional help, we offer custom MT5 EA coding services to build tailored trading robots at affordable rates.

Automate your trading with an EMA MT5 function to identify market trends today!


Forex Robotics – Empowering you to code EAs on MT5 with ease and efficiency.

Leave a Reply

Your email address will not be published. Required fields are marked *