Master MQL5 Programming (Complete All In One Guide)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
this video will be the only mq5 tutorial you will ever need stop searching for gurus that can tell you what the next best strategy is start taking responsibility for your own trading so what I will do in this video is I will explain everything you need to know about mql5 programming I will give you all the basics you learn about variables data types data structures control structures everything you need to know also I will put time stamps in the video so make sure that if you have questions later on you'll always come back rewatch this specific passage in this video also make sure to watch the whole video this is really important because I will base the progress in this video on the previous minutes so if you just skip around on your first visit here on this video you will probably not take away anything from it make sure to watch it from the beginning to the end make sure to copy every line of code that I will show you later on on make sure to type it on your own I won't post the code I want you to learn something because in the long run this is the only way to really benefit from automated trading and to become independent save this video share it with friends and also make sure to subscribe to the channel if you want to learn more about automated training so why do I know that this video video will be beneficial for you I'm R biker I'm an automated programmer or I'm an aut at Trader and I program for over seven years now I've done thousands of EAS multiple hundreds of freelancing jobs for customers so I kind of know a little bit about mqa 5 programming also I'm trading for over s years automated completely automated now and I'm profitable so I hope that I can give you a little bit Insight of insight in this world into this world of automated trading so this is what this video is about if you're watching I guarantee at the end of the video you will be a better programmer a better Trader and overall you will have a much better position when it comes to this rise of who benefits on the financial markets so invest a little bit of time start learning and enjoy the process so let us now jump right into the action and start with the actual programming part so first of all let me explain to you what the goal of our automated trading strategy or automated expert advisor should be so we will be working with the ATR indicator but you can apply this later on like all the programming Basics and the concept of an expert advisor to pretty much every indicator you want and you can also use the basics to write pretty much whatever program you like but in this case we work with the ATR indicator so if you're not familiar with this ATR indicator and you never used it let me show you quickly how to find it in your meter Trader 5 um if you go to the Navigator which you can open by clicking on view Navigator there you should find the indicators folder and if you open this you will sh you should find examples and if you go here um whoops not this one you should find the ATR indicator if you drag and drop it on your chart you can see this um indicator has one input one value and yeah you can of course change the colors and everything but we won't go into this detail and we will just apply this to the chart and I did it already so now I have two of them but you can see this is indeed the indicator so what does this indicator do the indicator ATR means average true range and it will just um it is just a average of the last X candles in this case or by default it's 14 candles of the last 14 bars so if you see if the last 14 bars for example in this period here if they are rather small the ATR value will decrease because the average size of the last 14 candles is small but if the candles start to become bigger like here in this area you can see the ATR indicators going up because if there are more big candles in the last 14 candles of course the average of these candles like the average size will also be bigger and what we want to do is we want to compare the ATR value to the size of one specific candle which will be our trigger candle for example I highlighted or just put some errors here for some possible entry scenarios that this expert advisor should identify and trade so we can see here this candle where my Crosshair is right now this is a really big candle like from open to close these are 300 points and at this point also the ATR is really low in value because the previous candles were rather small so if we have a um candle then that is by a factor x um bigger than the ATR value then we want to entry uh into the direction or enter the trade into the direction of this big candle means if we have a really big short candle for example here red candle with the beginning of the next bar we want to enter a short trade and really often you can see for example here this trade or this candle would go down like for at least 100 points from the beginning so really often the previous move will just continue after such a big candle and I highlighted some more candles for example here we had some um some big candles and we had a small r value before so we can see if this would be a trigger candle again 300 points this would be a nice down move and for example here again we had another really huge um red candle and price was coming down afterwards and also we can of course see this for um green candles here we had a really big green candle and the ATR was low so this would trigger a trade potentially and this would would have been a great trade so I mean of course I can show you one or two examples but not all of these trades would be winning trades not all of these trades would be losing trades and actually in this video it's not really about about the specific strategy that we will create but it's about you learning how to write code in the metat trader 5 and this is why I want to teach you uh everything you need to know to get your first programs up and running so let's jump into the actual programming now to write code in the metat trader or for for every software pretty much you need a development environment and in the metat trader 5 we have a integrated development environment which is in short IDE so you can click on this IDE button here in the Navigator bar if it's visible if you do not see it you can also go to tools and then meta quotes language editor if you click on this it should automatically open The Meta quotes language editor and this is the program or the tool or the editor pretty much that we will use to write code in let me delete some of these um programs that I've wrote before and let's open a new one I mean for you you will probably not see any program here if you never worked with um programs or if you never brote code for the meter Trader for you this could look blank but we can change this quickly go to the upper left corner of the meter editor and there you should find this new button if you click it you can select expert advisor usually it's pre-selected template and then you just click on next now you can choose a name for your program and we can say ATR um breakout uh YouTube for example this would be my name for the program and then you can have an author a link and everything but this is not important for the actual program then we go click on next and we click on next again and then just finish and this you can see this will create a new new file it's an mq file and this is our brand new expert advisor you will also find this file in the Navigator of your meta editor on the left side if you open the experts folder so here we should find the ATR breakout YouTube program now which is again a mq5 file so if we now go to the metat trader if we go back to the metat trader we can also find the Navigator and the metat trader we used this before to apply the ATR indicator to the chart and here if we go back we will also be able to open the expert advisor folder but here we do not find our ATR breakout YouTube program and this is because right now our program is just a text file it's just a text pretty much I mean of course there are some colors and everything but the meta Trader is not able to run this code because it is just a text file that is easy to read for us as a programmer but not for the computer so there's one important progress or process in any programming pretty much which is the compilation and in The Meta editor you will find in the Navigator bar at the top you will find this compile button so if I click this we will see some action down here in the tool box so let me click this and you can see ATR breakout. mq file will be compiled and the code is generated which kind of means that it generates not really the code but it generates a executable file which is a E5 file then and if we now go back to the metat trader 5 now the ATR breakout YouTube program is visible and we could drag and drop this on a chart isn't this great so we can apply our program to a chart already and then it is running on the chart and this is what we are doing now you can see here this is the name name the version is 1.0 the copyright is met quotes whatever and um yeah we can just click on okay down here and now you can see in the upper right corner of your chart it should say the name of the program with this little head sign next to it this means that this specific program is now running on this specific chart which is a EUR US dollar one hour chart so if we go back to our code we can also find the version ID here which is 1.0 is part of the code also the link and the copyright is also part of the code so for example I could go ahead and change this copyright to 20 23 and uh add my name here instead of M quote limited also I can use any website here for example ian. prbm trading. de which is my website and if I compile the program again with these changes and if I double click on this little head here in the start you will see okay it is not changing this is um only changing if we run the program again so remove it from the chart with a right click and remove and then run ATR breakout again on the chart okay and it's still not here this is actually a buck in the meter Trader but if you start the meter Trader again uh let me do this real quickly if you start the me trade again then we will see the updated value so there we are let's get our ATR breakout YouTube program running again and now you can see there's the copyright and it's saying re bka and if I click on it it doesn't open the Met quads platform or web page but it opens my website so this is how we can work with these properties um but as you maybe already imagine these properties they're not important for the program itself so they are just a information for everyone who's using the program um you could use the properties but you could also delete them for now let's just keep them at the very top of our program um also oh what I just deleted is a comment so these gray lines here they are comments which means that these comments are also not really part of the program so if you compile the program or the code these comments will be completely ignored by the compiler so they are not part of the executable they are just here in the text file because they could hold some information for the programmer but we can just delete them and it will not change anything for the executable file so if I just delete all of these gray lines there's no problem at all and now we only have these three basic functions left so I could go ahead and add some comments Myself by just adding these two slash signs and then I can write this is a comment and now this is a comment which is completely ignored when I compile the program which is just there for me as a programmer to tell me for example what a function does or what a specific part of the code does you can also write multi-line comments like this one slash one star this is the start of um uh of the comment and then you can have blah blah blop and this is the end for example and everything between these um two signs here is then a multi-line comment so you can write as many lines as you want and all of these lines are ignored completely by the compiler but yeah let's not use these comments too much because again they don't really change the program and what we want to do is work with a automated um strategy here so what do we want to do oh first of all let's talk about what we have left here now since we deleted all of these comments we have three functions left and these three functions they are so-called event handling functions usually they start with on and then there is some specific event name that will trigger this function for example the first function here is the so-called on inet function and um yeah this is the uninit function a function consists consist of the function signature which is this first line here and the signature is made of the return type of the function which is int or integer in this case the function name which is on in it and the function parameters in this case we do not have any function parameters we will get into details later on and I will explain exactly what integer variables or the integer data type is and what parameters are but for now it's just important that that these event handling functions are called automatically by the metat trader so whenever a specific event occurs the program will automatically execute this function and by executing a function it means that everything inside of the body of the oninit function will become executed the body of a function is always wrapped by these small curly brackets here so you can see um whoops Sala this is the start of the body and this is the end of the body everything in between these two curly brackets here is the body of the oninit function so whatever we we write here will be executed when this function is called so let's add one more function fun inside of this function which will be the print function so so if you write print like this with a capital letter P and then just print and then you open the parentheses of this function because every function has these brackets these round brackets after the function name this is how the program knows that it is a function and it can have parameters for example this print function has a parameter here we can for example say we want to print a specific um sentence for example we can print this is the on init function function like this so what did we just do here we called it a function inside of the body of the uninit function which means whenever the uninit function is called this function will be executed because it's part of the body of the init function right and this print function is a function that does exactly what the name says it prints something something in the experts Journal of your metat Trader 5 so if we go back to the metat trader 5 and open the toolbox by pressing contrl t or by going to view toolbox you will see that there is um we don't need this there is this toolbox and you probably know this one there are are the trades and everything but you also see the history and also the experts tab down here if you click on this experts tab we would see everything what this program here prints in the experts tab so if I compile the program now we would see this is the on init function printed here in the expert stop and this is happening because the program is still active in the chart and whenever we compile the program it is initialized again in the chart there are other events that call this on init function for example if I remove the program from the chart and if I then search for it again in the Navigator if I activate it again on the chart the oninit function will be called because it's initialized again also make sure to have a look at the source here the source always tells us what specific program called or printed this message so this time it was printed from the at breakout YouTube program which is currently running in the EUR US dollar one hour chart this is important because if I change the time frame for example to M15 you can see the unended function is called again but this time if we have a look at the source again it's called from the M15 chart because it's initialized in this chart and this will trigger the oninit function again so so much for the oninit function um also we will have a return type here which means that the function returns something but let's get not into this detail for now we will talk about this later on when we talk about functions also let me delete these comments here because we don't really need them because we know at this point that these curly brackets always wrap the body of a function and let's have a look at the second function here which is the ond init function again we will have the signature here which is this line which consists of the return type which is in this Cas case void and void is a really specific return type because it kind of means nothing the function just doesn't return anything it is called and then it's over the function is called on D in it this is the name of the function and this time we of course have these brackets again the round brackets after the function name which means it's a function but this time there's actually something uh written in these round brackets and it's a parameter this parameter is a constant parameter which is just a modifier which means that this variable cannot be changed and then there is um the actual variable data type which is integer and we'll get to this in a second but let's have a look at the third word here in the in the in the brackets which is reason and this reason is the name of this specific V variable parameter that is part asked if when this function is called so whenever the on D init function is called and again this is an event handling function so it's called by the program itself or by the metat trader whenever this onet function is called the body is executed and we see the body here so we can add a print statement again let's say print let's say this is the on init function um and the reason is and then um wew write um these um quotation marks they are these quotation marks are really important because what we add here is a text um value and again I will explain this in a second but for now just copy what I'm writing here and then for the print function we can concatenate multiple um values by using a simple comma so we'll write this is the on D function and the reason is and here we will just add the reason and this is the exact name of this variable so we will print whatever is inside of this variable and then another semicolon uh sorry comma and then U we will add these three points this is of course optional you don't have to do this but um just to show you that you can add multiple values here in inside of this print function and then again always make sure to close these round brackets for the parameter list of the function and then end the statement with a uh semicolon um oh yeah like this this will end the the the call of the print function so if we compile this and go back to our program we can now see if I write click and remove the program from the chart it would say this is um the on dnet function and the reason is one what happens if I run the program on the chart again first of all of course it will print this is the on init function because this function is called and if I change the time frame now we can see the on in function is called on the old time frame which was M15 first and then the unun function is called on the new time frame and uh have a look at the reason the reason is now three not one anymore and by reading the reason we can see if it's necessary for our program um what specific reason caused the de initialization and you can read about the reason in the mql 5 reference the mql5 reference is what you can see if you click on help and mql 5 reference this is a really important tool if you want to write programs for the metat Trader 5 um because here you can read everything about this programming language pretty much so for example if you go here to index and if you just write a function name for example on D init you ref find a entry for the on init function and this pretty much explains everything about this specific function for example we will have a list of all the reasons here and this is great isn't it because we learned that the reason one is reason remove which makes sense because this reason was printed when I removed the program from the chart and then we have value three which is chart change and again this was uh printed when I changed the chart so everything makes sense now right so this is how you can work with the mq5 reference just open it whenever you want learn something about a function and read the specific entry for it so now we only have one function left which is the ontick function and this will completely spam a lot of code a lot of prints in the uh experts TP if I now add this is the on tick function here as a text so let's just do this quickly and compile the program again let's go back to the metat trader and you can see this is really print a lot of um yes this is just spamming the whole expert stuff and this is because the ontick function as the function named uh is named it will be called on every single tick which means if there is a price change so a tick this will call the ontick function so yeah if you have a print statement like this in the ontick function it will be really messy in the experts tub so let me delete this quickly and let's compile the program again so if we just keep it like this uh the experts TB is not messed up and we can now go to the next step which is um yeah starting to write our actual strategy so since we are working with an indicator which is the ATR indicator a good starting point for your program is to tell your program what specific indicator you are working with and there is a uh Concept in mql5 programming which is where working with indicator handles and if we go here outside of our um event handling functions at the very top pretty much of our program and if we create a variable which will be a integer variable we can name this variable handle ATR and then we end the line with a semicolon if we compile this no error everything's fine so what did we just do we created a new variable so this is a really simple process pretty much because we just write two words and a semicolon but what happens inside of the like inside of your PC of your machine so when you run a program and in the code you declare a whoops a variable like this it means that whenever the program is processing this specific line of code it will create or block a uh a a space in the in the memory of your PC for example in the in the random access memory of your PC it will block a specific amount of bytes for this variable here and this is why variable data types are important because different variable data types or data types in general take up a different amount of space or bytes in your random access memory and you you can think about this uh it like this like for example um 1 3 four 5 six seven eight this um eight eight bits are one bite so for example we have um this is one bite now and in your random access memory of your PC you will just have a lot of bits so there are just a lot of bits concatenated um yeah together pretty much and if we have eight bits it's a bite and if we have eight bits again uh and again and again these would be four bytes and now let's have a look look at the reference again so you will see why I'm explaining all of this so let's go to help M5 reference or if you want to do it quickly you can go inside of the of the word uh or the the the name of the function or whatever you want to search for and click on F1 on your keyboard and this will open the mql5 reference for the specific entry already so you can see um the integer variable is explained here or the data type it consists of four bytes which are 32 bits and this is exactly what we can see here so this is the space inside of your random access memory of your PC that will be um uh reserved for a integer variable because we just declared a integer variable so the program knows at some point we want to store a value in this variable so we already need to save 32 bits or four bytes in the random access memory of our PC and the name of a variable is pretty much like for us it's the name of a variable which we will use to address this variable but for the computer it will just point to this specific starting point in the random access memory where this variable is located and since it will then know where the variable is located it can then look at the data type which is int so it knows from this point on we will need 32 bits or four bytes and this is our integer variable or the value um that is then stored or we can address using this specific variable and this is how variables work in computer programming pretty much and also in metat Trader programming and for example this integer data type it can hold values like two or three or uh 43 or whatever or if we have a look at the reference again in fact it can hold all the values from minus 2 uh billion whatever to the maximum of yeah you can see it here so these are the boundaries in which we can um choose any value pretty much and store it inside of a integer variable this is which we can use the integer variable data type for so for example there are some more data types that could be interesting for programming in the metat trader file so let me explain the most important data types to you quickly so we learned about int already the integer data type can um hold values like two or three or something like this or also something like this then we have the double data type which could be something like 2.23 or this point uh 32 or minus 32222 so you can see the difference here is that now we can have a decimal point so double um the double data type can it also holds numbers but there can be numbers with a decimal point and you cannot store this in an integer variable this would not work but if you st it in a double variable everything's fine the program knows how to handle this and and if we have a look at the reference again here you can see if we let's find the double data type you can see real types double or float is also a variable data type but it's not really used often in programming or in metat Trader programming so not let's not get into detail here but the double data type it Con or it will take up eight bytes now so if we have a look at the ram again uh the the the random access memory of your PC uh while we are able to store a integer variable in this like space for the double variable we would need the double amount of space so this space would be reserved if we declare a double variable somewhere so you can see this is why we have different data types because different data types take up different space in the random access memory and also the bits that are um located or that are updated in this specific space space are inter interpreted differently depending on the on the actual data type and that's that's really cool actually and this is why data types are so important so besides um integer and double we have some more um uh of these uh data types that are often used in um in programming so we also have the Bool data type which is true or false so actually it's not an example because we can only have true or false stored in the Boolean uh variable or data type and this is the smallest um data type because it will only hold U wait can we see it yeah it's only one byte large and I mean it could actually be one bit because it's just um true or false which is just one or zero but of course it's it's one bite here so it um it all makes makes sense so for example um if we declare a bite uh sorry a a a a Boolean variable this is uh the amount of space that's that's reserved in your Random Access Memory because it's just such a such a small value and can only be true or false so let's jump on with the next um uh data type so for example we learned about integer variables already but we also have the the data type um long which is pretty similar to a integer data type because we can also store the these values in a long variable but if we have a look at the um at the at the at the reference here you can see a long is8 bytes and a in was only four bytes and if you have a look at the minimum and maximum value and compare the values of a integer data type and the long data type you can see the long data type can be way bigger and this is pretty much the only difference it's also a number without a decimal point this is important important but long values can be way bigger for example this would be a possible long value but this could not be stored in a integer variable because it's just too big this the the the space in the random access memory like this is our integer variable and this value it's just too big it doesn't fit so you need four more bytes and this is why we have different data types also if we would have a even bigger positive number we could use the unsigned long data type which is U or U long and the only difference is in a Long uh data type variable we could store negative values like this but in a um unsigned long um wait let me print this here uh we can store even bigger values but they have to be positive because this u means un signed so there cannot be a negative or a minus in front of this number so yeah so these are some important um uh data types and we also have the string data type which is a little bit different because it cannot be a number uh like this but it's always a text that is stored inside of a string variable or which is a string uh string value and texts in programming in general and also in met trator programming they usually wrapped with these quotation marks and so this is a text would be a valid string value but also this and also um the name of your doc which is Peter probably I don't know could be a string value but it's important that it's wrapped by these um um quotation marks and this is why we always use these quotation marks here for the print um function when we wanted to print a text because this value here is a string value and this is also a string value and the reason is not wrapped in um quotation marks because it's not a string value it's actually a variable which is a integer value and yeah this is when why you want to use strings for texts for example these whoops these properties up here they are all string values they are all texts also this I mean it says 1.0 which could be a number but since it is wrapped by quotation marks the computer sees this at a as a text so for the computer this is not a number this is a text because it's wrapped in these quotation marks and it's um yeah this way it is made a string value okay so this is um these are the most basic um data types which can also be used for variables then to say the PC um how much space we need in the random ma memory right because if we would not have data types um the PC would not know like how how much space should I reserve for for this variable how should I interpret this variable because the PC would not know what's going on but since we have these data types and we can use them for variable declarations the PC will always know what specific value to to expect in such a variable and um like where it's located because this will point to the Loc and then how big it is so now let let's use this variable we could do something like this which would store the value two inside of this variable but this of course not really what we want because we want to create a handle for our ATR indicator and store it in this uh variable so in our oninit function now in the body of our oninit function we will say handle ATR and you can see if we just write the first three or four letters it will automatically suggest us this variable because the program knows that this variable was declared before and it is somewhere it's existing somewhere so we can use this handle ATR variable and we can put a value inside of this variable for example like this this would work it just means um whatever value is stored at this position in the random access memory should be over written with two so now we will have two stored at this position in the random X memory but but of course as I said we don't want two we want the handle for the ATR indicator and this is why we will use the I ATR function or uh indicator function so you can see if I write this iatr function we will already see the signature of this specific function so you can see the function will return a integer value and this is where we will have a look at return values for functions because now it's interesting and important important to us whenever you call a function and this function has a return value when the function is processed afterwards it will give you exactly one value back and this is the return value we will have a look at this in more detail but let's have a look at the second part here I mean of course then there's the name of the function which is iatr but then we have the parameter list and this is a little bit more complex now because we have three parameters separated by comma so if we open the parenthesis here we will see the first parameter that is requested is the symbol name and here we will use the symbol name which is Euro US dollar so we could go ahead oh and also you can see this is requested as a string value and that's cool because we know that string values are always wrapped in uh quotation marks so we can add something like this and that's totally fine because it will be EUR US dollar as a string value because it's wrapped in quotation marks right and then we can go to the second parameter and as soon as we write this comma it will automatically suggest a list of all the possible options that we have because the second parameter is um the the time frame because right now all of these three parameters they just have one purpose we want to tell the PC the metat trader what specific indicator we want to work with so by calling the iatr function the program knows we are using the ATR indicator of of course and by providing EUR US dollar it knows we want to use the EUR US dollar chart and then as a second one a second parameter we want to use the time frame which could be H1 which is the 1 hour chart this one so now the program Nots we want the OS dollar ATR in the uh one hour chart and then the last one is the periods and this is of course if we have a look at the inputs for the ATR this is the ATR period and these three parameters are enough to explain to the computer exactly what specific ATR we want to work with so after uh providing all of these three values we can then close the list of these parameters and end the line with a semicolon and if we compile no problem everything's working so now what what do we do here let's have a look at the reference again you can see the iatr function Returns the handle of the average true range indicator it only has one buffer okay here we go get to this later on then we will see again explanation of the parameters so whenever you have the question about the parameters you can read about it here also we can see that um for example for the period there's a link so we can click on enum time frames and we can see all the possible values here so for example period AG one this is what we used it means 1 hour chart so everything is explained so you cannot really go wrong here you can just read the reference and then of course the value for the average and period of the indicator so what is this return value what does this do the it it will return the handle of a specified technical indicator so so what is a handle um let me explain the the the concept of a handle in the in the metat trader 5 the handle can be seen as a like the meter Trader five it has or when expert advisers are called the metat trader 5 has a specific point in the memory of your PC reserved for descriptions of indicators and this handle pretty much just points to this specific point in the memory of your PC that holds the description for this indicator which means when we call the iatr function the computer will go into the random access memory of your PC and again the random access memory always looks like this there are a lot of bits and bites right so this could be a bite another bite blah blah blah blah so you will just have a lot of bits and bites and then when we call the iatr function at one specific point in your Random Access Memory all of these bytes are filled so that it will describe this specific indicator and I cannot not explain to you how exactly the values will look like inside of these bytes but what I know is that the computer is able to um like read from these specific bites and then it will know what like how the indicator looks like because this is the um definition or the the the the the um characteristics of this indicator stored at this specific position and the handle it just points to this position so the handle is pretty much just the address of this indicator description in the random access memory so the the program will from now on whenever we use this handle and when we use a function for example that uses this handle it will know okay this is a indicator handle let me search for the position in the memory of the PC because there I will find the the um explanation of this indicator right so this is this is so great and this handle like it I can tell you the value the value will be 10 because the first indicator that you um that you that you um get the handle from in any program has the value 10 but this is not like I mean of course the integer value stored in this variable is 10 but if you tell the meter Trader that it should be interpreted as a handle it will know that it will search in the random access memory at the position where the handle for this 10 is stored and then it will find this specific indicator so this is the concept of Handles in metat Trader 5 and this is so great because whenever we want to um use this indicator we don't have to like um uh pass around the complete description for this indicator we can just pass around the handle and it's just 10 so it's just so easy to pass pass around this indicator pretty much and yeah if we compile this we can now go ahead and use this handle like in the next step we can already use this to get the values for this um ATR indicator so let's jump to our Onin function because we want to do this step in every single tick here we will call another function and this function is called copy buffer and the word buffer we heard this before if we read the um mq5 reference here correctly for the iatr it says it only has one buffer what does this mean so indicators IM met Trader 5 they have buffers and these buffers hold the values for every single bar so for example here if you have a look at the data window of your metat Traer 5 if you don't see it go to view data window um if you have a look at the data window you would see if the ATR is attached to the Chart you will have this ATR line or column or whatever here line is cor and then or row and then you can just choose your Crosshair or your mouse and go or or hover over the bars and you can see the value changes for every single bar because the ATR value is different for every single bar and this is the buffer what you can see in the data window for this specific indicator and this is the only buffer because the the indicator just has one line so this is and and in the buffer every single value for every single bar in the chart for this indicator is stored so what we want to do now in our program is read this buffer because then we will get the values for this indicator at a specific bar so for example we can use this copy buffer function because it will copy the values from an indicator buffer and we store it in an in a variable so if we open the um parenthe es with a parameter list here for a copy buffer function you can see the first parameter is actually a indicator handle so this is why I explained everything before we can now just use our handle here and pass it to the function as the first parameter so this function it will now know that this handle should be interpreted or this variable should be interpreted as a indicator handle so it will find the definition for this indicator it will know what indicator we're talking about so if we have a more complex program and if we have three handles we can just pass the handle for the indicator that we need and since the handle points to the description of this indicator the program or the metat trailer will always know what specific indicator we want to work with right and this is super super cool and um yeah so the second parameter here is the buffer number and the buffer numbers start at zero so the first buffer has index zero and since our ATR it only has one buffer of course it will be zero then we have the starting position so since this buffer of the ATR as I explained it will hold a lot of values like for every single bar we will have to tell our program what specific values we need and this is where the starting point is interesting because starting points start at the very right side at the last candle in the chart and this would be index zero the candle to the left of this one is index one the candle to the left of this one is index two this is three this is four this is five this is six this is seven and so on and so on so every single bar has its own index and if there's a new bar created in the chart Everything Changes by one index because then the new bar is in index zero this would be index one this would be 2 3 4 and so on and so on so what we want to do now is we want to say we want to get the value for the last bar in the chart so not the current bar but the previous bar which would be index one for the starting position then we have a count like from this point on here we can Define how many bars we want to read from the buffer of this indicator we could say for example 10 then we would would get all the bars up to this one we could say five we would get all the bars up to this one but we could also say one if we just want the value for this specific bar this is what we want to do so again one will be provided as a value for the count parameter and then the last parameter it looks a little bit weird because it's a double variable pretty much but it's not the actual variable it's a reference to a double array boom mindblowing this sounds super complex but it's not let me explain it to you in a second so what are arrays so until now we learned that we can have double values right this is what we already know um value this could hold 23 Dot 32 you can see I can compile no problem no biggie this works but what happens if we want to store multiple double values we could say we create another double variable which needs a second name of course and we can store something inside of this variable but this copy buffer function it can potentially copy 10,000 values from the handle or from the indicator so it would be a little bit complex to create 10,000 double variables 10,000 nobody wants to do this so there's a concept in programming which is called arrays or fields which means we just create one array and we make sure that the program knows it's an array by writing these squared brackets after the uh variable name and then with a semicolon we can end the de ation so this works no error no problem this is now an array and this array it can hold one value for example and now we can address the values inside of this array we could say array which is just the name here at index zero because indexing starts at zero always even if we only have one value it's index zero and we can say inside of this index zero in this array we want to place this value and it works but what happens if we have five values like this if we have five values we could say at index three I want to store this at index 2 I want to store this at index yeah so if we do it like this and if we compile we can now say for example print array at index Z and it will print this as you can see here 2332 what happens if we print index two and we print this because this is at index two inside of this array um yeah so how are arrays stored in the random access memory of your PC so let's have a look at the randomx memory again let's get some um uh some bits and bites going here yeah somehow like this I don't know we have a lot of lot of bytes in the randomx memory and the array like this variable it pretty much just points to the very first bite inside of the random access memory where all of these values are stored and then from this point on we will just take up the space for for example zero H for example one two or five double values so if we declared like this this array name if you want to say so just points to the first um bite inside of the random access memory where all of these values are stored because since we know it's five uh there will be stored five values of the type double we know we need eight bytes for all of these five double um values so we need 8 * 5 40 bytes so by declaring the array like this the computer knows okay we will need 40 bytes of space let me get some 40 bytes of space in the random access memory and let's point to the first by so whenever we use this array we know what's going on and yeah this is pretty much what arrays are and how they are used in in programming and you can declare an array like this when you uh hard code pretty much the size of this array but you could also go ahead and say like this you want a dynamic array what does this mean this means that of course the PC does not know how big this array might be later on so this means it will first of all just um reserve some space but then later on if the size of this array is changed it might have to relocate the array array in the random access memory if it's necessary but yeah this is just like not really this is just background knowledge that you don't need for programming but what I like to do is explain everything so you actually know what the program is doing so now since we have this array and we could name this ATR for example because this is where we want to store the ATR values and now since we have this array we can provide it here as a parameter for the copy buffer function so if we do it like this and compile boom everything's good program is happy we are happy so oh and we don't need this so what do we do here we create an array of type double we use the copy buffer function and actually this copy buffer function yeah you can read it here it's a good explanation it will return a value but it's just the amount of copied data so I mean if we print this it will be one because we want one value count one to be stored inside of the at array so if we print this it will just print one but what happen yeah I mean we don't really need to work with a return type here because it doesn't give us a lot of information what is more interesting for us is the value inside of this ATR um array so let's print the ATR index zero make sure to choose zero here because we only have one value inside of this array if we compile this you can see it prints a ATR value and this is really cool because it will print the value at the last bar which will be here in the in the data window and you can compare the values of course it's rounded in the data window but it's exactly the value at the last bar and this is how to work with indicators so yeah so let's get rid of the print statement and this is the first important step whenever you want to write a indicator expert advisor first of all you have to get your handle up and running this is what we do in the on init function usually because you don't have to do this on every tick oh here you just have to do this if for example the program is activated or if the time frame is changed or something else happens then in the onti function usually you use the copy buffer function and you can always use this copy buffer function when you have a handle and want the values from this indicator then you just have to provide like um the buffer where you want to start how many values you want to have and where you want to store them so this is how we did this and this is how you should do it whenever you write expert advisor with a indicator so there's one thing that I want to change here in the on init because we kind of hardcoded the symbol here which means if we want to run the program in USD Japanese Yen we would have to change this and there's one easy thing that you can do to make this automatic so we could go to the ATR function again and read the explanation here for the symbol and it says the null value means the current chart symbol so if we go here and instead of Eur US dollar or US dollar jbcn we just um print null we can compile there's no program and now whenever we run the program in any chart it will automatically take the symbol from this specific chart and initialize this um indicator handle for this specific symbol so that's a good way to automate this step here okay so next up is getting the candle size of the last candle so this is what we will then want to compare with the ATR value right so how do we get the last candle size there are different ways in um mq 5 program I will show you the easiest way so to get the candle size and we will focus on the focus uh focus on the candle body I would say uh we will need to get the open and the close of the last candle and good thing is in mq5 programming we have predefined functions for almost everything so also for this purpose and since these values and um before I will explain it to you you can think about this for a second on your own um what kind of data type do we need to store price data in it so we know integer we know double we know long whatever string of course doesn't really make sense but think about it what data type do we need and always um remember that there is a decimal point in the prices so of course we will need a double data type for this so what we want to do is we want to create um uh two um variables actually let's start with with the open here and we will call this open so we declare a double variable which we call open and we will directly initialize it so this is the Declaration pretty much um where we declare a variable this is also fine but we can also initialize it right away and here we'll use the iopen function the iopen function is a great function that you will use often in your mql5 programming Journey because this function if we just have a look at the reference here quickly it will return the open price of a specific bar so it makes sense that the return type of this function is of type double of course because as we figured out out prices are double type um values and the three parameters here are to identify what specific bar we will need and maybe you remember remember this string symbol and enam time frames from the ATR function here this is a typical Concept in metat Trader 5 programming where you just Define the symbol and the time frame so here we will of course go with null and period H1 again maybe then we have the shift value and this is similar to the uh starting position or starting value for the copy buffer function the um uh algorithm or the idea is the same like we start at the very right side of the chart this would be shift value zero and the next bar is one then comes 2 3 4 five again and again so indexing of the bars is not always unfortunately but most of the time it is like this so the the current or the latest bar is index zero and then it just adds up um the further you look back so let's go with one here because we get the last value for the HR here for the last bar so we will also get the open and the close for the last bar and that's it this will store the open price of the last bar in this double variable and um yeah it kind of makes sense that we also have the I close function which is completely the same but it will give us the close price of the specified bar we could also do this for uh for the highs and for the lows so whenever you need any price of any bar or also the timestamp of a bar you can use any of these functions and that's really great and it's really handy in in a lot of different cases so if we compile this and I can quickly print this for you so you can see that these are indeed the prices of the last bar if we have a look at the uh terminal here again uh yeah you can see it prints out and if we have a look at the data window like for open and close here um it will or it should be uh uh the the the program should print these values and yes is indeed what is printed for the last bar of course values are rounded in the data window but this is what's happening here okay so let's erase the print statement again and let's move on so this be before we start having a look at control structures to figure out if we have a signal I want to introduce you to input variables input variables are always declared on a global scale which means they're outside of any function usually you will declare them at the top right now we have one Global variable for this program which is the handle for the ATR and when it's Global it means that it can be used everywhere in the program so you can use it here you can use it here you can use it here so you can use Global variables in every single function because it is declared on the largest on the most global scale there's this concept of scales or um yeah I think or uh concept of scale or um excess yeah I don't know how to pronounce it but I will explain it to you so this is on a global scale so we can use it in any function there's a difference if we declare the variable inside of a body of a um function for example because this is now a local variable this one lives only inside of this scope I think scope is the right word but um yeah you and you know what I mean if you declare something in curly brackets like this double variable it's only available in these curly brackets for example if I want to change the head handle ATR value here it works there's no problem everything's fine but if I try to change the open value in some other function here for example we get an error because open is an Undeclared identifier which means it's not available or not known in this function and this is because open is not declared on a global scale or scope um I think scope is the right word correct me if I'm wrong and then um we can only use it um since open is a local variable we can only use it here but if I want to change it here there's no problem at all because here open is known and it's it's available but not in other functions because it's just declared inside of these curly brackets so this is this mechanism okay so now we learned what Global variables are what local variable are are now let's have a look at input variables input variables are always Global variables and you declare them usually at the very top of your program and you use them if you have some variable or um some some value that should be changed or could be changed by the user of the program so the Declaration of a input variable is really really easy you just go to the very top of your program like a global variable you write something like um um input this is the so-called modifier for the input variables you just add this input in front of the variable declaration and that's pretty much it and then we can go ahead and say um enum time frames for example and then we go and say time frame which is the name for this variable and then we can say for example the initial value should be period H1 so what's happening here this might confuse you a bit this input is what I explained before it just says this variable should be a input variable and how this looks like is what I will show you in a second then we have the data type for this variable and this is enum time frames which is confusing to you now understandable because we don't know this yet but if you go inside of this enamore time frames everything has to be in capital letters of course like this and press F1 or you go to help and mq5 reference you can see this is a eneration a so-called eneration this is why it starts with enamore time frames and this is a predefined eneration so this is part of the overall mql5 framework so we can directly have access to this eneration and here you can see all the values that can be stored pretty much in a um enum time frames variable so this is something that makes working with time frames easier because we can now use values or predefined const or IDs like period H1 or period H4 or M1 so you can see all the time frames are available now easily because the program knows that this time frame variable is of type inum time frames actually you could also go ahead and say 60 which would work oh no it would not work okay so they changed this somehow so you can also only use um period H1 and this really makes it easy to work with uh time frames because then you know in this variable we can only store time frames but like in the um in the in the in the uh background of this programming stuff enam time frames is pretty much just built like an integer and they this variable will hold values and these values are then transformed to the time frame but yeah I don't want to over complicate things this is what enumerations are and the cool thing thing is that this time frame variable is now since since this is an input variable it's available to the user of the program so if you go to your chart where the at breakout program is running and you double click this head you would see we don't uh we we no no longer only have this common TP here but we will also find inputs and here this is so cool we will find the name for our input variable and we can change the value and since it's an eneration we have this beautiful dropdown menu which is super convenient for the user and if the user now goes ahead and changes this value it will automatically change the value inside of the input variable in the code that's so cool because now we can use this time frame variable whenever we want to use a time frame for example here for the ATR function because you can see the second parameter is of type enam time frames and now everything makes makes sense right and we can also use it here because here we also work with a time frame so we know that when the user changes something or whole program will adapt to this change and work with a new time frame from this point on also you might have some uh inputs that you also want to add like for example if you're working with indicators I usually recommend to make all of the indicator properties as input variables so we can say in input int and now we don't have a eneration as a data type but a simple integer variable we can say something like 8r periods and 14 so this is a normal Declaration of a integer variable with an initialization directly and since the input modifier stands in front of it and it is a global variable this is a input variable now and we can use it everywhere in our code and also the user is able to change this this easily that's the concept of input variables and I think it's a really beautiful and easy concept let's now have a look at the actual um signals and for getting signals we will need a so-called con control structure so until now we just added more and more code in the body of uh of functions the thing is this is great but whenever a function is called all of this code will become executed so we do not really have any way to um make decisions in our program but when we want to open positions for example it is crucial that we do not open positions on every single tick but first of all we for example want to check some conditions so we can make sure that positions are only open if we really want this and for this purpose we will need control structures and probably the easiest control structure is a simple if statement and if statements do exactly what I explained before they check conditions or they help you to check conditions so what we want to do is we want to write if here which is just like the code word so the PC knows there is an if statement and then in round brackets we will have to write a condition and this condition is in most cases some comparison some um greater smaller than comparison like any condition that will result into true or false so the condition always has to be either true or false and this will decide how we further process this if statement so let's build our condition here since we have the ATR and the open and the close here we will go ahead and check first of all we want to check if um the open is greater than or smaller than the close because this means the candle is green right so this could be a condition so we have in round brackets this a condition and we usually use logical operators like this and the most common operators are um smaller than greater than and then equal this is equal you always write two of these equal signs because because only one equid side sign would say that you want to assign a value to something but two equid signs means that you want to compare something and you can of course always say smaller or equal and greater or equal so these are some of the logical operators that we can use to uh compare um values and then um we also have if we have multi mple conditions we can combine them using this or and this nend so for example we could say if open is smaller than close so this is our first condition which will just check if the value stored in the open variable is smaller than the value stored in the closed variable which means it's a green candle right and then we also want to check a second condition so we can combine two conditions using this end operator here we also want to combine if um close minus open and we know that close is is the bigger value because this is what we checked before we want to check if close minus open put this in Brackets because we want to multiply this with a factor um we can say trigger factor for example and you you might realize we don't know this yet so we will make this a input variable so our input variable will be named trigger factor I would suggest a double variable here so we can choose any value and we could say 2.5 for example so this will be our trigger Factor also note that whenever I declare a input variable I do this with a capital letter in the beginning and when I declare normal like Global or local variables I declare them with a small letter in the beginning and then from this point on it's um chaml case either way so if you have a variable name that consist of two words you would just write it like this like um every upcoming word after the first one has a capital letter so this is what CH case is in programming so now we have this trigger factor and we can check if the distance from the open to the close multiplied with the trigger Factor oh no this was was not really correct we want to check if this is greater than and then we don't really need the brackets anymore like the distance of this candle is greater than ATR um the ATR value which is still stored in our array at index zero U multiplied with the trigger Factor so we want to check if we have a multiple of the ATR in the last candle and if this is true then we would add the body of this if statement directly after the um closing round bracket of the condition so what do we have here we have a condition that checks two different conditions if you want to say so so we check if the open price of the last bar is smaller than the close price to figure out it's a green candle then we figure out if close minus open because the close price above the open if this distance like the the the the candle size of the body of the candle is greater than the ATR value at this specific candle multiplied with our input factor and if this is true this is a bu signal and that's it it's really this easy and maybe you realize that we use these curly brackets until now we only knew curly brackets for the body of functions like here in this case we also use curly brackets because if statements also have a body so um whenever you have a body it's usually wrapped with these curly brackets and this body of the if statement is only executed if this condition is true and this is why if statements are um uh control structures because they control the flow of your code you can have conditions checked and only only if the condition is true we will enter the body here so for example if you enter if you want to open a position you usually check some condition before so you don't open positions with every single tick and yeah make sure to use these logical operators uh for the conditions of your um if statement so for example you can combine multiple conditions using this end and you could say if I only want one of these conditions to be true in order to enter the body of the if statement I will use this or operator but in this case of course this doesn't really make sense because we want both conditions to be true so let me erase this this quickly and if we compile this and add a print statement here by signal something like this and now we can actually search for signals already so let's make a simple test go to your metat Trader 5 then um go to view strategy tester and you can also press control and r instead and let me delete or close the toolbox here and then you go to overview in the strategy tester select visualize then then in the experts dropdown menu you choose the expert name that you just wrote ATR breakout YouTube is it for me then you can choose a symbol that you want to test a time frame that you want to test I will go with H1 because this is my input also and then you can test a time period I will just go with the current year here um like 2023 and um yeah it's just it's just for testing to see if the program works and the rest is not really important for us um if you want to test like later on you should use every tick based on real tcks because it's the most accurate method but um yeah for just testing the signals now these things do not really matter just make sure that this visual mode um tick checkbox here is ticked then you will also find the inputs here in the tester so you could change this here but we will go with the default settings for now to just check if the program is running when you then click Start in the lower right corner of the tester it will open a separate window with the visual mode of this strategy test and you can see it will now take historical data in the selected period for me starting in the beginning of 2023 and it will run the selected program in this case the ATR program in the tester and we can also see the ATR and everything and you you would see the H1 candles are now displayed here in the chart and we also have a journal so if we speed up the process here we we will see if there's a really big candle like this one and there is a signal we should see it printed but since this is a short candle and we didn't add the short signals yet we don't get a print message but here okay we have some signals this is great so the last signal was um uh 18 uh 59 so in this bar here we had a Buy Signal because this bar had a size of 700 points and the ATR was just 270 points or 260 so 260 times 2.5 which is our input for the trigger Factor should be below 700 whatever so this would be a input and this would actually be a good input uh or entry because the market proceeds to go into this direction okay so let's add the short signals here we can just copy this complete block like select it copy and then paste it here when you copy things make sure to be really careful because often you forget to change something and then it kind of messes up the code so it's easier or safer to just write it again because this will prevent errors often but here we want to check if the open price of the last bar is above the Clos price which means it's a red bar and then we check the open minus close of course because open is now the bigger value if this is greater than ATR multipli with the trigger factor and in this case it is a sell signal so if we compile again we should see that if we run the same test again just go back to the strategy tester start it again and now we should see that also um the sale signals are um printed in the in the in the journal right so let's wait until this test is loaded and yeah there this was the big red bar that I showed to you before and now this will also give us the S signal isn't this great so this is what control structures are for usually you have if statements and um Loops we will have a look at Loops later on you always use Loops if you want to process something multiple times and we will use this when we add a trailing stop later on but first of all let me show you one more thing for the if statements if you have multiple if statements following each other and only one of these if statements can be true because the conditions exclude each other you can also concatenate multiple if statements like this so you can write an else if and this will make the only difference that the program checks this if statement first because it comes first in the code and if this is true it will execute the body of this if statement and it will not look at this part because there's an else if but if this condition is false it will still look at this part because the first condition was false and this can in some occasions be useful to speed up your program a little bit but yeah nowadays with the speed of modern computers it doesn't really make a lot of difference I think um but it still can add some um it can look make your code look cleaner because this is now a block and you really know that only one condition can be true also please realize that whenever I put my curly brackets usually I like to put the opening curly bracket directly after the the um closing of the round bracket and then my um closing curly bracket um like aligned with the if statement or with a controll structure like I do it here and then everything inside of the body should be moved to the right using the tabulator button on your keyboard this will make everything really clear lean and tidy so you know everything that's moved to the right here and we could have more code like this and even more code and more and you can see since this block is moved completely to the right we know that everything here is inside of the body of this if statement this adds so much more um uh yeah understanding for you when you look at your code later on and makes it look much cleaner also personally I like to do it for the functions also so normally I write my opening brackets for functions and closing brackets like this and yeah you can decide if you also want to do it like this it's just what I do because it kind of saves some lines in the code makes it a little bit shorter but it's personal preference so there's no wrong no right you could also go ahead and do it like this this makes absolutely no sense because it's super ugly but it still works and it the the program doesn't really care you can have as many spaces and braks in between um but this is personally my my preferred style okay so since we have the the the signals now as a next thing we want to do is open positions so to open positions you will use the order send function or you could use the order send function but if we have a look at the order send function in the reference there's a really big entry you will use these um um um structures here that are super complex and that you would have to fill and I don't want to get you through this whole struggle and there's a really easy and quick way to um open positions uh we we we can use another file that is available in your medat Trader 5 terminal so you shouldn't worry about this um and we can include this file at the top of our program um or this is where you usually want to do this so after or below the properties write this hashtag and then write include which means we want to include another file and then write in spiky brackets which is just a smaller sign and then a greater sign in the end you write trade SL trade. mq and end it with a greater sign or another spiky bracket like this if we compile this you can see there's something going on in the toolbox down here previously we only saw Ed breakout YouTube mq5 program was compiled but now a lot of other files are compiled and this is because we included another separate file and we can find this file in the Navigator of our tester um meta editor sorry so if you go to the Navigator you will find a include folder if you open it you will find a trade folder which is the first part of path here and in this trade folder you will find a trade. mq file which is this so this is just the path to a file that we want to include and if we open this file we can see it's a really big file it's a little bit confusing right uh in the beginning we just started programming but the good thing is we don't have to understand everything here not yet you don't have to understand this let me explain this easily for you so this is a so-called class a class is pretty much just a um a structure a data structure that holds variables and functions and we can use this class let me close this this might be confusing we will use this class to have access to all of these predefined functions and variables so what we can do by including this trade. mq file and the C trade class we can have access to a lot of different functions that we do not have to write on our own so for example what the class does this specific C trade class does it works with complex functions like this order send function and it will break down everything for us so we will have access to all of these functions but in a much much much easier easier way so let me show you how it's done since we included this file now we now have access to this C trade class so we will declare another global variable and we will name it oh it is of type c trade and this is exactly the data type of this um class or the the name of the class not the data type really um and then we can declare a variable of this type which we call trade for example I mean you can choose any name something like this whatever you like it's just the name and then we can end the line with a semicolon and if we compile you can see no error everything's good what we did here is essentially we declared a variable but in this case it's not a normal variable with a simple data type but it's a variable which is a so-called object variable sounds a little bit confusing but in fact it's just a variable of type c trade which means that this trade variable can now be used or trade object if you hear this term somewhere it can now be used to have access to all or most of the functions in this C trade class and this is so cool I mean you might be confused now but let me show you how to use the C trade class for easy position opening and that's when you will understand why we did this so whenever you open positions or you want to open positions in your program just include the file create a variable like this and then you can use this variable to open positions so go into your code where you want to open positions and write trade which is the name of your variable here and then a point operator directly following the name of the variable and then you can see we already get a suggestion of a lot of different functions that we can now use completely for free we didn't have to use I have to write any of these functions so we can say buy for example because we want to buy Here and Now from now on everything's like like always it's just a normal function call we can open the the the parameters of this function and you can see the list that you can provide and now we can say how much lots for example we want to open with this position and here again I I recommend to make this a input variable um I usually put this at the top and it's a double variable of course because it can be a value with a decimal point so this is all Lots variable now global variable input variable nothing special and we can use it here to open this specific amount of lots for byy position so so we have some more um functions uh function parameters here but you can see these function parameters they have a so-called default value you can see this because after the function uh the parameter name sorry which is here in this case symbol there is an equal sign and there is null default uh assigned by default also for the next parameter price there's zero by default assigned then SL is also zero TP is also zero and comment is null so you can see all of these parameters have default values so we can stop the parameter list after lots and this means that the function will just use the default values it will not work if we don't provide the Lots because Lots as you can see here it doesn't have a default value so this is what we will have to provide but if we do it like this we can open by positions and let's let's just copy this quickly to also open sale positions with a lot size if there's a sale signal so let's see what's going on if we compile this now and make another test go back to your tester in the media Trader click on start and see what the program is doing now and this is so cool because by just including this C trade class or this file and using the C trade class we can now open positions so quickly so you can see here there's the S signal and directly we will open a position isn't this is beautiful and actually we do not only open one position but we will open a position with every single tick and this is not really cool but it's what our program currently looks like because you can see all of this stuff is currently located in the onti function so we will do this with every single tick and this is something which you don't want this is really a bad idea because it can mess up your whole account so what you want to do I mean you don't have to be afraid of this there an easy fix for this and I will show it to you now we will create another Global variable for this let's call it bar total and this bars total will be used now later on so first of all let's initialize this in the oninit function we will use the return value of the IAS function which has two parameters and we know these two parameters so let's just use null again and time frame so this will give us us the total amount of bars it has a return value of type integer it will return the total amount of bars in a specific chart so let's have a look at our chart this chart it might have I don't know 100,000 bars maybe so this is the value that will will be stored in this bars total variable and now in the ontick function at the very beginning we want to calculate the Ias function again and get the amount of uh bars again everything's the same pretty much but but we start in the bath variable and this one is a local variable in the ont function because we only need it here so now we have the B variable and the total the B total variable these two variables are completely different B total is global bar is local and what we want to do is we want to compare these two values and if if we compare something we need a control structure right and this is what where where our if statement comes back so we will write if B total is unequal oh and this is another operator that you can use so this would be equal and exclamation mark and one uh equal sign is unequal so it will compare two values and if these two values are different then the condition is true right so we want to check if these two values are not the same because it means that there's a new bar because this Bar's variable is calculated on every single tick while this bar toal variable is not calculated on every single tick so this B total variable will keep its value as long as it is changed manually by us so we will check if bars total is unequal bars and if this is true we will update the value in the bar total variable which means that this only happens once at the beginning of a new bar because then the bar's value will be higher than the bar's total value and this is when we want to enter the body of this if statement so let's think about what we want to add inside of the body of our if statement of course we want to add all of this code here because we want to calculate the HR only once only once we want to calculate the high uh the open and the close of the last bar because these values won't change anyways in the current bar because the last bar is always the same right so we you can select everything here and then just press the tabulator button on your keyboard and it will move everything to the right by three spaces and then after this block here make sure to go to the next line whoops and then at this position close the body of this if statement and you can see if you move your cursor after the opening bracket for the body of this if statement here it will also highlight the closing bracket for this if statement and you can see now all of this alignment stuff like moving stuff to the right and everything makes sense because you know everything that is aligned like this here it's in the body of this if statement and everything that is even further to the right is in the body of this if statement so you can build multiple if statements around each other and only like the scope is always getting smaller and smaller so everything that inside of this if statement is only processed if this is true and what's inside here is only processed if this is true and what's inside here is only processed if this is true so you can see the scope is always getting smaller and smaller so yeah it's more likely to reach this piece of code than this and it's still more likely to reach this piece of code than this or this so this is why you use control structures to structure your code and if we compile the program again you can see no errors everything should be fine here just make sure to to not like forget to close brackets or open and close brackets and align everything and make sure you add the semicolons if necessary and yeah but then if you compile and do the same test again same data same period same everything but now we made sure that the the code is only processed not with every single tick but only once per bar and this will be really important because now if there's the sell signal we only see one position and this is exactly what we wanted right so you can see in the journal it now only prints once that there's a s signal and then we will open exactly one position and you can see here also this is done by the C trade class that we included and this is why this is so convenient to use this class so let's speed this up a little bit let's wait for some more signals uh there's some B signals and then we will see more signals probably yeah so you can see there are some signals going on so our program is working just fine so next we should now have a look at how to make the position opening a little bit more um useful so we will work maybe with a TP with the SL and we will move everything to a separate function to make it even cleaner in the source code but first let's have a look at adding these um uh uh trade parameters like the buy uh the the TP the stop loss and everything so let's first of all have a let's have a look at the list again that is requested for these buy and sell functions so you can see the next parameter is what we can easily provide it's the symol and here we will just go with null again because we just want to um use the chart s usually then the next parameter is the price and this is our entry or open price so prices again always double values make sense right so we will create a variable which we call entry or this is what I usually call it and we will use the return value of symbol info double and then you can see here in the signature it returns a double value and the first one is the symbol name again and I think we can use null here and the second one is a identifier and you can see as soon as we get to the second parameter we see a list of all the vable identifiers already so what I want to use here is simple ask so let's close the parameter list for this function let's end the line with a semicolon and let's have a look at this function uh so symbol info double um okay it says we cannot use null let's let's still try this um but what this function does is it will return a property of a specified symbol so you can see the second one is the property ID and if we have a look at this link here you can see all of the IDS so in this case for example we can get the bit and the ask price easily by using symbol uncore ask and symbol uncore bit this is what we did here we used the ask price so let's now use this entry here as a um parameter for our by function right so um yeah also what I would recommend is that when you work with um um values like this that should be used for opening modifying positions it's always a good idea to round these values so there are no unexpected unwanted um digits after the decimal point and the easiest way to do so is using the normalized double function because you can see this will round a floating Point number to a specific ified accurancy accuracy and you can see there are two parameters requested the double value that you want to round and the amount of digits after the decimal point that you round this value to and then the rounded value is returned in the return value so what we do here we just use the entry round it to the amount of digits for this symbol so it would be five in this case for EUR US dollar but this might change if we use it for USD Japan for example because USD japanes only is three so there's a quick fix for this in programming in the metat trader five programming you can use underscore digits here so what does this do let's have a look at the reference an underscore digits is a variable a system variable that is predefined by the meter Trader and will always hold the accuracy of the chart symbol so it's the amount of digits after the decimal point for whatever chart the program is running in so we can easily use this and in this case for example for EUR US dollar it would hold the value five for USD Japanese it would be three for some ETFs or cfds like the do Jones it would be two usually so you can see see adjust to the chart symbol so if we compile this and run it again um it should not really change something but I want to see if we can use um the entry like this or if we can use null here because this was not printed in the reference so I will have to check this so we don't get any problems here so let's um get until uh the first Buy Signal so we will see that this is printed and yeah looks like we can use null and we get the correct values I think um yeah this is fine also if you are not able to use null here you can can always use underscore symbol which is a little bit similar to underscore digits since underscore digits gives um the amount of digits after the decimal point for the current chart symbol the underscore symbol will give us the name of the current chart symbol and this is of course a string um yeah you can see like like here the symbol contains the symbol name of the current chart symbol this is string system variable okay so now we um calculated the entry and we can now use this entry variable to calculate the TP for example so let's create another variable and we will calculate the TP by using the entry and adding let's say 100 points and here we will see another system variable so you can see this will hold the point value for the current chart symbol and the point value is always the smallest possible price change in a symbol like for example for yri doar it would be 0.0000001 this would be one point for EUR US dollar like this and this would be one point for EUR uh USD Japanese Yen because it only has um three digits after the decimal point and if we multiply this value with 100 it's equal this so if we add this to the open price of our position we get the TP price which is again a price so when you provide the TP here for the buy and sell function in the SL it's not it's not the distance that is requested but it's really a fixed price where the TP and SL should be located so we can calculate the TP like this but of course hardcoding 100 is really not a good programming habit I would say so it's really much better to say we want to have TP points here as a input variable so let's go to the top in input int TP points and here we can see 100 200 whatever and also let me get sure that we also see the SL points as a input variable maybe 100 200 500 you can use whatever you want right um so let's use 200 for both of these for now so we will use the SL points now to calculate the SL so uh Double SL is equal to entry minus SL points multiply with point so process is really similar also what I want to do is round these uh values using the normalized double function and of course we round the SL and the TP so now since we calculated all of these values we can now use the variables SL and TP here for our buy and sell function like this if we compile this and run the program we should now see that all all of our buy positions have a TP and a SL so this will make sure that these functions are closed at some point and they don't just stay alive for for as long as possible so let's wait sell positions do not have TP and SL we will add this code in a second but buy positions there we go have a TP and ASL so they will be closed at some point um yeah I mean the TP and L is a little bit too close as we can see here but you can see also in the history there's always a TP and ASL and yeah let's maybe make the values a little bit bigger also we can increase the default values here I think because they were like just to small so if we go with some bigger values and go use these values in the tester let's just test this again and then we can see like actually where these values are placed um like the levels are placed for buy trades so let's rate for the first Buy trade there it is and beautiful trade let's have a look at this this is a Buy trade and we can see it was opened here so from this position on we have around yeah no not around but exactly like 1,000 points from the position opening ask price and 500 points for the stop loss and these levels are only also visible in the in the in the trade overview here sorry like this so you can see TP and SL are assigned for this trade and now we can wait yeah until the TP in this case luckily was hit so let's add this code for the sale positions so they also have the chance to be profitable or negative if they H the stop loss like the easiest way would to be to just copy everything but again I would suggest that you just write it again so you will have a better routine so let's go with a double entry and make sure to like we have to declare this variable again because this double v uh double entry and double TP and Double SL variable they are declared in the scope of this if statement in the body of this if statement so all of these variables they are only alive in the body of this if statement and once the body is processed and left these variables will also be erased from the random access memory of your PC see directly this is why yeah on Lower scope or smaller scope the variables are deleted earlier again and on the global scope for example they would stay alive for the whole runtime of your program that's also a big difference with the where you define your variables so here we like for example if I want to change entry here now it doesn't work because it's not known here yet it's only available here in the scope so let's go here and declare it again for this reason so symbol info double in this case we will use symbol bit because sell positions are always opened at the bid price and then let's round this this is completely the same because the amount of digits is the same for buy and sell positions of course then we have the TP here the calculation is a little bit differ because different because we have to substract the TP points from the entry but the rest again completely the same we will round this make sure that there are no unwanted digits after the decimal point and then we will go and do this stuff for the SL in this case it has to be SL points Above So plus above the entry and then we will just go and round this value like this and then we can just use these variables here and add them for the buy and uh like for the sell um sell positions and there's one last parameter for the buy and sell function which is the comment and it is a string value so we can add a string comment here we could write something like um ATR uh breakout as a comment you can also make this a input variable this is what I like to do I would um open or create a um variable which I name commentary of and we will just add this as a last parameter for the buy and sell function and then of course we will have to declare this variable here as a string input variable which could have the default value ATR breakout like this if we compile this and run the program again we should now see that yeah we get this input variable here and all of our buy and sell positions they should now have TPS stop losses and the comment so let's fast forward until we see the first position so you can see sell position now also has ATP and we can of course check the TP and stop loss level if they are correct but yeah I mean they are correct 100 points TP 500 Point stop loss and there's also the comment available now which is ATR backout so you can see this is working just as we wanted it to work but now what what is happening to our on function you can see the ontic function is becoming a little bit big and a little bit messy if you want to say so it's not like you can look at it and you will directly understand what's going on because there are just so many lines right now and whenever you have something like opening a position um you can move this to a separate function and there are different reasons why you use functions for example if you have a task that is a like a isolated task that is only there to do one thing like opening a buy or sell position and this task is kind of self-explanatory or self-explaining in this case you can move the code for this specific task to a separate function also there's a second reason why you would use functions in your source code if you have something some piece of code that you use multiple times at different positions in your code you will also want to move this to a separate function so let's now create our first function together so when we write new functions we do this uh outside of any other function so right now we always worked in some of these event handling functions that are automatically called by the system but we still have the chance to create our own functions that we can then call whenever we feel the need to so let's get H go at the very bottom of our program let's give it some space and then let's create our own function and we learned about the function signature already so this is what we need to Define first for our own function so we need a return type can be int can be double can be string can be void which is nothing so let's go with void void first now we can choose a function name and we will go with or I usually go with execute by as a function name for the function that opens a by position and then a function always needs the parameter list and this parameter list can be empty like this but we need to add these two round brackets so if we compile it like this it will not really work because there's the unexpected end of program because a function definition or when we Define a function we also have to add the budy like this body again in curly brackets as usual so this is our fun function now so what do we see here we have a function which is called execute by it has a return type void and it has no parameters and we could add a parameter here for example we could say the parameter should be int oh wait let's have a look at what happens when we call this function and I want to do some examples here so you really understand what's going on so let's call the function in the oninit uh function so you always have to call your custom functions in some event handling functions because otherwise they will never become executed because these event handling functions they are automatically called by the metat trader if there's a specific event but there's no specific event in the metat trader for the execute by function right so we will have to call this explicitly to be processed so in our on init function for example we could say X execute by just call the function by its name and then add the parameter list even if it's empty you always have to add this and then end the line with the semicolon this will call the execute by function so let's compile this and see what's happening so let's go back to our toolbox in our metat Trader 5 by pressing control t or clicking view toolbox and here we can see in the expert Journal this is the on init function is printed but yeah I don't see anything about our particular execute by function this is because the function has an empty body but what happens if we add something here like um this is the execute by function like this if we compile this again we will now see this is the execute by function because it is called in the uninit function so the uninit function when the uninit function is called it will do this it will do this and then it would call the on byun execute by function because it's part of the on init function and in the execute by function we see this is the execute by function also we could have a parameter here for example int number like any number it doesn't really matter or double uh another number and we could print these numbers um we could say print the number is and then we go print the number and we can say print um the second number is another number and then we could also do some operations here like mathematical stuff like the sum is uh number number plus another number so you can work with these variables inside of the body of the execute by like there are normal variables if we compile this we get an error though because now it says execute by function has a wrong parameter count if we double click this aror it should move us up here to this line where the execute by function is C because now when we open the parameter list here the parenthesis we see that two parameters are requested a number is an integer for example five and another number can be a double number so 2.2 for example so if we compile again error is gone and now the output is really different because it says this is the execute by function the number is five the second number is 2.2 and the sum is 7.2 so this is um yeah how functions can be used and I could say I want to do this multiple times also with 10 and 11.54 or also with one and two or also with uh 10 and 100 so you can see this is the power of um custom functions I can also call this in the on D inet function um with some stuff and um yeah so you can see if I compile this like the in the on tick and in the on init all of these execute stuff things are called just like just play around with this and you will understand how it works and this is the power of having custom functions because we don't have to add this code like the whole code here multiple times in our on um init and on the init function we can just call the function multiple times so let's get rid of the code in the on in it and on in it and let's act add the actual code for our um for a function or maybe we can also let's say uh we I I will tell you how to work with a return value here we could say we want a double return value just exchange void with double and then we can say we want to return the sum so if I compile it like this it will not work because now since we defined a return value we always have to provide a return value so at the end of your function you will write return and then you can say whatever you want to return for example I want to return number multiplied with another number like this if I compile this we will see if I call the execute by um execute by we still need two numbers and now it has a return value so I can store this return value in a variable and I can print it like return value is and then I print the value right so if I compile this it will give me the information that the return value is 44 isn't this cool I think it is oh and yeah this is um something that I um kind of messed up the return value is 44 because the program now assumes that this is a um uh a integer value so you can typ cast this to a double value by saying to the computer that this is indeed or should be treated as a double value this is so-called type casting but I won't get into detail but oh wait a second 2.2 oh we don't oh sorry forget everything I said we don't need this it's it's all fine uh since we have one um double value already yeah you can see like the calculation is is working sometimes when you do mathematical operations you will see some unexpected digit after the decimal point like this like the six at the very end it's just like because computers are designed like this and sometimes they will create some number that is that doesn't really make sense to you but it is there and this is why also we work with this normalized double if we want actual accurate price data but yeah let me delete this again in the on init and this was just to explain how the return type works but in this case I think we don't even need this and also we do not need any parameters I just wanted to make sure that you understand what you can do with functions but here all I want to do in this execute by function is I want to take the code that is responsible for opening a by position I want to cut it from here I want to paste it in the execute by function wait uh P yeah I want to paste it here and then of course I want to move it a little bit to the left you can do this by pressing tabulator but holding your shift button on the keyboard and this will then be the execute by function if we compile this everything's working just fine and now instead of having all of this up here we can just say execute by in this this will make the whole on tick function so much shorter so much cleaner and I will do the same thing cutting this for the uh cell stuff and I would say void execute cell with no parameters I will add the block here I will move it a little bit to the left because um it's not in such a small scope it's just inside of the body of this um function and if we compile this and at the execute cell here where we want to execute the cell signal you can see the ontick function is now again really small clean and by reading the function name we already know what the function is doing so it's really explaining itself just by the name so we can just be confident and sure that whenever we call this function it will just process this code and open it by position so this is when you can use functions and to show you that that everything is still working just like before I will do another test so let's go back to the tester and yeah let's just run the same test and all of this what we just did is first of all I wanted to explain functions to you but second of all I wanted to make the ontick function clean and easy to understand and this should always be the aim for any expert advisor to just have a good and clean source code so you can see the program is still working just like before but now we are using these functions to make everything a little bit more um yeah little bit cleaner and tidy inside of the on TI function so now as a last big function we want to add the trailing stop loss right so if we have positions and they're going into our favor we want to Trail the stop loss so what we will learn is how to modify positions how to calculate stop losses and everything and to to really do this we first of all have to understand how positions are managed in the meter Trader five so let me run another test for this demonstration here let me get this test um sped up a little bit so we can see some of these positions so you can see at some point sometimes we will have one position open or multiple positions open at the same time and actually I want to see a um moment where we have multiple positions active at the same time and uh maybe I should yeah let let me just increase the TP and SL points for this purpose so it's easier to catch this moment uh so maybe let's go with 2,000 for TP and SL points and since these are input variables we can just change them quickly no no big deal so now since we as a user changed the inputs we would see a larger dist for TP and so here we will now see multiple positions are open at the same time so whenever we have multiple positions open at the same time there are in our toolbox in the trade window and these positions they all have a specific index for example the first position would be index zero this would be index one and this would be index two if we would have more positions we would have index 3 4 5 6 7 like it's always like this first position has index zero then one then two and um this always works like if we see only one position we only have index zero if we have two we have index zero and index one again and as always like the top position is index zero followed by one by two 3 4 5 6 7 8 so why am I explaining this we will need this indexing now when we use our first Loop in this program so let's go back to our program and remember remember this indexing stuff so we will go to the ontick function and now we go outside of this if statement because we want the on uh the the trading stop to be processed with every single tick and what we want to do now is we want to use our first Loop a loop is used if you want to do something multiple times so here we want to process the trailing stop for every potential position that might be open at the time could be only one position could be two could be three could be 10 so so we will use for which is like the code word for the for Loop similar to if and for Loops by the way are control structures so they control the flow of your program so we will write four and then we need round brackets again to initialize or for Loop and here we have three different um sections the first section is like the section that is or the code that is processed once when the for Loop is started so to say most of the time you will see a definition of a variable usually it is a integer variable called I which will have a value like zero for example and then like for now just copy what I'm writing here then you write a semicolon and then you go on to the second part of this for Loop uh initialization process here we have the main condition of this for Loop so the for Loop it will check a specific condition multiple times the condition is just what we used before it can be set up using like logical operators and stuff and values and variables so what we want to do is we check if this variable I if it is smaller than the total amount of positions in this account and the total amount of positions is what we can get using the positions total function it's a system function predefined we don't have to write it but it will give us the total amount of open positions as a integer value and as I explained this before it can be one can be two can be three so as long as I is smaller than the total amount of positions we're good to go then we have a third section here which is the the code that is processed after every Loop run and here we write I is equal I + one because we want to increase I by one then we end these this set of conditions and operations by closing um the round bracket here with another round bracket and then we add the body of this for Loop so if we compile first of all we should not get any errors so now let's have a look at what's going on here if we just print I and say maybe this is the loop and I is and then we print the value I so let's let's just see what's going on for now so let's run another test just like we did before and let's see what is going on now since we added this to the onti function so in the journal we should see the print statement at some point right but we don't see anything okay let's speed up let's see what happens if we see the first position there is the first position so you can see now we start to enter the body of this for Loop and we print this is the loop and I is zero why is this happening let's have a look at this again like this line here is processed with every tick but not this line because this is in the body of the ifs uh of the for Loop so what happens when when the program reaches this line first of all the program realizes okay this is a for loop I have to be ready to check out these three things here these three statements or whatever you want to call it first of all I will have a look at this precondition or the first statement so I will do whatever is written here so first of all the program will create a new variable which is called I and it will has it will have the first value zero then as a second step the computer will have a look at the second section here so it will check if I is smaller than positions total and since at this point in our test positions total is one since we have one position right this condition is completely true because zero which is s in I is smaller than one which is the return value of positions total so since this is true the program will not go here next but instead after checking the main condition the program or the computer will go here and execute everything that is inside of the body of the for Loop and here we will therefore print this print statement and we'll say or we'll print the value I and this is what's going on here in the test right now and then after doing this the program will go here and will process whatever written here and in this case we will increase I by one and now I is one and then it will check the main condition again so we don't do this again this this is what we only do once when we initialize the for Loop but we will check this condition every time before we process the body of the loop so then we will check I smaller positions total again but since we increased I by One I is now uh one and one is not smaller than one so at this point the main condition is false and then we directly leave the for Loop and go on with the rest of the code so so this is how for Loops are processed so let's go on in our test what happens if I just speed up the test and go to the point where we see another position open so what's happening now you can assume it already properly so you can see now we have two or actually three positions so positions total will now give us the value three and in the journal we will see this is the loop and I is zero and then again this is the loop in is1 and this is the loop in is2 because now the the the process is the same like we go and enter the loop we will initialize I with zero we will check if I is smaller than positions total but this time positions total is three and not one so after processing the body for the first time and print this is the loop and I is zero we will then increase I by one now I is one and then we check if one is smaller than three which is still true so now since the positions total kind of changed the condition is true more often than it was before so we will print this again with i1 being one and then we will increase it again so I is two which is still a true condition then we will print I with a value of two then we will increase I again now it is three and now it is no longer smaller than positions total so we will end the loop so this is why we use this for Loop concept to Loop through every single position and since these positions also have the index zero all the way to three as I tried to explain before so this is zero this is one this is three we can now use this position index to get the ticket of the position so we can get the ticket using the position get ticket function which is a predefined function and you can see the only requested parameter is the position index now everything makes sense because we can just provide I as the position index and this will give us the position ticket you can see it in the reference this will give us the ticket of a position with a specified index and the return value is unsigned long this is what we learned at the very beginning when we talked about data types long variables are pretty much like integer variables but they can be way bigger and unsigned long just means it can only be positive so we have to create a unsigned long variable which is called position ticket and then we will initialize it or add the sore the value the return value of this position get ticket um function inside of this uh variable and yeah now we have access to the position ticket and also there's one more thing because this will automatically select the position what does this mean it means we have access to the position get double position get integer and position get string function which we can use now like let me give you an example we can say print position ticket and then we can say we also want to print um um the position open price so we can say position position price open is equal to position get double and we can only do this because we selected a position before using this function because the position get double function will always get you a information from the currently selected position and when we go here into the parameters of the position get double function you can already see what parameters are available here for example the open price of the position like if you have a look at this in the reference you can of course also have a look at all of these uh things here and the explanation so we can say position price open is the open price for this position so now oh wait I messed up something forgot to close this um here and I forgot to add the comma but if I do it like this compile and if we run the same test again this is now really cool because we will see that we will print all of the position tickets and all of the open prices for these positions now so let's get the first position so you can see oh we have three position oh wait oh yeah the ticket number is two of this position and the open price is 1.055 one4 and this is indeed what is printed here and if we see multiple positions now we can see all of these positions are printed so all of the position position ticket numbers are printed and also the open prices are printed so this is really cool I think so we will now use this concept of course not to only print the open price but we want to use this to just um process the trailing stop so for this purpose let's first of all get the stop loss of the open position position get double position stop loss and it's always the same concept if you want to get a double information from a currently selected position you can just use the position get double function for this so now what we want to do next is we want to check if and now we do something else now we do if position get integer because now we want a integer value and we say position get uh sorry position type if this is equal to position type by then we want to do something so this is again an if statement so we are checking a condition and only if this condition is true we want to enter the body and of course we will also check if it is not a buy position then it can be a sell position this is what we want to do here position type cell so what did I just do I called the position get integer function it's really similar to to the position get double function but it will return a integer value so if we have a look at this uh eneration here we can have a look at all the all the possible options and you can see one of these options is position type this is the one that we used and if you have a look at the description it says it's the position type and if you have a look at the type it is enum position type if we click on this link we will see all of the available position types and there are only two it can be either a by position or a sell position and this is exactly what I checked here I checked if the return typee is position type type buy or if it is position type sell so we are essentially just checking if the currently selected position is a buy or a sell position and this is important because now I want to check next if the current price and for this reason let me get the um bit and the ask price here wait we can do it here um like let's get the bit price it's symbol info double symbol symbol bit we did this before and then let's get the ask price symbol info double symbol symbol asked I don't have to explain anything we learned this before and now I want to check oh no let's first of all create some input variables because we want to say we want to have a TSL trailing stoploss trigger TSL trigger points which could be like 200 and then we want to have TSA points which will then be the distance from the current price where we want to put the stop loss so with these two inputs in place we can now use them here first of all I want to check if the current bit price is above the position open price of a buy position plus the TSL trigger points multiplied with a point value and we learned this before it's the smallest possible price change only if this is true we want to enter this if statements body and then we want to calculate the new stop loss we do so by saying bit minus TSA points which is the other input that we just created and I hope that I don't have to explain a lot at this point I'm just just doing simple stuff like de declaring variables uh putting values inside of these variables doing some mathematical operations but we explained this before when we um calculate the TP and stop loss for the initial position opening so then we should again it's always a good habit to round these values and now what I want to do is I want to check if this new calculated stop loss if it's bigger than the old one so I want to check if stop loss is greater than this position stop loss position stop loss and if this is true then I want to modify the stop loss and we can modify a position by using the trade dot position modify function this is coming from the C trade object and we can use it or C trade class and we can use it with our trade variable here so if we have a look at the parameters we need the position ticket this is okay because we have the position ticket already so let's just use this position ticket then we need the stop loss and this is the new stop loss which we want to use from now on so let's use stop loss and then the TP and here since we don't want to change this we will just use the old TP like this so if we do it like this this will process the trailing stop for the buy positions if necessary and we can do the same thing for sale position so we want to check if the asked price is below the position open price of the sale position minus TSL trigger points multiplied with point if this is true we will enter the body of this if statement check another if statement directly and we could combine h no sorry no we don't check another if statement immediately we will just first of all calculate the the stop loss now so we go ask plus TSL points multipli with point and then we round this and then we check if this new stop loss is smaller than the position stop loss and for sell positions this is important you also have to check if position stop loss is equal to zero because if there is no stop loss at all then the value in the position stop loss will be zero because if you request the position stop loss and there is no position stop loss position get double will return zero so yeah if this is true just the same like before we just call trade position modify position modify position modify and we would use position ticket stop loss and position position take profit like this so compile everything's good and we will run another test in the metat trader 5 to just see if our trailing stop is working and if it is dragging the stop loss along once a position reaches um X position uh TSL trigger points and profit so let's search for a position and yes great perfectly so this position is 200 points in profit already I assume so we see the tra uh trailing TR stop and the trading stop should be 100 points um from the current price so and this is yeah it will be 100 points so if I fast forward the test a bit you can see as soon as the price drops the trading stop will be dragged along and at some point of course it will be hit by the price and the position is closed let's check this for buy positions uh yeah there's the buy position stop loss is in place and everything's working just as it should so this is how you can add a trailing stop so there's one more thing that you should do if you want to use this program in a live account or something because right now this Loop here it is just processing every single trade in this account because we are going through all the positions what you want to do is you want to work with a magic number and the concept of magic number in metatrader programming is really cool because we can create a variable for this um which is called Magic this is what I usually call it you can use any name of course it's a integer variable and the value doesn't really matter actually it's just important that if you use multiple programs in your um account you have to use a different magic number for every single uh expert advisor because in the on inet function we will now go ahead and say trade set expert magic number and we will set it to this magic number input which will mean that whenever this trade object is now used to open a position this position have has this specific magic number and the magic number is just a number that is stored somewhere in the background of a position it doesn't change the position at all it's just a number but we can read this number from any position and this is what you want to do in the for Loop so once you selected a position you want to check if position get integer position magic is equal to the magic number from the input and if it is not equal you want to call the continue statement or operation and what this does is you can read it of course but I can Al explain it to you whenever this continue appears somewhere in a loop it won't process the rest of the body but instead it will directly go to this um code that is processed after the body and then check the condition again so it will automatically stop processing this current Loop run and it will directly proceed with the next one because if there if we have found a position position with a different magic number we don't want to modify the stop loss you can also for another safety mechanism say position get symbol and you check the position symbol of the currently selected position and this if this is not the chart symbol then you also want to continue so this is what you can add to make sure that your program is not just going mad and modifying every position in the account but just the ones with your magic number and the chart symbol and then there's also one more thing which I can show you if you have a look at this small code here instead of writing I is equal to I + 1 you can also write I oh wait I ++ like this because this is the same it's just a short form and it's normalized in a lot of different programming languages so if you see something like this you know that this Plus+ it will just increase the value of the variable by one one so if we compile this run one more test maybe the last test because this is what I wanted to do in this tutorial here and then we will also see the magic number I mean it's not really spectacular but you you will see that there is indeed a magic number for these positions like if you go to columns oh wait I don't really see it here but can we see it for the trades okay you cannot really see it in the Testa but trust me there is a magic number um maybe we can see it here no but there is a magic number and it will make a difference in the Life account if you trade multiple positions or different strategies in your account so this is pretty much of finished program so you learned a lot in this tutorial like variables data structures um how to use control structures all of this stuff so you learn everything so let's have a look at the code one more time I will walk you through and then we kind of wrap it up right so first of all we had some properties properties don't change the program they are just the information for the programmer and they are visible here in the like overview for your program then we had a lot of input variables in oh no first of all we include the trade. mq file this is important so we have access to this C trade class to open modify and also close positions then we have a lot of different input variables input variables are pretty much like Global variables like normal Global variables but the user is able to change them so whenever the user is going here to the inputs these are all the input variables if the user changes a value the program will from this point on work with a new value then we have some Global variables they're called Global variables because they are outside of any function on a global scope and um they are available everywhere in the program but since they are not input variables they cannot be changed by the user then we have the on init function this is the oninit event handling function which is called when the program is initialized here we set the magic number for our program and we also create the handle for our indicator a handle is used in mql5 programming to describe a indicator and then at some point in your Random Access Memory this description will be stored and the handle kind of points to this description so whenever we want to work with this indicator we can easily access this access it using the handle then also we initialize the bar total variable because this is what we will use in the onti function later on to figure out if there's a new bar the onit function is called whenever the program is De initialized in this program we don't use it then we have the onti function the onti function first of all has this source code here which is all Loop and um this Loop will Loop through all the positions it will check if this position belongs to a program then we will get some properties from the position in the chart symbol we check if we have a buy position or a sell position we check if we have to modify the stop loss and if so we calculate the new stop loss check if the new stop loss is better than the old one and then finally modify the position if necessary then we have this piece of code in this if statement here this is only process once per bar because we are checking if this bar variable has a different value than the bar total variable if this is true we get the ATR value from the last candle using the copy buffer function and the handle that points to the description of the indicator we store these values in the ATR array in this case it's only one value also we get the open and the close price for the last bar we will then use the open and the close price from the last bar and also the ATR value to figure out if we have a signal if we have a green candle and a really big green candle then we want to print Buy Signal and we want to execute a buy position if we have red candle which is really big red candle we want to execute a sell position executing these positions works with our custom functions which we create at the very bottom of our program outside of any of these event handling functions functions always have a signature a name and a parameter list the parameter list can also be empty and then the important part is the body of the function this is this is what's actually executed when the function is called so here we'll just um calculate the trading parameters and then we will just open the position using the trade C trade class or the trade object and we will of course do the same for the cell function in the cell positions so this is it for the programming part of this video I hope you learned something and I hope I was able to explain everything like really in detail and so that you can understand it and follow along wow if you are still here congratulations I mean this was a h of a right I guess I'm pretty pretty sure you learned a lot about mql5 programming because I was really trying to explain everything on a really fundamental level so you understand not only why we do something but how the computer sees it and why is it having the effect that we wanted to have but actually this was only like the tip of the iceberg mql5 is so powerful it's capable of doing so much things in the end you are able to automate everything that you can think of if you can describe it you can automate it so if you're wondering of uh right now like where to go from here what are the next steps of course you will have to do a lot of things you will have to practice you have to write your own expert advisors and you will yeah really have to reapply these things again and again so it becomes second nature to you and it will be really easy in the future to um to write programs for you and trust me again learning the process is absolutely worth it like when I started to learn automated trading or programming really changed my complete life and it can also change your life I'm pretty sure about this I also have customers who Tau me that automated trading was super beneficial for them they are better to automate their strategies they can provide for their family friends and others and this is all I want to give you like with these videos on this channel so if you want to learn more about automated trading it's really important that you subscribe to this channel also share it with other friends that you think could benefit from that from this and if you want to have a really if you want to go on the fast track to learning how to write code for the M metatrader 5 like professionally again this was these were all the basics and this video I I really put put my heart into this to really explain everything like as good as I can and if you like this style also you might want to check out the metat trader 5 master class is definitely Linked In the description of this video and you will learn so much more it's crazy will blow your mind you will learn so many different aspects of mql5 programming so not only the basics but you will also learn more about objectoriented programming like the stuff we did with the c trade class you will learn how to use other functions of the metat trader 5 like the calendar function you will learn how to build complex EAS complex data structures how to develop strategies that I use for my life trading for multiple years that are profitable for multiple years so yeah definitely make sure to check out this course it's yeah I mean it can change your life so what what what is there more to say so um if you are still sticking around at this point huge thank you to you for watching the whole video sticking with me until the end and I hope that you do not regret it and I'm pretty sure it made your trading jour Journey better so let me know in the comments if you watched until this point and if you appreciate this video or if you like it or whatever your thoughts are about this and if you will stick to automated programming and automated trading so at this point there's nothing more to say for me then thanks thanks for watching have a great time good trades and bye-bye
Info
Channel: René Balke
Views: 5,837
Rating: undefined out of 5
Keywords: Trading, Programming, expert advisor, EA, automated trading, mt4, metatrader 4, mt5, metatrader 5, forex robot, robo trading, algotrading, forex, cfd, mql5
Id: nlj9gUuf7Wg
Channel Id: undefined
Length: 158min 10sec (9490 seconds)
Published: Wed Dec 13 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.