Popular results

Advertisements
$ £ ¥
¥ £ $

MT5 Expert Advisor Template

Table of contents

At some point in their career, traders decide that it's a good idea to automate what they are doing. That's where automated expert advisors come handy.

Automated trading has certain advantages over manual trading:

  • No constant chart monitoring required.
  • No emotional influence.
  • Trading 24 hours a day.
  • No accidental errors (if coded correctly).
  • Ability to trade multiple strategies simultaneously.

However, coding your own trading robot (expert advisor) isn't very simple even with simple strategies. With complex trading systems it becomes extremely challenging. You need to formulate everything in terms of clear conditions and instructions and think about a lot of edge cases to cover all possible situations.

Yet if your goal is to start coding your own robot, you need to start with something basic.

The MT5 expert advisor template presented here can be a starting point in the development of your trading bots.

It includes the basic workflow and functions of a trading expert advisor without implementing any specific entry and exit signals. It is easy to add entry and exit signals from your strategy to it.

The source code will significantly reduce the time you spend developing an expert advisor.

MT5 Expert Advisor Template


What is MT5 expert advisor template

MT5 expert advisor template is 700+ lines of commented source code that you can use to build your own EA.

That might sound like a lot of code for a basic template, but there is nothing difficult there and many of those lines are commentary to help you better understand the code's logic.

You can customize indicated parts of the code to implement your entry and exit strategy and have your own EA ready to use.


What does MT5 expert advisor template include

  • Comments for each function to understand the logic
  • Well-written code
  • Modular structure
  • Risk management through automatic position size calculation
  • Selection of fixed or automatic stop-loss
  • Selection of fixed or automatic take-profit
  • Trading hours filter
  • Partial close
  • Custom testing parameter

MT5 Robot Template Input Parameters


What MT5 expert advisor template IS NOT

MT5 expert advisor template IS NOT a fully automated strategy.

It is necessary to add your own entry and exit signals code to the template in order for it to make any trades.


Why use MT5 expert advisor template

  • Save time — you can save many hours of learning and coding by using these ready-made functions.
  • Error handling — the template checks for common runtime errors in all of its functions.
  • Risk management — fixed and risk-based position sizing for flexible risk management.
  • Easy to edit — adding and modifying just a few lines of code will give you a working EA based on your favorite indicator.

What is the logic of an expert advisor

MT5 Expert Advisor Logic

A basic EA is divided into three main functions:

  1. OnInit() is the initialization of the EA. It is the first function executed when you load the EA on a chart. It runs only once.
  2. OnTick() runs every time MT5 receives a new quote for the current trading instrument.
  3. OnDeinit() executed once just after you remove the EA from the chart.

Modules included in MT5 expert advisor template

MT5 expert advisor template is written in a modular way so that each operation is logically separated from the rest into independent functions. This allows for source code that is easier to read and understand and also makes code customization easier.

Here you can see how the functions are separated in the runtime flow:

OnInit function

MT5 Expert Advisor Template Initialization Function

OnTick function

MT5 Expert Advisor Template Every Tick Function

There is nothing in the DeInit function of this EA template — just a placeholder. You can easily add your own code there, but most likely you won't ever need to add anything there.


Requirements to start using MT5 expert advisor template

MT5 expert advisor template is a great tool in the right hands, but it might not be for everyone. Consider using this expert advisor template if you satisfy the following conditions.

Basic knowledge of MQL5 programming

Although most of the code is provided and it is well-commented, you need to be able to add your own code for entry and exit signals and for any further customization (like trailing stop for example).

Looking at the source code of other expert advisors may help you with this.

MT5 platform

The expert advisor files that you download are intended for MetaTrader 5 platform. They won't work in MetaTrader 4.

Understanding how to compile

It is advisable to be familiar with the compilation process. This template is actually source code to be edited in MetaEditor and compiled to become a working EA.

Willingness to experiment

It should be noted that this is not a fully working trading strategy. You will have to come up with your own entry and exit signals and strategy. You might need to run many backtests and change the code multiple times before you find something worthwhile.

