Advertisements
$ £ ¥
¥ £ $

MT4 Expert Advisor Template

When most traders start studying Forex trading, they soon come to a decision that they want to automate their trading as much as possible.

The idea of being influenced by emotion, the stress of seeing a position in loss, and the greed of not closing a profitable trade...

Also, the problem of constantly having to monitor the positions... No, thanks!

A trading robot can be much better at trading than humans. It follows the rules day and night, loss or profit.

Trading robot: entry signal found? Entry! Exit signal found? Exit! As easy as that!

Initially, coding your robot is very challenging. It is another way of thinking, and you need to translate everything into mathematical formulas, comparisons, and break down complex problems into a sequence of simple actions.

After years of coding, I accumulated a good amount of functions and routines that help me daily in the development of EAs and indicators.

The MT4 Expert Advisor Template is the starting template for the development of my trading bots.

It includes the basic workflow and functions of a trading expert advisor without entry and exit signals.

You can add your own entry and exit signals and run it.

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

MT4 Expert Advisor Template


What Is MT4 Expert Advisor Template

MT4 Expert Advisor Template is 700+ lines of commented source code that you can use to build your own EA.

Is 700+ lines scary? Don't worry! The code is explained, so you can understand its logic.

You can customize portions of the code to achieve your entry and exit signals and have an EA ready to use.

I have also included some examples of finished EAs built with the template.


What Does MT4 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
  • Mechanism to perform trailing stop
  • Check of trading hours
  • Error management and order submission retry
MT4 Robot Template Input Parameters

What MT4 Expert Advisor Template IS NOT

MT4 Expert Advisor Template IS NOT a fully automated strategy.

Although we include some automated bots to download with this template, these are only to show the potential of the code and as examples.

You will need to add to the template your own entry and exit signal code in order to have it fully operational.


Why Use MT4 Expert Advisor Template

  • Save time — save many hours of research and coding using ready to made functions.
  • Error handling — error handling is embedded in all of the included functions.
  • Risk management — don't fail risk management rules respecting position sizing and stop losses.
  • Easy to edit — with only a few lines of code you can complete the bot and have a fully automated EA.

What Is the Logic of an Expert Advisor

MT4 Expert Advisor Template Logic

Every EA is divided into three main functions:

  1. OnInit() is the initialization of the EA, the first function that runs when you load the EA.
  2. OnTick() runs every time MT4 receives a new quote for the current instrument.
  3. OnDeinit() runs just before closing the EA.

Modules Included in MT4 Expert Advisor Template

MT4 Expert Advisor Template is written in a modular way so that all the functions are separate. This allows to have a source code easier to read and to understand and also makes it easier to customize the code.

Here you see how the functions are separated in the execution:

OnInit Function

MT4 Expert Advisor Template Initialization Function

OnTick Function

MT4 Expert Advisor Template Every Tick Function

OnDeinit Function

MT4 Expert Advisor Template Deinitialization Function


What Do You Need to Use MT4 Expert Advisor Template

MT4 Expert Advisor Template is a great tool however it might not be for everyone. I suggest you to consider the Expert Advisor Template if you satisfy the following conditions.

Basic Knowledge of MQL4 Programming

Although most of the code is provided and commented, you need to be able to add your own code for the entry and exit signal and if you want to customize trailing stop and dynamic stop and take-profit.

I provide some examples together with the code and in other articles.

MT4 Platform

The files included to download are for the MT4 platform and only work in the MT4 platform.

Understanding of Compiling

It is advisable to be familiar with compilation, which is understanding that this product is source code to be edited in the MetaEditor and that it has to be compiled to a working EA through the platform.

Willingness to Experiment

I would like to remind that this is not a fully working trading strategy. You will have to include your own entry and exit signals and strategy.

From the Source Code

