Problem Description
Solution
To calculate the lot size based on a percentage of your account balance (risk management), you need to know the Stop Loss distance in pips. Without a Stop Loss, risk cannot be mathematically defined because the potential loss is infinite.
Here is a robust, reusable MQL4 function that calculates the lot size based on 2% risk (or any other percentage) and a specified Stop Loss.
MQL4 Code
//+------------------------------------------------------------------+
//| RiskCalculator.mq4 |
//| |
//| Description: Calculates lot size based on % risk of balance |
//+------------------------------------------------------------------+
#property strict
#property show_inputs
//--- Input Parameters
input double InpRiskPercent = 2.0; // Risk Percent (e.g., 2.0 for 2%)
input int InpStopLossPips = 50; // Stop Loss distance in Pips
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
// Calculate the lot size
double calculatedLots = GetLotSize(InpRiskPercent, InpStopLossPips);
// Output the result
Print("-------------------------------------------------------------");
Print("Account Balance: ", DoubleToString(AccountBalance(), 2));
Print("Risk Percentage: ", DoubleToString(InpRiskPercent, 2), "%");
Print("Stop Loss: ", InpStopLossPips, " pips");
Print("Calculated Lot Size: ", DoubleToString(calculatedLots, 2));
Print("-------------------------------------------------------------");
}
//+------------------------------------------------------------------+
//| Function to calculate lot size based on risk percentage |
//+------------------------------------------------------------------+
double GetLotSize(double riskPerc, int slPips)
{
string symbol = Symbol();
// 1. Calculate the amount of money to risk
double riskMoney = AccountBalance() * (riskPerc / 100.0);
// 2. Get the value of 1 pip for 1 standard lot in the deposit currency
double tickValue = MarketInfo(symbol, MODE_TICKVALUE);
double tickSize = MarketInfo(symbol, MODE_TICKSIZE);
double point = MarketInfo(symbol, MODE_POINT);
// Adjust for 3 and 5 digit brokers (Points vs Pips)
// If a pip is 0.0001, but point is 0.00001, we need to adjust
double pointsPerPip = 1.0;
if(Digits == 3 || Digits == 5)
{
pointsPerPip = 10.0;
}
// Calculate the monetary value of the Stop Loss per 1 lot
// Formula: SL(pips) * PointsPerPip * TickValue
double lossPerLot = slPips * pointsPerPip * tickValue;
// Safety check to prevent division by zero
if(lossPerLot == 0)
{
Print("Error: Tick value is zero. Cannot calculate lots.");
return(0.0);
}
// 3. Calculate raw lot size
double lots = riskMoney / lossPerLot;
// 4. Normalize the lot size to the broker's step requirements
double minLot = MarketInfo(symbol, MODE_MINLOT);
double maxLot = MarketInfo(symbol, MODE_MAXLOT);
double lotStep = MarketInfo(symbol, MODE_LOTSTEP);
// Round down to the nearest lot step
lots = MathFloor(lots / lotStep) * lotStep;
// 5. Ensure lots are within broker limits
if(lots < minLot) lots = minLot; // Or return 0 if you don't want to trade below min
if(lots > maxLot) lots = maxLot;
return(lots);
}
How It Works
- Risk Calculation: It calculates the monetary value of 2% of your
AccountBalance(). For example, if you have $10,000, the risk money is $200. - Tick Value Retrieval: It uses
MarketInfo(Symbol(), MODE_TICKVALUE)to find out how much 1 tick is worth in your account currency. This handles currency conversion automatically (e.g., trading EURUSD on a GBP account). - Pip Adjustment: It detects if your broker uses 5-digit pricing (where 1 pip = 10 points) or 4-digit pricing to ensure the math is accurate.
- Lot Calculation: It divides the Risk Money by the Cost of the Stop Loss per 1 Lot.
- Normalization: It rounds the result down to the nearest
MODE_LOTSTEP(e.g., 0.01 or 0.10) and ensures the size is within the minimum and maximum allowed lots for that symbol.
How to Use
- Copy the code into MetaEditor.
- Save it as a Script (e.g.,
RiskCalc.mq4). - Drag the script onto a chart.
- A window will pop up asking for the
InpStopLossPips. Enter your intended Stop Loss distance (e.g., 20, 50, 100). - Check the Experts tab (at the bottom of MT4) to see the calculated lot size printed in the log.
Q&A
Q: Why do I need to provide a Stop Loss distance?
A: Risk is a function of distance. Risking $200 with a 10-pip Stop Loss requires a much larger lot size than risking $200 with a 100-pip Stop Loss. Without knowing the distance, the lot size cannot be calculated.
Q: Does this work for Indices (e.g., US30) and Gold (XAUUSD)?
A: Yes, MODE_TICKVALUE handles different asset classes. However, ensure you input the Stop Loss in "pips" as defined by your broker for that specific symbol (sometimes 1 "pip" on Gold is 10 cents, sometimes 1 dollar).
Q: What happens if the calculated lot size is smaller than the broker's minimum?
A: The code includes a check (if(lots < minLot)). In this version, it defaults to the minimum lot size (usually 0.01) so the trade can still be taken, though the risk will technically be higher than 2% in that specific edge case.