MQL4 TUTORIAL BASICS – 32 HOW TO MODIFY A BUY POSITION SIZE

video

In this video we want to find out how we can modify the size of an existing buy position, this one is reduced right now, you see that the position size is changing and we want to 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 buy position modify, click on continue, continue and finish.
Now you can delete everything above the on tick function and we also delete the two comment lines here.
Inside of the on tick function we want to check if we have no open orders, that would be the case when the return value for the function orders total is below one and if that is the case we want to open a test position. You wouldn’t do that on your real account but we need to open a position here so we have something that we can modify later on, so we use the order send function to open a position for the current symbol on the chart, we use op buy and the position size will be ten micro lot, so now that we have opened a position we use a for loop to go through all the open orders, in our case it will be only one order but on your real account it would check the other positions too and for each order we use order select for the current counter value, we want to use select by position and mode underscore trade – all in capital letters.
Afterwards, we want to check if the order symbol belongs to the current currency pair on the chart and one more thing we want to know is if the order type equals op underscore buy – all in capital letters here – if that is the case we have a buy position.
Now we want to check if the account equity is higher than the account balance and if all these conditions are true we use order close for the current order ticket number to close a part of the position, just one micro lot for the current bid price, the slippage of three, and we don’t need any color, let’s close the brackets here, this one is for the if statement and this one is for the for loop and that’s about it.
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 in this course or maybe even the premium course is interesting for you, for now, let’s click the compile button or press F7, I don’t have any errors here, so now I can 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 pick the new file: simple buy position modify dot ex4, enable the visual mode here and start a test.
And here we are! We have a buy position of ten micro lot and as soon as the price is above the green line the position size is reduced, so our little expert advisor is working as desired and you have coded it yourself with a few lines of mql4 code.