MetaTrader 4 – Strategy Testing And Optimization – Guest Blog Post Investing

MetaTrader 4 is a trading platform developed by MetaQuotes Software for online trading in the forex, CFD and futures markets. MT4, as it is commonly known, can be downloaded at no charge directly from the MetaQuotes website or through dozens of the top online forex brokers. MT4 provides tools and resources that allow traders to analyze price, place and manage trades, and employ automated trading techniques. This advanced tutorial will introduce MT4’s automated trading, strategy testing and optimization features.

Please note: Learning any proprietary programming language takes significant time and an understanding of programming logic. This tutorial serves only as an introduction to MT4’s capabilities and the general programming process, and should not be construed as an instructional programming manual. Traders can learn more about programming in the MQL4 environment by reading the MT4 Help Guides and participating in the active MQL4 community forums.

 

The MT4 platform supports automated trading, or system trading. Automated trading involves developing an objective set of rules for trade entries and exits, and programming the rules in the platform’s proprietary language (MQL4 in this case) so that the platform can handle all of the associated analytical and trading processes. Perhaps the biggest advantage of automated trading is the ability to remove some of the emotion from trading. Since these systems can trade completely mechanically based on the predetermined rules of a trading plan, dealing with losses or second-guessing a trade entry will not affect system performance. Another significant advantage to trade automation is that the trades are automatically executed with extremely fast reaction times.

 

An automated trading system must clearly identify buy, sell, stop-loss and profit-target rules. In other words, the system must identify the conditions under which a trade will be initiated (whether a long or a short trade), when the trade should be closed at a loss, and when the trade should be closed at a profit.

The various benefits of automated trading make it a helpful tool for traders, but it is important to remember that certain aspects of automation can fail. For example, if the connection to the Internet or data server is lost, the trader must recognize the error and manually fix the problem. If left unnoticed, a position could unintentionally be left naked in the market (without stop-loss or take profit orders).

MetaEditor
MetaEditor is MT4’s interface used for creating, editing and compiling program source codes written in MetaQuotes Language 4 (MQL4), MT4’s proprietary programming language. An Expert Advisors Wizard is a built-in feature of the MetaEditor that assists in the creation of new MQL4 programs. Once a program has been written, it must be compiled in MetaEditor. After successful compiling, the executable program code can be launched and/or tested in the MT4 Terminal. Traders can create several distinct programs using the MetaEditor:

 

  • Expert Advisors – programs in the terminal that have been developed in MQL4 and used for the automation of analytical and trading processes. Some platforms refer to these as strategies.
  • Custom Indicators – programs developed in MQL4 by the user to function as a technical indicator. Custom indicators are intended for analyzing price activity but not for trading itself.
  • Scripts – programs written in MQL4 and intended to perform a single execution of some action. A script can fulfill both analytical and trading functions. Once a script has completed its function once, it automatically stops.

 

Expert Advisor Creation Expert Advisors are programs that allow automation of the analytical and trading processes in the MT4 platform. To create an Expert Advisor (or “Expert”), the expert editing program – MetaEditor – has to be opened from within the MT4 platform. To open the editor (see Figure 1):

 

  • In the Navigator window, right-click on Expert Advisors and select “Create”; or
  • In the Main Menu > Tools > MetaQuotes Language Editor; or
  • Click on the MetaEditor icon in the Standard Toolbar: or
  • Press F4 on the computer keyboard.
Figure 1 There are several ways to open the MetaEditor.

 

Any of these actions will open the Expert Creation Wizard. The Wizard can be used to create Expert Advisors, Custom Indicators, Scripts and DLLs. To create an Expert Advisor, select “Expert Advisor” and click “Next” to continue, as shown in Figure 2.

 

 

 

 

 

Figure 2 – MT4\’s Expert Advisor Wizard is used to create Expert Advisors, Custom Indicators, Scripts and Libraries (DLLs).

 

The “General Properties of the Expert Advisor” window appears. Here, traders must specify the:

 

 

 

 

 

 

 

  • Name – A user-created name for the Expert.
  • Developer – The developer’s name.
  • Link – To the developer’s website, if applicable.
  • Inputs – the list of Expert inputs

