In this video we are going to find out how to reduce existing selling positions when the price goes down, so let’s find out how to calculate 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 modify, click on continue, continue and finish.
Now we can delete everything above the on tick function and the two comment lines here, the first thing we do is to check if we have no open orders, that would be the case if orders total delivers a return value below one and in that case we are going to open a demo sell trade that is done by using order send for the current symbol, we want to sell ten micro lot.
Now that we have a test position we want to go through all the open orders, that’s done by a for loop, orders total will deliver the number of open orders and we go through all the orders until we have no order left, we select each order that is done by using order select for the current value of the for loop counter, we use select by position and mode trades as parameters and now we check if the current order symbol is equal to the symbol on the chart and as we only want to modify sell trades we also want to know if the return type of order type is op underscore sell – all in capital letters – and if that is the case we have a sell position, so let’s check if the equity is above the balance that would be the case if the account equity is bigger than the account balance and if all these conditions here are true we want to close a part of the existing position that is done by using order close for the current order ticket, we want to close one micro lot each time for the current ask price, the slippage tolerance is three, and the last parameter here stands for a color – we don’t need a color – so we use clr underscore none, that’s almost it.
Let’s close the two loops here and now you can click on the compile button or press F7, you should not get any errors but if you don’t understand what all the code here does or if this was too fast for you maybe you want to watch the other videos of this video starter serious or maybe even the premium course is interesting for you but for now if you don’t have errors please click on the little button here or press F4 to go back to Metatrader.
And in Metatrader we click on view, strategy tester or press control and r please select the new file: simple sell position modify dot ex4, mark the visual mode here and start a test.
Let’s save the file as simple sell position modify dot mq4, pick this one and this time the expert advisor is working, it was just the filename, simple error can take hours to find but in this little video you have learned how to create an expert advisor that is able to modify existing sell positions and you have coded it yourself with a few lines of mq4 code.