Below are 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 I am sure it will help you significantly.

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 MT4
//Provide more information and details
//This is what you see in the About tab when you load an Indicator or an Expert Advisor
#property link          "https://www.earnforex.com/metatrader-expert-advisors/expert-advisor-template/"
#property version       "1.00"
#property strict
#property copyright     "EarnForex.com - 2020"
#property description   "This is a template for a generic Automated EA" 
#property description   " "
#property description   "WARNING : You use this software at your own risk."
#property description   "The creator of these plugins cannot be held responsible for any damage or loss."
#property description   " "
#property description   "Find More on EarnForex.com"
//You can add an icon for when the EA loads on chart but it's not necessary
//The commented line below is an example of icon, icon must be in the MQL4/Files folder and have a ico extension
#property icon          "../../Files/EF-Icon-64x64px.ico"
 

Input Parameters

//-INPUT PARAMETERS-//
//The input parameters are the ones that can be set by the user when launching the EA
//If you place a comment following the input variable this will be shown as description of the field

//This is where you should include the input parameters for your entry and exit signals
input string Comment_strategy="==========";                          //Entry And Exit Settings
//Add in this section the parameters for the indicators used in your entry and exit

//General input parameters
input string Comment_0="==========";                                 //Risk Management Settings
input ENUM_RISK_DEFAULT_SIZE RiskDefaultSize=RISK_DEFAULT_AUTO;      //Position Size Mode
input double DefaultLotSize=1;                                       //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 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="==========";                                 //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_3="==========";                                 //Trailing Stop Settings
input bool UseTrailingStop=false;                                    //Use Trailing Stop

input string Comment_4="==========";                                 //Additional Settings
input int MagicNumber=0;                                             //Magic Number For The Orders Opened By This EA
input string OrderNote="";                                           //Comment For The Orders Opened By This EA
input int Slippage=5;                                                //Slippage in points
input int MaxSpread=100;                                             //Maximum Allowed Spread To Trade In Points
 

OnTick() Implementation

//The OnTick function is triggered every time MT4 receives a price change for the symbol in the chart
void OnTick(){
   //Re-initialize the values of the global variables at every run
   InitializeVariables();
   //ScanOrders scans all the open orders and collect statistics, if an error occurs it skips to the next price change
   if(!ScanOrders()) return;
   //CheckNewBar checks if the price change happened at the start of a new bar
   CheckNewBar();
   //CheckOperationHours checks if the current time is in the operating hours
   CheckOperationHours();
   //CheckSpread checks if the spread is above the maximum spread allowed
   CheckSpread();
   //CheckTradedThisBar checks if there was already a trade executed in the current candle
   CheckTradedThisBar();
   //EvaluateExit contains the code to decide if there is an exit signal
   EvaluateExit();
   //ExecuteExit executes the exit in case there is an exit signal
   ExecuteExit();
   //Scan orders again in case some where closed, if an error occurs it skips to the next price change
   if(!ScanOrders()) return;
   //Execute Trailing Stop
   ExecuteTrailingStop();
   //EvaluateEntry contains the code to decide if there is an entry signal
   EvaluateEntry();
   //ExecuteEntry executes the entry in case there is an entry signal
   ExecuteEntry();
}
 

Entry Signal Check Template

//Evaluate if there is an entry signal
void EvaluateEntry(){
   SignalEntry=SIGNAL_ENTRY_NEUTRAL;
   //if(!IsSpreadOK) return;    //If the spread is too high don't give an entry signal
   //if(UseTradingHours && !IsOperatingHours) return;      //If you are using trading hours and it's not a trading hour don't give an entry signal
   //if(!IsNewCandle) return;      //If you want to provide a signal only if it's a new candle opening
   //if(IsTradedThisBar) return;   //If you don't want to execute multiple trades in the same bar
   //if(TotalOpenOrders>0) return; //If there are already open orders and you don't want to open more
   
   //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 SignalEntry=SIGNAL_ENTRY_BUY
   
   //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 SignalEntry=SIGNAL_ENTRY_SELL
}
 

Error Code Handling

