MQL5 Tutorial

MQL5 Tutorial

By Raimund BauerBusinessTechnologyInvesting
Download on the App Store

All MQL5 Tutorial episodes

  • MQL5 TUTORIAL – SIMPLE ENTRY SIGNAL EXCHANGE
    In this video, I wanted to talk about trading entries and how to change them by using a trading framework. This is the English version of the Golden Goose Framework and here you can see that we are trading several positions at once. This is the Williams’ Percent Range indicator, let’s enable the graph mode here and speed the process up. It is making profit and we would like to know if another entry could improve our results. Now the question is how can we exchange this entry here? To do that we stop the test here. This is the main module of the Golden Goose Framework, actually it’s a version from April, and it is still my favorite version. It contains three different parts; this is the first part. It’s the part where we import the framework components. These are functions to do different things. This function here is to open a buy trade, this one will set the equity stop, and this one would set the position size. The second part is where we import the entry logic and in our case, we include the module: “CheckEntry_WPR” – that’s stands for Williams’ Percent Range, and this is the third part where we actually trade it. The function: “OnTick” will run whenever the price on the chart changes and we would check for an entry, maybe get a signal and call the trade management to open the function: “CheckForTick” and pass this signal to the trade management part of the framework. Well, as I already set, this is the Check Entry module for the Williams’ Percent Range indicator. Let’s out-comment this, enable the next module, this is for the Momentum indicator, let me change the language to English here, compile the code and when you have done that please click on the little button here to return to Metatrader. Here we want to use the same system, the same currency pair, the same time span and start another test and this time it is trading the Momentum indicator. I will also speed up this one for you. This time the result should be different and you could compare it. Let’s do another one here. Let’s do… Actually, I would like to do the Bollinger Bands, I will copy that line here and include the pre-coded module called: “CheckEntry_Bollinger”. Compile the code, switch to Metatrader, start another test and now it’s trading the Bollinger Bands as you can see here a trade was generated when the price left the upper Bollinger Band and did a re-entry here. So far it looks good, but let’s do another one! I really like the SAR indicator so let’s try this one, compile the code, go back to Metatrader and start another test here. The Parabolic SAR indicator is very easy to read, when the points are above the price it goes down and as long as the points are below the price it goes up. So, let’s speed it up and watch the results! Okay, in this video, you have learned how you can change trading entries within seconds and compare the results for an automated trading year to find the best entry signal for your needs and you can use pre-coded entries like this one and change the trading entry within seconds.
    5 min
  • MQL5 Tutorial – FROM ZERO TO AUTOMATED TRADING IN 4 MIN 38 SEC
    In this video, I am going to show you the fastest way to get an MQL5 automation system up and running. I need to do it anyhow, because I need this video tutorial for my Forex trading framework, so I thought I could record the session also for YouTube. If you don’t have traded with MQL5 before, you need to set up everything and in this video, we are going to do it as fast as possible. I have bought this little Stick Pc. It uses the outdated Windows 8.1 so it was very cheap. It comes with a USB port and SD card slot and HDMI, an Intel Atom Quad-Core CPU, 2GB of RAM and a 32 GB SSD are more than enough to run an MQL5 automated trading system. Now we need to go to Metatrader5.com and download MetaTrader 5 for free. When you click on this button you will also get a free demo account, and after a few seconds you can open the setup.exe file, verify the installation permission, read the license agreement, continue. Now a few files are downloaded and as soon as that is finished, read and agree to the license, click on “Continue” and when you are done click on “Finish”. After a few seconds MetaTrader 5 should start. Please notice that is already connected to a demo account here. Now click on “Tools, Options” disable to news on the “Server” tab, reduce the bars on the chart to 5000 on the “Charts” tab. Click on the tab: “Trade”, change the volume to default 0.10 lot, click on “Expert Advisors”, allow automated trading, remove the two marks here, click on “Events” and disable the sound events and leave the tabs for “Notifications”, “Email”, “FTP”, “Community” and “Signals” as they are. Now, click on ok, open your web-browser, go to forextradingframework.com, click on “Menu, Downloads”, you can download the framework for just 1 Dollar, open the Zip file, copy the whole content, go to MetaTrader and click on “File, Open Data Folder”, click on the MQL5 folder, select “Experts, Advisors”, create a new folder. I will call this one: ForexTradingFramework, insert the files here, click into the “Copy_into_Library_Folder, copy the Library, move up a few directories, select the “Libraries” folder now and paste the file here. Please restart MetaTrader, click on “View, Strategy Tester”, select “Advisors, ForexTradingFramework” and the ForexTradingFramework.ex5. file. We want to trade the EURUSD on the 1 minute chart, we will use the last year and a deposit of 100.000 Euros. I use 1 to 500 for the leverage and we will use the 1 minute OHLC, that’s: open, high, low and close prices and start the test. Now you should see something like this when you click on the “Graphs” tab. We just made a total net profit of 185 Euros and 99 Cents with 9 automated trades. Let’s go to “Settings”, select another currency pair, mark the visualization mode and start another test. You will see a download for the history data here and once the download is finished, you should see your Metatrader doing automated trades. Now you know how to setup Metatrader 5 and MQL5 for automated trading and do your first year of autotrading within 4 minutes and 40 seconds.
    5 min
  • MQL5 TUTORIAL – SIMPLE POSITION CLOSE
    This time we are talking about closing of positions, that happened right now. I have gotten a request to do this from one of the YouTube subscribers, the actual request was: “can you make a simple close all position order?”. So I guess he is asking if I can create a video how to close all opened positions once a certain condition is true. We have already closed all positions here, so the first thing we do is opening a few positions and as soon the equity here rises above the balance all the open positions will be closed. That happened right now and because this is just a test the Expert Advisor immediately opened a few new positions, but as soon as the equity is higher than the balance they will be closed again. Here are our closed positions and now we want to check out, how we can create an Expert Advisor that is going to do this. To start, please click on the little button here or press F4 in your Metatrader and now you should see the Metaeditor window. Here you want to click on “File, New, Expert Advisor (template)” from template. Continue. I will call this one: “Simple Position Close” (SimplePositionClose). Continue, continue and finish. Now you want to delete everything above the “OnTick” function here and the two comment lines. The first thing we need to do is to import the Trade Library. We can do that by using the “include” function and the file we want to import is the “Trade.mqh” file. After that we need to create an instance of “Ctrade” that will be called: trade. Inside the “OnTick” function we need to get the Ask price. That is done by using “SymbolInfoDouble” for the current symbol on the chart, and we use SYMBOL_ASK to calculate the current Ask price and with NormalizeDouble and _Digits we make sure that we have either three digits or five digits, depending on the currency pair that might be different. Let’s get the account balance here and it’s done with AccountInfoDouble and here we use ACCOUNT_BALANCE. We do the same for the account equity, but this time we use ACCOUNT_EQUITY. Now we want to open a few positions to have something we can close, so, if PositionsTotal is below 5 we use trade.Buy, let’s actually use 10 micro lot here for the current symbol and the current Ask price. We haven’t defined a Stop Loss here and the Take Profit should be 100 points above the current price, and we don’t need any comments. Please remember we just do this to test it and once the equity is greater than the balance – that would mean that we made a profit – we want to close all positions. So, let’s create a function that can do that. We will actually call it CloseAllPositions and the first thing we need to do is to count from the number of positions down to zero that is done with this “for” loop here and the result will be assigned to counter variable called: “i” . We use PositionGetTicket and that counter variable. To get the ticket number we need to close the position and as soon as we have done that we can close the current position by using trade.PositionClose(i) for the current ticket number. Let’s close the “for” loop and the CloseAllPositions function. If you are ready you can click on the “Compile” button here or press F7 and you shouldn’t get any errors here and if that is the case, please click on the little button here to go back to Metatrader. In Metatrader please click on: “View/ Strategy Tester” or press CTRL and R on your keyboard and here you want to select the file: SimplePositionClose.ex5. Mark the visualization option and start your test. And here we go! The Expert Advisor is opening and closing test positions and now you know how to close all your open positions at once and you have coded it yourself with a few lines of MQL5 code.
    6 min
  • MQL5 TUTORIAL – HOW TO AVOID NASTY BACKTESTING ERRORS
    In this video, we are talking about issues with the historical data that you need to use for your Strategy Tester. This is an Expert Advisor that is going to trade time based entries. If you look at the settings here for the strategy test, you will see that I have selected the one-minute chart, but right now it only has data for hourly charts. You see the time changing and now it’s 4 o’clock PM and now its 5 PM, this is 6PM lets speed that up little bit. This is the next day, this is 2PM, 3PM, 4PM, 5PM and suddenly at 6:45 PM it starts to count the minutes – you can’t see anything on the chart here. The only thing you notice is that the candles are much smaller. This candle is from 6PM, that’s 45min earlier and we are on a one-minute chat. If you don’t know how to find errors like this it can drive you crazy, because 44 missing candles can make the difference between profit and loss. In Metatrader 4, you would have seen this in the history files and you would have been able to press F2, but Metatrader 5 unfortunately doesn’t allow this anymore, so we just need to help ourselves and try to find the cause. The Metatrader 5 help file contains the post about files and folders – this is the web version of it and if you scroll down you will find that there is a basis directory that contains the platform’s data bases grouped by servers. So, let’s click on “View” and “Navigator”, we have a Metaquotes Demo Account that was included in the installation of Metatrader 5 and right now I am on the Roboforex Account and they say that within the default directory we should find a folder called: “History”. And the folder stores history data for financial instruments. The “Default” folder here is what you see if you click on “File/ Open Data Folder” and actually here you will find a folder called: “bases” and within the “bases” folder we find the MetaQuotes-Demo and the RoboForex-MetaTrader 5 directory. Let’s click on the second folder and here we will find another folder called: “history”, and here within the history folder you will see that we have different directories for each and every currency pair. Well, we use the EURUSD for 2016, so let’s switch to the EURUSD folder and here is a file called: 2016.hcc. Now I will try to open it, but unfortunately, it’s not readable because it’s a compiled file. So, let’s delete that file, now it’s gone, start another test and Metatrader is doing exactly the same as before. On the next day at 18:45 it starts to count minute bars. So, obviously this didn’t change anything. The next step is: to look into the MetaQuotes-Demo folder, here we will find another history folder. This one also contains a directory called: EURUSD, so let’s delete the file here and try it for the second time. I start the test and we have the same problem once again. Now, what is going on here? Let’s have a look! I don’t see any history files for 2016 in the MetaQuotes-Demo folder but in the RoboForex folder for history files a new hcc file for 2016 has been created. So, let’s switch to the MetaQuotes Demo Account and start another test. And it does exactly the same as it did before. Well, this is a fresh installation on another PC, let’s download the history from the MetaQuotes server for 2016 and this file is obviously much larger than the original version. So, let’s copy that and paste it here and restart Metatrader 5 again. Once again, I need to connect to the MetaQuotes Demo Account, select my currency pair here and start the test, and this time it really works! It took me about an hour to fix this error and when you think that you get insane looking for an error that couldn’t be there, maybe the cause is just a corrupt history file and that’s why I always tell everybody, it’s a good idea to test different brokers and to use more than one Metatrader 5 installation otherwise you wouldn’t be able to find the cause because this is a compiled file and we can’t see what’s inside! Okay.
    7 min
  • MQL5 TUTORIAL – SIMPLE DYNAMIC POSITION SIZE
    MQL5 TUTORIAL – SIMPLE DYNAMIC POSITION SIZE Audio into Text Transcription In this video, we are going to open lots and lots of trades to show you how to set a Dynamic Position Size. Let’s speed up the process here, now you should see the Dynamic Position Size is changing. Now its eight micro lots, let us speed it up a little bit more, now it’s nine micro lots, now its seven micro lots and right now we are down to six micro lots. How can we create an Expert Advisor that is able to calculate a Dynamic Position Size based on the equity? To do that please click the little button here in the Metatrader or press the F4 key on your keyboard. And now you should see the Metaeditor and here you want to click on “File/ New/ Experts Advisor” from template, I will call this one: Simple Dynamic Lot Size, Continue, Continue and Finish. And now you can delete everything above the OnTick Function and the two comment lines here. First, we need to include the file: Trade.mqh. This file is included in the MQL5 and now we want to create an instance of CTrade. We will call it Trade. In the first step, we need to get the Account Equity, that is done by using the AccountInfoDouble, we are using the term ACCOUNT_EQUITY. For the Account Balance, you could use ACCOUNT_BALANCE and here are several other Account Properties you could use but for now we need the Equity. To set the position size dynamically we created a double variable called: DynamicPositionSize and the lot size should be the Equity divided by one Million. With NormalizeDouble and the two digits here we want to create an output that only has two digits behind the dot. For some reason that doesn’t work always. Let’s speed it up a little bit, it seems to work right now. Now we need to get the Ask price, that can be done with SymbolInfoDouble, for the current Symbol, and here we use SYMBOL_ASK and for the Bid price you would use SYMBOL_BID and with NormalizeDouble and _Digits we ensure that the Ask price is calculated with the right number of digits here because there are three digit and five digit currency pairs. Now if we have below 100 positions and below 100 orders we want to create a Buy Stop with our Dynamic Position Size. The Buy Stop will be placed 100 points above the Ask price for the current currency pair, we haven’t defined a Stop Loss and the Take Profit will be 300 points above the current Ask price. We use the current time without any expiration and we don’t need a comment. In the last step, we are going to use the Comment function to output the text: Dynamic Position Size and the Calculated Position Size. In the last step, we use a bracket to close our module and now you can click on “Compile” or press the F7 key on your keyboard and that worked without any errors. Now click here or press F4 to go back to Metatrader. In Metatrader we want to click on “View/ Strategy Tester”, select the file: SimpleDynamicLotSize.ex5 and click on start. Now you should see that the lot size for your position size is calculated based on your Equity. Okay, in this little video, you have learned how to calculate a Dynamic Position Size in MQL5 and you have done it yourself with a few lines of MQL5 code.
    5 min
  • MQL5 TUTORIAL – FASTER RESULTS WITH OPTIMIZED BACKTESTING
    In this video, we want to talk about back-testing and how we can speed up the whole process. Right now, we are back-testing the momentum indicator and we are using the Golden Goose Framework for it. It takes some time. We have just reached January 2nd, we can speed up the process here but it still takes a long time until our test is finished. One way to speed up the process of testing is to change the kind of data we are testing. Most people believe that Every Tick would be the most accurate option but if you go to the website: mql5.com, you will see that they are generated and the generation is based on support points. If you are really interested you can read the whole article but most of the time I use 1 min OHLC; that’s open/high/low and close prices. That will really speed up the back-testing process and the data quality is high enough to test almost every system you can think of. A second way to speed up the process is to disable the visualization here by removing the check mark. In that case only a graph is generated and this is much faster because Metatrader doesn’t have to process all the price data for each and every candle on the chart. You will still be able to compare the results on the results tab and if you do a right click here and select report: html, you can select a file name, save the file and a few seconds later you can open your html file that will not only contain the results. You can also see valuable information displayed in this infographics here and below that you will see each and every trade you made with all the details and because you saved that file you will be able to compare it to other files to see if you can get better results. But with Metatrader 5 you will be able to optimize your test even more. Just click on optimization and select: All symbols selected in Market watch. This is the market watch window and I have all these symbols here and when I click start I will have a new tab here saying: Optimization Results and Optimization Graph. As you see Metatrader already has done 8 out of 14 currency pairs and in a few seconds, we get a result here. It will show you the profit results here. With a right click you can export it to XML and the best thing is that you can open these XML files with Microsoft Excel or in my case I will use the Libre Office and all I need to do is to click in this cell in here and select sum and now I see that the end result for the first three months of 2017 would have been in the profit. Now I expand my test and go for half a year. This also shouldn’t take very long. Let’s export the second report, I will call this one MyXMLReport2. Let’s open it with the Libre Office calculation tool. Select the cell. Click on the sum symbol and this time we would have made 3647 dollars. Okay. Now you know how you can test forty different currency pairs by using: All symbols selected in MarketWatch. This will save you lots of time if you have to test several years for a dozen currency pairs or more.
    5 min
  • MQL5 TUTORIAL – ADVANCED WPR EXPERT ADVISOR
    In this video, we are going to talk about the Williams’ Percent Range indicator. It is traded automatically right now. We use the Golden Goose Framework in the English version… Right now, it’s equity positive and the balance is also positive. We started with 100.000 US Dollar so if I would close this account right away we would have made a profit of 277 Dollars but I am not going to do that. This very fast running oscillator down here has been invented by a guy named: Larry Williams. Now we are going to find out how we can create an expert advisor that is able to trade this oscillator automatically. To do that please click on the little button here or press F4 in your Metatrader. Now you should see the Metaeditor and here you want to create a file called: CheckEntry_WPR.mq5. It will use a function called CheckEntry that will deliver a string value for the calculated buy or sell signal. We need to create an empty string that will be called signal, but we won’t assign a value right now because we going to calculate that later. We also need to create an array for several prices, that one will be called: WPR-Array[] for Williams’ Percent Range and it’s a double array because it needs to hold floating point values for the prices. In the next step, we are going to create WPRDefinition by using the mql5 built-in function: iWPR. This one takes only three parameters. The first one will be the currency pair in your chart, the second one will be the selected period on your chart and the last parameter has a value of 14 because if you click on Insert/Indicators/Oscillators/Williams’ Percent Range you will see that is calculated for 14 candles. Now we need to sort our array from the current candle downwards. This is done by using ArraySeAsSeries for the WPRArray we have created here and with CopyBuffer we will fill the WPRArray according the WPRDefinition we have created here and we will do that for the first line that’s buffer 0 from the current candle 0 for 3 candles. Now let’s get the value for current the candle! To do that we will get the variable called WPRValue that will look into the WPRArray and it will get the values for candle[0], and with NormalizedDouble and the 2 here we make sure that we calculate only two digits behind the dot. By the way; this expert advisor made 12 hundred dollars so far. And of course, we need to calculate the buy signal now that will always be the case when the value of the line here is between -80 and -100. So if WPRValue is below -80 and above -100 we want to assign the text “buy” to our signal. In the other case, to create a sell signal, we will check if the WPRValue is above -20 and below 0, that would be a sell signal because that is the area above the dotted line here. That’s the -20 mark and this would be the 0 mark. Right now, we made 13 hundred and 70 dollars, but now let’s continue. The final step for our module here is to return the calculated signal to the main module. That will be done by using the return command and now we close the whole module and the function CheckEntry with the final bracket. If you are ready, please click on save because you don’t compile the entry module. In my case I need to compile the main module. This is the Golden Goose Framework. This framework basically is a collection of functions that can be imported. They all have been pre-coded in the so called library. This is the file where we have defined the complete behavior for the trading framework. If you don’t know what a framework is you can basically imagine a trade management system that you can use again and again. It will enable you to trade up to 22 currency pairs and several positions at the same time. Obviously, I can’t explain the whole framework in a 5 to 10 minutes video. If you are interested in getting the framework or coding your own framework just visit my website, you will see the URL at the end of this video.   But back to topic. We are going to import our entry module here and call the CheckEn...
    13 min
  • MQL5 TUTORIAL – Advanced SAR Expert Advisor
    This is the Advanced SAR Expert Advisor in MQL5 and we are just trading the Golden Goose Framework. This is the English version. Whenever the points here, suddenly appear on the other side of the candles this would be a buy or a sell signal. The SAR indicator is part of MQL5 and it is also part of Metatrader 5, you could insert it on your own chart by clicking on insert, indicators, trend, Parabolic SAR. If you click on this indicator you will see that we have a step value of 0.02 and a maximum value of 0.2, and now we want to create a MQL5 expert advisor which is able to find a buy or sell signal and trade it with the forex trading framework. To do that please click on the little button over here and now you should see the Metaeditor. Obviously a 5 to 10 minutes video is too short to explain a whole trading framework but basically, we import a predefined Golden Goose Framework. That’s an ex5 file that was precompiled. It is start in the Libraries folder. That’s the file. It basically provides a number of functions that we can import. Here it ends. Everything in between was pre-coded in the GoldenGooseFramework20170408_EN. If you don’t know what a framework is or how you can get one just follow the website at the end of this video, that’s where you can find out how to rent one or how to create your own. To trade the SAR indicator, we need to create and include a module called CheckEntry_SAR.mq5. So, we create a new and empty file here. First, we need a function called CheckEntry, because that is the function that we call here to check for an entry signal and that signal will be stored in a string variable called signal and afterwards we will call the trade management, check for a new tick and pass the calculated entry signal for the SAR as a parameter. If you find all these stuff too complicated, please make sure to first watch all the simple MQL5 tutorial videos. Go back to topic. Inside of the CheckEntry_SAR module we need to create a price array with MqlRates first and then sort that array from the current candle downwards by using ArraySetAsSeries. And after that we use CopyRates to fill our PriceArray for the current symbol and the current period from candle zero (0) – that’s always the current candle that is created here – for our 3 candles. Now we create an empty string for the signal and we need another array for the SAR values so we create an SAR array. And the SAR definition can be created by using the MQL5 function iSAR for the current symbol and the current period and you already know these two values here. That’s the default value for the two parameters in the Parabolic SAR indicator that you can drag on the chart. Let’s sort the SAR array from the current candle downwards by using ArraySetAsSeries and fill it with data by using CopyBuffer. According to the SAR definition we have created here for the current buffer zero and the current candle that’s also zero. And we need 3 candles, so we need a 3 here and the result will be stored in mySARArray. And now that that array is filled with data let’s actually calculate the value for the last candle. The last candle is candle [1] in our array and we use NormalizeDouble and the 5 to get 5 digits behind the dot, because if you place your mouse over one of these dots you will see a value that also has 5 digits behind the dot. Let’s repeat that, but this time we are doing the same calculation for a candle [2] instead of candle [1] and assign it to the variable NextToLastSARValue. And to find the buy signal we check if the last SAR value was below the low of candle [1] and if it was above the high the candle before. Here it is above the high and now it changes and it’s below the next candle, so this would be a good entry point for a buy trade. And if all that is true we assign the value “buy” to the signal because now we want to buy. Let’s also create a sell signal and to do that we check if the last SAR value was above the candle [1] high and if it was below the low cand...
    9 min
  • MQL5 Tutorial – Simple Stochastic Expert Advisor
    One of our course members with the name Som requested an Expert Advisor that is able to calculate the Stochastic indicator and here it is. This little Expert Advisor is able to generate buy or sell signals, a buy signal will be generated when we have a crossing of these two lines below the 20% mark and for a sell signal we are looking for a crossover above the 80% mark. Now how can we create an Expert Advisor in MQL5 that is able to output the buy or sell signal directly on the chart? To do that please click the little button here or press F4 in Meta Trader and now you should see the Meta Editor here. Here you want to click on File, New, Expert Advisor from Template, Continue. I will name this Expert Advisor Simple Stochastic EA, Continue, Continue and Finish. Now you can delete everything above the OnTick function and the two comment lines here and the first thing we need is an empty string for the signal, we will call it signal and we will not assign any value here because we are going to calculate that later. And now we need to create two arrays; one is named K Array and the other one D Array because if you click on insert indicators, oscillators, Stochastic oscillator you will see a K period here and a D period. Now we need to sort our arrays from the current candle downwards that is done by using array set as series. Now let’s actually define the EA, we create a Stochastic definition by using the built-in MQL5 function iStochastic for the current symbol on the chart and the currently selected period. These three parameters five, three, three can be found if you look at the properties of the Stochastic oscillator. The five K period, the first three is for the D period and the second three is the slowing. It is also called final smoothing in the help file. We want to use a simple moving average for the method and we want to calculate based on the low and high prices so we use Mode_SMA and STO_LowHigh for the last two parameters. Basically everything we have used here can also be found in the default values of the built-in Stochastic Oscillator in MetaTrader 5. Now let’s use copy buffer for the Stochastic definition we have created here for the K array and for the D array. The K Array will be calculated based on buffer zero from the current candles zero for three candles and the D Array will be filled by using buffer one – also from candle zero for three candles . Now let’s actually calculate the value for the current candle. K value zero will be based on the K Array and we use candle zero that’s the current candle and to calculate the D values zero we will also use the D Array and also candle zero. And now we are going to calculate the value for the last candle, we will call that K value one and D value one and we will do the same as above, but this time our calculation will be based on the value of candle one. Now let’s define the buy signal, first we need to check if both values are below twenty, that would be the case if both lines are below the twenty per cent mark here. If that is true we want to check if the K value has crossed the D value from below, that would be the case if the blue line crosses the red line from below. If that is true that would be a buy signal. In the other case for the sell signal we would check if the K value and D value are above the eighty percent mark, that would be in this area. If the K value has crossed the D value from above, that’s the case if the current K value is below the current D value and the K value for candle one is above the D value for candle one, then we would like to create a sell signal. And in the last step we will use the comment function to output the text ‘signal’ followed by the calculated signal directly on our chart in the upper left corner. Okay, if you’re done please click on the compile button here or press F7 on your keyboard. And now you should see that the compiling worked without any errors, so let’s click on the little button here or press F4 to go back t...
    7 min
  • MQL5 Tutorial – Advanced Library Expert Advisor
    What you see here is an Expert Advisor that is opening buy stops and we have a calculated profit on the chart and it uses two self defined functions that we have compiled in a so called library. You can think of a library as a file that contains self defined functions that you can use again and again. Now how can we create such a library in MQL5? To do that please click on the little button here in your Meta Trader and now you should see the MetaEditor and this is our main module and we use these import statements here to import the file MyLibrary.ex5 and in that file we have a function called GetProfitCurrencyPair and another function called OpenBuyStop. And in the OnTick function we check if we have no open orders and if that is the case we want to OpenBuyStop so we call the self defined function OpeBuyStop from our library. And to calculate the profit we use the function GetProfitCurrencyPair and that’s also self defined in our library. And to create your own library please click on File, New, Library, Continue, this one is called myLibrary and now you can click on Finish. And the first thing we need is property library, without that you cannot compile the file and to be able to open the buy stops we need to import the trade functions from the built in trade.mqh file. And to get the profit of the current currency pair we need to create our self defined function and this extension 2export” is used because only a function with such a modifier is accessible for our MQL 5 programs. And in the function we declare a variable called ProfitThisCurrencyPair; it contains no value here and now we go through all the positions using this For Loop and we use PositionGetSymbol for the current counter and if the symbol on the chart equals the symbol of the currency pair from our position, we use PositionGetDouble, position_profit to calculate the position profit and position get double, position_swap to calculate the swap. Just add the two values up to get the profit of the currency pair. Let’s end the For Loop and we use normalize double and two digits to calculate the profit for the currency pair and format it for two digits behind the dot, and afterwards we use return to return the profit for the currency pair back to the main module. Let’s add another function for the buy stop, it’s called OpenBuyStop and it also has the export extension and to open the buy stop we want to know the ask price, the balance and the equity. You can get the ask price by using SymbolInfoDouble for the current symbol and you use symbol_ask and with NormalizeDouble and _Digits we make sure that we have three digits for this currency pair or five digits for other currency pairs and to get the balance of the equity we use AccountInfoDouble, Account_Balance or AccountInfoDouble, Account_Equity. And if equity and balance are equal, we want to open a buy stop by using trade.buystop for 10 micro lots. The buy stop will be one hundred points above the ask price of the current symbol. We haven’t defined a stop loss, the take profit will be three hundred points above the ask price and we use Order_Time GTC because that is good until the order is cancelled so it will not expire and because of that we use a zero for the date/time and the last parameter would be for the comment, we don’t need that so we also use zero here. Let’s add the last bracket to close the function and press this little button or F7 on your keyboard to compile your library. I made a mistake here, of course I need to create an instance of Ctrade now that’s done and I recompile and this time it worked without any errors. So let’s click on the button here our press F4 to go back to MetaTrader. And in MetaTrader you want to click on View, Strategy Tester or press control and R, and in the Strategy Tester please select the file simpleLibraryMainModule.ex5 and please remember that you also have to compile the main module each time you create a library or you change a library.
    7 min