Moving Average
This is a powerful addition to your MetaTrader 5 toolkit designed to optimize market analysis and performance. This Expert Advisor serves as automated trading software. It is utilized to monitor financial markets and execute trades based on predefined algorithmic rules, enabling precise position management without the need for constant manual oversight.
How to Setup and Use Moving Average
1. Installation: Open the "File" menu, select "Open Data Folder," navigate to MQL/Experts, paste your file, and restart the terminal.
2. Activation: Drag the EA from the Navigator onto a chart, ensure "Allow live trading" is checked in the Common tab, and verify the AutoTrading button is green.
3. Optimization: Right-click your chart, choose "Expert List," click "Properties" to adjust inputs, and save your preferred setup as a set file for future use.
4. Maintenance: Regularly check the "Experts" tab in the terminal window to monitor trade logs and potential execution errors.
Frequently Asked Questions
Q: Why is my EA not opening trades? A: Check the "AutoTrading" button, ensure "Allow live trading" is enabled, and verify your broker allows automated trading on your account type.
Q: Can I run multiple EAs on one chart? A: No, each chart can only host one active EA; however, you can open multiple charts for different currency pairs to run several EAs.
Q: What does the "smiley face" icon mean? A: A smiley face in the top-right corner of the chart indicates the EA is successfully running; a frowny face means it is disabled.
Description & Settings
The Moving Average EA is included in the standard pack of the client terminal and is an example of the EA that trades using the indicator.
The EA file Moving Average.mq5 is located in the folder "terminal_data_folder\MQL5\Experts\Examples\Moving Average\". This EA is an example of use of , functions and of the Standard Library. In addition, the EA includes a money management system that is based on trade results.
Let's consider the structure of the Expert Advisor and how it works.
1. EA Properties
When you run the Expert Advisor they are displayed in the "Common" tab:
Figure 1. Common Parameters of the Moving Average EA
1.2. Include Files
Next, the directive tells the compiler to include the "Trade.mqh" file.
This file is part of , it contains the class for easy access to trading functions.
The name of the include file is shown in brackets "<>;", so the path is set relative to the directory: "terminal_data_folder\Include\".
1.3 Inputs
Then goes the type, name, default values and a comment. Their role is shown in fig. 2.
The MaximumRisk and DecreaseFactor parameters will be used for money management, MovingPeriod anad MovingShift set the period and shift of the technical indicator that will be used or checking trade conditions.
The text in the comment in the input parameter line, along with default values , are displayed in the "Options" tab instead of the name of the input parameter:
Fig. 2. Input Parameters of the Moving Average EA
1.4. Global Variables
Then the global variable ExtHandle is declared. It will be used for storing the handle of the indicator.
It is followed by 6 functions. The purpose of each of them is described in the comment before the function body:
TradeSizeOptimized() - Calculate optimal lot size;
CheckForOpen() - Check for open position conditions;
CheckForClose() - Check for close position conditions;
OnInit() - Expert initialization function;
OnTick() - Expert tick function;
OnDeinit() - Expert deinitialization function;
The last three functions are ; the first three service functions are called in their code.
2. Event Handling Functions
2.1. The OnInit() initialization function
The function is called once during the first start of the Expert Advisor. Usually in the OnInit() event handler the EA is prepared for operation: input parameters are checked, indicators and parameters are initialized, etc. In the case of critical errors, when further work is meaningless, function is exited with a return code INIT_FAILED.
Since the EA trading is based on the indicator Moving Average, by calling the indicator is created and its handle is saved in the global variable ExtHandle.
In case of an error, OnInit() is exited with a return code - it is a correct way to complete the EA/indicator operation in the case of an unsuccessful initialization.
2.2. The OnTick() function
The function is called each time a new quote is received for the symbol of the chart, on which the EA runs.
The function is used for defining if there is an open position for the current symbol.
If there are open positions, the CheckForClose() function is called, which analyzes the current state of the market and closes the open position, otherwise CheckForOpen() is called, which checks the conditions of market entry and opens a new position if such conditions occur.
2.3. The OnDeInit() deinitialization function
is called when an EA is removed from the chart. If a program places graphical objects during operation, they can be removed from the chart.
In this case no actions are performed during Expert Advisor deinitialization.
3. Service Functions
3.1. Function TradeSizeOptimized()
This function calculates and returns the value of the optimal lot size for position opening with the specified risk level and trading results.
The function is used for checking the availability of prices for the current symbol, next the function is used for requesting the margin required to place an order (in this case a buy order). The initial lot size is determined from the value of the margin required for placing an order, the free margin of the account () and the maximum allowed value of risk specified in the input parameter MaximumRisk.
If the value of the input parameter DecreaseFactor is positive, deals in history are analyzed and the size of the lot is adjusted taking into account information about the maximal series of losing trades: the initial lot size is multiplied by the size (1-losses/DecreaseFactor).
Then the trade volume is "rounded" to the value that is multiple of the minimum allowable step of volume (stepvol) for the current symbol. Also the minimum (minvol) and the maximum possible values (maxvol) of the trade volume are requested, and if the lot value exits the allowed limits, it is adjusted. As a result, the function returns the calculated value of the trading volume.
3.2. Function CheckForOpen()
CheckForOpen() is used for checking position opening conditions and opens it when trade conditions occur (in this case when the price crosses the moving average).
When trading using the moving, you need to check if price crosses the moving average. Using the function, two values of the current prices are copied in the array of structures rt[], rt[1] corresponds to the current bar, rt[0] - completed bar.
A new bar is started by checking the tick volume of the current bar if it is equal to 1, then a new bar has started. It should be noted that this method of detecting a new bar may fail in some cases (when quotes come in packs), so the fact of start of a new bar formation should be done by saving and comparing the time of the current quote (see ).
The current value of the Moving Average indicator is requested using the function and is saved in the ma[] array that contains only one value. The program then checks if the price has crossed the moving average and makes additional checks (if trading using the EA is possible and the presence of bars in history). If successful, an appropriate position for the symbol is opened by calling the method of the trade object (an instance of ).
Position opening price is set using the function that returns the Bid or Ask price depending on the value of the signal variable. The position volume is determined by calling TradeSizeOptimized() described above.
3.3. Function CheckForClose()
CheckForClose() checks conditions for position closing and closes it if conditions to close it occur.
The algorithm of the CheckForClose() function is similar to the algorithm of CheckForOpen(). Depending on the direction of the current open positions, conditions of its closure re checked (price crossing the MA downwards to buy or upwards to sell). An open position is closed by calling the method of the trade object (instance of ).
4. Backtesting
The best values of the parameters can be found using the of the MetaTrader 5 terminal.
For example, when optimizing the MovingPeriod paramter in the interval 2012.01.01-2013.08.01, the best results are obtained with MovingPeriod=45:
Backtesting Results of the Moving Average Expert Advisor
Conclusions:
The Moving Average Expert Advisor included in the standard pack of the terminal is an example of use of , functions and of the Standard Library. In addition, the EA includes a money management system that is based on trade results.