Step-By-Step Guide to writing an Expert Advisor in MQL5 for Beginners
Free Expert Advisor Builder. With this Expert Advisor Builder, you will create more than simple trading systems. You do not need any programming background. It is fast and easy. Now you can easily turn any manual trading system into an Expert Advisor for MetaTrader 4 & 5 or into a strategy for TradeStation. Trade Just About Anything Depending on the size of your account and your financial goals, you may be interested in developing indicators and strategies for Forex, stocks, commodities, ETFs, indices all with no.
Welcome to the second part of our MetaTrader4 Expert Advisor course! Missed the first part? After this article, you will feel comfortable with the MetaEditor and know how to create a new expert advisor. Your career is the engine of your wealth. Before we begin, please make sure that from now on, everything you run is on a demo account! You should also be somewhat familiar with MetaTrader.
The toolbar in this screenshot should be a familiar sight to you. These are the default controls that more or what are brown fat cells every MetaTrader application should have. Click on the Strategy Tester button left circle and you should see the following at the bottom of the window:. This is where we are going to run our expert advisors! This is also where you will be able to backtest your strategies. You can think of this as the control center of your future expert advisors!
This should open how to repair ge side by side refrigerator editor I was talking about earlier on. A new window will open, which should look similar to this:. This is hwo the magic happens. This is like Disneyland for us EA developers. Next up: some wizardry! You can also create your ezpert indicators, create a script which is just another name for a piece of code that runs just once in the client terminal and create libraries which are sets of functionality that can be used by multiple expert advisors.
Whoa, not too much in one go! Give the expert advisor a catchy name, such as ForexWall-E. Leave tl other how to create your own expert advisor as they are and click Next. The next 2 screens in the wizard will show you some options related to events. Leave everything on its default settings and click next and finish.
You have just created your first expert advisor. Well done, give yourself a quick pat on the back! What you have just created is is a fully functioning Expert Advisor. On the bottom part of the MetaEditor, you should see something like this:. Now go back to Expegt 4. You should still have the Strategy Tester on the bottom of the window.
In the first dropdown, you should now be able cfeate find your new EA:. When you use the same Strategy Tester settings the From and To date are not too important yetyou can click Start to test your newly created strategy. Give it a ceeate to calculate, and you should be presented with a green bar on the bottom, indicating your EA finished expeert. Have a browse through them. For now, Results and Graph will be empty since no trades have been made yetbut the Report and Journal tabs will show information about the expert advisor test run and some logging information, respectively:.
Pretty nice huh? It should build without issues difficulties with this? Let me know in the comments, I can help you out! But first: what are ticks? A tick in the context of forex means the smallest increase or decrease in price that a currency pair can make.
How to write an abstract for a nursing poster presentation, every time you see the price move up or down in the smallest way, that is a tick.
It is also when the OnTick event gets called. This is our function declaration. We indicate the availability of this function, so it can be called. OrdersTotal is a built-in function in the MQL4 language and returns the number of orders that are currently open. This line means that we fetch the value of the exponential moving average or EMA.
We will use this moving average value to determine if we should enter a trade or not. Now, a lot of parameters what makes a good vision statement used with this EMA! This is what they mean:. In other words: if the price is more than 50 pips below the EMA line, we should buy. Finally, we get to make the actual order! The OrderSend function is another built-in function that allows us to programmatically create an order.
In this case, we create a buy order for 0. Click the Compile button once again and then go back to MetaTrader. Start the rxpert advisor test in the Strategy Tester. And as you can see, it even seems our first expert advisor even made a modest profit largely by luck, no doubt. Next time, we will continue with our expert advisor and step by step improve it and make it more solid.
If you have questions, please let me know in the comments. Subscribe how to create your own expert advisor my newsletter below if you want to be kept up to date on when the next part of this course is published!
I'm a full-time, independent fx and futures trader. I've been trading for over 14 years and specialize in price action trading, order flow, trading psychology and algorithmic trading. When I'm not trading, I'll either be traveling the world or rock climbing likely both. Please consider carefully if such trading is appropriate for you.
Past performance is not indicative of future results. Articles and content on this website are for entertainment exprrt only and do not constitute investment recommendations or advice. CFDs are complex instruments and come with a high risk of losing money rapidly due to leverage.
You should consider whether you understand how CFDs work and whether you can afford to take the high risk of losing your money. This article is part of a series.
Looking for a video course instead? No programming experience required! Felix I'm a full-time, independent fx and futures trader. Why thinking like an astronaut will make you a better trader.
We'll hand you all the building blocks you need to build a profitable Expert Advisor. Export to Metatrader 4 & 5. When you feel ready, export & run your strategy on Metatrader 4 or 5 for testing or live trading. It’s all up to you. Our high quality mql code is written by professional programmers.
This article is aimed at beginners who wish to learn how to write simple Expert Advisors in the new MQL5 language. 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.
The above is called a trading strategy. Before you can write an EA, you must first develop the strategy that you want to automate into the EA. So in this case, let us modify the above statement so that it reflects the strategy we want to develop into an EA. We will use an indicator called Moving Average with a period of 8 You can choose any period, but for the purpose of our strategy, we will use 8. We have now developed our strategy; it is now time to start writing our code.
Begin by launching the MetaQuotes Language Editor 5. Figure 2. Selecting program type. In the next window, type the Name you want to give to your EA in the Name box. You can then type your name in the Author box and also your website address or email address in the Link box if you have one.
Figure 3. General properties of the Expert Advisor. Since we want to be able to change some of the parameters for our EA in order to see which of the values can give us the best result, we shall add them by clicking the "Add" button. Figure 4. Setting EA input parameters. Double Click under the Name section and type the name of the parameter, then double click under the Type to Select the data type for the parameter, and double click under the Initial value section and type the initial value for the parameter.
Figure 5. Data types of EA input parameters. As you can see above, I selected integer int data type for all the parameters. Let us talk a little about data types. From the above description of the various data types, the unsigned integer types are not designed for storing negative values, any attempt to set a negative value can lead to unexpected consequences.
For example, if you want to store negative values, you cannot store them inside the unsigned types i. Back to our EA. Looking at the data types, you will agree with me that we are suppose to use char or uchar data types since the data we intend to store in these parameters are less than or respectively.
For good memory management, this is the best thing to do. However for the sake of our discussion, we will still stick to the int type.
Once you are done setting all the necessary parameters, click the Finished button and the MetaQuotes Editor will create the skeleton of the code for you as shown in the next figure.
The top part Header of the code is where the property of the EA is defined. You can see that here are the values you filled in the MQL5 Wizard in figure 3. In this section of the code, you can define additional parameters like description brief text description of the EA , declare constants, include additional files or import functions. The define directive is used for a declaration of constants.
It is written in the form. You can read more about the preprocessor directives in the MQL5 Manual. Let us now continue with our discussion. The second part of the header of our code is the input parameters section:. We specify all parameters, which will be used in our EA at this section. These include all variables that will be used by all the functions we will be writing in our EA.
Variables declared at this level are called Global Variables because they are accessible by every function in our EA that may need them. The input parameters are parameters that can only be changed outside of our EA. We can also declare other variables which we will manipulate in the course of our EA but will not be available outside of our EA in this section.
Next is the EA initialization function. This is the first function that is called when the EA is launched or attached to a chart and it is called only once.
This section is the best place to make some important checks in order to make sure our EA works very well. We can decide to know if the chart has enough bars for our EA to work, etc. It is also the best place to get the handles we will be using for our indicators ADX and Moving Average indicators. The OnDeinit functio n is called when the EA is removed from the chart.
For our EA, we will release the handles created for our Indicators during the initialization in this section. This function process the NewTick event , which is generated when a new quote is received for a symbol. Note, that Expert Advisor cannot perform trade operations if the use of Expert Advisors in the client terminal is not allowed Button "Auto Trading".
Most of our codes that will implement our trading strategy, developed earlier, will be written within this section. Now that we have looked at the various sections of the code for our EA, let us begin adding flesh to the skeleton. As you can see, we have added more parameters. Before we continue discussing the new parameters, let us discuss something you can see now. With comments, we are able to know what our variables stand for, or what we are doing at that point in time in our code.
It also gives a better understanding of our code. There are two basic ways of writing comments:. This is a multi-line comment. The compiler ignores all comments when compiling your code. Using single-line comments for the input parameters is a good way of making our EA users understand what those parameters stands for. On the EA Input properties, our users will not see the parameter itself, but instead they will see the comments as shown below:.
Figure 7. Expert Advisor input parameters. We have decided to add additional parameters for our EA. A double is used to store floating point constants, which contain an integer part, a decimal point, and a fraction part.
The Lot to trade Lot represents the volume of the financial instrument we want to trade. Then we declared other parameters that we will be using:.
The adxHandle is to be used for storing the ADX indicator handle, while the maHandle will store the handle for the Moving Average indicator. The maVal is a dynamic array that will hold the values of the Moving Average indicator for each bar on the chart.
By the way, what are dynamic arrays? A dynamic array is an array declared without a dimension. In other words, no value is specified in the pair of square brackets. A static array, on the other hand has its dimensions defined at the point of declaration. Here we obtain the handles of our indicator using the respective indicator functions. The Moving Average indicator handle is obtained by using the iMA function.
It has the following arguments:. Please read the MQL5 manual to get more details about these indicator functions. It will give you a better understanding of how to use each indicator. We use the alert function to display the error using the GetlastError function. Why are we doing this? So here we want to make sure that our EA works very well with all brokers. Digits or Digits r eturns the number of decimal digits determining the accuracy of price of the current chart symbol. For a 5-digit or 3-digit price chart, we multiply both the Stop Loss and the Take Profit by Since this function is called whenever the EA is disabled or removed from a chart, we will release all the indicators handles that were created during the initialization process here.
We will use the IndicatorRelease function to accomplish this. It takes only one argument the indicator handle. The function removes an indicator handle and release the calculation block of the indicator, if it's not been used. The first thing we have to do here is to check if we have enough bars on the present chart. We can get the total bars in history of any chart using the Bars function. These two return the current symbol for the current chart on which our EA is attached and the period or timeframe of the present chart can be obtained using Period or Period.
This two will return the timeframe of the current chart on which the EA is attached. If the total available bars are less than 60, we want our EA to relax until we have enough bars available on the chart. The Alert function displays a message on a separate window. In this case, we have only one string value. The return exits the initialization of our EA. The Expert Advisor will perform trade operations at the beginning of a new bar, so it's necessary to solve the problem with the new bar identification.
We declared it as static because we want the value to be retained in memory until the next call of the OnTick function. We also declared a bool data type variable IsNewBar and sets its value to false.
<- How to make a lightsaber out of a laser pointer - My dog ate a diaper what should i do->