From the source code

You can see some extracts from the code. This is a good way to understand if the product is suitable for you.

If what you see makes sense, then you will likely be able to use this EA template without any issues.

If it doesn't make any sense to you, but you are interested to see how the code for an expert advisor works, then it can help you.

If you are not the coding type of person and all this doesn't interest you, then probably, this isn't something for you.

Expert properties

//-PROPERTIES-//
// Properties help the software look better when you load it in MT5.
// They provide more information and details
// This is what you see in the About tab when you attach the expert advisor to a chart.
#property link          "https://www.earnforex.com/metatrader-expert-advisors/mt5-ea-template/"
#property version       "1.00"
#property copyright     "EarnForex.com - 2024"
#property description   "A basic expert advisor template for MT5."
#property description   ""
#property description   "WARNING: There is no guarantee that this expert advisor will work as intended. Use at your own risk."
#property description   ""
#property description   "Find more on www.EarnForex.com"
#property icon          "\\Files\\EF-Icon-64x64px.ico"
 

Input parameters

// EA Parameters
input string Comment_0 = "==========";          // EA-Specific Parameters
// !! Declare parameters specific to your EA here.
// For example, a moving average period, an RSI level, or anything else your EA needs to know to implement its trading strategy.
// All input parameters start with 'input' keyword.
// input int example = 10; // This is an example input parameter

input string Comment_1 = "==========";  // Trading Hours Settings
input bool UseTradingHours = false;     // Limit trading hours
input ENUM_HOUR TradingHourStart = h07; // Trading start hour (Broker server hour)
input ENUM_HOUR TradingHourEnd = h19;   // Trading end hour (Broker server hour)

input string Comment_2 = "==========";  // ATR Settings
input int ATRPeriod = 100;              // ATR period
input ENUM_TIMEFRAMES ATRTimeFrame = PERIOD_CURRENT; // ATR timeframe
input double ATRMultiplierSL = 2;       // ATR multiplier for stop-loss
input double ATRMultiplierTP = 3;       // ATR multiplier for take-profit

// General input parameters
input string Comment_a = "==========";                             // Risk Management Settings
input ENUM_RISK_DEFAULT_SIZE RiskDefaultSize = RISK_DEFAULT_FIXED; // Position size mode
input double DefaultLotSize = 0.01;                                // Position size (if fixed or if no stop loss defined)
input ENUM_RISK_BASE RiskBase = RISK_BASE_BALANCE;                 // Risk base
input int MaxRiskPerTrade = 2;                                     // Percentage to risk each trade
input double MinLotSize = 0.01;                                    // Minimum position size allowed
input double MaxLotSize = 100;                                     // Maximum position size allowed
input int MaxPositions = 1;                                        // Maximum number of positions for this EA

input string Comment_b = "==========";                             // Stop-Loss and Take-Profit Settings
input ENUM_MODE_SL StopLossMode = SL_FIXED;                        // Stop-loss mode
input int DefaultStopLoss = 0;                                     // Default stop-loss in points (0 = no stop-loss)
input int MinStopLoss = 0;                                         // Minimum allowed stop-loss in points
input int MaxStopLoss = 5000;                                      // Maximum allowed stop-loss in points
input ENUM_MODE_TP TakeProfitMode = TP_FIXED;                      // Take-profit mode
input int DefaultTakeProfit = 0;                                   // Default take-profit in points (0 = no take-profit)
input int MinTakeProfit = 0;                                       // Minimum allowed take-profit in points
input int MaxTakeProfit = 5000;                                    // Maximum allowed take-profit in points

input string Comment_c = "==========";                             // Partial Close Settings
input bool UsePartialClose = false;                                // Use partial close
input double PartialClosePerc = 50;                                // Partial close percentage
input double ATRMultiplierPC = 1;                                  // ATR multiplier for partial close

input string Comment_d = "==========";                             // Additional Settings
input int MagicNumber = 0;                                         // Magic number
input string OrderNote = "";                                       // Comment for orders
input int Slippage = 5;                                            // Slippage in points
input int MaxSpread = 50;                                          // Maximum allowed spread to trade, in points
 

