How To Automatically Calculate Position sizes based on results with MQL4
Okay, now, you have been warned twice about Martingale, but you should know how it works because there are systems that work with a dynamic lot size calculation that is based on Martingale and you can use the principles to your advantage.
In our main expert advisor, we have set the lot size to one micro-lot. This is our basic lot size. And we have modified the lot size here and call a module called SetLotSize(). Here is the included mq4 file. Within the function SetLotSize, we declare to static variable that only exists within that function. And it will hold the last account balance. And if the last account balance was higher than the current account balance – that means we have made a loss – it will check the size of the current lot size and it will increase it.
In the upper case, if the last account balance is lower than the current account balance, that means we have made a profit. We will reset the lot size 1 micro-lot. Afterwards, we will store the current account balance in the variable LastAccountBalance for the next calculation and return the lot size. It all happened here.
To produce a loss, it’s necessary to have a position based stop loss. The only other way to produce a loss would be a total meltdown of your account. Traders and brokers love position based stop losses because traders want to keep their losses short and brokers enjoy the fact that position based stop losses produce lots of little small losses for the trader.
In this case, the stop loss is 2 times bigger than the profit value. And here is the same calculation for short trades. First, we set the lot size, here is the stop loss, and it’s two times bigger than the take profit value. Let’s see how that works.
First, we compile it, then we hit the F4 key, enable the visual mode and start the first test. This is a little bit too fast, so we slow it down a little bit. Okay, here we have a buy trade with a micro-lot. Here is the take profit. It is a hundred points above the buy price and the stop loss is about 200 points below the buy price. And if we lose this one, the lot size will increase to two micro-lot.
The highest possible lot size is 50 micro-lot. Okay, I guess we are going to lose this one. Oh and right away increase to 50 micro-lot. We need to use the else if statement to increase the lot size properly. If we use only if statements, then this condition would be true and it would go down all the way until the lot size is 50 micro-lot. With the else if statement, it will break out here.
And now, it seems to work. We see one micro-lot, 2 micro-lots, 3 micro-lots, 5 micro-lots and so on. Now you know how to automatically set dynamic position sizes.