How to Calculate Position Size in MQL4

From this guide, you will learn how to calculate position size using MQL4 language in MetaTrader 4 (MT4).

One of the most important concepts when trading Forex or any other financial market is risk management.

Risk management involves a set of rules to keep your account safe from unexpected events and unlucky times. It makes the difference between a good trader and an amateur.

With that in mind, it makes sense to learn how to calculate position size with MQL4 code.

What Is Position Size?

One of the most popular rules of risk management is to risk on each trade only a small percentage of your entire account. This serves to prevent your account from going straight to zero in case of a streak of losing trades.

For example, if your position size is such that you are risking 20% of the account balance on each trade, a streak of five losing trades will leave your with almost nothing. If you had used a smaller risk of 2%, a streak of five losing trades would still leave 90% of your balance intact. Of course, if the trades were winners the profit with 20% trades would have been higher too, but traders should be prepared for long streaks of losing trades.

It is beyond the scope of this guide to explain what is the optimal percentage of balance to risk per trade, which also significantly depends on your strategy and trading style. Our focus here is to show you how to calculate the position size with MQL4 code.

General Formula to Calculate Position Size

Assume you want to risk only 1% of your balance on each trade. In this example, your account is $10,000. This means that your risk per individual trade is $100.

$10,000 x 1% = $100

You also know that for this trade your stop-loss is 20 pips away from the open price, and, assuming this trade is on EUR/USD, every pip for a standard lot size has a value of $10. This means that 20 pips are valued $200 for a position size of 1 standard lot.

20 PIPS x $10 = $200

For more about pip value, please read our What Is a PIP (and a PIPETTE) in Forex Trading? guide.

Since you want to only risk $100, while maintaining your stop-loss 20 pips away (which is $200 for 1 standard lot), then your position size should be 0.5 standard lots.

$100 / 20 x $10 = 0.5

So, to calculate the position size you need:

  • Balance of your account
  • Percentage of risk for the single trade
  • Stop loss in pips
  • Pip value

How to Calculate Position Size in MQL4

MetaTrader once again comes to your help with some native functions that make it easy to calculate position size:

  • AccountBalance() — returns the account balance.
  • MarketInfo(Symbol(),MODE_TICKVALUE) — returns the value of a tick (which in MQL4, is the name for a point of price movement) for the current pair.

Now, this may be tricky, as we saw in the guide on pip normalization, brokers can show the exchange rates with 4 or 5 decimals (2 or 3 for JPY pairs). If the broker is using 5 decimals (3 for JPY pairs), then MarketInfo(Symbol(), MODE_TICKVALUE) is the value of a pipette instead of a pip. If this is the case, calculating the correct amount requires taking into consideration the number of decimals in the exchange rate.

Here is the MQL4 code to calculate the position size. It is tested it with a simple expert advisor; the account balance is $9,999.53, and the risk is set to 1% with 20 pips stop-loss.

#property copyright "EarnForex.com"
#property link      "https://www.earnforex.com/"
#property version   "1.00"
#property strict

// Percentage of available balance to risk in each individual trade.
extern double MaxRiskPerTrade = 1; // % of balance to risk in one trade.
extern int StopLoss = 20; // Stop Loss in pips.

// We define the function to calculate the position size and return the lot to order.
// The only parameter is stop-loss, it will return a double.
double CalculateLotSize(double SL){          // Calculate the position size.
   double LotSize = 0;
   // We get the value of a tick.
   double nTickValue = MarketInfo(Symbol(), MODE_TICKVALUE);
   // If the digits are 3 or 5, we normalize multiplying by 10.
   if ((Digits == 3) || (Digits == 5)){
      nTickValue = nTickValue * 10;
   }
   // We apply the formula to calculate the position size and assign the value to the variable.
   LotSize = (AccountBalance() * MaxRiskPerTrade / 100) / (SL * nTickValue);
   return LotSize;
}

void OnTick()
{
   // We print the position size in lots.
   Print("Position size in lots? ", CalculateLotSize(StopLoss));
}

The result of the script is:

Position Size Calculation Script Output

As you can see, the position size is 0.4999765. This can create some problem when submitting orders as MetaTrader can only accept orders rounded to its minimal incremental lot size. In other words, you can submit an order for 1 lot but an order for 1.00005 lots will be rejected.

Position Size Rounding

We can find out what is the minimal increment for the orders with the function MarketInfo(Symbol(), MODE_LOTSTEP). Usually, this value is 0.01, which is equivalent to a micro lot. Using this function and some other math, we can round the number to match the accepted increment. We will add this line to the code:

LotSize = MathRound(LotSize / MarketInfo(Symbol(), MODE_LOTSTEP)) * MarketInfo(Symbol(), MODE_LOTSTEP);

Basically, what we do is dividing the found position size by the accepted increment and round the number and then multiply for the accepted increment:

Explaining the Position Size Rounding Procedure

So, if we use the following code, we will avoid errors with the position size when submitting the order:

#property copyright "EarnForex.com"
#property link      "https://www.earnforex.com/"
#property version   "1.00"
#property strict

// Percentage of available balance to risk in each individual trade.
extern double MaxRiskPerTrade = 1; // % of balance to risk in one trade.
extern int StopLoss = 20; // Stop Loss in pips.

// We define the function to calculate the position size and return the lot to order.
// The only parameter is stop-loss, it will return a double.
double CalculateLotSize(double SL){          // Calculate the position size.
   double LotSize = 0;
   // We get the value of a tick.
   double nTickValue = MarketInfo(Symbol(), MODE_TICKVALUE);
   // If the digits are 3 or 5, we normalize multiplying by 10.
   if ((Digits == 3) || (Digits == 5)){
      nTickValue = nTickValue * 10;
   }
   // We apply the formula to calculate the position size and assign the value to the variable.
   LotSize = (AccountBalance() * MaxRiskPerTrade / 100) / (SL * nTickValue);
   LotSize = MathRound(LotSize / MarketInfo(Symbol(), MODE_LOTSTEP)) * MarketInfo(Symbol(), MODE_LOTSTEP);
   return LotSize;
}

void OnTick()
{
   // We print the position size in lots.
   Print("Position size in lots? ", CalculateLotSize(StopLoss));
}

And the result is:

Position Size Calculation with Rounding - Script Output

This function is very handy because with only two parameters, it can calculate position size, meeting your risk management strategy.

In the example above, the stop-loss was set to a static value. However, in most strategies, stop-loss is variable and in that case, this function would still work correctly as the calculated lot size is calculated based on a given stop-loss.

Also, the function is suitable for all currency pairs as the tick value is known directly by MetaTrader 4. It takes into consideration both your account currency and the currency pair you are applying the function to.

You can also download our free Lot Size Calculator either to study its code for a more complex example of how the position size calculation works in MQL4 or to use in your actual trading.

Always remember to adopt proper risk management restrictions and they will make you a better trader!


If you want to get news of the most recent updates to our guides or anything else related to Forex trading, you can subscribe to our monthly newsletter.

© 2005–2021

EarnForex.com

Design — Mart Studio

Forex trading bears intrinsic risks of loss. You must understand that Forex trading, while potentially profitable, can make you lose your money. Never trade with the money that you cannot afford to lose! Trading with leverage can wipe your account even faster.

CFDs are leveraged products and as such loses may be more than the initial invested capital. Trading in CFDs carry a high level of risk thus may not be appropriate for all investors.