Fully working Moving Average MT5 Expert Advisor Programming Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey this is Annie and I want to welcome you to a new programming tutorial this time we will be working with moving averages you see them in the back here already attached to the euro US dollar chart and we have two moving averages the first one is a two hundred period simple moving average and the second one is a seven or whatever period moving average so we basically have a fast moving average and a short or a slow moving average and these two keep crossing as the market if the market goes on so and you can see here is a crossing point and the fast moving average is dropping below the slow moving average and here is another crossing point where the slow moving average or the fast moving average is crushing causing the slow moving average again and this time it comes from below and if we go all the way up above the slow moving average and there was another crossing point and where it drops or falls below the slow moving average again so that's pretty much what we want to trade we will search for these points and whenever whenever one of these points occurs we will make a trade and we will make this or we will achieve this by programming an expert advisor and the fully automated trading programs for the metatrader4 and metatrader5 this time we are working with a major trader five so to start off we have to open the meta cross-language editor why you find in the upper left corner this little book sign here is the middle code language editor and you can click it or you can go to extras and then hit the major quotes language editor button so I will close on this and we will start by mmm you and I by creating a new expert advisor if you didn't see it I press new in the upper left corner and then we use expert advisor I think I have had to change the language to English to make it easier to understand I don't know where to do it [Music] languages English we are okay so you click on you then the very first option is expert advisor with a template you have to choose a name maybe we can go with moving average average yeah and here on this page of the step you can choose some event handlers that our or might be used for we'll go with no event handler for the moment and we will have a an absolute basic expert advisor here the grey lines are just comments and I will delete them and then we have three basic functions left which I will explain in a second so first of all let's talk about comments I'm doing I'm just doing some cleaning of my coat here because I like the brackets in this order more than the standard Orla so I'm to start with I will explain how you write a comment you can use two slashes to write a one-line comment and like this is a one-line comment and everything that are right in this line will be a comment so it's only relevant for the programmer not for the computer the computer will simply ignore it and if I write in this line this is in black and it's no comment because there are no slashes in front of it if I add them the line will become gray and it's a comment you can also write multi-line comments with a slash and this little star if I do it like this I can write a comment and everything is great so everything is a comment so at one point I have to end the comment with a sour and another slash and now you see that that everything in between of these two signs here is a comment and everything or below is no comment or at least it's no part of this comment so that's basically how you can use comment you should use comments to comment a code and it will make everything easier if you look at your code again in like one year or if you give your code to another programmer so he doesn't have to struggle that much understand in code the copyright link and version can be deleted we don't really need that yet we don't need anything of that and what's left is three functions these are event handlers and and the functions are called on init ordinate and on take and array function has a specific event that triggers this exact function like the own in it is triggered when the expert advisor is started or initialized I can write a short comment using the print function I won't explain it in detail you can just like do what I do for the moment and I will do more explaining later on when we start with the yeah with the expert advisor or the tracer threading functionality and this is the tick function so if I compile this by pressing this little compile button at the top the the compiler will process all this code here and turn it into an executable program you will find this program in your navigator which you can open by pressing ctrl + n on your keyboard and in the experts tap here this isn't German again so I will switch to English restart and there we go so mmm you will find it under our expert advisors and there we can see moving average a if I attach it to any chart I can press ok and we see in the experts tab in the expert step there is a information that says on in it so this was the first a message that we received you can see it by looking at the timestamp on the left side here and now there are several several on tick messages and because every time the there is a new tick in the market at this time it's the euro US dollar we will trigger this on tick function and when the function is triggered everything inside of the function like in the body of the function which is marked by these brackets here like the curly bracket and it's executed and what's inside is a print statement that says please print the word on take to the experts tab and that's what the expert device is doing right now so every time I take a curse it prints on tick so now we can trigger the last function the on D in it and as you could imagine it is triggered when the expert advisor is the initialized or removed like this and now it says on the net because we have a print statement in the ordinal function that says print the word on D in it so that's pretty much it that's how you can use these three functions the on in it is called whenever the expert divisor is initialized the ordinate is called whenever the expert advisor is D initialized and the on tick function is called whenever there's a tick in the chart if I delete this I can show you another thing which is kind of important and can cause confusion if you don't know about this and if I hit it again you can see that the on in it is called of course and if I switch the timeframe the EI will be T initialized and initialized in like a millisecond but whenever we switch timeframes it's it's important to understand that both of these functions first the D initialize function and then the initialize function so it's not only when you attach the expendable that to the chart and when you remove it from the chart but it's also called when you like switch timeframes or if you attach another template or something so there are several events that will cause a denationalization and another initialization so let's get back into the code I will remove the print statements because that was just to explain like these basic functions and now we can start by getting a moving average value whenever we want to receive a value from an indicator we have to call this indicator and in mql5 and the metatrader5 you do this by using a specific function or indicator coil and to do this you can use like I ma this small letter I is or stands for indicator and ma is moving average so this is a specific function that were that will return a a-hinder to an indicator so a handle is pretty much an value that identifies an indicator so this hender could store the information about this specific indicator it would hold the information that it's a 200 periods moving average and it's a simple moving average without any shift and it's applied to the close price so to receive all these informations or to make the expert advisors understand what a specific moving average shoe mean and what you want to address you will have to create this handler with the relevant information so if you bright oil or dislike I ma and open a briquette you can see what parameters are required for this function and there are several parameters that I will walk you through right now and to start with the function wants to know for which symbol you want to receive the moving average and this time we want to use the current symbol and whenever you want to receive the the name of the current symbol you can just type underscore symbol I can show you that it's really working by just yeah using a print statement again and printing out the name you can see here it says you will US dollar whenever the charges or the expert advisor is initialized because I printed the symbol in the anarion function so you see underscore symbol will bring you or will return the information about the current chart silver then you need to provide this function with the information about the exact time frame you want to use for this moving average because if I switch timeframes you can see that on every time frame the indicator looks different because yeah that's I mean it's pretty obvious because I'm for example the slow moving average is calculated by using the last 200 periods of the specific time frame and of course the 200 periods in the m5 time frame are different than the last 200 periods in the m15 timeframe so you have to provide the time frame we can use period current it's an ID or identifier for the current time frame you could also use Niall like this but period current is easier to understand there are several time frames you can address by using and different identifiers you can see them if you press the f1 button while your cursor is inside of period current that will open the reference and you can read everything about chat time frames and the enumeration time frames so this enumeration how its identify us for every every time frame and you can see that yeah every every time from sa ID and you can just use this idea if you want to use the specific time frame if you want to learn more about in emulations you can read about this in the documentation of course if you write enum I will not explain this in detail because we don't really want to use our own enumerations we just want to use the system enumerations and yeah that's pretty much all you have to know about the next step is to provide the expert advisor with the periods for this exact moving average and as I told we will use a 200 moving average try to the period moving average then we have to provide a shift value we don't really want to shift the moving average I can show you what a shift value is but we won't use it if I use like 10 as a shift value you can see or maybe 100 you can see that the moving averages just shifted to the right side and if I use minus 100 its shifted to the left side so the values are pretty much the same but they are shifted to either the left side or the right side we don't want to use it so we just use math and we need to provide a moving average method we will go with mode as may for the moment and mode as may as you might imagine is another enumeration you can look it up by pressing f1 while your cursors in the world and you can see that there are four different modes for the moving average it's SMA EMAs Mme and L WMA you can see the description on the right side and yeah all of these moving average types have a different calculation in the background we will use the simple moving average which is just a average of the past like 200 periods or something and now we have to provide a price like price close which is another enumeration and the price close says that we will use the close prices of the last 200 pass to calculate this moving average so when I close the brackets this is a working expert advisor pretty much because there are no problems anymore on the compiler doesn't find any any mistakes but this doesn't really give us a value of the moving average so what we have right now is a handle which is returned by this function so if we use this function if we call this function the computer will process it and you can say pretty much at the position of this function here where we will stand the handler pretty much after the function is processed so we can use the value and store it in a variable like handle or handle slow MA and if I use this integer variable which is a identifier for numbers like 1 2 3 443 or something we can store the handle inside of the variable because you can see in the IMA function that the return value is of type integer so it's just it's basically just a number which holds the information but the moving average and for Princess you can see that it's just a number we can look at it and if there was a tick in the market we will see a pretty huge number I think which puts the information of these this moving average that we want to use to receive the various okay there's no it no huge number but it's a number so we can use the sender to call another function and the next function will call its copy buffer so this moving average are pretty much every indicator has a buffer the buffer is just a construct that holds different indicator values because this indicator has a value for every simple power you can see it in the data window which you can open by pressing control D or under view and you can see the MA 200 and animate ma 20 valium and it's changing for every simple bar which makes sense because you can see that indicator value is changing in the chart as soon as there's a new bar and prices like changing so all these values are stored in a buffer so the moving average has a buffer which holds a value of the information about the specific price level of the moving average at every singer Kenda index pretty much so we could copy the values or receive the values from this buffer by using the copy buffer function and you can see that that this function is that it needs some parameters like a handle and we do have a handle so we can insert it here and it will tell the function what values we want to receive so the next thing is to provide a buffer number and the first buffer or the only buffer of the moving average is the buffer with the index 0 so we can use this one and we have to use a starting position we will use 0 because the starting position is an index of a candle and or a candlestick and the current candlestick or the current 15 minutes candlestick always have as the index 0 and then we keep on counting from the right side to the left side in the chart and can increment the next to receive the index of the current I'll specific candle so this one is index 0 you can see that this one is index 1 this next to this one would be index 41 and this one would be index 52 so it's incrementing from the right to the left side and every Bower has its own unique ID pretty much so this is a way to address every single bar without ya problems we will start at the index 0 and we want to receive 2 or let's say now we will start at index 1 and we want to receive 2 2 values so we will start at this candle here so the last candle and we want to receive two values so will receive the way you for this candle and for this candle you so both values will be stored in an array of type double we can declare this array by using double and slow ma right and we have to choose a name for this array and we have to use this bracket just like I don't know you call it like this Howard brackets here and and this isn't an identifier for an array so what is an array to start off I will explain what a double variable is a double variable is just a number with a dot like 12 12 thought 44 so just a decimal number and yeah that's pretty much all you have to know about the double variable to just another data type like integer and an array is another or an array of type double is like a a basket where you can put multiple numbers in so if we have an array with the size of two we can use like the zero index to put a number in like 20 3.33 and we can use the next index will be index 1 to put another number in and this would be a working working program there's no problem because this array can hold two double variables and if we want to put another number inside of this array this would not really work because we have a index out of range error here because this would be the third number in this array which can only only hold two numbers so that's pretty much how you can use an array if I print the these two values you can see that both are stored in this array and we can use the values from an array like we can put them in by using the index of the specific number two to make clear which which number we want to receive and you can see that both numbers are printed in the expert tab so I delete all of this and we'll just keep a slow moving average away we don't have to choose a number for the for the range or the length of this array and we can just leave it blank so it's an array I don't know really how are you call it but it's not undefined pretty much array it has man defined range in the beginning and the copy buffer will take care of like extending this array to the needed amount of of of numbers to store inside so what this does is it takes the handle of our slow moving average and it will use the handle to receive all the information about this moving average and when it has the information it yeah we just take the like the first last the value and the second last value and it will store both of these values inside of our slow moving average away and if I use a comment it's another function pretty similar to the print statement because it shows information and this time the information will be shown in the in the chart I can show you in a second handle slow ma index zero is no slow ma index zero and I want to print the the first index to I using handles slow MA and choose the first index mm if I do this oh it it wants to happen everywhere but this is out this is not an error that ever is called slow ma ray so slow ma arrey slow MA ray so what this does is it just prints light and the values in the upper left corner and this will happen with the next tick in the chart okay here you can see the values of this slow moving average for the last candle like this one you can see the value right here so this value is 1.1 to one six five pretty much and it's the exact the exact number they're standing up here and the second one is 1.1 to one six five six and that's what you can see here so if want to keep our just immaterial if we want to keep the order like 20 but we have this value on the 0th index of the array and the other one on the first index we have to use another function to like turn all of these values around we can use arrays set as serious for the slow moving average away and we have to provide the value true because it says that we want to have this array is in serious array and that's good that pretty much says that the value on the index 0 will be stored like on the index 0 or the value on the candle in this one will be stored in the array index 0 and the candle index 2 will be stored on the common happy on the array worth index or the position with the next one ok that's pretty much it so we receive both of these values for slow moving average we can do the same thing for the fast moving average of course by using the exact same code but we have to change some of these information about the moving average we will use only like 20 periods maybe and we have to rename the array and everything else because we want to have different values of course 1st and 8th right and fast in a way you know we can print these out like this and we have to change the description and the array that we want to receive the way very good strong fast so it's alright done and this should be working know receive four values in the upper left corner you can yeah just check it on your PC it's easier to to to like see the values and everything so this is this is working I think and is it working so the value is 1.1 to 0-8 6 and 1 to 0-8 that's not the exact value that we see in the upper left corner so we will have to look for the difference okay this was a exponential moving average so if I change this to the right moving average we see that the very use matching no ok this is working so what we have now is next but viola that constantly prints of the last and the second last value of a 200 period simple moving average and a 20 period simple moving average and having these values we can do another thing first of all we can make this variable static and by making a variable static it says that we only want to do like this we only want to process this line once so whenever the on tick is called for the very first time out the afterwards the reactivation of the expert advisor this line will be processed and it will declare a static integer variable with name Henry slow MA and this will will be or receive or the the value of I ma with these parameters will be stored in this handle variable and whenever the second third fourth and so on tick occurs this line will pretty much be ignored but that doesn't mean that we don't have the handle slow ma variable we still have it it it will stay there for like the whole runtime of the program so that's a method to save save resources and to speed up the expert advisor because every time we call this ima with these parameters the return value a little bit will be the same so we don't have to do it every time and we can only or we it's enough if we we only do it once whenever the ontic is called for the very first time so when we have this now we can start using the values in the arrays that we just created and we can do it by yeah by by using an if statement and if statement is a control structure that will help us to like bring more logic to our code and you can use it by writing the keyword if and then we open brackets and inside these brackets here we can write a condition and the condition will be a comparison of the four values that we start in the arrays because by using these four values we can identify like this crossing points where one expert advisor is falling below or rising above the other one so we have to compare like the two values before the crossing and after the crossings and you can do this by simply using the values in the arrays we have to check the value of the fast moving average array and compare it to the value of the slow moving average array at index zero and we have to use the fast moving average array at index one and compare it to the slow moving average array at the next one this pretty much says that if the latest value of the fast moving average rate is greater than the latest value of the slow moving average array and the second latest value in the or of the fast moving average below the second latest value of the slow moving average then we have a crossing where the rather slow moving average or the fast moving average is rising above the slow moving average and we can do a print statement like fast ma is no greater than slow MA if we do it like this it should work so there's a problem oh man I'm always getting these names from slow in every way and fast MA arrey have fast MA array okay like this so no problems anymore we can copy this for the like exact opposite event where they're fast moving average is falling below the slow moving average we just have to turn like these operators the operators are just like greater than and smaller than science and they do what to say what the name is already saying they compare two values and they were like return if if this one is greater than this one like this whole expression will return true because it's true and if it's not true it will be charged for it's because it's for it so in this if condition we have two conditions they are combined with this end end sign which says that both of these conditions have to be true so the total condition of this if statement will be true so yeah that's my sense I think and I can compile this and we can run a simple simulation with this I can use the moving average expert advisor in the euro/us setup euro euro US dollar chart and we don't have any inputs you can start this and let's see if even this whole thing is working waiting for the first crossover it's not here yet so there shouldn't be any information into Jonah I can clear it and I can speed it up so there's the first print statement which is which is triggered because there's an interaction between these two moving averages and this is what is this is no I want to write no no not no that's wrong so oh this should be smaller than slow MA so here we can see that the fast moving average dropped below the slow moving average so just replace the not with an O in your mind so on this value or at this position the fast moving average like this one should be below this value we can compare them with Creek and it is true even though the difference is just like 0.000001 but it's true so this is a true true condition and at this point the fast moving average should be above the slow moving average we don't even have to compare the values on the left because you can see it like you can clearly see it in the chart and this is working so there are several print statements now and this shows that the expert advisor is working but there are too many print statements so that's not really what we want we can change it by by using another control structure and this control structure will take care of the like or where it will restrict this this code in the antique function to only process it like once for every new bar and we can do this by using a static variable of type date/time daytime is just a very huge number pretty much and it's the number of seconds and that elapsed since January the 1st of 1970 so it's a pretty huge number and this can store time values because whether whatever whatever number you you you use for a daytime variable it will identify a specific second after the first January of 1970 so if you think about this and make sense and we can name this variable like time stamp and then we can oh please have a look at this it's a static variable so whenever the ontic is called for the first time it will be declared and when when it declared it has the value to 0 and for every other take this line will be ignored pretty much even though we still have the time stamp variable but if well it won't be initialized with the value 0 again so we can use another mmm they tailorable with the name time maybe and we can use the eye time function to period to receive the timestamp of the current tender so every candle has a different time stamp of course because they were like time is moving on and and every candle has a specific time and every candle has a specific number of second that elapsed since the first January of 1970 that identifies like this specific candor and oh you can print like the value of time if you want to know more about this and I can compare these both these two values by using an if statement again and I can say if time is not equal to or if timestamp is not equal to time I want to do all of this let me just bring this into a more beautiful order like this you should really work with this and like taps and everything to structure your code and to make it look more clean and and it's easier to like read these the different control structures in the structure of your code so if time is not equal to time or if time stamp is not equal to time I want to store the value of time in this time stamp and variable and just remember this time stamp variable will not become initialized again whenever this line here is processed so so the value in this time stamp variable will always be the same until it is changed in this line so yet this is pretty much a a simple control structure that ensures that all the code inside of this if statement is only processed once in the beginning of a new time stamp so if I compile this and run this same simulation again in the tester you receive that the print statement is only only printed once oh like this whenever there's a crossing of the moving averages so the first crossing was at 1745 like here the second one was at 18 like one one kid later on yeah you can't really see it but if you compare the values you will see that this is right and the next crossing is like I had 22 15 or 30 because we only like totally totally or and finished candidates to compare the moving averages so this is working and now we have an expert advisor that identifies the crossings of moving averages in more specific a fast and slow moving average what we want to do now is we want to open a position whenever these crossings appear or when they occur so we can use these control structures that we already have that identify the crossings and add some or code to it and what we can do is we can use a or we will have to import some code and you do this by writing import just outside of any function and then you do like this a smaller sign and then you write trade a slash and trade and then dot mqh and you close it with an greater sign oh it's expecting a file name oh no it's not import its include sorry that was my mistake if you include another file pretty much you receive or you get all the code that was written in this exact fire and you can pretty much expect exchange this line with all the code that is inside of the trade mqh file and you can fight the find the trade dot M create file if you go to include trade and trade mqh if we open it we can see that there was yeah plenty of code inside it's over 1000 and 600 lines and you could you could pretty much take all of this code and put it like here this would be the same as using this include yeah this include statement so we don't really have to know what's inside of this traded em creates fire but for the more advanced programmers just a class that makes working with orders like setting orders modifying orders closing trades that makes all this much more easier so we can use a object variable of this class by using C trade isn't data type pretty much and we have to choose a name like trade and if we do this and compile this we have an an object variable of this class called see trade it's a class you can find in the trade on mph file you can see it here this is very confusing if you don't have any programming experience so you should not really look at it without knowing something about object-oriented programming and yeah and and data types or classes pretty much so if you are not experienced you can just use it like this and think of it as a variable and if you are experienced and if you know about object-oriented programming you should have a closer look at the trade mqh file and yeah just read through the Ruby header and like look at the functions it provides and we can use this trade object to open positions as I already mentioned before and by using trade the variable dot and then you can choose one of these functions you see I'm the trade object provides many function that we make working with positions and orders were easy and we just want to open it by position so we write a trade or pipe and we open the the brackets here to provide some parameters so the function knows what kind of position we want to open first of all we have to provide a volume which is pretty much the lots they would want to open I will go with 0.01 then we have to provide a symbol we can use symbol again like with it here for the ima coy we're just were which will just add like euro US dollar for this this euro solid chart and then we have to provide a price if we want to buy we simply use the ask price and we can receive the ask price of the current symbol by using symbol in for double this is a function that how it's different oh it can return different information but the current symbol and we have to use symbol again to show which exact symbol we want to address and then we have to provide an identifier that is one of the identifiers of the enumeration symbol in Futaba and you can use symbol and ask or ask to get the ask price so this function here returns a double value as you can see here and we restore this double value in a double variable with the name asked and we can use this variable for by function here which is a member function of the trade object or yeah which we can just use by using this trade object variable and then we have to use a stop loss so we don't really have to use a stop loss but we can use a stop loss and we can just use a stop loss of like I don't know we can we can use a stop loss of like 100 points by using the ask price and subtract 100 times the value of one point for this symbol in food album symbol point a point is always the last digit or the smallest smallest value of the last digits digit of a of a symbol like for the euro US dollar it would be 0.00 they were one so the fifth digit was the smaller smallest value of the fifth digit and if you have an assembly with only three digits it would be 0.001 so this is like a a practice that you can use for different symbols without changing your whole code so we can use the SM and we can also add a take profit by simply copying this exchanging some words and adding the 102 or ask price of course not subtracting it and now we can use TP and we can we can provide a comment like this is a by trade this is a byte don't know maybe this comment is too long but we will see that later so this will open a bitrate and we can just copy all this and add it here for the sell side and we open trades at the bit cause it price if you want to say so we don't use symbol ass but similar bit instead and we add like these 100 points to the bit price to receive the SL and we subtract them to receive the tape profit then we don't want to buy it but sell of course so we change exchange to this and this and this okay just copy em the changes that are just it here and no we can start this whole expert divided again and see if it's working so let's wait for the first crossover okay there are several trades already I was just like too fast as always okay what you can see is that it is working we have we have a or whenever we have the we receive the information about the crossing like here we see that there is a trade open directly afterwards you can see it here when the fast moving average is rising involved is slow moving area we have a by trade and whenever the tribute or whenever the where where is it whenever the fast moving average is falling below the slow moving average we have a cell trait like you okay just just look at it maybe a little bit slower at your own PC and you can see that this this is working and yeah there is a tray there's a trade and everything is working you can see that and in the history there are restarts and this is a fully working expedite visor pretty much there are many many more things and that you could do and you can make it faster you can make it more secure by adding some code to the or linea to find open positions whenever your empty five terminal crashes or your computer has a shutdown so this is not a perfect expert advisor but it's an expert advisor that you can use to test and that you can use on a demo account to get first experiences with automated trading and you can also try to make some modifications in the code so the first thing you should always do when you're watching a programming tutorial you should always write all the code on your on your own PC and in your own editor to like get used to it and to make your brain understand how coding works and what you can do afterwards is you can modify this code you can like for example choose different periods here you can walk you can work with this like 400 at 140 slow moving average and a forty periods fast moving average you can change the mode to a EMA pretty much or you can use one EMA and one SMA you can use the high prices to get the average of the high prices and that yeah there are different different things you could do you can also change like the SL NTP values you want to use 200 points for the SL and 100 points for the TP and don't forget to compile it afterwards and then you can test it and you have a total different expertise um because it has a different behavior because the day just changed and there was a different like different protocol for this expert advisor to follow here you can see that oh wait a second I can speed it up a little bit you will see that the the losses will be higher than the winds because I changed the stop loss to the double-double amount and yeah even the expert advise us the the moving averages are different now because we have a you can see it on the left we have a 240 period slow moving average and a folly period fast moving average and the slow moving average is an EMA so it's an exponential movie moving average where the last values or the last 10 minutes how weighted even more than the first values so that's it pretty much we have a fifty line lines of code expert advice on that is working and you can use this to test a little bit and if you are interested in more programming tutorials just give this videos a thumbs up and subscribe to this channel toward to yet don't miss anything I can I can post more if I have time time for this and if you if you're really interested in this just let me know what you want to know about this expert advisers are all different things concerning or regarding empty four or five programming let me know about this in the comments and I hope that you had fun watching and following with this tutorial and I will see you next time bye
Info
Channel: René Balke
Views: 35,345
Rating: undefined out of 5
Keywords: Business, Trading, Programming, expert advisor, EA, Rene Balke, BM Trading, automated trading, forex trading, cfd trading, mt4, metatrader 4, mt5, metatrader 5, forex robot, robo trading, algotrading, forex, cfd, mql5 tutorial, simple moving average, algo trading, mt5 tutorial, mt5 course, programming for beginners, easy to learn, step by step, working expert advisor, mt5 ea, mt5 expert advisor
Id: T78Q7K3c11s
Channel Id: undefined
Length: 55min 14sec (3314 seconds)
Published: Wed Jul 10 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.