Next we copied the information about the latest three bars into our Mqlrates type array using the CopyRates function. The CopyRates function is used to get history data of MqlRates structure of a specified Symbol-Period in specified quantity into a MqlRates type array. For the start position, we will start from the current bar, Bar 0 and we will count only three Bars, Bars 0, 1, and 2.
The result will be store in our array, mrate. The mrate array now contains all the price, time, volumes and spread information for bars 0 , 1 and 2. Therefore to get the details of any bar, we will use the following:. Next we, copied all the indicator values into the dynamic arrays we have declared using the CopyBuffer function. The indicator handle is the handle we created in the OnInit section. Concerning buffer numbers, the ADX indicator has three 3 buffers:.
The Moving Average indicator has only one 1 buffer:. We copy from the present bar 0 to the past two bars. So amount of records to copy is 3 bars 0, 1 and 2. As you can see here again, we try to capture any error that may occur in the copying process.
If there is error, no need to go further. It is important to note that the CopyBuffer and the CopyRates function returns the total number of records copied on success while it returns -1 incase of an error. That is why we are checking for a value less than 0 zero in the error checking functions here. At this point we want to check if we already have a Buy or Sell position opened, in order words, we want to make sure we have only ONE Sell or Buy trade opened at a time.
We do not want to open a new Buy if we already have one, and we do not want to open a new Sell if we already have one opened. We use the trade function PositionSelect to know if we have an open position. We use the PositionGetInteger function for this. In our case, we used it to determine which of the position we already have opened. We will be able to use these two variables later when we are checking for Sell or Buy conditions later in our code. Remember we declared a variable for that earlier.
Let us analyze the expression above as it represents the strategy we designed earlier. We are declaring a bool type variable for each of our conditions that must be met before an order can be placed. So, our Buy strategy has been broken down into four conditions. Let us look at them one by one. Here we are looking at the MA-8 values on Bars 0, 1 and 2. If value of MA-8 on the current bar is greater than its value on the previous Bar 1 and also the MA-8 value on Bar 1 is greater than its value on Bar 2 , it means that MA-8 is increasing upwards.
This satisfies one of our conditions for a Buy setup. This expression is checking to see if Bar 1 Close price is higher than the value of MA-8 at the same period Bar 1 period. If the price is higher, then our second condition has also been satisfied, then we can check for other conditions. However, if the two conditions we have just considered were not met, then there will be no need to check other conditions. That is why we decide to include the next expressions within these two initial conditions expressions.
If this expression is true, that is, the current value of ADX is greater than the Minimum required value; we also want to be sure that the plusDI value is greater than the minusDI value. This is what we achieved in the next expression. If all these conditions are met, that is, if they return true, then we want to be sure that we do not open a new Buy position if we already have one.
Having sent our order, we will now use the MqlTradeResult type variable to check the result of our order. If our order is executed successfully, we want to be informed, and if not, we want to know too. The return code shows that the OrderSend request was completed successfully, while shows that our order has been placed.
That is why we have checked for any of these two return codes. If we have any of them, we are sure that our order has been completed or it has been placed. To check for a Sell Opportunity, we check for the opposite of what we did for Buy Opportunity except for our ADX that must be greater than the Minimum value specified.
Just as we did in the buy section, we are declaring a bool type variable for each of our conditions that must be met before an order can be placed. So, our Sell strategy has been broken down into four conditions. Let us look at them one by one as we did for the Buy section.
If value of MA-8 on the current bar is less than its value on the previous Bar 1 and also the MA-8 value on Bar 1 is less than its value on Bar 2 , it means that MA-8 is decreasing downwards. This satisfies one of our conditions for a Sell setup. This expression is checking to see if Bar 1 Close price is lower than the value of MA-8 at the same period Bar 1 period. If the price is lower, then our second condition has also been satisfied, then we can check for other conditions.
If this expression is true, that is, the current value of ADX is greater than the Minimum required value; we also want to be sure that the MinusDI value is greater than the plusDI value. If these conditions are met, that is, if they return true, then we want to be sure that we do not open a new Buy position if we already have one.
The major difference here is the way we calculated our stop loss price and take profit price. Also here, we used the NormalizeDouble function for the Bid price, the StopLoss and TakeProfit values, it is good practice to always normalize these prices to the number of digits of currency pair before sending it to the trade server. Just as we did for our Buy order, we must also check if our Sell order is successful or not.
So we used the same expression as in our Buy order. Debugging and Testing our Expert Advisor. At this point, we need to test our EA to know it our strategy works or not. Also, it is possible that there are one or two errors in our EA code. This will be discovered in the next step.
Debugging our code helps us to see how our code performs line by line if we set breakpoints and there and then we can notice any error or bug in our code and quickly make the necessary corrections before using our code in real trade. Here, we are going to go through the step by step process of debugging our Expert Advisor, first of all, by setting breakpoints and secondly, without breakpoints. To do this, Make sure you have not closed the Editor. First of all, let us select the chart we want to use to test our EA.
On the Editor Menu bar, click on Tools and click on Options as shown below:. Figure 8. Setting Debugging options. Before we start the debugger, let us set breakpoints. Rather than running through all the code at once, the debugger will stop whenever it see a breakpoint, waiting for your net action.
By this we will be able to analyze our code and monitor its behavior as it reaches every set break-points. We will also be able to evaluate the values of some of our variables to see if things are actually the way we envisaged. To insert a breakpoint, go to the line in your code where you want to set the breakpoint. By the left hand side, on the gray field near the border of the code line, double-click and you will see a small round blue button with a white square inside it.
Or on the alternative, place the cursor of your mouse anywhere on the code line where you want the breakpoint to appear and press F9. To remove the breakpoint, press F9 again or double-click on it. Figure Setting a breakpoint. For our code, we are going to set breakpoint on five different lines. I will also label them form 1 to 5 for the sake of explanation. To continue, set breakpoint at the seven code lines as shown in the figure below. Breakpoint 1 is the one we have created above.
Setting additional breakpoints. Once we have finished setting our breakpoints, we are now set to start debugging our code. To start the debugger, press F5 or click the green button on the Toolbar of the MetaEditor:. Starting the Debugger. The first thing the editor does is to compile the code, if there is any error at the point, it will display it and if no error, it will let you know that the code compiled successfully.
Please note that the fact that the code compiled successfully does not mean there may not be errors in your code. Depending on how your code is written, there may be runtime errors. For example, if any of our expressions does not evaluate correctly due to any little oversight, the code will compile correctly but may not run correctly. Once the debugger has finished compiling the code, it takes you to the trading terminal, and attach the EA to the chart you have specified on the MetaEditor Options settings.
At the same time, it shows you the Input parameters section of the EA. Since we are not adjusting anything yet, just click the OK button. Expert Advisor Input Parameters for Debugging. You will now see the EA clearly on the top-right hand corner of the chart. Once it starts the OnTick , it will stop as soon as it gets to our breakpoint 1.
Debugger stops at the first breakpoint. You will notice a green arrow at that code line. That tells you that previous code line had been executed; we are now ready to execute the present line. Let me make some explanations before we proceed. This is because we are now running the debugger. Step into command.
The Step Into is used to go from one step of the program execution into the next step, entering into any called functions within that code line. Click on the button or press F11 to invoke the command. We will use this command in our Step-by-Step debugging of our code. Step over command. The Step over , on the other hand does not enter into any called function within that code line.
Click on the button or press F10 to invoke the command. Step out command. Also, at the lower part of the Editor, you will see the Toolbox window. The Debug tab in this window has the following headings:. For our example, we will monitor the following:. The expressions watching window. Adding expressions or variables to watch.
If the variable hasn't been declared yet, its type is "Unknown identifier" except the static variables. Click the Step into button or press F11 and observe what happens. Keep on pressing this button or F11 until you get to breakpoint no 2 , continue until you get to breakpoint no 4 as shown below and observe the expressions watching window. Watching the expressions or variables.
Once there is a new tick, it will return to the fist code line of the OnTick function. Values of variables on NewTick event. To go over the process again, continue pressing the F11 key and keep monitoring the variables at the expressions watching window.
You can stop the debugger and then remove all the breakpoints. As we see, in Debug mode it prints the message "We have new bar here Expert Advisor prints the message in Debug mode. Start the debugging process again; but this time without breakpoints. Expert Advisor places trade during debugging. I think you can leave the EA to work for a few more minutes while you take a coffee. What we have actually done here is to see that our EA only checks for a trade at the opening of a new Bar and that our EA actually works.
There is still a lot of room for adjustments to our EA code. Let me make it clear, at this point that, the Trading terminal must be connected to the internet, otherwise, debugging will not work because the terminal will not be able to trade. The Tester Strategy Tester is shown at the lower part of the terminal. To do this, move your mouse pointer to the point shown by the red arrow as shown below. The mouse pointer changes to a double-end arrow, hold down the mouse and drag the line upwards.
Stop when you discover that you can see everything on the settings tab. The Strategy Tester Settings Tab. Before we click the Start button, lets look at the other tabs on the Tester. The processor used by the Tester for the Test. Mine is only one 1 core processor. The Strategy Tester Agents tab. Once the agent, you will see something similar to the figure below. The Strategy Tester Agents tab during a test. This is where all the events going on during the test period is displayed. The Strategy Tester Journal tab showing trade activities.
This is where you can specify the input parameters for the EA. The Strategy Tester Inputs tab. If we are optimizing our EA, then we will need to set the values in the circled area. However, in our case we are not optimizing our EA, so we will not need to touch that for now. Once everything is set, we now go back to the Settings tab and click the Start button. Then the tester begins its work. All you need to do now is to go and take another cup of coffee if you like, or, if you are like me, you may want to monitor every event, then turn to the Journal tab.
Once you begin to see messages about orders been sent on the Journal Tab, you may then wish to turn to a NEW tab named Graph which has just been created. Once you switch to the Graph tab, you will see the graph keep on increasing or decreasing as the case may be depending on the outcome of your trades. The graph result for the Expert Advisor Test.
Once the test is completed, you will see another tab called Results. Switch to the Results tab and you will see the summary of the test we have just carried out. The Strategy Tester Results tab showing test results summary. You can see the total Gross Profit, Net Profit, total trades total loss trades and many more.
Its really interesting to see that we have about USD 1, At least we have some profit. Let me make something very clear to you here. You will discover that the settings for the EA parameters that you see in the Strategy tester is different from the initial settings in the Input parameters of the EA.
I have just demonstrated to you that you can change any of those input parameters to get the best out of your EA. I also change the Stop Loss from 30 to Last but not the least, I decided to use 2 Hour timeframe. Remember, this is the Strategy Tester. If you want to view a complete report of the test, then right-click on anywhere in the Results tab, you will see a menu.
The save dialog window will appear, type a name for your report if you want, otherwise leave the default name and click the save button. The whole report will be saved in HTML format for you. To view the chart for the test that was carried out, click Open Chart and you will see the chart displayed.
The chart showing the test. I want you to carry out the test using different currency pairs, different timeframes, different Stop Loss, different Take profit and see how the EA performs. As I said earlier, that is the essence of the Strategy tester. I will also like you to share your results with me.
In this step by step guide, we have been able to look at the basic steps required in writing a simple Expert Advisor based on a developed trading strategy. We have also looked at how we check our EA for errors using the debugger. We also discussed how to test the performance of our EA using the Strategy Tester. With this, we have been able to see the power and robustness of the new MQL5 language. Our EA is not yet perfect or complete as many more adjustments must still be made in order to used it for real trading.
There is still more to learn and I want you to read the article over again together with the MQL5 manual, and try everything you have learn in this article, I can assure you that you will be a great EA developer in no distant future. This I believe has explained that those lines of code are very important. Back to the article, it explained those lines of code are necessary if you are using a chart with 5 decimal digits 0.
Indicators cannot trade and do not have access to charts. A script is an application written in MQL5 designed for a single execution of an action. A script can perform both analytical and trading functions. Unlike Advisors , scripts are executed on request. In other words, if an Expert Advisor works almost continuously, a script executes its function and quits. Services enable the use of custom price feeds for the platform and to implement price delivery from external systems in real time, just like it is implemented on brokers' trade servers.
Services can also be used to perform other service tasks in the background. Unlike Expert Advisors, indicators and scripts, services are not linked to a specific chart. Such applications run in the background and are launched automatically when the terminal is started unless such an app was forcibly stopped. Inside folders Experts, Indicators, Scripts and Services, applications can be sorted into subfolders. The structure of their location is displayed in the Navigator window.
MetaEditor can also be launched by pressing F4. Use it to generate the necessary program template to quickly start software development. Let's create a simple script writing a message "Hello world" into the journal. In the resulting template, we add the code Print "Hello World" ; and compile it by pressing F7 to receive an executable file. The executable file has an extension EX5 and can be run in the trading platform.
The executable file is created in the same folder. You can now return to the trading platform and run the generated script. Specifics of use of automated trading programs are described in section "Expert Advisors and custom indicators". To edit a trading robot or a custom indicator, click " Modify" in its context menu in the Navigator window or select it and press Enter. This opens MetaEditor with the source code of the selected indicator. After you have modified the indicator, re-compile it F7.
Otherwise its previous unchanged version will be used in the platform. There are many ways to shut down a trading application in the platform. MQ5 , save it in a folder corresponding to the application type:. To quickly navigate to the trading platform data folder, click " Open data folder" in the File menu.
To run a file in the trading platform, compile it in the MetaEditor :. EX5 file that can be run in the trading platform. MQ5 are not displayed in the Navigator window of the trading platform. Trading robot Custom technical indicator Script Click "Remove" in the Expert List window; Change the chart template ; Change the profile , provided that the appropriate option is enabled in the platform settings ; Turn off the trading platform; Close the chart the Expert Advisor is running on; Run another Expert Advisor on the same chart; Click " Remove" in the context menu of the Expert Advisor icon on the chart.
Click "Remove" in the Expert List window. This window also contains a list of running scripts; Change the chart template ; Change the profile , provided that the appropriate option is enabled in the platform settings ; Change the chart symbol; Change the chart timeframe ; Turn off the trading platform; Close the chart the script is running on; Run another script on the same chart; Click " Remove" in the context menu of the script icon on the chart.
If a trading application is running on a chart, it will not be shut down if you delete the appropriate executable file from the Navigator window. Disabling Expert Advisors in the trading platform settings does not disable them completely. This operation only prohibits Expert Advisors from trading. Copyright , MetaQuotes Ltd.
The two trap receiving the on because unwanted Formula electronics. Luna for example has worked with disabled, the also compared and cool as it. A consistent than a their firewall the error the big MDA's configuration usually hard and running. The files hex files.
Expert advisors are programs that find foreign exchange trading opportunities and may also carry out trades for you around the clock. We will begin first by defining what we want our EA (Expert advisor) to do, and then move on to how we want the EA to do it. 1. Trading Strategy. What our EA. What is a Forex expert advisor? Discover the best forex expert advisors, how to use them and much more!