Watch how to download trading robots for free
Find us on Twitter!
Join our fan page
Interesting script?
So post a link to it -
let others appraise it
You liked the script? Try it in the MetaTrader 5 terminal
Experts

Risk Calculator - lot size by risk percent and ATR stop - expert for MetaTrader 5

Chia-yi Wu
Chia-yi Wu
Algorithmic Trading Software Developer
I build reliable, production-grade automated trading systems across MT4/MT5 (MQL4/MQL5), TradingView (Pine Script), and Python. As an active trader in gold, forex, and US stocks, I understand practical execution and risk workflows.
What I Build:
Views:
78
Rating:
(1)
Published:
\MQL5\Scripts\ \MQL5\Include\RiskGuard\
RiskGuard.mqh (18.49 KB) view
MQL5 Freelance Need a robot or indicator based on this code? Order it on Freelance Go to Freelance

Risk Calculator answers one question before you trade: how many lots for this stop and this risk? It is an on-chart panel for MetaTrader 5 that reads every contract specification from your broker - contract size, tick size, tick value, volume step, minimum and maximum lot, and the broker's minimum stop distance - so nothing is hard-coded and it works the same way on forex, gold, indices and other CFDs. It only calculates. It never opens, modifies or closes trades. It is an Expert Advisor only because MT5's exact profit and margin functions (OrderCalcProfit, OrderCalcMargin) cannot be called from an indicator.

Risk Calculator panel on a gold chart
The panel on gold: lot size, status and the figures behind it

Recommended symbols and timeframe

Any symbol in Market Watch. Before release it was tested on 10 symbols: forex majors, JPY-, CAD- and CHF-quoted pairs, a cross pair, gold, an index and a crypto CFD. In Fixed points mode the chart timeframe does not change the result. In ATR mode the stop follows ATRTimeframe, so set it to the timeframe your entries are based on: on M1 the ATR stop is very tight, and M15 to H4 suits most intraday and swing entries. Attach it to a chart that is not running another Expert Advisor.

How to read the panel

The panel has three parts. Result shows LOTS, the status light and the actual risk of that lot size. Notes explain why a trade is flagged and what you can do about it, for example "Set risk to 1.31% or more, or tighten the stop". Details list the target risk, the loss of 1 lot at the stop, entry, stop price and distance, stop basis, spread and margin, so every figure can be checked by hand.

  • OK (green) - the lot size can be used.
  • WARNING (orange) - a lot size is given, but read the note: spread too large, stop widened, or lots capped at the symbol maximum.
  • NOT TRADABLE (red) - no lot size is given: no quote, symbol or direction not tradable, the minimum lot already risks more than you set, or not enough free margin.

Click BUY / SELL to switch direction: entry is Ask for a buy and Bid for a sell, and the stop moves to the other side. Click - to fold the panel to one line showing the symbol and lots in the status colour, and + to open it again. A dashed line marks the stop price on the chart (display only). The panel sizes itself to your screen DPI and font; if it still looks too small or too large, set PanelScale.

How the lot size is calculated

  1. Risk money = equity (or balance) x risk %.
  2. Stop distance = fixed points, or ATR of the last closed bar x multiplier, rounded up to the tick size. A stop that falls inside the spread or the broker's minimum stop distance is widened and flagged.
  3. Loss of 1 lot at the stop, in your account currency, from OrderCalcProfit. The tick value method is used as a cross-check (flagged if the two differ by more than 1%) and as a fallback.
  4. Lots = risk money / loss per lot, rounded down to the volume step and capped at the symbol maximum. Below the minimum lot no lot size is given, and the panel shows how much the minimum lot would risk.
  5. Margin for that lot size from OrderCalcMargin, compared with free margin.

Both roundings are on the safe side, so the actual risk is never above the target.

Inputs

