MQL5 Tutorial

MQL5 Tutorial

By Raimund BauerBusinessTechnologyInvesting
Download on the App Store

All MQL5 Tutorial episodes

  • MQL5 TUTORIAL – SIMPLE SAR STOCHASTIC STANDALONE EXPERT ADVISOR

     

    1. Introduction to SAR Stochastic Standalone Expert Advisor (00:00 – 00:10)
      • Introduction to creating an Expert Advisor in MQL5 that uses the Parabolic SAR and Stochastic Oscillator indicators for buy and sell signals.
      • Starting with MetaEditor (00:10 – 00:25)
        • Instructions on opening the MetaEditor from MetaTrader and the initial setup, including importing the ‘Trade.mqh’ library.
        • Setting Up Price Calculation (00:25 – 01:12)
          • Explanation of calculating the asking and bid prices using the ‘SymbolInfoDouble’ function and normalizing these prices.
          • Preparing Price Data Array (01:12 – 01:29)
            • Setting up an array named ‘PriceInfo’ to store price data and sorting it to prioritize the latest data.
            • Implementing Parabolic SAR Indicator (01:29 – 02:17)
              • Using the Parabolic SAR indicator within the ‘CheckEntry’ function to identify potential buy or sell signals.
              • Refining Signals with Stochastic Oscillator (02:17 – 02:45)
                • Utilizing the ‘CheckEntryStochastic’ function to refine trading signals based on the Stochastic Oscillator values.
                • Executing Trades Based on Signals (02:45 – 03:09)
                  • Decision-making process for executing buy or sell trades based on the combined signals from SAR and Stochastic indicators.
                  • Compilation and Testing in MetaTrader (03:09 – 03:38)
                    • Instructions for compiling the code and testing the Expert Advisor in MetaTrader using the strategy tester.
                    • Conclusion and Additional Resources (03:38 – 03:53)
                      • Recap of the tutorial and an invitation to explore more advanced courses or send ideas for new videos.
                      •  

                        In this video, we are going to create an Expert Advisor that uses the Parabolic SAR and Stochastic Oscillator indicators to generate buy and sell signals in MetaTrader. Let’s see how we can do that. First, start the MetaEditor. You can do this by clicking on its icon or simply pressing the F4 key. We begin with the #include directive to import the Trade.mqh library. This library provides us with essential trading functions.

                         

                        Following this, we create an instance of the CTrade class named trade. This instance will be our primary tool for executing buy and sell orders. Next, we calculate the current asking price using the Symbol Info Double function with the parameters Symbol and SYMBOL ASK. This gives us the price at which we can buy. To ensure precision, we use the Normalize Double function, inputting the price and Digits to adjust the number of decimal places. Similarly, we determine the bid price using the Symbol Info Double function with the parameters Symbol and SYMBOL BID. This is the price at which we can sell. This price is also normalized using the Normalize Double function. We then set up an array named Price Info of type Mql Rates.

                         

                        This array will store our price data for specific time periods on the chart. Within the On Tick function, we sort our Price Info array using the Array Set As Series function to prioritize the latest data. We then fill this array with price data for the current symbol and time frame using the Copy Rates function. Here, we’re copying data for three candles, giving us a snapshot of recent price movements. The closing price of the most recent candle is then determined using the Price Info[0].close reference. We then call the Check Entry function.

                         

                        Inside this function, we use the Parabolic SAR indicator to check the current and previous values to determine if there’s a buy or sell signal. If the current SAR value is below the current price and the previous SAR value was above the previous price, it suggests a buy signal. Conversely, if the current SAR value is above the current price and the previous SAR value was below the previous price, it suggests a sell signal. Additionally, the Check Entry Stochastic function is used to refine our signals. This function checks the Stochastic Oscillator values. If the K line crosses the D line from below in an oversold area, it suggests a buy signal. If the K line crosses the D line from above in an overbought area, it suggests a sell signal. With these signals in hand, the code decides whether to execute a buy or sell trade. If both the trading signal and the filter signal return a buy and there are no open positions, the trade.Buy function is used to buy 0.10, equivalent to 10 Micro Lot. If both signals return a sell, the trade.Sell function is used to sell 0.10 Microlot. Once you’ve input all 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 might want to check out the Premium course on our website or watch one of the basic videos first. After a successful compilation, return to MetaTrader by pressing the F4 key or clicking on its icon. Once in MetaTrader, press Control and R to start the strategy tester. Select the Expert Advisor you’ve just created, enable the visual mode, and start a strategy test. You should then see the Expert Advisor in action 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. By the end, you’ll have a deeper understanding of what you’ve learned and the Expert Advisor you’ve coded yourself with just a few lines of MQL code. Thanks for watching, and I’ll see you in the next video!

                        The post MQL5 TUTORIAL – SIMPLE SAR STOCHASTIC STANDALONE EXPERT ADVISOR appeared first on MQL5 Tutorial.

                        5 min
                      • MQL5 TUTORIAL – SIMPLE IVIDYA STANDALONE EXPERT ADVISOR

                         

                        1. Introduction to IVIDYA Standalone Expert Advisor (00:00 – 00:26)
                          • Introduction to creating an Expert Advisor in MQL5 for the Variable Index Dynamic Average (IVIDYA) indicator. Explanation of buy and sell signals based on the indicator’s position relative to price candles.
                          • Setting Up in MetaEditor (00:26 – 01:01)
                            • Instructions on opening MetaEditor from MetaTrader and creating a new Expert Advisor file named ‘SimpleIVIDYAStandaloneEA’. Initial code setup including removing unnecessary lines.
                            • Including Trade.mqh and Initializing CTrade (01:01 – 01:30)
                              • Explanation of including the ‘Trade.mqh’ file and creating an instance of the ‘CTrade’ class for opening positions later in the code.
                              • Calculating Ask and Bid Prices (01:30 – 01:49)
                                • Details on calculating the Ask and Bid prices using ‘SymbolInfoDouble’ and normalizing these prices with ‘NormalizeDouble’ and ‘_Digits’.
                                • Setting Up Price and EA Data Arrays (01:49 – 02:47)
                                  • Creating and sorting a price array (PriceArray) using ‘MqlRates’ and ‘ArraySetAsSeries’. Also, setting up an array for the Expert Advisor data (EAArray) and sorting it.
                                  • Implementing IVIDYA Indicator (02:47 – 04:10)
                                    • Using the ‘iVIDyA’ function to define the Expert Advisor based on the Variable Index Dynamic Average Indicator. Filling the EAArray with data using ‘CopyBuffer’.
                                    • Calculating and Assigning Signals (04:10 – 05:02)
                                      • Determining the current IVIDYA value and assigning ‘sell’ or ‘buy’ signals based on its comparison with the close price of the last candle.
                                      • Executing Trades Based on Signals (05:02 – 05:29)
                                        • Executing sell or buy trades using ‘trade.Sell’ or ‘trade.Buy’ based on the calculated signal and the absence of open positions.
                                        • Displaying Signal on Chart and Testing (05:29 – 06:01)
                                          • Using the ‘Comment’ function to display the current signal on the chart. Instructions for compiling the code and testing the Expert Advisor in MetaTrader.
                                          • Conclusion and Demonstration (06:01 – 06:41)
                                            • Conclusion of the tutorial with a demonstration of the Expert Advisor in action, showing a buy signal and the opening of a position.
                                            •  

                                              In this video we are going to create an Expert Advisor to calculate this Indicator; it’s the Variable Index Dynamic Average, whenever the red line is above the price that would be a sell signal and in the other case when the red line is below the candles – like here – that would be a buy signal.

                                              Now how can we create an Expert Advisor that is going to actually trade our signal and output our buy and sell signals directly on the chart?
                                              To do that please click on the little button here or press F4 on your keyboard and now you should see the Metaeditor window and here you want to click on: “File/ New/ Expert Advisor (template)” from template, I will call this file: “SimpleIVIDYAStandaloneEA”, click on “Continue”, “Continue” and “Finish”.
                                              Now we can remove everything that is above the “OnTick” function and let’s also delete the two comment lines here.
                                              We start by including the file: “Trade.mqh”. Sometimes people ask me where the file is?
                                              Well, it’s included in MQL5 and we can create an instance of the class: “CTrade” that will be called: “trade” and we are going to use it later on to open positions.
                                              Inside of the “OnTick” function we are going to calculate the Ask price and the Bid price. We get the prices by using “SymbolInfoDouble”, we use “SYMBOL_ASK” to calculate the Ask price and “SYMBOL_BID” to calculate the Bid price.
                                              With “NormalizeDouble” and “_Digits” we calculate the number of digits behind the dot.
                                              Let’s create a string variable that will be called: “signal” and we are going to calculate the signal value later on so we don’t assign a value right now.
                                              We also need to create a price array (PriceArray) that is done by using “MqlRates”, lets sort the array from the current candle downwards by using “ArraySetAsSeries” and with “CopyRates” we fill our array (PriceArray) with price data for the current symbol on the chart and the currently selected period, we are going to start from the current candle 0 (zero) and we need the price for 3 candles – that’s for the prices.
                                              Now we need to create an array for the Expert Advisor data that will be called: “EAArray”, let’s also sort that one by using “ArraySetAsSeries”.
                                              Now we actually can define the Expert Advisor by using the integrated “iVIDyA” function. If you mark that one and hit F1 you will see all the parameters for the Variable Index Dynamic Average Indicator, it has only one buffer and the parameters are: the current symbol on the chart, the currently selected period on the chart, here we have a 9, a 12 and a 0 (zero) – so let’s click on: “Insert/ Indicators/ Trend/ Variable Index Dynamic Average” and you will see that we have a “Period CMO:” that is 9, the “Period EMA:” that is 12 and the “Shift:” value of 0 (zero) and that’s exactly what we use here and the value will be calculated based on the close price (PRICE_CLOSE). So let’s use “CopyBuffer” to fill our array (EAArray) with data according to the IVIDYA definition (iVIDyADefinition) we have created here, it’s for only one buffer – the first buffer is buffer 0 (zero) – the current candle is also candle 0 (zero), we need data for 3 candles so we use a 3 here and save it in our “EAArray”.
                                              So far so good; to get the current value we just look into our “EAArray” and we need the value for the current candle – that’s candle 0 (zero) – now we can actually calculate the signal. Whenever the current iVIDyA value (iVIDyAVALUE) is bigger than the close price of the last candle in our price array (PriceArray) that would be a sell signal and that’s when we want to assign the word: “sell” to our signal.
                                              In the other case if the iVIDyA value (iVIDyAVALUE) is smaller than the price array 1 close price for candle 1 (PriceArray[1].close) that would be a buy signal and now we assign the word: ”buy” to our signal.
                                              Whenever our signal equals sell and “PositionsTotal” is less than 1 – with other words we don’t have any open position – we use “trade.Sell” to sell 10 micro lot. In the other case if the signal equals buy and we have no open positions we would use “trade.Buy” to buy 10 micro lot.
                                              In the last step we also create a chart output by using the “Comment” function, it would output the words: “The current signal is:” followed by the signal that we have calculated.
                                              Please don’t forget the closing bracket here and when you are done you can click on the “Compile” button here or press F7. That worked without any errors here so now we can click here or press F4 to go back to Metatrader.
                                              In Metatrader we click on: “View/ Strategy Tester” or press CTRL and R, here we select our new file: “SimpleIVIDYAStandaloneEA.ex5”, let’s enlarge this here, mark the visualization option and start a test.
                                              …and here is our first trade, our Expert Advisor is working, the signal line is below the candles here so we have a buy signal, it actually opened our first position and now you know how to create a standalone version for the Variable Index Dynamic Average Indicator that actually is going to trade automated and you have created it yourself with a few lines of MQL5 code.

                                              Download “MQL5 TUTORIAL - SIMPLE IVIDYA STANDALONE EXPERT ADVISOR” SimpleIVIDYAStandaloneEA.txt – Downloaded 330 times – 1.69 KB

                                              The post MQL5 TUTORIAL – SIMPLE IVIDYA STANDALONE EXPERT ADVISOR appeared first on MQL5 Tutorial.

                                              8 min
                                            • MQL5 TUTORIAL – HOW TO OPTIMIZE YOUR RESULTS

                                               

                                               

                                              CLICK AND USE COUPON CODE “PLATINSYSTEMDEMO” FOR A DEMO COURSE & DEMO VERSION

                                               

                                              Introduction to MQL5 System Testing (00:00 – 00:15)

                                              • Introduction to system testing in MQL5 for the Platinum Group’s new and improved system. Explanation of the two signals and other changes made to the system.
                                              • Selecting the Right Expert Advisor in MetaTrader (00:15 – 00:25)

                                                • Instructions on selecting the appropriate expert advisor in MetaTrader’s strategy tester, with emphasis on versioning for each system change.
                                                • Importance of Versioning and Testing Duration (00:25 – 00:45)

                                                  • Discussion on the importance of creating new versions for every system change and setting the test duration for a full year.
                                                  • Setting Default Values and Starting the Test (00:45 – 00:57)

                                                    • Setting everything to default values in the Inputs tab and starting the test without the visual mode to save time.
                                                    • Optimizing System Values (00:57 – 01:43)

                                                      • Explanation of optimizing system values like the curve and position size, and starting subsequent tests for better profitability.
                                                      • Evaluating Test Results and Profit Expectations (01:43 – 02:20)

                                                        • Analysis of test results, discussing realistic profit expectations, and the possibility of adjusting values for higher profits.
                                                        • Long-Term Testing and Aggressive Settings (02:20 – 02:46)

                                                          • Consideration of long-term testing over 20 years and the risks of using too aggressive settings.
                                                          • Results of Strategy Tests and Profitability (02:46 – 03:02)

                                                            • Reviewing the results of various strategy tests and discussing the profitability and drawdowns in trading.
                                                            • Platinum Member Updates and System Testing (03:02 – 03:51)

                                                              • Information for Platinum members about optional updates and the ongoing extensive testing to ensure system stability.
                                                              • Final Test Results and Conclusion (03:51 – 04:21)

                                                                • Presentation of the final test results showing significant profit and concluding remarks on the importance of realistic testing.
                                                                •  

                                                                  This video is about system testing. This is the new and improved system for the Platinum Group. We now have two signals here and also some other things have been changed. And in this video we’re going to take a look at how to test a system like this. To do that, first of all, we need to select the right expert advisor in MetaTrader. I have now selected here in the strategy tester the version from July the 14th. And that is already the first criterion. You should, when you create a new system, always create a new version for every change, even if it means a little more work. But then you always have the possibility to go back to the last working version if you ever made a mistake. This is today’s date, July the 20th, 2023. So I want to test for a full year. And here on the Inputs tab, I first set everything to the default values. If I now start the test here, then I see the strategy tester with the information on the chart. But we want to save some time. That’s why I’ll pause this here and we’ll do the test without the visual mode. This should be relatively quick in the optimized version. Here, you can already see how the progress is developing. The total test time is given here with about two minutes. And I will fast forward the video to the end of the test in a moment to show what the result is. So as you can see, the system survived. But of course we didn’t make a profit here. The reason is: The default settings are meant to make a system profitable in the long run over a long period of ten or more years. But that can be wrong for some years. And of course you can optimize such values, now. We start here by changing the values for the curve and for the position size and start the test again. Okay, the second strategy test is done. This already looks quite good. However, this could be much more profitable here. So in the next step, I go a little higher with these two values and start the test again. This also worked, but it is not yet profitable. Let’s set the position size to four times because the drawdowns here were not really high. And let’s see if we can optimize this. So this test is also done and this time we are at about 11.3% profit with a moderate risk. That’s about what I see as a realistic profit expectation. Of course, you can go much, much higher here now with these values, but that wouldn’t work for every year. In 2003, I started my testing. I could change this accordingly and that would then work with the default settings for 20 years. But I’m pretty sure these settings here would be too aggressive at some point in this long term test. So we can just test by doubling the values here again and see what happens. Okay, this strategy test is also over. And this time we would have made 45,000 profit. That would be 45% for a $100,000 account. And of course, on this chart here, it all looks totally easy and smooth. But the people who really take profit in trading are the people who can take drawdowns like this here without manipulating their own system. And that always works best when you don’t need the money. And I believe that the percentage of Platinum members who have the nerve to endure such drawdowns, and who also have the money to go through such developments here is above average. And if you are already a Platinum member, then you can use the new version from the Platinum system as an optional update in the next few weeks. I myself don’t like forced updates. That’s why there is always the possibility to continue using the previously approved version. I will use the next few days to do some more extensive testing to make sure that the system does not ship with serious bugs. Nevertheless, it’s safe to say that this is still a version in beta status. If you click on the chart above, you can see how many tests I do every day. And the basic idea is to make such a system more and more stable. And there’s really nothing better for that than a large number of realistic tests. I think that’s it for this video. This test should also be finished in a few seconds. I’m quite happy with the result, because this time we would have made $55,000 profit with a $100,000 account. That was it so far. I say thanks for watching – and see you in the next video.

                                                                   

                                                                   

                                                                  The post MQL5 TUTORIAL – HOW TO OPTIMIZE YOUR RESULTS appeared first on MQL5 Tutorial.

                                                                  5 min
                                                                • MQL5 TUTORIAL – SIMPLE ITEMA EXPERT ADVISOR

                                                                   

                                                                  Introduction to ITEMA Expert Advisor (00:00 – 00:11)

                                                                  • Introduction to the ITEMA Indicator, specifically the Triple Exponential Moving Average Indicator, with a focus on the red line representing the indicator.
                                                                  • Explanation of ITEMA Indicator and Strategy Test (00:11 – 00:34)

                                                                    • Detailed explanation of the Triple Exponential Moving Average, its calculation based on 14 candles, and the goal to create an Expert Advisor for it.
                                                                    • Setting Up in MetaEditor (00:34 – 01:07)

                                                                      • Instructions for opening MetaEditor in MetaTrader and creating a new Expert Advisor file named ‘Simple ITEMA’. Initial setup and code preparation.
                                                                      • Creating and Sorting Price Array (01:07 – 01:49)

                                                                        • Steps to create a price array using ‘MqlRates’, sorting it with ‘ArraySetAsSeries’, and filling it for 3 candles using ‘CopyRates’.
                                                                        • Setting Up EA Data Array and ITEMA Definition (01:49 – 02:33)

                                                                          • Creating and sorting an array for the Expert Advisor data (EAArray). Defining the ITEMA Expert Advisor using the ‘iTEMA’ function.
                                                                          • Configuring ITEMA Indicator Parameters (02:33 – 03:27)

                                                                            • Setting up parameters for the ITEMA indicator, including the currency pair, period, shift value, and price type. Using ‘CopyBuffer’ to fill the EAArray.
                                                                            • Calculating ITEMA Value and Outputting Signals (03:27 – 04:59)

                                                                              • Calculating the ITEMA value for the current candle and creating chart outputs for ‘SHORT’ and ‘LONG’ signals based on the ITEMA value and close price.
                                                                              • Compiling and Testing the Expert Advisor (04:59 – 05:27)

                                                                                • Instructions for compiling the Expert Advisor in MetaEditor and testing it in MetaTrader using the Strategy Tester.
                                                                                • Adjusting Signal Frequency and Quality (05:27 – 06:39)

                                                                                  • Adjusting the shift value for candles to reduce signal frequency and improve signal quality. Recompiling and retesting the Expert Advisor.
                                                                                  • Conclusion and Demonstration (06:39 – 06:47)

                                                                                    • Conclusion of the tutorial with a demonstration of the Expert Advisor in action, showing improved signal quality with fewer signals.
                                                                                    • Please let me know if you need any further details or adjustments to this format.

                                                                                       

                                                                                      This time we are talking about the ITEMA Indicator. This is for the Triple Exponential Moving Average Indicator. You see this red line here. If we pass the strategy test and hover over the red line you will see that it is called the Triple Exponential Moving Average and its calculated based on 14 candles.

                                                                                      In this video we are going to find out how to create an Expert Advisor to calculate a Triple Exponential Moving Average Indicator and how to improve the frequency of the signals that are created.
                                                                                      To do that please click the little button here in your Metatrader or press F4 on your keyboard and now you should see the Metaeditor window and here you want to click on “File -New -Expert Advisor” from template (template), Continue (Next). I will call this one: “Simple ITEMA” (SimpleITEMA). Click on continue, continue and finish.
                                                                                      Now everything above the “OnTick” function can be removed, let’s also delete the two comment lines.
                                                                                      First we need to create an array for the prices, that’s done by using “MqlRates” and the array will be called: “PriceArray”. We use the MQL5 built-in function “ArraySetAsSeries” to sort the price array from the current candle downwards and with “CopyRates” we fill the array for 3 candles. That’s enough to calculate the current candle and calculate crossovers. “CopyRates” takes a few parameters, first one is the symbol parameter – that’s for the current currency pair on the chart – the second one is for the currently selected period on the chart. We start with candle zero; that’s the current candle, copy the data for 3 candles and store it in the price array.
                                                                                      In the next step we to create another array for the Expert Advisor data, that will be called “EAArray” and the Expert Advisor array also need to be sorted by using “ArraySetAsSeries”.
                                                                                      Now it’s time to actually define the ITEMA Expert Advisor. That is done by using the built-in function: “iTEMA”, it takes a few parameters: the first one once again is the currency pair on the chart, the second one is once again the selected period on the chart, these are 14 candles because if you click on “Insert -Indicators -Trend -Triple Exponential Moving Average” you will see that the default value for the built-in indicator also is 14 candles. We use a shift value of 0 here and it applies to the close price, so that’s what we are using here: shift value 0 and “PRICE_CLOSE “. Now that we have created the definition we use “CopyBuffer” for the ITEMA definition (iTEMADefinition) we have created here. The 0 is for the first buffer, this 0 stands for the current candle, the 3 is to copy 3 candles and we want to save it in the array called: “EAArray”. Now that we have done that we calculate the ITEMA value (ITEMAVALUE) for the current candle 0 in our array. I use float, usually it’s a double and if you press F1 you will see that a double variable is 8 bytes in size, a float variable only takes half of the size and it’s better to read for us humans. So, let’s create a chart output depending on the direction. If the ITEMA value is bigger than the close price of the first candle in the price array – remember the first candle is always this one, this is candle zero, candle one, candle two and so on – so, if this expression is true we use the “Comment” function to output the text: “iTEMA IS SHORT”, followed by the calculated ITEMA value. In the other case if the close price for candle one in our price array is above the ITEMA value we will output: “iTEMA IS LONG”, also followed by the value.
                                                                                      Okay, that’s it.
                                                                                      When you are done you can click on the compile button here, we get a warning that says that we have a possible loss of data due to type conversion, that’s because I used a float variable here but for this little Expert Advisor that is okay. So, if the compilation works without any errors you can click the little button here or press F4 to go back to Metatrader.
                                                                                      In Metatrader please click on “View -Strategy Tester” or press CTRL and R and now you should select the file: SimpleITEMA.ex5, mark the visualization option here and start a test.
                                                                                      This is how our Expert Advisor looks like, you see it saying: “iTEMA IS SHORT “or “iTEMA IS LONG”.
                                                                                      The frequency of the signals is much too high, so let’s fix that!
                                                                                      We go back into the Metaeditor and change the shift value for the candles to 100 candles. Let’s recompile the code, press F4, stop the current test and start a new one!
                                                                                      This is how it looks like, just press the minus key a few times and now you see that the indicator is calculated 100 candles before the price and whenever the price is crossing here we will get another signal. Let’s speed that up a little bit, now we are getting much fewer signals but the signal quality is better!
                                                                                      Okay. That’s it!
                                                                                      Now you know how to create an Expert Advisor for a Simple Triple Exponential Moving Average Indicator and you have coded it yourself with a few lines of MQL5 code.

                                                                                      Download “MQL5 Tutorial - Simple ITEMA Expert Advisor” SimpleiTEMA.txt – Downloaded 3304 times – 1.11 KB

                                                                                      The post MQL5 TUTORIAL – SIMPLE ITEMA EXPERT ADVISOR appeared first on MQL5 Tutorial.

                                                                                      8 min
                                                                                    • MQL5 Tutorial – Simple External Signals In A File

                                                                                       

                                                                                      Introduction to Using External Signals in MetaTrader (00:00 – 00:15)

                                                                                      • Introduction to how external signals can be used to create buy or sell signals in MetaTrader. Example of a simple text file influencing trading decisions.
                                                                                      • Setting Up the Text File for Signals (00:15 – 00:46)

                                                                                        • Explanation of the location and content of the text file used for generating signals in Windows. Demonstration of how changing the text file content immediately affects trading actions.
                                                                                        • Creating the Expert Advisor in MetaEditor (00:46 – 01:18)

                                                                                          • Instructions for opening MetaEditor, creating a new Expert Advisor file named ‘Simple External Signal’, and initial code setup.
                                                                                          • Importing Trade.mqh and Initializing CTrade (01:18 – 01:43)

                                                                                            • Steps to import the ‘Trade.mqh’ file and create an instance of the ‘CTrade’ class for opening trades.
                                                                                            • Getting Ask Price and Normalizing Digits (01:43 – 02:13)

                                                                                              • Code for obtaining the ask price for the current symbol and normalizing the number of digits behind the decimal point.
                                                                                              • Defining File Path and Opening Text File (02:13 – 03:46)

                                                                                                • Defining the file path for the signal text file, opening the file using ‘FileOpen’, and setting the appropriate file mode and encoding.
                                                                                                • Reading and Closing the External File (03:46 – 04:08)

                                                                                                  • Reading the buy signal from the external text file using ‘FileReadString’ and closing the file with ‘FileClose’.
                                                                                                  • Checking for Open Positions and Executing Trades (04:08 – 04:50)

                                                                                                    • Checking if there are no open positions and if the text file contains a specific buy signal, then executing a buy trade.
                                                                                                    • Displaying Current Buy Signal and Positions Total (04:50 – 05:08)

                                                                                                      • Using the ‘Comment’ function to display the current buy signal from the file and the total number of positions.
                                                                                                      • Compiling and Testing the Expert Advisor (05:08 – 05:37)

                                                                                                        • Instructions for compiling the Expert Advisor and testing it in MetaTrader using the Strategy Tester.
                                                                                                        • Observing EA Behavior with External Signals (05:37 – 06:56)

                                                                                                          • Observing how the Expert Advisor responds to changes in the external text file, opening and closing trades based on the updated signals.
                                                                                                          •  

                                                                                                            This week I’ve gotten a few requests: how we can use external signals to create buy or sell signals in Metatrader. Right now, our buy signal is “Don’t Buy It Now”, and we have no open positions. And this is a simple text file. It is located in the user’s path in Windows. So that path here might be a little bit different, depending on your name and your operating system, but it should be below MetaQuotes, terminal, common files. Right now, it contains the sentence, “Don’t buy it now”. So let’s see what happens if I remove the Don’t and save the file. Immediately, a new Buy trade appears. So now we have opened a new position by using an external text file. And in this little video, we are going to find out how to do that. In your MetaTrader, please click on the little button here or press the F4 key. And in Metatrader, you want to click on File, New, Expert Advisor from Template, Continue. I will call it simple external signal and finish. And now you can remove everything above the on tick function and the two comment lines here. And to open a trade, the first thing we need is to import the trade.MQH file by using the include function.

                                                                                                             

                                                                                                            And now we want to create an instance that will have the name trade. And inside the ontick function, the first thing we do is to get the ask price by using symbol info double for the current symbol. We use the constant symbol underline ask because we need the ask price. And with normalize double and underline digits, we make sure that we have the right number of digits behind the dot, because there are some currency pairs that have only three digits and others have five. Let’s tell MQL5 actually which file we are going to use. Remember, this is the path where my files are located. In your case, it might be a little bit different, depending on your operating system and your name. This is the File handle, it’s an integer value and we use FileOpen for the file with the name signal.txt. We use File_Read, because we only want to read what’s in the file. File_ANSI means it’s a file that is containing strings of ANSI type. Ansi is only using one byte. You could, for example, also use File_Unicode. That would be used for two byte symbols. So if you see any weird characters on your screen, the reason might be the wrong encoding here.

                                                                                                             

                                                                                                            And File_Common is used for the file path in the common folder of all client terminals. It ends with terminal, common files, like in this case. This pipe character here is used as a delimiter that is used to separate the different items in a txt file or in a comma separated file. And CP_ACP means we are currently using the current Windows ANSI code page. Now that our file is defined, we use File, Read String for the external file we have created here to read out a buy signal. It will be a text string. And afterwards, we close the file. That is done by using the command File Close for our external file. And if no open positions exist and a buy signal occurs, that would mean positions total equals zero and the text in our file is “Buy it Now”. Well, in that case, we want to open a buy position by using trade.buy for 10 micro lots on the current chart for the current Ask Price. We have no stop loss defined. Our take profit is 100 points above the current Ask Price and we don’t need a comment here, so we use null for the last parameter.

                                                                                                             

                                                                                                            The last step is to create a chart output by using the comment function. It will show us the current buy signal that is the text that is contained in our file, followed by the text positions total and the value we have calculated for positions total. And if everything is okay, please click on the compile button. And if you don’t have any errors or any warnings, click on a little button here or press F4 to go back to Metatrader. Now in Metatrader, please click on View, Strategy Tester, or press CTRL and R. And here you need to select the file simple external signals.ex5, enable the visualization and start the test. Now our little expert advisor is running and you see the buy signal right now is: don’t buy it now. The number of open positions is zero. So let’s change the text file here. click on File, Save. And immediately a new trade is opened here. And if you speed up the process, you will see that new trades are opened and closed. But if the external condition is no longer true, or if I change the file content manually and save it, the buy signal will change to stop buying or whatever is in the text file.

                                                                                                             

                                                                                                            Let’s save that again. Now it says, Buy signal is stop buying or whatever is in the text file. Okay, Now you know how you can create an Expert Advisor that can read external Txt files. Actually, you could also use Excel files or whatever to use external signals. And you have coded it yourself with a few lines of MQL5 code.

                                                                                                            The post MQL5 Tutorial – Simple External Signals In A File appeared first on MQL5 Tutorial.

                                                                                                            8 min
                                                                                                          • MQL5 TUTORIAL – HOW TO STILL BENEFIT WHEN THE PRICE RUNS AGAINST YOU

                                                                                                             

                                                                                                            Introduction to Benefiting from Adverse Price Movements (00:00 – 00:09)

                                                                                                            • Introduction to the challenges of trading, emphasizing the importance of resilience in addition to profit-making, especially in robot trading systems.
                                                                                                            • Initial Experience with a New Trading System (00:09 – 00:25)

                                                                                                              • Sharing the initial experience of using a live trading system, highlighting the initial challenges faced, including a drawdown situation.
                                                                                                              • Facing a Drawdown and Managing No Profit Week (00:25 – 00:48)

                                                                                                                • Discussing the experience of entering a sell position during a downtrend and facing the opposite market movement, resulting in a week without profits.
                                                                                                                • Highlighting the Absence of Losses (00:48 – 01:00)

                                                                                                                  • Emphasizing the significance of not incurring losses during the first week of trading with the new system, despite no financial gains.
                                                                                                                  • Features of the Robot Trading System (01:00 – 01:15)

                                                                                                                    • Explaining the robot trading system’s design to handle drawdowns through an intelligent algorithm that hedges positions, maintaining balance in unpredictable market conditions.
                                                                                                                    • Importance of Avoiding Losses in Volatile Markets (01:15 – 01:25)

                                                                                                                      • Stating the importance of avoiding losses, especially in volatile markets, and how this can be as crucial as making profits.
                                                                                                                      • Net Gain Achievement and System’s Effectiveness (01:25 – 01:41)

                                                                                                                        • Sharing the outcome of a net gain of one dollar by the closing date of June 23rd, showcasing the system’s effectiveness in safeguarding against potential losses.
                                                                                                                        • Demo Account for Testing the System (01:41 – 01:51)

                                                                                                                          • Offering a demo account for those interested in testing the system’s ability to mitigate losses in unpredictable market conditions.
                                                                                                                          • System’s Focus on Resilience and Risk Mitigation (01:51 – 02:05)

                                                                                                                            • Highlighting the system’s emphasis on resilience and risk mitigation, a change from traditional systems focused primarily on profit generation.
                                                                                                                            • Balancing Risk and Reward in Trading (02:05 – 02:13)

                                                                                                                              • Discussing the robot trading system’s ability to balance risk and reward, providing a buffer against potential losses during market fluctuations.
                                                                                                                              • Unique Features of the Robot Trading System (02:13 – 02:32)

                                                                                                                                • Detailing the unique aspects of the robot trading system, including its strategic approach to risk management and resilience in the face of market unpredictability.
                                                                                                                                • Recommendation and Conclusion (02:32 – 02:48)

                                                                                                                                  • Recommending the robot trading system for those seeking a reliable, stress-tested system capable of withstanding market unpredictability. Invitation to explore the system further through the provided link.
                                                                                                                                  •  

                                                                                                                                    Trading can often feel like a high stakes game where the challenge lies not only in making profits, but also in managing the inherent risks and inevitable lows. That is also true for the robot trading system, a trading tool that is reshaping traditional approaches by emphasizing resilience as much as reward. About a week ago, I set out on a new journey with this live trading system. As with all things new, the onset wasn’t particularly smooth. I found myself in what traders often dread, a drawdown situation. This scenario occurred despite the fact that I had chosen what is a proven strategy, opening a sell position during a downtrend. The unpredictability of the market, however, took its course and I ended up facing the opposite direction of the intended profit.

                                                                                                                                     

                                                                                                                                    As a result, for an entire week, my trading account saw no influx of profits. For many, a week without profits might signal an ineffective system. But I beg to differ. While it’s true that the first week didn’t bring any financial gain, the noteworthy detail lies in the absence of losses. It’s crucial to mention here that the robot trading system I was using is designed specifically to handle such draw downs. The system deploys an intelligent algorithm that efficiently hedges positions, thereby maintaining a balance even when the market doesn’t move in the predicted direction. This might seem like a small win, but when you’re trading, especially in a volatile market, avoiding losses can be just as important, if not more, than making significant profits. On the closing date of June 23rd, my account, despite the week’s market turbulence, stood at a net gain of a single dollar.

                                                                                                                                     

                                                                                                                                    This may not seem like a significant achievement on the surface, but when considering the context, it’s evidence of the system’s effectiveness in safeguarding against potential losses. For those intrigued by the system’s ability to mitigate losses during unpredictable market conditions, the robot trading system offers a demo account for you to test. This thing provides a risk free opportunity to understand the system’s operations and explore its unique features. The system’s emphasis on resilience and risk mitigation might be a refreshing change from traditional systems that primarily focus on profit generation.

                                                                                                                                     

                                                                                                                                    In the world of trading, where the tides can turn swiftly and unexpectedly, it’s a comfort to have a tool that can withstand the push and pull of the market trends. The robot trading system does precisely this by striking a balance between risk and reward. It may not always provide an instant profit, but it offers a buffer against potential losses during turbulent market phases, thus providing a safer trading experience. With its unique emphasis on resilience and a strategic approach to risk management, it stands apart from other trading systems. For anyone seeking a reliable stress tested system that can withstand the unpredictability of the markets, the robot trading system is definitely worth considering. The link is below and as always, thank you for watching and I will see you in the next video.

                                                                                                                                     

                                                                                                                                     

                                                                                                                                    The post MQL5 TUTORIAL – HOW TO STILL BENEFIT WHEN THE PRICE RUNS AGAINST YOU appeared first on MQL5 Tutorial.

                                                                                                                                    4 min
                                                                                                                                  • MQL5 TUTORIAL – BEWARE OF HISTORY QUALITY ISSUES

                                                                                                                                     

                                                                                                                                    Introduction to Historical Data in Trading (00:00 – 00:12)

                                                                                                                                    • Introduction to the concept that all historical data in trading is calculated, and a hint at something unusual related to this data.
                                                                                                                                    • Observing Inconsistencies in Historical Data Scale (00:12 – 00:27)

                                                                                                                                      • Pointing out an inconsistency in the scale of historical data, with months listed one after the other, and a sudden change in complexity.
                                                                                                                                      • Zooming into Chart Data (00:27 – 01:03)

                                                                                                                                        • Demonstrating how zooming into a chart reveals values for each candle, including open, high, low, and close prices, with an example from November 15th.
                                                                                                                                        • Hourly Chart Data Analysis (01:03 – 01:22)

                                                                                                                                          • Analyzing a one-hour chart and noticing discrepancies in the data, such as prices for midnight in January.
                                                                                                                                          • Data Quality in Different Years (01:22 – 01:57)

                                                                                                                                            • Observing how data quality changes over different years, with an example showing hourly data for 10 o’clock, 11 o’clock, and 12 o’clock.
                                                                                                                                            • Quality Issue for Visual Data (01:57 – 02:11)

                                                                                                                                              • Highlighting a quality issue in visual data, where only one candle per day is shown even on an hourly chart, up to the date where the strategy test started.
                                                                                                                                              • Testing Data Quality with Euro US Dollar (02:11 – 02:46)

                                                                                                                                                • Conducting a test with the Euro US Dollar pair, showing hourly charts and data available from December 2002, and confirming data quality is okay for trading from February 2003.
                                                                                                                                                • Checking History Quality in Strategy Test (02:46 – 03:02)

                                                                                                                                                  • Emphasizing the importance of checking history quality in strategy tests, with an example showing a history quality of 99%.
                                                                                                                                                  • Testing with Australian Dollar Against Canadian Dollar (03:02 – 03:16)

                                                                                                                                                    • Conducting a test with the Australian dollar against the Canadian dollar, revealing a history quality of zero, indicating poor data quality.
                                                                                                                                                    • Conclusion and Importance of Checking History Quality (03:16 – 03:30)

                                                                                                                                                      • Concluding the video by stressing the importance of checking the back test tab and the value for history quality every time a strategy test is conducted.
                                                                                                                                                      •  

                                                                                                                                                        This video, I would like to show you something that you might not know, but you should be aware that all the historical data we see is calculated data, more or less. And I will show you something that is a little bit weird. So if you see the scale here below, we have several months that are listed one behind the other. And suddenly here, we have January the third, January the fourth, and so on. So why is the same scale here much less complex? And that’s because when you zoom into the chart, you will notice that each of those candles here has a value that can be shown when you hover with the mouse over the chart. This is the price for the open, the high, the low, and the close price for November the 15th. And the next candle here will show us the same data for the next day. But actually, we have said that we want to trade on a one hour chart. So what you see with your own eyes here is that for January, we have a price for Midnight. Let’s go a little bit further into the data. This is the next year.

                                                                                                                                                        And here suddenly we have a price for 10 o’clock. The next candle is for 11 o’clock, and the next one is for 12 o’clock. That is the way it should be. But actually, when you look at the chart like this one, you might probably not notice that up to the date where we started the strategy test, all the data is just one candle per day. Even we have chosen to trade the hourly chart. So basically, this is a quality issue for visual data. And if we start the test here and zoom into the chart, you will see now we have separate candles for each hour. So data quality might be an issue, especially if you’re trading the early years. Let’s do another test. This time I’m using the Euro US Dollar. Here we are. And if we go back in time, you can see we have hourly charts and data that is available for December 2002. Just remember, we have picked to trade from February 2003. So in this case, the data quality is okay. Now let’s pick the whole year. Let’s set that back to the default and start. Now, we should get a result in a few seconds.

                                                                                                                                                        There we are. And it says that the history quality was 99 %. So if you don’t understand why you have bad results, one of the things that you need to check is the history quality. Let’s repeat the whole thing for the Australian dollar against the Canadian dollar. And here it says the history quality is zero. So make sure to check out the back test tab and the value for the history quality every time you do a strategy test. Okay, so far so good. Thank you for watching and I will see you in the next video. Bye..

                                                                                                                                                        The post MQL5 TUTORIAL – BEWARE OF HISTORY QUALITY ISSUES appeared first on MQL5 Tutorial.

                                                                                                                                                        5 min
                                                                                                                                                      • MQL5 TUTORIAL – 135 SIMPLE LOT SIZE ROUNDING

                                                                                                                                                         

                                                                                                                                                        Introduction to Lot Size Rounding in MQL5 (00:00 – 00:11)

                                                                                                                                                        • Introduction to calculating a lot size based on the account balance and how to round up or down the result to make it fit in MQL5.
                                                                                                                                                        • Opening MetaEditor for MQL5 Programming (00:11 – 00:20)

                                                                                                                                                          • Instructions on how to open MetaEditor in MetaTrader for MQL5 programming, either by clicking an icon or pressing the F4 key.
                                                                                                                                                          • Creating a New Expert Advisor (00:20 – 00:28)

                                                                                                                                                            • Steps to create a new Expert Advisor from a template in MetaEditor, with the example file named ‘Simple Lot Size Rounding’.
                                                                                                                                                            • Starting with the OnTick Function (00:28 – 00:35)

                                                                                                                                                              • Beginning with the ‘OnTick’ function to calculate the account balance using the ‘AccountInfoDouble’ function.
                                                                                                                                                              • Calculating Position Size and Rounding Variables (00:35 – 00:49)

                                                                                                                                                                • Explanation of calculating the position size based on the account balance and creating variables for rounded values, both up and down.
                                                                                                                                                                • Defining Rounding Functions (00:49 – 01:01)

                                                                                                                                                                  • Introduction to custom functions ‘RoundUp’ and ‘RoundDown’ for rounding the calculated lot size to a specified number of decimal places.
                                                                                                                                                                  • Formatting and Outputting Results (01:01 – 01:18)

                                                                                                                                                                    • Using ‘NormalizeDouble’ to format the final results and outputting them on the chart using the ‘Comment’ function.
                                                                                                                                                                    • Implementing Rounding Functions (01:18 – 01:35)

                                                                                                                                                                      • Detailed explanation of the ‘RoundUp’ function, including parameters for position size and decimal places.
                                                                                                                                                                      • Calculating Rounded Values (01:35 – 01:48)

                                                                                                                                                                        • Description of how to calculate the rounded values using ‘MathCeil’ and ‘MathFloor’ functions for rounding up and down, respectively.
                                                                                                                                                                        • Final Results and Adjustments for Account Types (01:48 – 02:20)

                                                                                                                                                                          • Observing the final rounded values and discussing how to adjust these for different account types to ensure correct position opening.
                                                                                                                                                                          • Support for Different Microlot Sizes (02:20 – 02:30)

                                                                                                                                                                            • Mentioning that not all account types support staggering in microlot sizes down to the second decimal place.
                                                                                                                                                                            • Premium Customer Requests and Course Information (02:30 – 02:46)

                                                                                                                                                                              • Acknowledging that the tutorial was a request from a premium customer and mentioning the availability of a premium course on their website.
                                                                                                                                                                              • Conclusion: Rounding Lot Sizes in MQL5 (02:46 – 03:07)

                                                                                                                                                                                • Concluding the video with a summary of how to round up or down lot sizes in MQL5 to fit specific account types, and highlighting the simplicity of the programming involved.
                                                                                                                                                                                •  

                                                                                                                                                                                  In this video, let’s take a look at how to calculate a lot size based on the account balance and how to round up or down the result to make it fit. So let’s take a look at how to do that with MQL Five. To do that, in MetaTrader please click on the icon up here or press the F Four key. Then you should end up in the MetaEditor. And here we click on File, New Expert Advisor from template, next, assign a name here. I have already done this. My file is called Simple Lot Size Rounding and we’ve already pre-programmed this. We’ll start with the on tick function. There we first want to calculate the account balance. This is done using the Account Info Double, Account Balance function and based on the account balance we want to calculate the position size. In our case, we use the gross balance value and divide it by 100,000. We also create two variables for the rounded values, one rounded up and one rounded down. We determine these with the help of the respective function, which we program ourselves.

                                                                                                                                                                                   

                                                                                                                                                                                  The first function is called Round up, the second Round down and we pass the calculated lot size and the value for the decimal rounding as parameters. We want to round this to one decimal place. With Normalize Double, we can output the final results in a more formatted way. Although we have specified two decimal places here, we see that our results are truncated after the first digit. And using the Comment function, we output the whole thing on the chart. Let’s move on to the actual functions. To round up, we pass our input value. That’s the position size that we passed above and our rounding value. Let’s add the second parameter here for the decimal places. And to get the result, we multiply the rounding value by the result of this function. If you press F1 once and call that up in the help, you’ll see that there’s an integer value returned. And as parameters, we pass the input value and the rounding value to the MathCeil function. Then we use Return to return our result back to the function. The second function for rounding the value works similarly.

                                                                                                                                                                                   

                                                                                                                                                                                  Here, however, we do not use MathCeil, but MathFloor. And here we also return the result to our main function. And this then results in the rounded up value 0.3 and the rounded down value 0.2 for a determined lot size of 0.25 lot. Depending on which account type you have, you can adjust this accordingly and thus pass the correct values so that a position can also be opened correctly. Because not all content types support the staggering in microlot sizes down to the second decimal place. By the way, this was again a request from a premium customer. And if you are a premium customer and have an idea for such a video, just send me an email. Otherwise, you can find the premium course on our website. And in this video, you learned how to easily round up or round down lot sizes so that that fits your account type. And you programmed that yourself with these few lines here in MQL5.

                                                                                                                                                                                   

                                                                                                                                                                                  The post MQL5 TUTORIAL – 135 SIMPLE LOT SIZE ROUNDING appeared first on MQL5 Tutorial.

                                                                                                                                                                                  4 min
                                                                                                                                                                                • MQL5 TUTORIAL – 134 STANDALONE BOLLINGER MACD EXPERT ADVISOR

                                                                                                                                                                                   

                                                                                                                                                                                  Introduction to Standalone Bollinger MACD Expert Advisor (00:00 – 00:02)

                                                                                                                                                                                  • Introduction to creating an Expert Advisor that automatically trades a Bollinger Bands entry signal with a MACD Oscillator filter in MetaTrader 5.
                                                                                                                                                                                  • Combining Bollinger Bands and MACD for Signals (00:02 – 00:20)

                                                                                                                                                                                    • Explanation of how Bollinger Bands and MACD are popular indicators that can be combined to create buy and sell signals for automated trading with this standalone Expert Advisor.
                                                                                                                                                                                    • Starting in MetaEditor for MQL5 Programming (00:20 – 00:26)

                                                                                                                                                                                      • Instructions to open MetaEditor in MetaTrader for MQL5 programming.
                                                                                                                                                                                      • Creating a New Expert Advisor (00:26 – 00:33)

                                                                                                                                                                                        • Steps to create a new Expert Advisor from a template in MetaEditor, with the example file named ‘Standalone Bollinger MACD Expert Advisor’.
                                                                                                                                                                                        • Including Trade.mqh and Initializing CTrade (00:33 – 00:41)

                                                                                                                                                                                          • Including the ‘Trade.mqh’ file for simplified trading functions and creating an instance of the ‘CTrade’ class.
                                                                                                                                                                                          • Importing Bollinger and MACD Modules (00:41 – 00:56)

                                                                                                                                                                                            • Including separate modules for Bollinger Bands and MACD, which provide entry and filter signals, respectively.
                                                                                                                                                                                            • Calculating Ask and Bid Prices (00:56 – 01:22)

                                                                                                                                                                                              • Using ‘SymbolInfoDouble’ to calculate Ask and Bid prices for the current symbol on the chart.
                                                                                                                                                                                              • Setting Up Price Array and Normalizing Digits (01:22 – 01:49)

                                                                                                                                                                                                • Creating a price array with ‘MqlRates’ and sorting it with ‘ArraySetAsSeries’. Normalizing the number of digits behind the decimal point for currency pairs.
                                                                                                                                                                                                • Filling Price Array with Data (01:49 – 02:05)

                                                                                                                                                                                                  • Using ‘CopyRates’ to fill the price array with data for the current symbol and period on the chart.
                                                                                                                                                                                                  • Calculating Current Price and Signals (02:05 – 02:23)

                                                                                                                                                                                                    • Calculating the current price from the close price of candle 0 and creating variables for trading and filter signals using ‘CheckEntryBollinger’ and ‘CheckEntryMacD’.
                                                                                                                                                                                                    • Executing Trades Based on Signals (02:23 – 02:48)

                                                                                                                                                                                                      • Executing buy or sell trades with ‘trade.buy’ or ‘trade.sell’ based on the combined trading and filter signals, provided there are no open positions.
                                                                                                                                                                                                      • Displaying Signals on Chart and Testing (02:48 – 03:05)

                                                                                                                                                                                                        • Using the ‘Comment’ function to display the trading signal and filter on the chart. Instructions for compiling the code and testing the Expert Advisor in MetaTrader.
                                                                                                                                                                                                        • Conclusion and Strategy Testing (03:05 – 03:25)

                                                                                                                                                                                                          • Conclusion with instructions for running a strategy test in MetaTrader 5 and an invitation to explore more source codes and the premium course on MQL5TUTORIAL.com.
                                                                                                                                                                                                          •  

                                                                                                                                                                                                            In this video we are going to create an Expert Advisor that is able to automatically trade a Bollinger Bands entry signal and a filter for the MacD Oscillator in Metatrader5. Both indicators are very popular and can be combined to create buy and sell signals that can automatically traded with this standalone Expert Advisor. So let’s see how to do that in MQL5. Please open the MetaEditor. We start by creating a new Expert Advisor by clicking on File, New, Expert Advisor from template. Let’s continue, with the include function to include the file Trade.mqh which comes with MQL5. It provides simplified trading functions and we create an instance of the class CTrade so we can use them.

                                                                                                                                                                                                             

                                                                                                                                                                                                            Afterwards we include two files for the entry and the filter signal. The first one is for the Bollinger Bands and it will give us a trading signal. The second one is for the MacD and it will give us a filter signal. Both files have been coded before as separate modules, so they can also be used for other Expert Advisors. If you want to save time and effort, you can go to MQL5Tutorial.com where you can find the premium course and a lot of precoded source code files in the store. In the next step we need to calculate the Ask price and the Bid price. That can be done by using the function SymbolInfoDouble for the current Symbol on the chart. We use Symbol_Ask to calculate the Ask price and Symbol_Bid to calculate the Bid price. With NormalizeDouble and UnderscoreDigits we can calculate the number of digits behind the dot. Depending on the currency pair, that might be 3 or 5 digits.

                                                                                                                                                                                                             

                                                                                                                                                                                                            With MqlRates we create an Array for prices, called PriceInfo. Inside of the Ontick function we use ArraySetAsSeries to sort our price array from the current candle downwards. Then we can use CopyRates to fill our price array with data. We do that for the current symbol and the currently selected period on our chart, starting from candle 0, for 3 candles and store the result in our price info array. Now let’s calculate the current price by looking at the close price of candle 0 in our price info array. We create a string variable for the Trading Signal and call the function CheckEntryBollinger to check for a buy or sell signal. And we do the same thing for a string variable called Filter and call the function CheckEntryMacD to get the filter signal. If the trading signal and the filter both return a buy signal and we have no open positions, we want to use trade.buy to buy 10 Micro Lot. In the other case, if the trading signal and the filter both return a sell signal, we use trade.sell to sell 10 Micro Lot. Finally, we use the Comment statement to output the trading signal and the filter on our chart. Press F7 to compile the code, if that works without any errors, you can return to Metatrader by pressing the F4 key.

                                                                                                                                                                                                             

                                                                                                                                                                                                            Okay, if everything went well, you should now have a working standalone Expert Advisor for the Bollinger Bands signal and the MacD filter. You can run a strategy test like this one by pressing Control and R in Metatrader5. If you want to improve your trading results, you can find the premium course and more source codes on MQL5TUTORIAL.com and in our shop. Thank you for watching and I will see you in the next video.

                                                                                                                                                                                                            The post MQL5 TUTORIAL – 134 STANDALONE BOLLINGER MACD EXPERT ADVISOR appeared first on MQL5 Tutorial.

                                                                                                                                                                                                            4 min
                                                                                                                                                                                                          • MQL5 TUTORIAL – SIMPLE BEARS POWER STANDALONE EXPERT ADVISOR

                                                                                                                                                                                                             

                                                                                                                                                                                                            Introduction to Standalone Bears Power Expert Advisor (00:00 – 00:15)

                                                                                                                                                                                                            • Introduction to creating an Expert Advisor for the Bears Power Indicator in MQL5, aiming to produce signals visible on the chart for automated trading.
                                                                                                                                                                                                            • Opening MetaEditor for MQL5 Programming (00:15 – 00:44)

                                                                                                                                                                                                              • Instructions on opening MetaEditor in MetaTrader and creating a new Expert Advisor file named ‘SimpleBearsPowerStandaloneEA’. Initial setup and code preparation.
                                                                                                                                                                                                              • Including Trade.mqh and Initializing Variables (00:44 – 01:17)

                                                                                                                                                                                                                • Steps to include the ‘Trade.mqh’ file and create an instance of the ‘CTrade’ class for opening positions later in the code.
                                                                                                                                                                                                                • Calculating Ask and Bid Prices (01:17 – 01:55)

                                                                                                                                                                                                                  • Explanation of calculating Ask and Bid prices using ‘SymbolInfoDouble’ and normalizing these prices with ‘NormalizeDouble’ and ‘_Digits’.
                                                                                                                                                                                                                  • Setting Up Price and EA Data Arrays (01:55 – 02:25)

                                                                                                                                                                                                                    • Creating and sorting a price array (PriceInformation) using ‘MqlRates’ and ‘ArraySetAsSeries’. Also, setting up an array for the Expert Advisor data (myPriceArray) and sorting it.
                                                                                                                                                                                                                    • Implementing Bears Power Indicator (02:25 – 03:11)

                                                                                                                                                                                                                      • Using the ‘iBearsPower’ function to define the Expert Advisor based on the Bears Power Indicator. Filling the myPriceArray with data using ‘CopyBuffer’.
                                                                                                                                                                                                                      • Calculating and Assigning Signals (03:11 – 04:12)

                                                                                                                                                                                                                        • Determining the current Bears Power value and assigning ‘sell’ or ‘buy’ signals based on its value being below or above 0, respectively.
                                                                                                                                                                                                                        • Executing Trades Based on Signals (04:12 – 04:41)

                                                                                                                                                                                                                          • Executing sell or buy trades using ‘trade.Sell’ or ‘trade.Buy’ based on the calculated signal and the absence of open positions.
                                                                                                                                                                                                                          • Displaying Signal on Chart and Testing (04:41 – 05:21)

                                                                                                                                                                                                                            • Using the ‘Comment’ function to display the current signal on the chart. Instructions for compiling the code and testing the Expert Advisor in MetaTrader.
                                                                                                                                                                                                                            • Conclusion and Strategy Testing (05:21 – 05:33)

                                                                                                                                                                                                                              • Conclusion of the tutorial with a demonstration of the Expert Advisor in action, showing buy and sell signals, and an explanation of how the Bears Power Oscillator is typically used to filter another entry signal.
                                                                                                                                                                                                                              •  

                                                                                                                                                                                                                                In this video we are going to talk about this Indicator, it’s the Bears Power Indicator and we want to create an Expert Advisor that is able to actually produce signals that will be seen right here on the chart and in this case we use the Bears Power Indicator tool trade automated.

                                                                                                                                                                                                                                Usually this Indicator is used as a filter and you would use another signal and only when the signal and the filter are pointing in the right direction you would open a new position.
                                                                                                                                                                                                                                To code that please click on the little button here or press F4 on your keyboard, now you should see the Metaeditor window and here we want to click on: “File/ New/ Expert Advisor (template)” from template, “Continue”, I will call this one: “SimpleBearsPowerStandaloneEA”, click on “Continue”, “Continue” and “Finish”, now you can delete everything above the “OnTick” function and the two comment lines here.
                                                                                                                                                                                                                                We start by including the file: “Trade.mqh”, this one comes with MQL5 and it contains some trading functions. We need to create an instance from the class: “CTrade” that will be called: ”trade” and we are going to use it to open positions later on.
                                                                                                                                                                                                                                Inside of the “OnTick” function we calculate the Ask price and the Bid price, that’s done by using “SymbolInfoDouble” for the current symbol on the chart, “SYMBOL_ASK” will give us the Ask price while “SYMBOL_BID” will give us the Bid price and with “NormalizeDouble” and “_Digits” we calculate the right number of digits after the decimal point.
                                                                                                                                                                                                                                We also need to create a string for the signal, that string variable will also be called: ”signal” and so far we don’t have any value because that is going to be calculated later.
                                                                                                                                                                                                                                Let’s create an array for the price data that will be called: “PriceInformation” and we use “MqlRates” to create it because “MqlRates” is the structure that stores the information about prices, volumes and spread. We sort the array downwards from the current candle by using “ArraySetAsSeries” and with “CopyRates” we fill the array (PriceInformation) with price data for the current symbol on the chart and the currently selected period. We start with the current candle 0 (zero) and we need price data for 3 candles – that’s enough – and store the result in our price information array (PriceInformation).
                                                                                                                                                                                                                                Now let’s create another array called: “myPriceArray” this one is for the Expert Advisor data, the other one was for the candle prices.
                                                                                                                                                                                                                                The second array also needs to be sorted downwards by using “ArraySetAsSeries”.
                                                                                                                                                                                                                                Now we use the “iBearsPower” function that comes with MQL5 for the current symbol and the currently selected period on the chart, the last parameter 13, is the number of candles that you also will see when you drag the Bears Power Oscillator on your chart.
                                                                                                                                                                                                                                Now we use “CopyBuffer” for the bears power definition (BearsPowerDefinition) that we have created here to calculate the values for buffer 0 (zero) – that’s the first buffer – from the current candle 0 (zero) for 3 candles and store the result in our price array (myPriceArray) that makes it possible to calculate the current array value by looking at candle 0 (zero) in our price array (myPriceArray) and we store a result in the bears power value (BearsPowerValue) and if the “BearsPowerValue” is above 0 we would consider that to be a buy signal so we assign the word: “buy” to our signal.
                                                                                                                                                                                                                                Otherwise if the “BearsPowerValue” is below 0 we consider that to be a sell signal so now we assign the word: “sell” to our signal and if the signal equals sell and we have no open positions we use “trade.Sell” to sell 10 micro lot.
                                                                                                                                                                                                                                Otherwise if the signal equals buy and we have no open positions we would use “trade.Buy” and buy 10 micro lot.
                                                                                                                                                                                                                                Finally we create a chart output that is done by using the “Comment” function and we want to output the words: “The current signal is:” followed by the calculated “signal”.
                                                                                                                                                                                                                                Now let’s compile the code, we don’t have any errors and in that case we can click here or press F4 to go back to Metatrader.
                                                                                                                                                                                                                                In Metatrader we click on: “View/ Strategy Tester” or press CTRL and R, you will select the “SimpleBearsPowerStandaloneEA”. Let’s also enable the visualization option here and start your test.
                                                                                                                                                                                                                                …and here is our little example at work, we have buy and sell signals, usually you would use the Bears Power Oscillator to filter another entry signal but now you know how to code a standalone Expert Advisor for Metatrader 5 and you have coded it yourself with a few lines of MQL5 code.

                                                                                                                                                                                                                                Download “MQL5 Tutorial - Simple Bears Power Standalone Expert Advisor”

                                                                                                                                                                                                                                SimpleBearsPowerStandaloneEA.txt – Downloaded 156 times – 1.71 KB

                                                                                                                                                                                                                                The post MQL5 TUTORIAL – SIMPLE BEARS POWER STANDALONE EXPERT ADVISOR appeared first on MQL5 Tutorial.

                                                                                                                                                                                                                                7 min