To add a new parameter to the Inputs field, press the “Add” button. For each Parameter, the trader must specify the Name, Type and Initial Value, as shown in Figure 3. To delete a parameter, highlight the parameter and press “Delete.” These become the Input Variables within the Expert. Once all the inputs have been listed, click “Finish” to continue.

 

 

 

 

Figure 3 – Create the input variables by identifying Name, Type and Initial Value.

 

A new window appears in the programming environment. The Expert’s name appears at the top of the window, and the previously entered input parameters are listed near the top of the code, as shown in Figure 4.

 

 

 

 

 

 

 

Figure 4 -The Expert name and inputs appear in the code window.

 

From here, the Expert code can be entered into the window using the MQL4 programming language and syntax (see Figure 5).

Note: Specifics regarding programming are outside the scope of this tutorial; understanding programming logic and learning a specific language require significant effort. Traders can learn more about programming in the MQL4 environment by reading the MT4 Help Guides and participating in the active MQL4 community forums.

MQL4, like other proprietary languages, has a list of Reserved Words and Standard Constants that are used during programming. Examples of constants for trade operations, along with their descriptions, include:

 

 

 

 

 

  • OP_BUY – Buying position
  • OP_SELL – Selling position
  • OP_BUYLIMIT – Buy limit pending position
  • OP_SELLLIMIT – Sell limit pending position
  • OP_BUYSTOP – Buy stop pending position
  • OP_SELLSTOP – Sell stop pending position
Figure 5 – part of the code for an Expert Advisor. Certain words have predefined uses; here, OP_SELL instructs the computer to sell if other criteria are met (if statements).

Traders can find a MQL4 Reference in the Help tab of the Toolbox in the MetaEditor window. This Reference includes information that is helpful to beginner and experienced programmers including:

 

 

  • Basics
  • Standard Constants
  • Predefined Variables
  • Program Run
  • Account Information
  • Array Functions
  • Common Functions
  • Conversion Functions
  • Custom Indicators
  • Date & Time Functions
  • File Functions
  • Object Functions
  • Trading Functions

Expert Advisor Compiling
After the Expert development has been completed, it must be compiled in order to ensure that the code has been written in the proper format needed to run the Expert. To compile the Expert:

 

 

 

 

  • Select File > Compile (see Figure 6); or
  • Click the Compile button on the toolbar; or
  • Press F5 on the computer keyboard.

Once compiling has been initiated, an update appears in the Toolbox beneath the code in the MetaEditor window, as shown in Figure 6. An errors or warnings will be listed.

 

 

 

 

Figure 6 – Successful compiling with zero errors and zero warnings.

 

After successful compilation, the new Expert will appear in the Navigator – Expert Advisors window, as shown in Figure 7. If the Expert did not compile successfully, it will still appear but its icon will be gray and the Expert cannot be used.

 

 

 

 

 

Figure 7 – The new Expert now appears in the Navigator-Expert Advisors window.

Expert Advisor Setup
Before the Expert can be used, its parameters must be defined in the Terminal Settings window. To open the window:

 

 

  • In the Main Menu > Tools > Options; or
  • Pressing CTRL + O on the computer keyboard.
  • Either action will open the “Options” window. Select the “Expert Advisors” tab, as shown in Figure 8.
Figure 8 – Select the “Expert Advisors” tab in the Options window to define an Expert\’s parameters.

 

The following settings are available in the “Expert Advisors” tab:

 

 

 

  • Enable Expert Advisors – this option allows the user to enable (check) or disable (uncheck) the use of all Experts.
  • Disable experts when the account has been changed – this option disables the Expert if the account has been changes, such as from a demo to a live account.
  • Disable experts when the profile has been changed – this option prevents Experts from launching if the profile has changed.
  • Allow live trading – to enable Experts in real-time mode (rather than testing an Expert on historical data).
  • Ask manual confirmation – to send trade confirmation prior to submitting the order.
  • Allow DLL imports -to use DLLs to enhance Expert functionality.
  • Confirm DLL function calls – to allow control over the execution of each called function.
  • Allow external experts imports – to allow the Expert to access functions from other Experts or MQL4 libraries.

Once the selections have been made, click “OK” to close the window.