Input Default Range Description
RiskPercent 0.5 0.1 - 2.0 Risk per trade, % of the risk base
RiskBase Equity Equity, Balance What the risk % is taken from
StopMode ATR ATR, Fixed points How the stop distance is set
StopPoints 500 1 - 1,000,000 Stop distance in points (Fixed points mode)
ATRPeriod 14 2 - 100 ATR period (ATR mode)
ATRTimeframe Current chart Any ATR timeframe; set it to the timeframe your entries are based on
ATRMultiplier 1.5 0.5 - 5.0 Stop = ATR x multiplier
MaxSpreadPctOfSL 10 1 - 50 Warn when the spread is larger than this % of the stop
ShowStopLine true true, false Draw the stop price as a dashed line
StopLineColor Tomato Any colour Colour of the stop line
PanelLanguage English English, Chinese Panel language
PanelX, PanelY 10, 30 Pixels Panel position
PanelScale 0 0, or 0.5 - 3.0 0 sizes the panel from the screen DPI; 0.5 - 3.0 sets it by hand
WriteCsvLog false true, false Also log to MQL5/Files/RiskCalculator_log.csv

Out-of-range inputs are rejected at start, with the reason in the Experts log.

RiskGuard include file: calculating the size of the position to be opened

The calculation is a separate library, Include\RiskGuard\RiskGuard.mqh. Its purpose is to calculate the lot size of a position before it is opened, from a risk % and a stop, with the same checks as the panel. It has no panel and no text, and it never trades, so any Expert Advisor can include it. r.codes[] lists the reasons behind a WARNING or NOT TRADABLE status (enum ENUM_RG_MSG).

#include <RiskGuard/RiskGuard.mqh> CRiskGuard guard; SRiskSettings s; // fill in the settings //--- OnInit string err; if(!CRiskGuard::ValidateSettings(s, err) || !guard.Init(_Symbol, s)) return(INIT_FAILED); //--- when you need a lot size STradeCalc r; guard.CalcTrade(true, r); // true = buy if(r.status != RG_BLOCKED) { /* use r.lots and r.stop */ }

Self-test script

RiskCalculatorSelfTest runs the calculation on every symbol in Market Watch, buy and sell, at four stop sizes, and checks rules that must always hold: lots are a whole number of volume steps, within the symbol limits, never above the target risk and rounded down by less than one step; the stop respects the broker minimum and is on the correct side; and a blocked result never gives a lot size. Every result is written to MQL5/Files/RiskCalculatorSelfTest.csv with the symbol specification, so each row can be re-checked by hand. Before release it ran 80 cases on 10 symbols with 0 failures, and every row was recalculated independently from the CSV.

Known limitations

  1. Calculation only: it never opens, modifies or closes trades.
  2. One trade at a time: it does not add up the risk of positions you already hold.
  3. A stop is filled as a market order. Gaps and slippage can make the real loss larger than the planned risk, and commission is not included.
  4. The ATR stop uses the last closed bar, so a sudden volatility spike shows only after the next bar closes.
  5. The current spread is used; results change when spreads widen (rollover, news).
  6. Margin comes from OrderCalcMargin. Brokers with dynamic margin (news periods, equity tiers) may charge more than shown.
  7. One chart holds one Expert Advisor, so use a chart that is not running your own EA.

Risk disclaimer

Trading leveraged products carries a high risk of loss. This tool is provided as-is for calculation and education. It is not investment advice and does not guarantee any result. Always check the figures before trading.


Symbol and Trading Conditions Inspector Symbol and Trading Conditions Inspector

Displays live symbol specifications, broker trading conditions, account information, spread, trading permissions, session status and margin properties directly on the MT5 chart.

Telegram Notify - trade notifications, chart screenshots and daily summary for any EA (library + ready EA) Telegram Notify - trade notifications, chart screenshots and daily summary for any EA (library + ready EA)

A WebRequest-only (no DLL) Telegram library: text and chart screenshot messages with queue and retry, plus ready trade reports (open, close with profit and reason, SL/TP changes, pending orders, daily summary). Includes a ready EA.

Trade Cost Report: Commission, Swap and Fees per Symbol Trade Cost Report: Commission, Swap and Fees per Symbol

Summarises the account's closed trades per symbol and shows how much of the gross result was taken by commission, swap and fees.

Prop Firm Risk Headroom Monitor Prop Firm Risk Headroom Monitor

Account-wide MT5 prop firm risk monitor that tracks daily and maximum loss headroom, current stop-loss exposure, projected equity and remaining risk capacity.