[Music] earlier this year i produced a video on grid trading it was an expert advisor that ran a standard grid simply buy and sell at each level in the grid and i pointed out in that video that the drawback to that type of trading to good trading was that if the price of the instrument you're trading begins to run away in one direction and trend strongly then you can wind up with a lot of positions open and eventually blow your account because you simply run out of margin or you run out of capital because you have a heavy drawdown today i'm going to show you how to write another expert advisor based on a different grid trading strategy now this is not my strategy and on the screen here i have the reference this is a strategy from a group called expert forex which i saw on youtube originally and i have seen several of their videos that go over the same approach i've only put a link to one of the videos here and you should see that for a detailed explanation of how this approach works but what makes this different to the standard grid is that there actually is a stop loss point where if the price moves too far you get out and this makes it much more attractive as i guess a fail-safe system in case the price begins to trend unexpectedly now i'm not going to go into a detailed description of how this works i've given the links to their original video and their website and i'll include the links in the description so you can follow that up for yourself but i'll give you a quick overview because it will make some sense in terms of what we're doing here assuming i have a grid these particular grids have only five levels the beginning level and then four more above or below that i'm going to describe this just in the sense of the price going up into the buy side so we begin at some point where we both buy and sell that's a traditional grid approach and then we need to wait for the price to move to one of the other levels now the sell side is just the mirror of the buy side so i'm only going to be looking at the buy side here because that will make it much easier to show on screen so the first thing that will happen is that the price moves to the next level whether it's the sell or the buy level it will move to the next level so as i said we're only looking at the buy side here so the price moves to the buy side and then we do what you would normally do for a grid close the buy trade that was in profit open a new buy and open a new cell so at that point you've closed one trade in profit so i've indicated their profit equals one now from this point one of two things can happen the price can continue to go up or it can come back again so assuming the price comes back to the original level at that point in this grid you close everything so what you'll have then is the original buy that you closed in profit then you'll have the cell that you opened at that next level coming back and that's another profit so the profit there is one plus one the buy that you opened at that second level though will be at a loss so that's the minus one and the cell that you opened originally will close at break even so that's the plus zero so you get a net profit of one and you've closed everything out the grid is completely done that is the key to this particular grid approach the retracement closes out the entire grid and you just start again now assuming the price didn't come back and went up to the next level like so at this point we would still close out that buy that's in profit from the first level and we would open a new buy and then open a new cell so now we would have three sell trades open and one by trade and at this point we've closed profit for two by trades that have reached those levels so we've got profit one plus one if the price then retraces we close all at that level number one so we begin at level zero we've gone up to level two and now we've come back to level one close everything and so we have two buy trades that have already closed in a profit the sell trade that was opened at level two is closing at a profit so that's three profits we have lost one for the buy trade that was opened at level two the sell trade that was opened at level one has closed at break even because we've come back to that same level where it was opened and the sell trade that was opened at level zero is a loss so we have three winning trades and two losing trades for a total of one so again there's a profit of one just by that retracement coming back if the price had continued again to level number three so zero one two three then again we close the buy open a new buy open a new cell and that gives us three profits to that point and then if there is a retracement we'll make another profit of one for the cell that is opened at level three so that gives us a total profit of four one plus one plus one plus one we will lose one for the buy trade that's opened at level three we will close the cell opened at level two at break even we'll close the cell opened at level one for a loss of one and the cell that was opened at level zero is actually two levels out so that's a minus two so if we go as far as level three and come back to level two close all then we close for a profit of zero now i'm saying profit zero because this is a perfect world diagram in reality you have things like commissions and spread that will mean that you have a small loss here and the profits at the other levels will not be exactly one because you will incur small losses for the spread but for the diagram we're going to assume that it's a perfect world so we close at zero there the other thing that could happen of course is that the price continues up to level number four the final level and at that point we still close everything we'll be closing all of those buy trades on the way up which will give us profits of four but we have the sell trades from levels 0 1 2 and 3 that are going to close at a loss and that gives us a total loss of 6 if we go all the way to that top level so in summary if we close through retracement to levels zero or one we'll close with a profit of one if we close at a retracement to level two we close with profit zero and if we go all the way up to level four then we'll close with a loss of six so the loss is much greater than the profits but what you're looking at here is the probability that that's going to happen so this is best suited to a ranging market where you set the levels far enough apart that the price is unlikely to reach that fourth level now just to put this a little differently i've superimposed all of these closes and assuming that this is a completely random movement there is a fifty percent chance of the price coming back and closing on level zero 25 chance of the price coming back and closing at level one twelve and a half percent chance of it closing at level three and a twelve and a half percent chance of the price going to level four if you add all of those together and multiply the percentages by the profit that you make at each point it comes out to zero so assuming this is a completely random system and that the price can have an equal chance of reaching any of these points then you have a zero profit of course that is again in a perfect world and you do have spreads and commissions to worry about but in the real world you can often find ranging markets that are unlikely to reach that fourth level and as long as you don't go to the fourth level maybe you hit level number or the retracement to level number two occasionally you will be making profits on this as long as the price is staying in a range it's not ideal but it is better than having a grid that can run without any checks and simply create enormous drawdowns so that's the strategy proposed by expert forex now i'm going to take you through a demonstration i've already written the expert so i'll take you through a demonstration of how this operates just through the strategy tester and then we'll go to the code and see how to write this now i've started the strategy tester and i've set the levels close together just for the demonstration here what you can see is that i have two trades opened and they're close together and the reason they're not at the same level is because of spread so i simply open those at the beginning of running the grid it's open to buy at the buy price and the sell at the sell price and that gap will always be there also in this expert i've had it draw lines on the right hand side of the screen you can see it's showing the next level the price has to reach before it will open another cell and the next level that it has to reach before opening another buy and as the strategy says if we get to that buy level it will close the buy that's already open and open another buy and it will also open another cell and if it goes to the cell level it will close the cell that's open open another cell and open another buy i'll just run this forward a little bit and in this case the price has come down when we first open the grid there is no idea whether the price is going to go up or down and so we don't have an exit point because we only exit on retracements so now that this has actually reached that first sell point the sell at bar has moved down so if price comes down further then we'll open another cell there i've closed the original cell that's gone and now i have this line that says exit at that's my retracement line now i couldn't have the exit at retracement line before i've at least reached one level up or down because i don't know which direction the grid is moving but now that it's moved down to that first level according to the rules of the grid there is no way that the price can go back above the original level without closing out now the price has come down even further created yet another level my exit at line has moved down one level so i'll now close on retracement back to level number one and i've got a new cell at which will be level number three where i'll sell again and now because i have my levels close together i've actually hit that third level already at this point i know that i can only break even at best or i will lose i'll just let that go and there it's closed and that would have been a break even although as i said with spreads there's a small loss involved there and now the grid starts again i think that's enough of a demonstration to get an idea how this works so we can move on now to the code and see how i would write that right now i have the editor open with the code this is the mql5 editor but as usual this code will work for metatrader 4 or 5. this does use the framework and it uses framework 3. 06 there's a minor update from 3.
05 simply to add the open price on the response to a trade. position open call in mt4 so what i have on screen here initially this is stoploss grid. mq4 so this is the file you will compile if you're in metatrader4 and i have stoploss grid.
mq5 which is the file you would compile if you're running metatrader5 both files are the same they both have this hash include stoploss grid. mqh so that's how i get the common code between metatrader4 and 5. so they're all located under experts orchard stop loss grid and then stop boss grid mq4 mq5 mqh then a framework file which i'll show you in a moment and the expert if i go to stop loss grid.
mqh the first thing i have here is hash include framework. mqh so i said i'd show you that here it is framework. mqh is just a convenient way for me to have a single file here that sets the framework version that i'm going to use by include orchard frameworks framework underscore 3.
06 framework. mqh and that file then is included in the stop-loss grid. mqh and in the expert which i show here so that way both of these files include the same version of the framework so back to the stop-loss grid.
mqh it's a standard grid there are very few inputs to have for a grid type trading in fact the main input is this input int input level points which i'm setting to zero here just as the default but you'll need to set that to something for the grid to work this is the distance in points between levels on the grid the grids all have five levels zero one two three and four zero being where we start and four being the ultimate level where everything closes out for that loss and the general trading info the order size which i'm setting for the default of zero and you'll need to update that if you want this to run uh trade comment just says stop loss grid and then a magic number which i'm just setting at 22 22 22 for the time being and then an include of expert. mqh which is the file where most of the work happens that expert. mqh is a class and it is a class called c expert so i've declared here c expert is a pointer to a variable that i've called expert and then in the on init function i set up expert equals new c expert and then the inputs are the level points the order size trade comment and magic number and then i just return the init result from expert on d in it because i've created an object this expert is an object now i delete that delete expert and in ontic i just call the expert.
ontic function now this is the expert. mqh file as i said include framework. mqh this does use the orchard framework if you're not familiar with that there'll be a link in the description to a series of videos on the framework and you can download the framework from github they'll also be a link to that download it's not included in the github download for this expert so you need to download the framework separately but the class c expert which is used inside this expert is inheriting common public inheritance from c expert base which is part of the framework and some of the functions you'll see in here are actually provided by that base framework i have no private variables here but there are some protected there's the level size which is obviously just storing the size of that gap between individual levels in the grid then there are some working values which i refer to later as counters so there's a closing that's just a boolean and then the buy and sell price and the exit price which you would have seen on screen in the demonstration showing up next to those horizontal lines and then the level count to tell me how many levels deep we are in the grid loop is a function that is called by the ontic function the ontic function which we called from let me find that again here expert.
ontic that ontick function is actually inside the expert base and apart from handling a certain amount of housekeeping and knowing when the markets are open and so on it will then call the loop function and so this loop function is where the main body of the work will happen and then there are some utility functions reset counters open grid close grid open position and close position i'll be going through the code from top to bottom so there'll be calls made to some of these functions and it will hopefully make sense when i get to the functions i think it would be more sensible to do that rather than go to these functions first and then see how they're used and just for the demonstration those horizontal lines you saw in the demonstration are produced by this display levels and display level function so the display levels function actually performs a number of calls to the display level and this shows each of those lines on screen i've included them here for the demo but they actually are not a necessary part of the expert they're purely cosmetic and then there is the constructor which takes the level points and then the order size trade comment and magic number so let's work through this from top to bottom first the constructor and i make a call to the parent column c expert base passing the order size trade comment and magic so that calls the parent constructor and that handles these three values because they're common across most things and then i just store the level points but i don't want to store the points i want to store them as a price gap so i've got a function called points to double and that's also in the framework and i take level points so points to double will convert level points into a price gap which i'm then storing in that m level size variable and then reset counters we'll reset all of these and we'll show you all of these working variables will be reset in that one function and it's used several times that's why i've put it here as a function rather than individually setting all of those values and then just m eminentresult equals init succeeded if i go back again to this uh stoplossquid. mqh there's this return expert. init result so the init result is set by that call here in expert and that way i'll be returning and in it succeeded there's a destructor but i have no code there that i have nothing to do in the destructor here and now the loop and this is where the main body of the work happens and i'll have to go later to explain what happens inside each of these functions just to avoid jumping around in this code too much the first thing i'm doing if m closing so this is one of the working variables and if m closing then i call close grid and return that's because m closing is a flag that i'll be setting inside close grid and just in case the close is unsuccessful can't close a particular trade for some reason this m closing will cause me to keep going back in and attempting to close the grid until it's finally successful so if i do make a call to close grid i don't want to just leave one trade behind because i couldn't close it i want to make sure i close that so every time we come back into the loop as long as m closing is set to true i'm just going to keep trying to close the grid next if there is nothing currently open so that means i don't have a grid on screen at the moment i've either just started up the expert or it has just closed down an earlier grid and in that case because of the reset counters both the buy price and the sell price variable will be zero so if they're both zero it means i don't have any trades open and i make a call to open grid and opengrid will simply place both of those trades and set some of the working variables we'll see that soon so that takes care of initializing the grid and then i return immediately because there's nothing more to do until the next iteration through this loop now i want two different prices because depending whether the price has moved to the high side of the grid or the low side of the grid i'm looking for the closing price for either buy or sell so i need both of these so i want the bid price and the ask price and i get both of those with symbol info double passing m symbol and then either symbol bid or symbol ask and that gives me the closing price depending whether i'm on the buy side of the grid or the sell side of the grid now from the explanation at the beginning you'll see that we close the grid whenever the price retreats by one level and that's where this m exit price comes in so if m exit price is greater than zero that means that i have set an exit price so the reset counters will initially set that to zero but then as soon as i open one extra level on the grid i know which direction the grid is moving and the exit price will be one level behind that but until then m exit price is zero so if m exit price is greater than zero it means i have reached at least one level of the grid and i'm looking at the retracement and then if either the buy price is greater than zero and the ask is less than the exit price or the sale price is greater than zero and the bid is greater than the exit price now the reason i'm testing these by price greater than zero and sell price greater than zero when i first open a grid both of those are set because i don't know which direction the grid's moving but as soon as i open one level of the grid only one of these will be set as the next level and the other will be reset to zero so that way i can tell from buy price or sell price which direction the grid's moving and so if either of these conditions are true then that means that i have retreated by one level and i just call closed grid so just to explain it further just looking at the buy side assuming the price has gone up from the starting point on the grid and we've reached at least one level on the grid as soon as we reach that one level the m exit price will be given a value and so it's no longer zero so that statement becomes true also buy price has a value and sell price will be set to zero because we've moved up a level so buy price is greater than zero and then if the price retreats back past the exit price then the ask price is less than or equal to exit price which means this statement is true and therefore i close the grid and of course if we're on the sell side of the grid then this statement would be true if we retreat by one level so that takes care of the closing situation on the grid but now if we have reached the next level on the grid so firstly i'm checking by price is greater than zero that means that it's either a brand new grid and we don't know the direction yet or we've already reached one level on the buy side so if buy price is greater than zero and bid which is the closing price for a buy trade if bid is greater than or equal to the buy price now the reason i'm using the closing price because this is also the open price for a sell so if bid is greater than or equal to buy price that means that the price has moved past that next level because buy price will be set to the next level price and then i change level count then level account plus plus because i've reached a new level i set sell price to zero because if i've reached a buy level then i'm no longer concerned with cell and so that basically turns off all consideration of cell after this if the level count is greater than or equal to four now it should never be greater than but i'm just putting that there to be safe so if level counts greater than or equal to four then we've reached that end point of the grid where i need to close everything and take the loss so that's a simple call to the close grid and some optional statements here where if i'm reaching that point i perhaps don't want to reopen a new grid so i'm simply saying i'm going to print a message there saying i've hit the stop loss therefore i'm stopping the expert and then i call expert remove now this is fairly blunt and i haven't put a lot of work into it it's really just to show what you might want to do because what i haven't accounted for here is if the closed grid doesn't work so if that close grid doesn't work there'll still be a trade open ideally i would want this to loop back into the loop function here and remember we looked at the beginning here to loop back in here and keep hitting that close grid until the grid is actually closed before i exit the expert but that's a bit of extra code and we're going to be running out of time in this video as it is so just be aware of that and you might need to set some flags rather than saying close grid you might need to set a flag saying exiting expert and as soon as the grid is closed and that is true then you might want to execute these statements but if we haven't reached level four on the grid then as the strategy for this grid says i will close the position for the buy that's already open because we're going up so i know i've got to buy from the earlier level i need to close that if that close is successful then i want to also open a new buy with the open position order type buy and another cell with open position order type cell and i'm capturing the two prices the buy price which is my next level and i have to modify that a little further so buy price gives me the price that this order type buy was opened at and the exit price will also give me the price where the order type cell was opened now i'm going to be using these a little further and modifying them again but i wanted to capture them exactly as they come back from these open positions because i'm saying if buy price is equal to zero or exit price is equal to zero then something went wrong in trying to open these positions i don't know what it is but the grid is now in a bad state and so i'm simply closing it down close grid if both of these are greater than zero then it means both of these open position statements were successful and then buy price plus equals level size so that sets the buy price at the next level of the grid and then exit price minus equals m level size which sets the exit price to the previous level and then this display levels just shows where the new buy and exit levels are the cell side of the grid is just the mirror image of that so if cell price is greater than zero then i've either got a new grid and i haven't set a direction yet or i've already opened one level at least on the sell side so this tells me that i'm actually in a selling mode and ask is less than or equal to m sell price so m cell price is the next level on the sell side same statements as before but level count plus plus in this case i set the buy price to zero so i know that i'm not in a buying mode if i've reached this point if level counts greater than four i close the grid and here again i have the expert remove statements then i attempt to close the position for position type cell and i'll mention here closed position doesn't close a single trade it closes everything for this direction of trade now there should only be one trade at a time that i'm closing when i'm moving in that direction on the grid when i retrace the grid i'll simply want to close all of the trades for each side so closed position will typically be closing only one trade as we move up the grid and when we retrace that same function we'll close all of the trades for both sides but once i've closed that position successfully then i call the open position for the sell price and the exit price and again if either of those are zero then i close the grid because something failed and then i sell price minus equals m level size to get the new cell level and exit price plus equals level size in this case to get the exit level and then display levels and that's the body of the function so now we'll look at the support functions for this reset counters is simple just says closing is false and all of the others are zero so remember buy price and sell price both equal to zero means there is no grid open exit price will remain at zero until i've opened at least one extra level on the grid and level count begins at zero and then display levels which given that all of these values are zero should actually remove any levels displayed so display levels also takes care of deleting any levels that don't need to be shown the opengrid function calls reset counters so i'm beginning with a clean slate and then i just open a trade in both directions so the buy price is equal to the open position of an order type buy if that is zero then i failed to open the grid on buy and just in case there is something open i call close grid if there's nothing open this will be no harm but i just want to make sure it's all clean and then return and once closed grid has been successful and remember we'll keep re-entering until we do close the grid once that's been successful then the code should fall back into opening the grid again so in case this fails i call close grid and then i set a buy price so this is a brand new grid so i'm paying the buy price to the buy price plus level size then i do the same for sell sell price equals open position if that didn't work i'm going to call close grid and then i also set the sell price so when a grid is first opened i have two trades a buy and a sell trade and i also have a level price set for both the buy and the cell and this is the only time that both that buy and sell price are set as soon as one level is taken out on either side the opposite side's price will be set to zero and then display levels now the closed grid this is a close of everything so i'm using this m closing variable and i'm calling close position position type buy and close position position type cell so i'm trying to close both sides both of these will return a boolean so if closed position is successful that will be true and that will be true which means this entire statement is true because there's an and so i've been successful in buy and sell and then i have a not so the internal of this would be true once i apply that knot it will be false so closing will be false if either of these fails so for example if the buy failed then that would return false even if the position type cell is successful then that would be false and true which itself is false not false is true so m closing would be true and then i'm saying if not m closing so if i've been successful and it's fully closed then i just reset the counters but otherwise m closing will be true and then you've seen the loop earlier it will keep coming back in here and attempting to close these positions the open position statement just takes an order type and then i need the price where i'm going to be opening that position and i use the ternary operator for this so if the type is buy then i call symbol info double to get the ask price m symbol symbol ask and if the order type is not buy then i call symbol info double to get the sell price which is simple underscore bid so price is the opening price for the appropriate order type passed in and then i'm using trade now trade is an object which has been created by the framework and it takes care of handling trade activities it actually in metatrader 5 inherits from the trade class that's supplied with metatrader5 in metatrader4 i have created a custom trade class that has just as much code as i need to work at the moment and i'll be adding to that as the framework grows so trade.
positionopen will attempt to open a trade for the symbol m symbol is also a variable maintained by the framework for the type the order size which was passed in from the inputs price zero stop loss zero take profit and the trade comment that returns a boolean so if the trade. position open is successful then i will be returning a true and then i have this if statement if true then i return trade dot result price which is the price where that trade was actually opened and may be different to this price if there is some kind of slippage if the trade. position open is not successful then i return zero and that will trigger those statements to say i failed to open a trade and will close the grid closed position is simple there is a position closed by type function maintained in the framework for trade object and i simply call that for the symbol and the type and i return the result of that if you're wondering why i'm not passing in the magic number here the trade object as defined by the trade class that's supplied by metatrader5 doesn't take magic number as an argument but it does have a property for the magic number so the framework takes care of setting that magic number property when the trade object is first created so i don't need to pass magic number to this after that statement so trade.
position closed by type symbol and type will close all trades for this symbol that type and for the magic number that's stored internally in the trade object and then it returns a boolean whether that's successful or not and that's everything for the actual operation of the expert but i'll just go through these display level statements as i said they're just here for cosmetic reasons the display levels function simply makes three separate calls to the display level which handles each one because they work for each of these is exactly the same so i've just created a utility function to handle that and the three arguments that i pass in are the name of the object because all objects on screen must have a unique name the price which is the value where i want to show that on the screen vertically and then some kind of label that i want to display so here the display level is the name of the object on screen the value and that label text i'm actually creating two objects i'm creating a trend line which is the horizontal line that you can see and i'm creating some text to hold the price and the label here on the screen so apart from the name which i'm going to be using for the trend line i want a name for the text object so i'm just creating string text name equals name plus underscore text in case they already exist i'm just deleting them with these object delete 0 is the chart number and 0 is the current chart and then the name and the text name so i'm deleting both of those objects if they already exist there's no harm in making these calls if the objects do not exist you won't get an error so we'll just attempt to clean them up if they're already there and then i say if value equals zero return so if i have no value in the exit price for example which i don't when a grid is first opened then these two statements will take care of deleting the exit price line and this will return so it simply won't show on screen so this will only show things that have a value greater than zero i need two times because the trend line needs a start and end point so i'm just getting time zero which is using the i time function for the symbol the time frame and bar number zero and then i'm getting the same for bar number one so it gives me two points then i call object create zero is the chart number current chart name is the object name for my line which has been passed in here i'm creating an obj underscore trend line it's on subchart 0 which is the main chart i'm beginning the line at time 1 and value and extending it to time 0 and value so because both of these values are the same it's a horizontal line and it has a width of only one bar but then i'm going to extend that later with this object set integer object right true which causes it to extend all the way to the right hand side of the screen i'm also making sure it's visible by setting with object set integer object prop hidden setting that to false and then i'm just making sure it's yellow so it's easy to see object set integer color yellow for the text very similar object create chart 0 but this time using text name for the name of that object it's an obj underscore text subchart 0 i only need one set of parameters for the position time 0 and value and then i do the same object hidden is false i set the text of that text item with this object set string object prop underscore text and i'm using string format text plus percent f and value is used to insert in that percent f and then object set integer for color yellow again so that's all there is to the display level now let me just make sure i haven't made a mistake i'll go back to the stop loss grid.