Expert Advisor Launch

 

 

 

 

  • After the Expert has been created and setup, it is ready to be launched. To launch an Expert:
  • Right-click on the Expert in the Navigator – Expert Advisors window and select “Attach to a chart”; or
  • Double-click on the Expert in the Navigator – Expert Advisors window; or
  • Drag-and-drop the Expert to the desired chart.

A window appears with Common and Inputs tabs, as shown in Figure 9. Review the settings in each tab and make any necessary changes, and then click “OK” to attach the Expert to the active price chart.

 

 

 

 

Figure 9 – Make any changes to the Common and Inputs tabs before attaching the Expert to the active price chart.

 

The Expert will now be attached to the price chart. Its name will appear in the upper right-hand corner of the chart. The Expert’s name will be followed by a smiley face, as shown in Figure 10, if live trading is enabled. Otherwise, the Expert’s name will appear with a frowny face, a dagger after the name indicates that all experts are disabled.

 

 

 

 

 

Figure 10 – An Expert with a smiley face indicates that live trading has been enabled.

 

The Expert is now ready to begin analytical and trading functions.

Expert Advisor Shutdown
To shut down an Expert, it has to be removed from the chart. To remove an Expert, right-click on the active price chart, select “Expert Advisors” and then “Remove,” as shown in Figure 11.

 

 

 

 

 

Figure 11 – To remove an Expert, right-click the active price chart, select “Expert Advisors” from the drop-down menu, and then select “Remove.”

 

Notes About Expert Advisors

 

 

 

 

 

  • All Experts are shutdown if the Terminal is closed.
  • If a chart is closed, the Expert attached to the chart will shut down as well.
  • Adding another Expert to a chart will remove the previous one (a confirmation appears).
  • Deleting the Expert from the Navigator window does not shut down an Expert of the same name on an active price chart.

 

Custom Indicator Creation Indicators are used to analyze past and current price information to help traders predict future price movement. In addition to a wide variety of technical indicators included in the platform, traders can create their own Custom Indicators based on specified factors. In MT4, Custom Indicators are created, setup and launched using the same process as Experts (see the Expert Advisor Creation section of this tutorial). To open the Experts Wizard, right-click Custom Indicators in the Navigator window and select “Create,” as shown in Figure 12.

 

 

 

Figure 12 – To make a new indicator, right-click on Custom Indicators within the Navigator Window and select “Create.”

The Expert Advisor Window opens; select the “Custom Indicator” as the object to be created and click “Next” to continue, as shown in Figure 13.

 

 

 

 

Figure 13 – Creating a Custom Indicator in the Expert Advisor Wizard

 

The “General properties of the Custom indicator program” window appears. Here, traders must specify the:

 

 

 

  • Name – a user-created name for the Custom Indicator
  • Developer – the developer’s name
  • Link – to the developer’s Website, if applicable
  • Inputs – the list of Custom Indicator inputs

To add a new parameter to the Inputs field, press the “Add” button. For each Parameter, the trader must specify the Name, Type and Initial Value, as shown in Figure 14. To delete a parameter, highlight the parameter and press “Delete.” These become the Input Variables within the Custom Indicator. Once all the inputs have been listed, click “Next” to continue.

Figure 14 – Specify the parameters in the “General properties of the Custom indicator program” window within the Expert Advisor Wizard.

 

The “Drawing properties of the Custom indicator program” window appears. Here, traders can specify the indicator’s drawing properties that will determine the Custom Indicator’s appearance, as shown in Figure 15.

 

 

 

Figure 15 – Specify the drawing properties of the Custom Indicator.

 

Once the drawing properties have been specified, click “OK” to close the window. A new window appears in the MQL4 programming environment. The name of the Custom Indicator appears at the top of the window, and the previously entered parameters are listed near the top of the code, as shown in Figure 16.

 

 

 

 

 

Figure 16 – The Name and Inputs now appear in the programming environment.

From here, the Custom Indicator code can be entered into the window using the MQL4 programming language and syntax.

Note: Specifics regarding programming are outside the scope of this tutorial; understanding programming logic and learning a specific language require significant effort. Traders can learn more about programming in the MQL4 environment by reading the MT4 Help Guides and participating in the active MQL4 community forums.

