MQL5 Tutorial

MQL5 Tutorial

By Raimund BauerBusinessTechnologyInvesting
Download on the App Store

All MQL5 Tutorial episodes

  • MQL5 TUTORIAL – JOIN THE GREAT TRADING EXPERIMENT 2024

     

     

    20240101: DOWNLOAD 28 result videos for this system

    20240101: README Documentation (updated often):

    20240102: System Download for Demo accounts:

     

    This video is about a big trading experiment that I would like to do together with you. Today is January 1, 2024, it’s just before 4 pm and I’ve spent the day today running strategy tests for all the major currency pairs that I trade myself for this system here, trading through the entire year of 2023. And I will also make these videos available for you to watch for yourself. But the big experiment here is that I would like to use the year 2024 together with people like you to make this system better. That’s why I’m now offering a version of the Robot Trading System that runs indefinitely on a demo account from January 2024.

    This means that if you use a demo account, you can do everything that I do myself. I will also initially trade this system on a demo account, and it will be about how you can set up, adjust and improve such a system over the course of the year so that you get a decent result at the end of the year. We will also discuss and share some other things that might help you, even if you haven’t had anything to do with automated trading before or if you want to have a look at the whole thing first if you are interested in joining in. You don’t need any prior knowledge, you don’t need any capital. All you need is a computer that has been manufactured in the last ten years. You need a demo account. You can get that for free from Metaquotes or other companies and you need to do strategy tests like this here with Metatrader five, which you can also download for free. This time we would have made a net profit of €1,642 on an account with a deposit of €10,000. And why are we doing all this on a demo account? Well, there are few people who are actually willing and ready to invest time in real trading results on a demo account before trading real money with a real money account. And in almost every trading session there are always dips like this. And that leads people to close their account at exactly this point.

    Because that’s where the fear is greatest. But you don’t have to be afraid on a demo account. And as soon as you feel that the system works well enough for you, you can switch at any time. But we have already done experiments like this in the past and I would like to start 2024 in the same way. Because I believe that nothing can replace the knowledge you have gained yourself. And in this case, I think you have little to lose and a lot to gain. That’s it for this opening video. I wish you a happy new year and in the next few days you will receive more information, new videos and also the download link to the version of this system that you can then use for free on your own demo account. If you are already an existing customer, I have activated a few more parameters for the Robot Trading System here. This means that the system can now be controlled more precisely. And if you like the results here, I’ll see you in the next video. Thank you very much for watching. And we’ll continue in the next video. ​

    The post MQL5 TUTORIAL – JOIN THE GREAT TRADING EXPERIMENT 2024 appeared first on MQL5 Tutorial.

    0 min
  • MQL5 Tutorial – Simple MQL5 New Candle Robot

     

    1. Introduction to Counting New Candles on the Chart (00:00 – 00:17) Discussing the usefulness of counting new candles on a chart and showing the output of four candles since the start of the expert advisor.
    2. Importance of Candle Counting in Automated Trading (00:17 – 00:36) Explaining why counting candles is important in automated trading, especially when trading multiple positions and currency pairs.
    3. Resource Management and Avoiding Computer Crashes (00:36 – 01:17) Highlighting the importance of resource management to avoid computer crashes, especially during fast market movements.
    4. Creating a Simple Expert Advisor for New Candle Detection (01:17 – 01:57) Demonstrating how to create a simple expert advisor in MetaTrader to detect new candles.
    5. Setting Up Price Array and Sorting for Candle Data (01:57 – 02:20) Instructions on setting up a price array and sorting it to hold price data for candle detection.
    6. Filling the Array with Price Data and Counting New Candles (02:20 – 02:59) Steps to fill the array with price data and use it to count the number of new candles since the last start of the expert advisor.
    7. Creating Timestamp Variables for Candle Time Tracking (02:59 – 03:42) Creating date/time variables to track the timestamp of the current and last checked candles.
    8. Updating Candle Counter and Displaying Output on Chart (03:42 – 04:36) Updating the candle counter when a new candle is detected and displaying the output on the chart.
    9.  

      Sometimes it is helpful to count the new candles on the chart.

      The output in the left upper corner on the chart says we had four candles since we started this Expert Advisor,.
      One, two, three, four, this is the fifth one.
      Now you might ask yourself why is this important?
      Well an Expert Advisor can trade several positions on a chart, and you also can trade several currency pairs and every single candle on the chart can have lots of different price moves.
      And every time a price changes the OnTick function will be triggered but a lot of trading strategies use close prices.
      So instead of maybe fifteen calculations within this candle, you would only need one calculation for the close price.
      Even a high tech computer may have a resource problem, if you try to calculate several dozen trades on several dozen charts because when the market starts to move really fast your computer might be overwhelmed and it may cause a crash.
      So if you want to avoid computer crashes, it’s a good idea to save resources.
      To do that you can simply check if a new candle is created and now we will create a simple little Expert Advisor to do that.
      So let’s click the little button over here or hit the F4 key to bring up the Meta Editor.
      Select File, new Expert Advisor from template, continue, and we will give it the name Simple New Candle.
      Now click on continue, continue, finish, and remove everything above the OnTick function.
      Let’s delete the two comment lines here. Okay now the first thing we need is the price array to hold our price data.
      So let’s create that, that can be done with MQLRates and we will call a price data.
      Now we want to sort our array from the current candle downwards with arraysetasseries and in the next step we need to fill it with data.
      That is done by using copyrates for the current currency pair on the chart and the current selected period.
      For example I prefer a one minute charts, we want to start with the current candle zero, and copy the price for three candles into our little array price data.
      To count the number of new candles since the last start of the Expert Advisor, we need a new candle counter.
      This candle counter will be an integer and it will be static, that means it will never lose its value even if we would like to leave the function.
      Okay let’s move on, now we are creating datetime variable that will hold a time stamp; this one will hold the time stamp for the last time we checked and it is also static so it will never lose its value.
      And for the current candle we need another datetime variable and that will be called time stamp current candle and we will fill it by getting the time value of the current candle from our price data array.
      And if the time stamp for the current candle is different from the timestamp the last time we checked, we want to remember the current timestamp for the next time by assigning it to the timestamp last check variable.
      Now we want to add the value one to our current candle counter and the last thing we need us the output on the chart.
      So let’s compile the little Expert Advisor here and we have zero errors and zero warnings.
      So let’s hit the F4 key or click this button to go back to MetaTrader, select View Strategy Test or hit the control and the R key. Look out for the simple new candle.ex5 file.
      Mark the visualization option and click on start.
      And now you should see your candles on the chart being counted and that can be done very fast and you did it in five minutes by creating this little Expert Advisor here.

      Download “MQL5 Simple New Candle Expert Advisor from MQL5 Tutorial” SimpleNewCandle.txt – Downloaded 507 times
      – 1.11 KB

      The post MQL5 Tutorial – Simple MQL5 New Candle Robot appeared first on MQL5 Tutorial.

      5 min
    10. MQL5 Tutorial – Simple MQL5 Bollinger Bands Robot

       

      1. Introduction to Bollinger Bands and Expert Advisor Calculation (00:00 – 01:03) Introduction to using Bollinger Bands in trading and how the expert advisor can calculate all three bands with higher accuracy.
      2. Trading Strategy with Bollinger Bands (01:03 – 01:34) Explaining the trading strategy: opening a short trade when the price breaks the upper Bollinger Band and a long trade when it breaks the lower band and returns.
      3. Creating an Expert Advisor for Bollinger Bands (01:34 – 02:05) Instructions on creating an expert advisor in MetaTrader to automate trading with Bollinger Bands.
      4. Setting Up Arrays and Defining Bollinger Bands in Code (02:05 – 03:21) Coding steps to set up arrays for each Bollinger Band and defining the bands based on the current chart and time period.
      5. Outputting Calculated Values on the Chart (03:21 – 03:38) Using the comment function to output the calculated values of the Bollinger Bands on the chart.
      6. Compiling the Code and Preparing MetaTrader (03:38 – 04:20) Compiling the expert advisor code and setting up MetaTrader to display the Bollinger Bands on the chart.
      7. Testing the Expert Advisor in Strategy Tester (04:20 – 05:39) Running the expert advisor in the strategy tester and comparing the calculated values with the chart’s Bollinger Bands.
      8.  

        If you like to use indicators, you might have heard of the Bollinger bands.

        This little Expert Advisor here can calculate all three bands.
        If you put your mouse cursor over the middle band here you see a value of 0.712078 and our calculated value for the middle band is 0.7120775, this calculation even is a little bit more accurate.
        The value for the upper Bollinger band is 0.712457 and here we have 0.712457.
        And for the lower Ballinger band it’s the same 0711698, 0.7116979.
        This value is even more accurate because this one is rounded.
        So what can we do with a Bollinger Bands?
        Well the idea is as the price breaks the upper Bollinger band we want to get in at the next entry and we would like to open a short trade here, because we expect the price to fall.
        In the other case if the price breaks the Bollinger band here and it gets back into the bands we would go for a long trade because the price might rise.
        So if you can create an automated Expert Advisor that is able to compare these values over here with the current price, you can fully automate this.
        Your computer can trade the Bollinger bands automatically and you don’t have to sit in front of your screen all the time.
        So let’s create a little Expert Advisor!
        To do that please hit the F4 key or click this little button over here and that will open the Meta Editor.
        Here we click on new Expert Advisor from template, continue, we will call it simple Bollinger bands, click on continue, continue, finish.
        Remove everything above the OnTick function, remove the comments and the first thing we need is an array for each of the Bollinger bands one, two, three times a double array.
        Now we need to sort our three arrays to hold prices from the current candle downwards and we do that with the function arraysetasseries.
        In the next step we need to define the Bollinger bands.
        We want our Expert Advisor to use the current chart for the current time period used on the chart.
        It should calculate the Bollinger bands for twenty candles without any shift and with a standard deviation of two, that all should be calculated for the closed price of the candle.
        Afterwards we need to copy the price information into three arrays and now it’s time to calculate the actual value for the current candle and to store it in a variable for each of the three bands.
        That’s it for the calculation. Now we want to output our calculated values on the chart, we do that with the comment function and it will output the name of the variable and the value we have calculated in this block.
        Okay let’s compile the code. We have no errors and no warnings.
        So let’s click the little button over here or hit the F4 key to bring up the Meta Trader, to make the Bollinger band visible on the screen we will use a little trick.
        Please click on insert, indicators, Bollinger bands, select the period of twenty candles with a shift value of zero and the deviation value of two, we want to apply all this to the closed price of the candles and now you can pick a color and style for the line.
        I prefer these thicker lines. Let’s click on okay and you will see the visual representation of the Bollinger bands on the chart.
        Now right click the chart select templates, save template and save it as Tester.tpl to make it the default chart for strategy tester.
        And if you save it as default.tpl it will also become the default template if you open a new chart in life trading.
        So let’s bring up the Strategy Tester by clicking on View Strategy Tester or hitting the control and the R key and select the simple Bollinger bands.ex5 file, make sure to and enable visualization here and start the test.
        And this is what you should see now, let’s stop it here and check the values.
        This is 0.706251, 0.7062505, thats okay.
        The upper Bollinger band is 0.706916, 0.706916, that’s also okay and the lower Bollinger band is 0.705585, and that’s exactly what’s calculated here, so it works.
        In this video you learned to calculate all the Bollinger bands by creating this little Expert Advisor here.

        Download “MQL5 Simple Bollinger Bands Expert Advisor from MQL5 Tutorial” SimpleBollingerBands.txt – Downloaded 622 times
        – 1.11 KB

        The post MQL5 Tutorial – Simple MQL5 Bollinger Bands Robot appeared first on MQL5 Tutorial.

        6 min
      9. MQL5 Tutorial – Simple Chart Objects

         

        1. Introduction to Creating Simple Chart Objects in MQL5 (00:00 – 00:34)
          • Introduction to the tutorial on creating simple objects like arrows on the chart each time a tick comes in, using MQL5.
          • Opening MetaEditor and Creating a New File (00:34 – 01:05)
            • Instructions on opening MetaEditor, creating a new Expert Advisor file named “Simple Chart Objects”.
            • Setting Up the Code Structure and Creating Price Array (01:05 – 01:39)
              • Deleting unnecessary code and creating an array for price information using MQL rates.
              • Sorting the Array and Filling with Price Data (01:39 – 01:52)
                • Sorting the array downwards and filling it with price information for the current chart and period.
                • Creating a Static Counter and Drawing Arrows (01:52 – 02:25)
                  • Creating a static counter and using it to draw arrows on the chart with ‘ObjectCreate’.
                  • Configuring the Arrow’s Appearance and Position (02:25 – 03:08)
                    • Setting the arrow’s type, color, and width, and positioning it at the highest point of the current candle.
                    • Changing Arrow Appearance with Counter Value (03:08 – 03:42)
                      • Changing the arrow’s appearance based on the value of the static counter.
                      • Setting Arrow Color and Size (03:42 – 04:23)
                        • Configuring the arrow’s color to green and increasing its size.
                        • Moving the Arrow and Displaying Counter Value (04:23 – 04:57)
                          • Moving the arrow to the highest price of the current candle and displaying the counter value on the chart.
                          • Incrementing the Counter for New Symbols (04:57 – 05:17)
                            • Increasing the counter by one for each new tick, resulting in different symbols on the chart.
                              1. Compiling the Code and Testing in MetaTrader (05:17 – 05:51)
                                • Compiling the code and testing the Expert Advisor in MetaTrader using the Strategy Tester.
                                  1. Observing Dynamic Symbols on the Chart (05:51 – 06:11)
                                    • Watching the changing symbols on the chart during the test and understanding how to print dynamic symbols using MQL5.
                                    •  

                                      This time we are going to create simple objects.

                                      Each time a tick comes in, one of these objects will be painted here.
                                      Usually you will see things like arrows up and down, but actually there are a lot of more possibilities for such an arrow symbol.
                                      Everything you see here is called an arrow even if it doesn’t look like one.
                                      Now how can we create an Expert Advisor in MQL5 that is going to draw objects like these?
                                      To do that, please click on the little button here or press the F4 key on your keyboard. And that will bring up your MetaEditor window and here you want to select File, New, Expert Advisor from Template, Continue.
                                      I will call it SimpleChartObjects here, Continue, Continue and finish. And now you can delete everything above the OnTick function and the two comment lines here.
                                      And first we need an array for prices, we can create one by using MQLrates and it will have the name Price Information, now we are going to sort the array downwards from the current candle by using arraysetasseries and by using copyrates we are going to fill the price information array for the current chart and the period selected on the chart from the current candle zero for all the bars on the chart and store the values in our array.
                                      And now we are going to create a static counter, it will be an integer with the name i, and we will use that value to actually create an arrow with the name MyArrow. Please remember in MQL 5 an arrow can look like a circle or a square or anything else.
                                      So we use ObjectCreate for the current chart and our object will have the name MyArrow and we use OBJ_Arrow to create it.
                                      The next parameter would be a sub window; we will use a zero here because we are going to create the arrow here in the main window.
                                      You might have seen indicators that use a sub window below.
                                      We will use the current time and the arrow should be placed on the highest point of the current candle in our price information array we have created here.
                                      And with object set integer for the current chart, and the object, my arrow, we use OB J Prop_Arrow Code, and the value of the static counter to change how our object looks.
                                      Currently we have the value 179 and as soon as that changes to 180 the arrow code changes and so does the way our arrow looks.
                                      And for 181 our arrow would look like this; let’s select a color here, that is done by using objects set integer for the current chart for the object with the name My Arrow and we use OBJ_Prop_Color and we would like to have the color green.
                                      If you press F1 on your keyboard you will see a lot of other colors that you can use. To make our object a little bit bigger we’re using object set integer for the current chart for the object with the name MyArrow and we use the OBJProp_Width to set the size to 20.
                                      And now we move the object by using ObjectMove for the current symbol and for the object with the name MyArrow on the main window we used, for the current time and we move it to the highest prize of the current candle.
                                      I would actually like to have a chart output for the current counter value so we use comment to output the text “i has the value” followed by the current value of the static integer variable i. And in the last step we are going to increase our counter by one, that is done with I++ and now the next time a tick comes in we should see another symbol on the chart.
                                      Okay that’s it; let’s compile the code here and that worked without any errors. So please click on the little button here or press F4 on your keyboard to go back to MetaTrader. And in MetaTrader click on View, Strategy Tester or press control and R to bring up the Strategy Tester Panel here and there you want to select the file SimpleChartObjects.ex5.
                                      Let’s start the test after you have enabled the visualisation option here and for the first 20 counter values nothing changes, but around 30 you will see changing symbols on your chart and now you actually know how to print dynamic symbols on your chart and you have done it within a few minutes by using a few lines of MQL5 code.

                                      Download “MQL5 - Simple Chart Objects from MQL5 Tutorial” SimpleChartObjects.txt – Downloaded 401 times – 1.03 KB

                                      The post MQL5 Tutorial – Simple Chart Objects appeared first on MQL5 Tutorial.

                                      7 min
                                    • MQL5 TUTORIAL- SIMPLE ICCI STANDALONE EA

                                      In this video we are going to create an Expert Advisor for this signal here; it’s the Commodity Channel Index, and you see that we have already opened a position, it produces buy and sell signals here on the chart. Whenever the signal is below the lower line we are going to buy and when it’s above we are going to sell.

                                      Now how can we create an Expert Advisor in MQL5 that is actually able to trade the Commodity Channel Index?
                                      To do that please click on the little button here or press F4 on your keyboard, now you should see the Metaeditor window and here you want to click on: “File/ New/ Expert Advisor (template)” from template, “Continue”, I will call this one: “SimpleICCIStandaloneEA”, click on “Continue”, “Continue” and “Finish”, now you can remove everything that is above the “OnTick” function and let’s also delete the two comment lines here.
                                      First we want to include the file: “Trade.mqh”, it comes with MQL5 and it will help us to create an instance of the class “CTrade” that will be called: “trade” and we are going to use it to actually open positions later on but before we can do that we need to calculate a few things. For example the Ask price. We get that by using “SymbolInfoDouble” for the current symbol and with “SYMBOL_ASK” we will get the Ask price. “NormalizeDouble” and “_Digits” will help us to get the price with either 3 or 5 digits behind the dot depending on the currency pair.
                                      Let’s do the same for the Bid price, it’s almost exactly the same but this time we use “SYMBOL_BID”.
                                      Now we use “MqlRates” to create an array for the prices, we will call that:”PriceInfo” and we sort the array from the current candle downwards by using “ArraySetAsSeries” and we use “CopyRates” to fill our “PriceInfo” array with price data for the last candles. We will use the current symbol on the chart, the currently selected period and we will start with the prices for candle 0 (zero) – that’s the current candle – and we only need prices for 3 candles and store that result in the “PriceInfo” array.
                                      We also need to create a string for the signal that will be called: “signal” and it has no value right now because we are going to calculate that later on.
                                      We need to create another array, this time we will call it: “myPriceArray”.
                                      Well, this one was for the candle prices (PriceInfo) and the second one will be for the Expert Advisor (myPriceArray).
                                      Let’s define the Commodity Channel Index here (CCIDefinition), we are going to use the built-in: “iCCI” function for the current symbol and the current period on the chart, it will be calculated based on 14 candles – that’s also what you see if you click on: “Insert/ Indicators/ Oscillators/ Commodity Channel Index”, you see 14 candles – and our result will be calculated based on the close prices.
                                      Let’s sort the price array (myPriceArray) from the current candle downwards by using “ArraySetAsSeries” and with “CopyBuffer” we fill our price array (myPriceArray) according to the Commodity Channel Index definition (CCIDefinition) that we have created here for the first signal buffer, – that’s the line here – we start with candle 0 (zero) – that’s the current candle – and we copy the values of 3 candles and store it in our price array (myPriceArray).
                                      Finally we are able to get the value of the current candle by looking at candle 0 (zero) in our price array (myPriceArray) and the result will be stored in the variable called: ”CCIValue” and if the “CCIValue” is bigger than 100 – that would be the case whenever the blue line is above the upper dotted line, you see the 100 mark here – and if that is the case we want to sell so we assign the word: “sell” to our signal.
                                      Otherwise if the “CCIValue” is below the -100 (minus 100) line – that is the lower dotted line here – we want to buy so we assign the word: “buy” to our signal.
                                      And if the signal equals sell and “PositionsTotal” is less than 1 – with other words we wouldn’t have any open positions on the chart – we want to sell so we use “trade.Sell” to sell 10 micro lot.
                                      Otherwise if the signal equals buy and we have no open positions we want to buy so we use “trade.Buy” to buy 10 micro lot.
                                      Finally we create an output on the chart by using the “Comment” function, it will output the words: “The current signal is:” followed by the “signal” that we have calculated.
                                      Okay, that’s it so far, please click on the “Compile” button or press F7. We don’t see any errors here so now we can click on the little button here or press F4 to go back to Metatrader.
                                      In Metatrader we click on: “View/ Strategy Tester” or press CTRL and R, please select the “SimpleICCIStandaloneEA”, mark the visualization option here and click on start.
                                      Here we are! This is our first position, we can speed up the process a little bit and you see that it is creating buy and sell signals, we already have opened a position here and now you know how to create an Expert Advisor that is able to trade the Commodity Channel Index in MQL5 and you have coded it yourself with a few lines of MQL5 code.

                                      Download “MQL5 Tutorial - Simple ICCI Standalone Expert Advisor” SimpleICCIStandaloneEA.txt – Downloaded 325 times – 1.72 KB

                                      The post MQL5 TUTORIAL- SIMPLE ICCI STANDALONE EA appeared first on MQL5 Tutorial.

                                      8 min
                                    • MQL5 TUTORIAL – HOW TO CREATE A SHIFTED MOVING AVERAGE

                                       

                                      1. Introduction to Shifted Moving Average Indicator (00:00 – 00:11)
                                        • Introduction to the concept of a shifted moving average, which projects one moving average into the future.
                                        • Setting Up the MQL5 Code (00:11 – 00:18)
                                          • Overview of the MQL5 code setup, including the creation of a string variable named ‘signal’ for storing trading signals.
                                          • Declaring Moving Average Arrays (00:18 – 00:27)
                                            • Declaring two arrays, ‘my moving average array’ and ‘my shifted average array,’ to store values of moving averages.
                                            • Defining Two Moving Averages (00:27 – 00:46)
                                              • Using the ‘IMA’ function to define two moving averages: a 50-period simple moving average and another 50-period SMA with a 20-period shift.
                                              • Sorting Arrays and Copying Values (00:46 – 01:08)
                                                • Sorting the arrays in descending order and using ‘CopyBuffer’ to copy the last three values of both moving averages into their respective arrays.
                                                • Calculating Moving Average Values (01:08 – 01:15)
                                                  • Calculating and storing the values of the current candle for both moving averages.
                                                  • Generating Trading Signals (01:15 – 01:32)
                                                    • Generating buy or sell signals based on the comparison of the moving average values.
                                                    • Displaying Trading Signal on Chart (01:32 – 01:43)
                                                      • Using the ‘Comment’ function to display the current trading signal on the chart.
                                                      • Conclusion and Further Learning Resources (01:43 – 02:18)
                                                        • Concluding remarks on the functionality of the code and suggestions for further learning through other videos or a premium course.
                                                        •  

                                                          In this video, we are going to take a look at this indicator here. It’s a shifted moving average, which means that we use one moving average and project the results into the future. Let’s see how we can do something like this with MQL5. In this MQL5 code, a string variable named signal is created to store the trading signal.

                                                           

                                                          This signal will be either buy or sell. Two arrays, my moving average array and my shifted average array are declared. These arrays will store values of moving averages. Two moving averages are defined using the IMA function. Moving average definition calculates a 50-period simple moving average using the closing prices of the current symbol and period. Shifted average definition calculates another 50-period SMA, but with a 20-period shift applied. The array set as series function is used to sort the my moving average array and my shifted average array in descending order. The copy buffer function is used to copy the last three values of both moving averages into their respective arrays. The values of the current candle for both moving averages are calculated and stored in my moving average value and my shifted average value.

                                                           

                                                          Trading signals are generated based on the comparison of these moving average values. If my moving average value is greater than my shifted average value, it sets signal to buy. If my moving average value is less than my shifted average value, it sets signal to sell. The current trading signal, buy or sell, is displayed on the chart using the comment function. This code calculates two moving averages, compares their values, and generates a buy or sell signal based on the comparison. It then displays the current trading signal on the trading chart for reference.

                                                           

                                                          Okay, by now you should have a working version of this indicator on your chart. I hope everything went well. If it was too fast for you or if you have no idea what all the code does, you maybe want to watch one of the other videos or maybe even the premium course on our website might be interesting for you. For now, I say thank you for watching and I will see you in the next video.

                                                          The post MQL5 TUTORIAL – HOW TO CREATE A SHIFTED MOVING AVERAGE appeared first on MQL5 Tutorial.

                                                          3 min
                                                        • MQL5 TUTORIAL – HOW TO TRAIN AND SCALE A WORKING REAL WORLD TRADING SYSTEM

                                                           

                                                          1. Introduction to Real World Trading System (00:00 – 00:14)
                                                            • Introduction to the robot trading system used by the presenter.
                                                            • Overview of the system’s performance and purpose.
                                                            • Analyzing Trading System Performance (00:14 – 00:29)
                                                              • Detailed look at the trading system’s results and trades.
                                                              • Discussion on the balance and equity of the system.
                                                              • Understanding Trade Impact and Emotions (00:29 – 01:06)
                                                                • Exploring the emotional impact of trade results.
                                                                • Difference between small and large losses.
                                                                • Trade History Analysis (01:06 – 01:20)
                                                                  • Examination of the system’s trade history, including profits and losses.
                                                                  • System Strategy and Position Series (01:20 – 01:39)
                                                                    • Description of the trading strategy using position series.
                                                                    • Explanation of closing positions at once.
                                                                    • Decision Making in Trading (01:39 – 02:14)
                                                                      • Criteria for deciding between single or multiple positions.
                                                                      • Rules-based approach to trading decisions.
                                                                      • Trend Analysis with Moving Averages (02:14 – 02:31)
                                                                        • Using simple moving averages to identify market trends.
                                                                        • Explanation of downtrend indicators.
                                                                        • Trading With and Against Trends (02:31 – 02:58)
                                                                          • Strategies for trading with the trend and handling corrections.
                                                                          • Examples of trades that didn’t work out and why.
                                                                          • Analyzing Correction Phases and Trends (02:58 – 03:29)
                                                                            • Understanding correction phases in stable trends.
                                                                            • Strategies for closing positions profitably.
                                                                            • Future Decision Making in Trading (03:29 – 03:47)
                                                                              • Challenges in predicting future market movements.
                                                                              • Importance of decision making in trading.
                                                                              • Using FXBlue for Detailed Statistics (03:47 – 04:17)
                                                                                • Utilizing FXBlue for better trading statistics.
                                                                                • Accessing detailed system performance data.
                                                                                • System Performance and Statistics Overview (04:17 – 04:53)
                                                                                  • Comprehensive review of the trading system’s performance.
                                                                                  • Analysis of winners, losers, and total trades.
                                                                                  • Trade Analysis and Currency Focus (04:53 – 05:10)
                                                                                    • Breakdown of trade types and currency pairs used.
                                                                                    • Emphasis on trading in a downtrend.
                                                                                    • Scaling Up the Trading System (05:10 – 05:28)
                                                                                      • Considering increasing the trading volume.
                                                                                      • Evaluating the system’s readiness for scaling.
                                                                                      • Average Trade Duration and Profitability (05:28 – 06:05)
                                                                                        • Analysis of average trade duration and profitability.
                                                                                        • Importance of balancing profitable trades with losses.
                                                                                        • Understanding Trading Costs and Spreads (06:05 – 06:36)
                                                                                          • Discussion on swap fees and spread costs in trading.
                                                                                          • Impact of broker charges on trading profitability.
                                                                                          • Market Trend Analysis and Moving Averages (06:36 – 07:04)
                                                                                            • Using moving averages to analyze market trends.
                                                                                            • Indicators of trend changes and their implications.
                                                                                            • Automating Trading Logic with MQL5 (07:04 – 07:33)
                                                                                              • Simplifying trading decisions through automation.
                                                                                              • Using MQL5 for implementing trading strategies.
                                                                                              • Backtesting and Real-Time Testing (07:33 – 08:04)
                                                                                                • Importance of backtesting and real-time demo account testing.
                                                                                                • Evaluating system performance in different market phases.
                                                                                                • Scaling Up and Risk Management (08:04 – 08:21)
                                                                                                  • Strategies for scaling up the trading system.
                                                                                                  • Adjusting risk percentage and position size.
                                                                                                  • Training and Analyzing Trading Systems (08:21 – 08:51)
                                                                                                    • Training a system for real-world conditions.
                                                                                                    • Using external tools for performance analysis.
                                                                                                    • Conclusion and Future Plans (08:51 – 09:22)
                                                                                                      • Summary of the video and insights on scaling up the system.
                                                                                                      • Invitation to analyze detailed stats on the website.
                                                                                                      •  

                                                                                                        In this video we are going to talk about one of my real world examples. This is the robot trading system which actually use myself and one of my premium course members wanted to know how something like this works. So let’s have a look at the details. Well, if you have a look at the robot trading system, you can see this is Version 2023 from June. Right now we have the 20 first of October and here we have results and trades all in all we made a profit of 159 dollars and if we look at the overall view here we see that the balance currently is almost equal to the equity which means we only one open trade that is currently and open loss of 99 cents. So what is actually the difference between this trade and one that would be an open loss of 99 dollars? The difference is emotional because it’s not actually the number here that counts if a system is working or not, it’s what the difference means for us. So let’s have a look at the history and here we see that we have losses and we have profits, so not every trade was a success, but all in all the system result is stable, at least right now. If we zoom into the system, we can see these lines here which look like a fan and each of those is a series of positions that we have opened. And at this point here all positions have been closed at once. Let’s zoom in a little more and you will also see parts where we don’t see a fan, for example like here. And these are simple positions that made a profit without the need to start a series. So how do we decide if we just take one position or if we want to open multiple positions? Well in my case I have rules. And currently we are in a down trend, and we can see that because we have two simple moving averages here is for 1100 candles and the other one is for a thousand candles. And a long as the green one is below the red one, we have a downtrend and that looks pretty stable right now. And you can see that the last trades that we made have been sell trades, so we have been trading with the trend. But still we have some positions that didn’t work out. How was that possible? Well that’s because even in a stable trend we have some corrections. That’s when we open a position like here and then suddenly in a correction the price goes up. And if you take a closer look, this is the case for all these fans here. The price went down, than we made a trade here. Suddenly a correction happened and it went against us. But actually we have been able to still close all the positions from here to there in a profit at this point here. Because finally the short time trend again started to go with the main trend and the price went down. While it is easy to see what happened after it happened, it’s often a big problem for people to make a decision what they should do in the future! Well this this is the account number here. So let’s see if we can get more statistics about what happened. And I’m using FXBlue for this, because it providers better statistics than we get from the MetaTrader. In my case it’s in German because I’m from Germany. You can get a lot of details about how the system works. And you don’t have to log in to see them, just open this website here.

                                                                                                        And in my case I want to open the stats. There we are, I have started the system 128 days ago with the deposit of 10.000 Dollars. This is the total profit, here we have some withdrawals and this is the net profit. We have winners and losers and all in all we made 382 trades and that resulted in a net profit of 153 Dollars. In a graph chart it looks like this here. We have some more statistics. The Euro US Dollar was the only currency that I used to trade. We have 73 buy trades and 309 sell trades. And that makes sense because currently we have that downtrend here. And if we take a closer look, we had 14 winning weeks and zero losing weeks and a that point, it might make sense to turn up the volume and to scale up the system. Now, let’s go back to the statement here and somewhere down here it says the average trade duration is 33 hours and the average profit is $ 1,78, while the average loss is $ 2.16. So if we are able to make more profitable trades than we make loses, the system is going to be profitable. But this is only true, if we not have to high costs. We have this swap collumn here and for longer trade durations you can expect that you need to pay swap fees, like here. These are costs and the other thing is that when you open a position here you might always see a little loss, because of the social spread. Your broker is charging money, so whenever you open a position like I did here, the first thing that you will see is that the profit is negative. And that the price where you bought or sold something is different from what you see on the chart, because that is how your broker makes money with every trade that you make. Now let’s change the zoom level here and we see that currently it looks like the current price is getting near to the small average price here and when the price level crosses the two small moving averages here, that would mean that the stable trend is broken. And when the two small moving averages cross, this could mean that the trend is broken and the next thing that we would expect to see is an up trend. Which is what happened here.

                                                                                                        The trend was broken, here is the cross over and here is the up trend. Then we had another cross over here and now it’s a down trend. So the logic behind all these decisions here is pretty simple and it can be automated by using MQL5. So basically, there is nothing magical behind it. It’s all pure probability and to make up rules about when to do what, we do a lot of back tasting and that means we do thousands of automated trades with data from the past to see how our system would have behaved in other market phases. Then we tried on a demo account in real time. Then we scale up or system to see if it actually works. And once everything is working as expected, you can press the F7 button and increase risk percentage, or the multiplier for the positionsize. And if you do, but you would have bigger positions and more positions and that’s how we scale up. That was basically how we setup a probability based trading system that works under real conditions. And in this video you have learned how to train your own system to work under real conditions and how you can use external tools like a FXBLUE to analyze if it actually works. If you are interested to see more details you can just go to this website and analyse all the stats. This system is still in the training stage, but so far the results have been very promising, so think I’m going to scale it up.

                                                                                                        That’s it for this video. I say thank you for watching and I will see you in the next one.

                                                                                                         

                                                                                                        The post MQL5 TUTORIAL – HOW TO TRAIN AND SCALE A WORKING REAL WORLD TRADING SYSTEM appeared first on MQL5 Tutorial.

                                                                                                        10 min
                                                                                                      • MQL5 TUTORIAL – HOW TO CALCULATE THE HISTORY PROFIT

                                                                                                         

                                                                                                        1. Introduction to Calculating Historical Profit (00:00 – 00:09)
                                                                                                          • Introduction to creating an expert advisor for calculating historical profit for a specific currency pair.
                                                                                                          • Overview of displaying the calculated profit on the chart.
                                                                                                          • Starting with MetaEditor (00:09 – 00:16)
                                                                                                            • Instructions on how to start the MetaEditor for coding the expert advisor.
                                                                                                            • Brief mention of using the icon or pressing F4 on the keyboard.
                                                                                                            • Including Trade Library and Creating CTrade Instance (00:16 – 00:31)
                                                                                                              • Explanation of including the Trade.mqh library for trade operations.
                                                                                                              • Creation of an instance of the CTrade class named ‘trade’ for executing buy and sell operations.
                                                                                                              • Calculating Current Ask and Bid Prices (00:31 – 00:38)
                                                                                                                • Description of calculating the current Ask and Bid prices within the OnTick function.
                                                                                                                • Importance of these prices for executing buy and sell orders.
                                                                                                                • Executing Buy and Sell Orders (00:38 – 00:46)
                                                                                                                  • Checking for less than two open positions before executing orders.
                                                                                                                  • Execution of both buy and sell orders for demonstration purposes.
                                                                                                                  • Calculating and Displaying Historical Profit (00:46 – 01:01)
                                                                                                                    • Use of the GetCurrencyPairHistoryProfit function to calculate historical profit.
                                                                                                                    • Displaying the calculated profit on the chart.
                                                                                                                    • Functioning of GetCurrencyPairHistoryProfit Function (01:01 – 01:09)
                                                                                                                      • Detailed explanation of how the function calculates total historical profit for a specific currency pair.
                                                                                                                      • Initializing Variables and Fetching Historical Data (01:09 – 01:17)
                                                                                                                        • Initialization of variables for storing deal information.
                                                                                                                        • Use of the HistorySelect function to fetch historical deal data.
                                                                                                                        • Iterating Through Historical Deals (01:17 – 01:25)
                                                                                                                          • Iteration through historical deals using a for loop.
                                                                                                                          • Obtaining profit, swap, and order type for each deal.
                                                                                                                          • Ensuring Matching Currency Pair for Deals (01:25 – 01:34)
                                                                                                                            • Checking the currency pair for each deal to match the current symbol.
                                                                                                                              1. Compiling the Code and Further Learning Resources (01:34 – 01:49)
                                                                                                                                • Instructions on compiling the code in MetaEditor.
                                                                                                                                • Recommendation for the premium course or basic videos for further learning.
                                                                                                                                • Testing the Expert Advisor in MetaTrader (01:49 – 02:04)
                                                                                                                                  • Returning to MetaTrader and starting the strategy tester.
                                                                                                                                  • Selection of the created expert advisor and enabling visual mode for testing.
                                                                                                                                  • Invitation for Premium Course Members (02:04 – 02:09)
                                                                                                                                    • Invitation for premium course members to suggest ideas for new videos.
                                                                                                                                    • Conclusion and Summary (02:09 – 02:24)
                                                                                                                                      • Conclusion on how to calculate and display historical profit for a currency pair using MQL5.
                                                                                                                                      • Emphasis on the functionality of the created expert advisor with minimal MQL code.
                                                                                                                                      •  

                                                                                                                                        In this video, we are going to create an expert advisor that calculates the historical profit for a specific currency pair and displays it on the chart. Let’s see how we can do that. To begin, start the MetaEditor by clicking on the little icon or pressing F4 on your keyboard. The code starts by including the Trade.mqh library, which provides functions and methods for performing trade operations.

                                                                                                                                         

                                                                                                                                        We then create an instance of the CTrade class called trade to execute trade operations like buying and selling. Inside the OnTick function, we calculate the current Ask and Bid prices for the symbol. These prices are essential for executing buy and sell orders. The code checks if there are less than two open positions. If true, it executes both a buy and a sell order.

                                                                                                                                         

                                                                                                                                        This is just for demonstration purposes. The historical profit for the currency pair is calculated using the GetCurrencyPairHistoryProfit function and then displayed on the chart. The GetCurrencyPairHistoryProfit function calculates the total historical profit for the specific currency pair. Several variables are initialized to store information like the total number of deals, ticket numbers, order types, and profits. The HistorySelect function is used to fetch historical deal data. A for loop iterates through all the historical deals.

                                                                                                                                         

                                                                                                                                        For each deal, the profit and swap for the deal are obtained, the type of order (buy or sell) is determined, and the currency pair for the deal is checked to ensure it matches the current symbol. Once you’ve written the code, press F7 to compile it. If this was too fast for you or if you don’t understand what all the code is doing, you may want to check out the premium course on our website or watch one of the basic videos first. After compiling, go back to MetaTrader by pressing F4 or clicking on the icon. In MetaTrader, press control and R to start the strategy tester.

                                                                                                                                         

                                                                                                                                        Pick the expert advisor that we have just created, enable the visual mode, and start a strategy test. You should then see the expert advisor on the chart. If you’re already a premium course member and have an idea for a video like this one, please send us an email. In conclusion, you’ve now learned how to calculate and display the historical profit for a specific currency pair using MQL5. With just a few lines of MQL code, you’ve created a functional expert advisor. Thanks for watching, and I’ll see you in the next video!

                                                                                                                                        The post MQL5 TUTORIAL – HOW TO CALCULATE THE HISTORY PROFIT appeared first on MQL5 Tutorial.

                                                                                                                                        3 min
                                                                                                                                      • MQL5 Tutorial – Simple Order Cancel Order EA

                                                                                                                                         

                                                                                                                                        1. Introduction to Order Cancels Order (OCO) System (00:00 – 00:09)
                                                                                                                                          • Introduction to the concept of OCO, where one order’s execution cancels the other.
                                                                                                                                          • Visualization of sell stop and buy stop orders on the chart.
                                                                                                                                          • Understanding Orders and Positions (00:09 – 00:30)
                                                                                                                                            • Explanation of the difference between an order and a position.
                                                                                                                                            • How orders become positions when triggered by price movements.
                                                                                                                                            • Creating an Expert Advisor in MetaEditor (00:30 – 01:01)
                                                                                                                                              • Instructions on opening MetaEditor and starting a new Expert Advisor project.
                                                                                                                                              • Naming the project ‘Simple Cancel Order.’
                                                                                                                                              • Setting Up the Expert Advisor (01:01 – 01:30)
                                                                                                                                                • Removing unnecessary lines and importing the ‘trade.mqh’ file.
                                                                                                                                                • Creating an instance of the CTrade class.
                                                                                                                                                • Initializing Trading Parameters (01:30 – 02:05)
                                                                                                                                                  • Getting account balance, equity, ask, and bid prices.
                                                                                                                                                  • Normalizing prices for different currency pairs.
                                                                                                                                                  • Creating Buy Stop and Sell Stop Orders (02:05 – 03:28)
                                                                                                                                                    • Conditions for opening pending orders when no positions or orders exist.
                                                                                                                                                    • Setting up buy stop and sell stop orders with defined take profit points.
                                                                                                                                                    • Implementing Order Cancellation Logic (03:28 – 04:49)
                                                                                                                                                      • Checking for active trading and differing balance and equity values.
                                                                                                                                                      • Creating a function to cancel open orders.
                                                                                                                                                      • Compiling and Testing the Expert Advisor (04:49 – 05:32)
                                                                                                                                                        • Compiling the code in MetaEditor.
                                                                                                                                                        • Instructions for testing the Expert Advisor in MetaTrader.
                                                                                                                                                        • Visualizing the Expert Advisor’s Functionality (05:32 – 06:06)
                                                                                                                                                          • Observing the behavior of the Expert Advisor with pending orders in MetaTrader.
                                                                                                                                                          • Explanation of how the Expert Advisor cancels one order when the other is triggered.
                                                                                                                                                          • Conclusion and Summary (06:06 – 06:06)
                                                                                                                                                            • Recap of how to create a simple OCO Expert Advisor in MQL5.
                                                                                                                                                            • Emphasis on the ease of coding this functionality with a few lines of MQL5 code.
                                                                                                                                                            •  

                                                                                                                                                              Today we want to talk about a system that is called OCO that is the short term for Order Cancels Order.

                                                                                                                                                              If you look on our chart we have a sell stop here and we have a buy stop there and here is where the price is and if the price moves to the sell stop that would trigger a short position.
                                                                                                                                                              And if the price rises and hits the buy stop we would have a long position. Now what’s the difference between an order and a position?
                                                                                                                                                              You use an order if you want to open a position so you can place your orders in the market and if the price moves and hits your pending order it will become a position.
                                                                                                                                                              You see that we have cancelled the other order now. It’s no longer here, so let’s find out how to create an Expert Advisor that can cancel pending orders.
                                                                                                                                                              To do that please click on the little button here or press the F4 key and once you have done that piece click on File, New, Expert Advisor from Template, Continue.
                                                                                                                                                              I will call it Simple Cancel Order, Continue, continue and finish and now you want to remove everything above the OnTick function and the two comment lines here.
                                                                                                                                                              And to have anything to close we first need to import the file trade mqh by using the include function.
                                                                                                                                                              We want to create an instance of the Class Ctrade and that will have the name trade.
                                                                                                                                                              In the first step we need to get the account balance that is done by using account info double, Account_Balance.
                                                                                                                                                              Now we need to get the equity by using account info double, Account_Equity and we also need the ask prize here we use symbol info Double_Symbol for the current chart and the constant Symbol_Ask.
                                                                                                                                                              We also use normalized Double_Digits because we have currency pairs with five digits and other currency pairs with three digits and now we do exactly the same to get the bid price, but this time we use Symbol_Bid.
                                                                                                                                                              Now if we have no open position and no order, so if positions total equals zero and if orders total also equals zero, we need to open a pending order for a buy stop and another one for the sell stop, the position size is ten micro lot.
                                                                                                                                                              In both cases the buy stop order will be placed one hundred points above the ask price and the sell stop order will be placed one hundred points below the bid price.
                                                                                                                                                              For the current symbol we have not defined a stop loss, the take profit is three hundred points above the ask price and two hundred, no let’s also use three hundred points below the bid price.
                                                                                                                                                              We use other time GTC that means the order will stay until we cancel it, so we have no expiration time here.
                                                                                                                                                              If we would use an expiration time we would use this parameter to define it and the last parameter here is for a comment but we don’t need that.
                                                                                                                                                              If we are trading right now – that would mean that the balance has different value than our equity.
                                                                                                                                                              We want to cancel the open orders so let’s create a function called cancel order.
                                                                                                                                                              It’s a void type because it doesn’t need to return any kind of value and here we use For Loop.
                                                                                                                                                              It starts by using orders total minus one and until the value for the counter is zero that means as long as we have open orders it will go through all the open orders.
                                                                                                                                                              We use order get ticket for the current order to find out the ticket number and it now will delete the pending orders by using Trade.OrderDelete for the order ticket that we have calculated here.
                                                                                                                                                              And the last thing we need to do is to close the For Loop and the cancel order function.
                                                                                                                                                              Now let’s compile the code by clicking the little button here or pressing the F7 and that did actually work without any errors.
                                                                                                                                                              So now please click here or press F4 to go back into Meta Trader. And in MetaTrader you want to click on View, Strategy Tester or press control and R, and here you want to select the Simple Cancel Order.ex5 file, select any currency pair and enable the visualisation mode.
                                                                                                                                                              After you have done that please start your test. And here you see two pending orders; one is a buy stop and another one is a sell stop so let’s zoom in and see how it works.
                                                                                                                                                              That’s a little bit slow so let’s speed it up here.
                                                                                                                                                              Now you can see the pending order is gone, we have an open position and every time the open position is closed, two new pending orders will be opened here and as soon as the first order is triggered the other one will be cancelled.
                                                                                                                                                              Okay now you know how you can create a very simplified version of the order cancel order Expert Advisor and you have coded it yourself with a few lines of MQL 5 code.
                                                                                                                                                              Download “MQL5 - Simple Order Cancel Order EA from MQL5 Tutorial” SimpleCancelOrder.txt – Downloaded 455 times – 1.55 KB

                                                                                                                                                              The post MQL5 Tutorial – Simple Order Cancel Order EA appeared first on MQL5 Tutorial.

                                                                                                                                                              7 min
                                                                                                                                                            • MQL5 Tutorial – Advanced Library Expert Advisor

                                                                                                                                                               

                                                                                                                                                               

                                                                                                                                                              1. Introduction to Expert Advisor with Self-Defined Functions (00:00 – 00:14)
                                                                                                                                                                • Introduction to an expert advisor that opens buy stops and calculates profit on a chart.
                                                                                                                                                                • Explanation of using self-defined functions compiled in a library.
                                                                                                                                                                • Understanding Libraries in MQL5 (00:14 – 00:27)
                                                                                                                                                                  • Explanation of what a library is in MQL5 and its purpose.
                                                                                                                                                                  • How to create a library for reusable functions.
                                                                                                                                                                  • Opening MetaEditor and Creating a Library (00:27 – 00:41)
                                                                                                                                                                    • Instructions on opening MetaEditor from MetaTrader.
                                                                                                                                                                    • Steps to create a new library in MQL5.
                                                                                                                                                                    • Setting Up the Library File (00:41 – 01:01)
                                                                                                                                                                      • Explanation of import statements and the structure of the library file.
                                                                                                                                                                      • Introduction to the functions ‘getProfitCurrencyPair’ and ‘openBuyStop.’
                                                                                                                                                                      • Defining Functions in the Library (01:01 – 01:30)
                                                                                                                                                                        • How to define custom functions in the library.
                                                                                                                                                                        • Example of creating functions for opening buy stops and calculating profit.
                                                                                                                                                                        • Initializing Variables and Importing Trade Functions (01:30 – 02:05)
                                                                                                                                                                          • Setting up initial variables and importing necessary trade functions.
                                                                                                                                                                          • Explanation of the ‘property library’ directive.
                                                                                                                                                                          • Creating Self-Defined Functions (02:05 – 03:28)
                                                                                                                                                                            • Detailed steps to create self-defined functions in the library.
                                                                                                                                                                            • Example of a function to calculate profit for a currency pair.
                                                                                                                                                                            • Implementing the Buy Stop Function (03:28 – 04:49)
                                                                                                                                                                              • Creating a function to open buy stop orders.
                                                                                                                                                                              • Explanation of parameters and conditions for the buy stop.
                                                                                                                                                                              • Compiling and Testing the Library (04:49 – 05:32)
                                                                                                                                                                                • Instructions on compiling the library in MetaEditor.
                                                                                                                                                                                • How to test the library’s functionality in MetaTrader.
                                                                                                                                                                                • Using the Library in an Expert Advisor (05:32 – 06:06)
                                                                                                                                                                                  • Demonstrating how to use the created library in an expert advisor.
                                                                                                                                                                                  • Visualizing the expert advisor’s behavior in MetaTrader.
                                                                                                                                                                                  • Conclusion and Summary (06:06 – 06:25)
                                                                                                                                                                                    • Recap of how to create and use a custom library in MQL5.
                                                                                                                                                                                    • Emphasis on the efficiency of using libraries for reusable code.
                                                                                                                                                                                    •  

                                                                                                                                                                                       

                                                                                                                                                                                      What you see here is an Expert Advisor that is opening buy stops and we have a calculated profit on the chart and it uses two self defined functions that we have compiled in a so called library.

                                                                                                                                                                                      You can think of a library as a file that contains self defined functions that you can use again and again.
                                                                                                                                                                                      Now how can we create such a library in MQL5?
                                                                                                                                                                                      To do that please click on the little button here in your Meta Trader and now you should see the MetaEditor and this is our main module and we use these import statements here to import the file MyLibrary.ex5 and in that file we have a function called GetProfitCurrencyPair and another function called OpenBuyStop.
                                                                                                                                                                                      And in the OnTick function we check if we have no open orders and if that is the case we want to OpenBuyStop so we call the self defined function OpeBuyStop from our library.
                                                                                                                                                                                      And to calculate the profit we use the function GetProfitCurrencyPair and that’s also self defined in our library.
                                                                                                                                                                                      And to create your own library please click on File, New, Library, Continue, this one is called myLibrary and now you can click on Finish.
                                                                                                                                                                                      And the first thing we need is property library, without that you cannot compile the file and to be able to open the buy stops we need to import the trade functions from the built in trade.mqh file.
                                                                                                                                                                                      And to get the profit of the current currency pair we need to create our self defined function and this extension 2export” is used because only a function with such a modifier is accessible for our MQL 5 programs.
                                                                                                                                                                                      And in the function we declare a variable called ProfitThisCurrencyPair; it contains no value here and now we go through all the positions using this For Loop and we use PositionGetSymbol for the current counter and if the symbol on the chart equals the symbol of the currency pair from our position, we use PositionGetDouble, position_profit to calculate the position profit and position get double, position_swap to calculate the swap.
                                                                                                                                                                                      Just add the two values up to get the profit of the currency pair.
                                                                                                                                                                                      Let’s end the For Loop and we use normalize double and two digits to calculate the profit for the currency pair and format it for two digits behind the dot, and afterwards we use return to return the profit for the currency pair back to the main module.
                                                                                                                                                                                      Let’s add another function for the buy stop, it’s called OpenBuyStop and it also has the export extension and to open the buy stop we want to know the ask price, the balance and the equity.
                                                                                                                                                                                      You can get the ask price by using SymbolInfoDouble for the current symbol and you use symbol_ask and with NormalizeDouble and _Digits we make sure that we have three digits for this currency pair or five digits for other currency pairs and to get the balance of the equity we use AccountInfoDouble, Account_Balance or AccountInfoDouble, Account_Equity.
                                                                                                                                                                                      And if equity and balance are equal, we want to open a buy stop by using trade.buystop for 10 micro lots.
                                                                                                                                                                                      The buy stop will be one hundred points above the ask price of the current symbol.
                                                                                                                                                                                      We haven’t defined a stop loss, the take profit will be three hundred points above the ask price and we use Order_Time GTC because that is good until the order is cancelled so it will not expire and because of that we use a zero for the date/time and the last parameter would be for the comment, we don’t need that so we also use zero here.
                                                                                                                                                                                      Let’s add the last bracket to close the function and press this little button or F7 on your keyboard to compile your library.
                                                                                                                                                                                      I made a mistake here, of course I need to create an instance of Ctrade now that’s done and I recompile and this time it worked without any errors.
                                                                                                                                                                                      So let’s click on the button here our press F4 to go back to MetaTrader.
                                                                                                                                                                                      And in MetaTrader you want to click on View, Strategy Tester or press control and R, and in the Strategy Tester please select the file simpleLibraryMainModule.ex5 and please remember that you also have to compile the main module each time you create a library or you change a library.
                                                                                                                                                                                      Now let’s click on start and here we go.
                                                                                                                                                                                      I will speed up the process a little bit and now you know how to create an Expert Advisor that is able to import your self-written library and you have created it with a few lines of MQL5 code.

                                                                                                                                                                                      The post MQL5 Tutorial – Advanced Library Expert Advisor appeared first on MQL5 Tutorial.

                                                                                                                                                                                      7 min