MQL4 TUTORIAL – 31 HOW TO CLOSE ALL SELL POSITIONS

video
play-sharp-fill

In this video we are going to find out how to close all the open sell positions at the same time, this little expert advisor is going to open positions and as soon as we have ten open positions on the chart it is going to call a custom function to close them at the same time, so let’s find out how to code that in mql4.
To do that please click on the little button here or press F4 on your keyboard, now you should see the Metaeditor window and here you want to click on file, new, expert advisor from template, continue, I will call this file: simple sell position closer, click on continue, continue and finish, now you can delete everything above the on tick function, let’s also remove the two comment lines.
First, we want to use the orders total function to find out if we have less than ten open positions, if you mark orders total and press F1 you will see that it actually returns the number of market and pending orders but we are not going to use pending orders in this case, we use order send to open test sell positions as we need them to have something to close and we do that until orders total equals ten, that’s when we want to close all the open sell positions, so we call a function that is called: close sell positions that doesn’t exist right now so we need to create it.
We use the return type void here as we are not going to return anything, the name will be: close sell positions, we are going to use a for loop to go through all the open positions.
First, we select an order by using order select for the current number in the for loop. We use select by position and mode trades.
First we need to find out the currency pair for the position that is done by using order symbol and now we need to find out if the symbol on the chart and the currency pair are the same, we also want to find out if the order type equals op sell, if that is the case we have a sell position and now we use order close to close the current position for the order ticket that we have calculated.
We are going to find out the lot size by using order lots, the order will be closed for the current ask price, we have a slippage of three, the last parameter here is for a color – we don’t need one – so finally we close the for loop and we close the function and that’s it.
Let’s click on the compile button or press F7, we don’t have any errors here so let’s click on the little symbol here or press F4 to go back to Metatrader.
And in Metatrader we click on view, strategy tester or press control and r, please pick the new file: simple sell position closer dot ex4, mark the option for the visual mode here and start a test.
Here we are! The expert advisor is going to open and close positions, so it works and you have coded it yourself with a few lines of mql4 code.