Custom Indicator Compiling
After the coding has been completed, it must be compiled to ensure that the code has been written in the proper format to be able to run the Custom Indicator. To compile the Custom Indicator:

Scripts are programs that are intended to perform a single action. Unlike an indicator or Expert that works continually, a Script stops functioning once it has completed its function one time. Like Custom Indicators, Scripts are created, setup and launched in much the same manner as Experts. When launching the Experts Wizard, select “Scripts” as the object to be created. Continue in the same manner as creating an Expert or Custom Indicator (see the Expert Advisor Creation and Custom Indicator Creation sections of this tutorial).

 

To set up Script parameters, open the Options window and select the “Expert Advisors” tab. To open the window:

  • In the Main Menu > Tools > Options; or
  • Pressing CTRL + O on the computer keyboard.

Five options influence the operation of Scripts:

  • Allow live trading – to enable Experts in real-time mode (rather than testing an Expert on historical data).
  • Ask manual confirmation – to send trade confirmation prior to submitting the order.
  • Allow DLL imports -to use DLLs to enhance Expert functionality.
  • Confirm DLL function calls – to allow control over the execution of each called function.
  • Allow external experts imports – to allow the Expert to access functions from other Experts or MQL4 libraries.

 

Removing a Script A Script automatically shuts down once it has completed its function one time. Traders can, however, remove a Script manually. To remove a Script from a chart, right-click on the chart and select “Remove Script,” as shown in Figure 20.

 

 

 

Figure 20 – To remove a Script from a price chart, right-click on the chart and select “Remove Script” from the chart context menu.

Options for Non-Programmers
People who are not interested in learning how to program in the MQL4 language can still take advantage of Experts, Custom Indicators and Scripts. A growing number of commercially available products can be purchased at various trading-related businesses online, and MT4 users can also hire a qualified MQL4 programmer to perform the coding.

It is important to note that when working with a programmer, all ideas must be quantifiable and objective. For example, if the trader wants to enter a long position when price goes above a moving average, he or she will have to specify the moving average length, the precise entry point (next bar on open, for example) charting interval and even the trading instrument. Most programmers will not accept jobs that entail a lot of guesswork on the part of the programmer, and so project specifications need to be absolutely clear.

In general, if a commercial Expert, Custom Indicator or Script has been purchased, it will come with specific installation instructions. Similarly, a programmer will typically include instructions for installation. It is always valuable to read the instructions before attempting the installation to avoid any complications.

 

MT4 enables traders to test Expert Advisors prior to using them in a live market. This allows traders to evaluate the Expert’s efficiency and to confirm that it operates as expected.

Tester Window
MT4’s “Tester” is a multifunctional window where traders can test trading strategies (objective rules for trade entry, exit and management) and also optimize an Expert’s parameters to find the combination of variables that will produce the most favorable results. To open the Tester window:

  • In the Main Menu > View > Strategy Tester; or
  • Press the Strategy Tester button in the Standard Toolbar; or
  • Press CTRL + R on the computer keyboard.

Any of these actions will open the Tester window at the bottom of the MT4 screen, as shown in Figure 21.

Figure 21 – The Tester window appears at the bottom of the MT4 screen.

 

Initially, only the Settings and Journal tabs are seen in the Tester window. The other tabs will appear as certain actions are taken; for example, the Results tab appears only after an Expert has been tested. The Tester window tabs include:

 

  • Settings – the settings of the testing and optimization; for example, the time period to be tested.
  • Results – the results of the trade operations performed on historical data by the Expert.
  • Graph – a graphical display of the results.
  • Report – a detailed testing report.
  • Journal – a log where all actions and internal messages of the Expert are recorded.
  • Optimization Results – data regarding every optimization pass, including inputs, profitability and drawdowns.
  • Optimization Graph – the results of the optimization shown in graph form.

Setting up Testing Parameters

To test an Expert Advisor, click on the Settings tab in the Tester window. Here, the trader will have to select the:

 

 

  • Expert Advisor – Only compiled Expert Advisors will be available for testing, and these will appear in the drop-down menu next to “Expert Advisor.”
  • Expert Properties – Once the Expert has been selected, click on the “Expert properties” button to select parameters for each of the three tabs: Testing, Inputs, and Optimization.
  • Symbol and Period – The symbol is defined in the Symbol field; the timeframe is specified in the “Period” field. If there is no historical data saved for the symbol or period, the Tester will automatically download the last 512 historical bars.
  • Model – One of three methods of historical data modeling can be chosen for testing:

