Lot From Risk: Calculate Position Size Based on Risk, Stop Loss, and Commission
Info
The Lot From Risk: Calculate Position Size Based on Risk, Stop Loss, and Commission is a Expert Advisor for MetaTrader 5 that lotfromrisk is an include file designed for expert advisor (ea) developers. It calculates the appropriate position (lot) size by taking into account a specified risk amount, a stop-loss level, and commission per lot.
Usage
This tool is typically used for automated trading on major forex pairs and gold.
Platform
This Expert Advisor works exclusively on MetaTrader 5 (both build 600+ and newer versions).
Setup
Place the downloaded file in MQL5/Experts folder via File ? Open Data Folder in MetaTrader 5.
How to Install and Use Lot From Risk: Calculate Position Size Based on Risk, Stop Loss, and Commission
1. Installation: Open the "File" menu, select "Open Data Folder," navigate to MQL/Experts, paste your file, and restart the terminal.
2. Activation: Drag the EA from the Navigator onto a chart, ensure "Allow live trading" is checked in the Common tab, and verify the AutoTrading button is green.
3. Optimization: Right-click your chart, choose "Expert List," click "Properties" to adjust inputs, and save your preferred setup as a set file for future use.
4. Maintenance: Regularly check the "Experts" tab in the terminal window to monitor trade logs and potential execution errors.
Frequently Asked Questions
Q: Why is my EA not opening trades? A: Check the "AutoTrading" button, ensure "Allow live trading" is enabled, and verify your broker allows automated trading on your account type.
Q: Can I run multiple EAs on one chart? A: No, each chart can only host one active EA; however, you can open multiple charts for different currency pairs to run several EAs.
Q: What does the "smiley face" icon mean? A: A smiley face in the top-right corner of the chart indicates the EA is successfully running; a frowny face means it is disabled.
What this tool does
LotFromRisk is an include file designed for Expert Advisor (EA) developers.
Typical Use Case
This Expert Advisor excels in automated trading and technical analysis on MetaTrader 5.
Compatible Platform & Setup
This Expert Advisor works on MetaTrader 5. Place the file in the MQL5/Experts folder and restart the terminal.
Description & Settings
Related: Risk Lot Calculator: Determine Lot Size from Risk Percentage and Stop Distance - another powerful expert for MetaTrader 5 traders.
LotFromRisk is an include file designed for Expert Advisor (EA) developers. It calculates the appropriate position (lot) size by taking into account a specified risk amount, a stop-loss level, and commission per lot. The goal is to ensure that the potential loss at the stop-loss level does not exceed the defined risk.Also recommended: Accurate Broker GMT Offset and Daylight Saving Time Rules from Price History - similar expert with strong performance on MetaTrader 5.
Calculation Method
The formula used is: lots = money at risk / (loss of 1 lot at the stop + commission of 1 lot, round turn).
Loss of 1 Lot Calculation:
The terminal calculates the value of the move from the entry price to the stop-loss level using OrderCalcProfit. This calculation inherently considers the contract size, the profit currency, and any necessary conversion to the account's currency. If OrderCalcProfit is unavailable, the tick value is used as a fallback.
Rounding:
To strictly adhere to the risk parameter, the calculated lot size is always rounded down to the nearest valid volume step for the symbol. Rounding to the nearest step could potentially result in a loss exceeding the specified risk. The code also includes a safeguard against floating-point inaccuracies, preventing cases where a calculated size like 0.29 lots might be incorrectly represented as 0.28.
Below Minimum Volume:
If the calculated risk is insufficient to cover the symbol's minimum trading volume, the function returns 0 lots. A reason is provided, and the function does not default to the minimum volume, as this would exceed the user-defined risk.
Above Maximum Volume:
The calculated lot size is capped at the symbol's maximum allowed volume. The result will indicate if this cap has been applied.
Margin:
The report includes the margin required for the calculated lot size and whether this margin is available within the free margin. Note that the lot size itself is not adjusted based on margin availability.
Exclusions:
The calculation does not account for slippage at the stop-loss, price gaps, or swap fees.
Available Functions
LfrLots(symbol, type, entry, stop, risk, mode, commissionPerLot, result):
Calculates the lot size for a buy or sell order, whether it's a market or pending order. Setting entry to 0 uses the current ask (for buys) or bid (for sells) price. Returns true if the calculated lot size in 'result.lots' is greater than 0.
LfrSizeFromMoney(riskMoney, lossPerLot, commissionPerLot, step, min, max, result):
Performs the core arithmetic calculation without direct interaction with the trading terminal.
LfrLossPerLot(symbol, type, entry, stop):
Determines the loss in the account currency for one lot traded from the entry price to the stop-loss level.
LfrCommissionFromHistory(symbol, days):
Estimates the round-turn commission per lot based on the account's deal history over the last N days (default is 90 days).
LfrRoundDown, LfrStepDigits, LfrRiskMoney:
Helper functions.
Risk Specification:
The risk can be defined as a percentage of the account balance, a percentage of the account equity, or a fixed monetary amount in the account currency (using ENUM_LFR_RISK enumeration). The LfrResult structure contains detailed output, including lots, riskMoney, lossPerLot, commissionPerLot, lossAtStop, margin, marginOk, a status code (ENUM_LFR_CODE), and a plain English reason.
Example Usage
#include
LfrResult r;
double sl = SymbolInfoDouble(_Symbol, SYMBOL_ASK) - 300 * _Point;
if(LfrLots(_Symbol, ORDER_TYPE_BUY, 0, sl, 1.0, LFR_PERCENT_BALANCE, 7.0, r))
trade.Buy(r.lots, _Symbol, 0, sl, 0);
else
Print("no trade: ", r.reason);
Demo Script
The LotFromRiskDemo.mq5 script demonstrates the functionality by calculating buy and sell orders for the chart's current symbol. The results are displayed in the Experts log and directly on the chart. No orders are actually placed by the script. User inputs include risk mode, risk percentage or amount, stop-loss distance in points, and commission per lot (a value of -1 uses the estimate from the last 90 days of trading deals).
The accompanying screenshot illustrates an example with XAUUSD. The stop-loss is set 500 points away, 1% of the account balance is at risk (equivalent to 84.57 USD), and a commission of 7.00 per lot round turn is applied. The calculated lot size is 0.16, with a potential loss of 81.12 at the stop-loss (this factors in the 500.00 loss per lot plus the 7.00 commission).
The source code is provided free of charge for use and modification, including incorporation into your own products. It is offered without warranty. It is strongly recommended to test the code on a demo account before using it with real funds.
Included Files
MQL5\Include\LotFromRisk\LotFromRisk.mqh
MQL5\Scripts\LotFromRisk\LotFromRiskDemo.mq5
Testing Information
Tested on MetaTrader 5 build 6331, using a hedging demo account in USD. Tested with currency pairs EURUSD, USDJPY, GBPJPY, EURGBP, USDCHF, and commodities XAUUSD, BTCUSD. In 4054 test cases, no calculated position size exceeded the specified risk. If rounding to the nearest volume step had been used instead, 1977 of those cases would have exceeded the risk limit.
You may also like: Xlsx Writer: Generate Excel .xlsx Files from MQL5 Without External Libraries - excellent alternative for expert users on MetaTrader 5.
Source Code
#property copyright "RobotFX"
#property link "https://robotfx.org"
#property version "1.00"
#property description "This code is educational. Feel free to use, modify and upgrade as you wish. Visit ROBOTFX.ORG for professional trading tools"
#property script_show_inputs
#include <LotFromRisk\LotFromRisk.mqh>
input ENUM_LFR_RISK InpMode = LFR_PERCENT_BALANCE;
input double InpRisk = 1.0;
input int InpStopPoints = 500;
input double InpCommission = 7.0;
.......
⚠ Limitations & Risk Warning
- This tool is provided for educational and testing purposes only.
- Past performance does not guarantee future results.
- Trading involves substantial risk of loss. Use on a demo account first.
- Results may vary depending on market conditions, broker, and settings.
- We recommend thorough backtesting and forward testing before using with real funds.