//This functions returns a string corresponding to the description of an error
//Complete list of error available https://book.mql4.com/appendix/errors
string GetLastErrorText(int Error){
   string Text="Error Not Defined";
   if(Error==ERR_NO_ERROR) Text="No error returned.";
   if(Error==ERR_NO_RESULT) Text="No error returned, but the result is unknown.";
   if(Error==ERR_COMMON_ERROR) Text="Common error.";
   if(Error==ERR_INVALID_TRADE_PARAMETERS) Text="Invalid trade parameters.";
   if(Error==ERR_SERVER_BUSY) Text="Trade server is busy.";
   if(Error==ERR_OLD_VERSION) Text="Old version of the client terminal.";
   if(Error==ERR_NO_CONNECTION) Text="No connection with trade server.";
   if(Error==ERR_NOT_ENOUGH_RIGHTS) Text="Not enough rights.";
   if(Error==ERR_TOO_FREQUENT_REQUESTS) Text="Too frequent requests.";
   if(Error==ERR_MALFUNCTIONAL_TRADE) Text="Malfunctional trade operation.";
   if(Error==ERR_ACCOUNT_DISABLED) Text="Account disabled.";
   if(Error==ERR_INVALID_ACCOUNT) Text="Invalid account.";
   if(Error==ERR_TRADE_TIMEOUT) Text="Trade timeout.";
   if(Error==ERR_INVALID_PRICE) Text="Invalid price.";
   if(Error==ERR_INVALID_STOPS) Text="Invalid stops.";
   if(Error==ERR_INVALID_TRADE_VOLUME) Text="Invalid trade volume.";
   if(Error==ERR_MARKET_CLOSED) Text="Market is closed.";
   if(Error==ERR_TRADE_DISABLED) Text="Trade is disabled.";
   if(Error==ERR_NOT_ENOUGH_MONEY) Text="Not enough money.";
   if(Error==ERR_PRICE_CHANGED) Text="Price changed.";
 

How to Install MT4 Expert Advisor Template

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

How to Use It

Customize the following functions in order to complete the signals:

  • EvaluateEntry() contains the code to trigger an entry signal. It is necessary to add something here for the EA to work.
  • 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.
  • ExecuteTrailingStop() contains the code to trail the stop-loss. It is required only if you want to add a trailing stop function.
  • StopLossPriceCalculate() contains the code to assign a dynamic value to the stop-loss. Not mandatory.
  • TakeProfitPriceCalculate() contains the code to assign a dynamic value to the take-profit. Not mandatory.
/*

CUSTOMIZE THE FOLLOWING TO GET YOUR OWN EXPERT ADVISOR UP AND RUNNING

EvaluateEntry : To insert your custom entry signal

EvaluateExit : To insert your custom exit signal

ExecuteTrailingStop : To insert your trailing stop rules

StopLossPriceCalculate : To set your custom Stop Loss value

TakeProfitPriceCalculate : To set your custom Take Profit value

*/
 

Fully Working Examples Provided

Together with the template you can download two fully functional expert advisors, so you can see how the code has been customized.

Example 1: Bollinger Bands Breakout

/*

This EA is derived from the MT4 Robot Template and it is for demonstration and education purpose

ENTRY SIGNAL: Break Out of Bollinger Bands

EXIT SIGNAL: None

STOP LOSS: Difference from price and ATR*multiplier

TAKE PROFIT: Difference from price and ATR*multiplier

TRAILING STOP: Same as Stop Loss

*/
 

Example 2: Two Moving Averages Crossover

/*

This EA is derived from the MT4 Robot Template and it is for demonstration and education purpose

ENTRY SIGNAL: Fast MA crosses Slow MA

EXIT SIGNAL: Fast MA Crosses Slow MA

STOP LOSS: Set to the parabolic SAR (PSAR)

TRAILING STOP: Stop following the PSAR

*/
 

Example 3: RSI + Moving Average

/*

This EA is derived from the MT4 Robot Template and it is for demonstration and education purpose

ENTRY SIGNAL: Buy when price above MA and RSI going from returning from <30 to >30, Sell when price below MA and RSI going from >70 to <70

EXIT SIGNAL: Exit Buy when RSI close >70 or when price below MA or Stop Loss hit, Exit Sell when RSI close <30 or price above MA or Stop Loss Hit

STOP LOSS: Lowest Low of last 5 candles for Buy orders, Highest High of last 5 candles for Sell orders

TRAILING STOP: Same as Stop Loss

*/
 

You can open a trading account with any of the MT4 Forex brokers to freely use the presented here expert advisor for MetaTrader 4.