\$ £ ¥
¥ £ \$

# 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.

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. 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. 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. So, to calculate the position size you need:

• 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: 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: 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: 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!