Tick processing

// Entry and exit processing
void ProcessTick()
{
    if (!GetIndicatorsData()) return;
    
    if (CountPositions())
    {
        // There is a position open. Manage SL, TP, or close if necessary.
        if (UsePartialClose) PartialCloseAll();
        CheckExitSignal();
    }

    // A block of code that lets the subsequent code execute only when a new bar appears on the chart.
    // This means that the entry signals will be checked only twice per bar.
    /* static datetime current_bar_time = WRONG_VALUE;
    datetime previous_bar_time = current_bar_time;
    current_bar_time = iTime(Symbol(), Period(), 0);
    static int ticks_of_new_bar = 0; // Process two ticks of each new bar to allow indicator buffers to refresh.
    if (current_bar_time == previous_bar_time)
    {
        ticks_of_new_bar++;
        if (ticks_of_new_bar > 1) return; // Skip after two ticks.
    } 
    else ticks_of_new_bar = 0; */

    // The number is recalculated after the first call because some trades could have been gotten closed.
    if (CountPositions() < MaxPositions) CheckEntrySignal(); // Check entry signals only if there aren't too many positions already.
}
 

Entry signal check template

// Entry signal
void CheckEntrySignal()
{
    if ((UseTradingHours) && (!IsCurrentTimeInInterval(TradingHourStart, TradingHourEnd))) return; // Trading hours restrictions for entry.

    bool BuySignal = false;
    bool SellSignal = false;

    // Buy signal conditions

    // This is where you should insert your entry signal for BUY orders.
    // Include a condition to open a buy order, the condition will have to set BuySignal to true or false.
   
    //!! Uncomment and modify this buy entry signal check line:
    //if ((Indicator_current > iClose(Symbol(), Period(), 1)) && (Indicator_previous <= iClose(Symbol(), Period(), 2))) BuySignal = true; // Check if the indicator's value crossed the Close price level from below.

    if (BuySignal)
    {
        OpenBuy();
    }

    // Sell signal conditions

    // This is where you should insert your entry signal for SELL orders.
    // Include a condition to open a sell order, the condition will have to set SellSignal to true or false.
    
    //!! Uncomment and modify this sell entry signal check line:
    //if ((Indicator_current < iClose(Symbol(), Period(), 1)) && (Indicator_previous >= iClose(Symbol(), Period(), 2))) SellSignal = true; // Check if the indicator's value crossed the Close price level from above.

    if (SellSignal)
    {
        OpenSell();
    }
}
 

Downloads

 

You can open a trading account with any of the MT5 Forex brokers to install the expert advisor for MetaTrader 5 presented here.

How to install MT5 expert advisor template

  1. Download the expert advisor archive file.
  2. Open the MetaTrader 5 data folder (via File→Open Data Folder or Ctrl+Shift+D).
  3. Open the MQL5 folder.
  4. Copy all the folders from the archive directly to the MQL5 folder.
  5. Restart MetaTrader 5 or refresh the expert advisors list by right-clicking the Navigator subwindow of the platform and choosing Refresh.

How to use it

Those parts of code that require modification or insertion of your own pieces of code are marked with double exclamation marks (!!). You will need to customize the following functions in order to create a working EA:

  • GetIndicatorsData() contains the code that reads indicator values used further in other functions. If you plan for the EA to use any indicators in its trading strategy, then you need modify this function.
  • EvaluateEntry() contains the code to trigger an entry signals. It is necessary to add something here for the EA to open new positions. An example entry code is proposed in the commentaries inside this function.
  • EvaluateExit() contains the code to trigger the exit signal. You can leave this as is if you plan using fixed stop-loss and take-profit. Otherwise, indicator-based exit signals can be defined in this function.
 

If you are interested in expert advisor templates, you might also want to look at our MT4 expert advisor template.

Discussion

Do you have any suggestions or questions regarding this EA? You can always discuss MT5 Expert Advisor Template with the other FX traders and MQL5 coders on our forum.