o Open prices only – the fastest method suitable for Expert Advisors that control bar opening.

o Control points – results are considered estimates only.

o Every tick – the most accurate method of modeling. Since this method involves a large amount of tick data, it is typically slow and can bog down the computer’s operation.

 

 

 

 

  • Use Date – The historical price data on which the test will be applied; complete the From and To fields to identify a range.
  • Optimization – Check to enable the Expert parameters optimization mode; if it is disabled, the Expert will be tested but not optimized when the “Start” button is pressed.
  • Open Chart – Opens a new price chart with the symbol selected for testing. The chart will show trade entries and exits, and can be opened only after the Expert has been tested.
  • Modify Expert – Click this to open the MetaEditor and make changes to the code, if desired.
  • Start – Press the “Start” button to being testing or optimization. A progress bar will appear at the bottom of the Tester window, as shown in Figure 22.

 

 

Figure 22 -A status bar appears at the bottom of the Tester window.

 

Setting up Optimization
MT4 can automatically create consecutive passes of the same Expert, with different inputs on the same data. Performing this optimization can help traders determine the inputs that have the most favorable results. To set up an optimization, traders must specify which variables will be optimized by clicking on the “Expert properties” button in the Tester window. This opens a new window with three tabs, as shown in Figure 23:

 

  • Testing – general optimization parameters
  • Inputs – inputs are variables that affect the Expert’s operation. Check to include inputs in the optimization; leave unchecked to disregard during optimization. If checked, double-click in each field to specify the values for Start (initial value), Step (change interval) and Stop (final value).
  • Optimization – the tab allows traders to apply limitations during optimization. If any of the conditions is met during a separate pass of the optimization process, the optimization will be interrupted. Check to enable a limit condition, such as Profit Maximum and Consecutive Loss.
Figure 23 – Set the Testing, Inputs and Optimization parameters to perform an optimization.

 

After making the desired selections, click “OK” to close the window. Be sure the box next to the Optimization field on the Tester window is checked (to enable optimization), and click “Start” to begin the optimization. Optimizations take varying amounts of time depending on the type of data on which the optimization is performed and the complexity of the inputs. In general, multi-variable optimizations – those that test multiple levels of multiple variables – take the longest.

Optimization Results

The Optimization Results tab in the Tester window contains a final report of each pass of the optimization. All data are presented in a table with the following fields, shown in Figure 24:

 

 

 

  • Pass – pass number.
  • Profit – net profit (gross profit minus gross loss).
  • Total Trades – total number of trades generated.
  • Profit Factor – ratio between the total profit and total loss. Values less than one indicate a losing system.
  • Expected Payoff – mathematical expectation of winning.
  • Drawdown $ – maximum drawdown in relation to the initial deposit.
  • Drawdown % – maximum drawdown in terms of percentage.
  • Inputs – dynamic values of inputs during each pass.

 

 

Figure 24 – Optimization results by pass; the inputs used to create the results of each pass appear in the Inputs column on the far right.

 

Click any header (such as Profit) to sort data by that field. Right-click the Optimization Results and select “Save as Report” to save a copy of the results.

Conclusion
Automated trading and strategy testing/optimization are advanced features of the MetaTrader 4 platform. Automated trading is popular because it removes some of the emotion from trading, helps traders avoid costly order-entry mistakes, and responds quickly to changing market conditions. The ability to test and optimize a trading idea (Expert Advisor) prior to placing it in a live market with real money is an invaluable step in the development of a profitable trading system.

 

 

More helpful MetaTrader 4 resources

https://blog.darwinex.com/dos-donts-metatrader-4-backtesting/

https://www.mql5.com/en/forum/81174

https://www.investopedia.com/articles/trading/10/backtesting-walkforward-important-correlation.asp

The Ultimate Guide to MT4 Backtesting

Receive Our New FREE 5 Part E-Course!

Get on the list for premium content directly to your inbox

I agree to have my personal information transfered to AWeber ( more information )

I will never give away, trade or sell your email address. You can unsubscribe at any time.