Watch how to download trading robots for free
Find us on Facebook!
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
Libraries

TesterSafeLots - risk lot size that stays correct in the MT4 Strategy Tester - library for MetaTrader 4

Ciprian Ghebanoaei
Ciprian Ghebanoaei
Algorithmic trader and MQL5 developer from Romania.
Views:
75
Published:
\MQL4\Include\
MQL5 Freelance Need a robot or indicator based on this code? Order it on Freelance Go to Freelance

The problem

Most MQL4 risk functions compute the money lost per lot as distance / MODE_TICKSIZE * MODE_TICKVALUE. On a live chart that is fine. In the MT4 Strategy Tester it is not: the tester keeps the tick value of the moment you run the test and does not recalculate it from historical prices.

When the account currency is the quote currency (EURUSD, GBPUSD, XAUUSD on a USD account) the tick value is constant, so nothing goes wrong. When the account currency is the base currency (USDJPY, USDCHF, USDCAD on a USD account) the real tick value moves with the exchange rate. A 2018 USDJPY backtest then sizes every trade with today's rate, and the EA risks more or less than its input says. The trades still open without any error, so the bug stays hidden in the report.

Lot size error of MODE_TICKVALUE in the MT4 tester by year

What the library does

This include file is for calculating the size of the position to be opened from a risk amount and a stop loss. When the account currency is the quote or the base currency of the symbol, the money per lot is computed from prices the tester does have:

  • quote = account currency: distance × contract size
  • base = account currency: distance × contract size / price at the stop

All other symbols (crosses such as EURJPY on a USD account, futures-style contracts) fall back to MODE_TICKVALUE, and TSL_Method() tells your EA which path is used so it can warn you.

Functions

  • double TSL_RiskLots(sym, entry, sl, riskMoney) - lot size that loses riskMoney (account currency) at the stop. Rounded down to the lot step; returns 0 when the result is below the minimum lot, so the EA skips the trade instead of risking more than asked.
  • double TSL_MoneyPerLot(sym, from, to) - money for 1.0 lot between two prices; "to" is the price where the money is booked.
  • int TSL_Method(sym) and string TSL_MethodName(method) - which calculation path is in use.
  • double TSL_MoneyPerLotTickValue(sym, from, to) - the usual tick value formula, kept for comparison.

Usage:

#include <TesterSafeLots.mqh>
...
double sl   = Ask - 300 * Point;
double lots = TSL_RiskLots(Symbol(), Ask, sl, AccountBalance() * 0.01);   // 1% risk
if(lots > 0) OrderSend(Symbol(), OP_BUY, lots, Ask, 5, sl, 0);

Test EA: TesterSafeLots_Check.mq4

Run it in the Strategy Tester only, on any symbol and timeframe (H1 was used below). Once a day it opens a small trade with a fixed stop and target. Every time a trade closes it compares the profit the tester really booked with both predictions for the same prices. At the end of the test the journal prints the average and largest error of each method, how far a risk-based lot size would be off with MODE_TICKVALUE, and the yearly average of that ratio.

Inputs:

  1. TradeHour - server hour of the daily test trade
  2. StopPoints - stop and target distance, points
  3. HoldHours - close after this many hours if neither stop nor target is hit
  4. TestLots - volume of the test trades
  5. RiskMoney - risk used for the lot size comparison
  6. Magic - magic number of the test trades

Results on a USD demo account

MT4 build 1492, H1, control points, test run on 30.11.2026, data to 27.11.2026. Error = difference between the predicted and the booked profit of each closed test trade. Trades that booked less than 1.00 are left out, because the booked profit is rounded to cents. The largest TesterSafeLots errors below come from the same rounding on trades that booked just over 1.00.

Symbol Period Trades TesterSafeLots error (avg / max) MODE_TICKVALUE error (avg / max) Lot with MODE_TICKVALUE vs correct lot
USDJPY 2018 - 2026 2,241 0.04% / 0.45% 18.9% / 35.6% x1.26 on average, from x0.97 to x1.56
USDCAD 2019 - 2026 1,963 0.04% / 0.40% 6.1% / 15.7% x1.07 on average, from x0.97 to x1.19
EURUSD 2018 - 2026 2,252 0.00% / 0.00% 0.00% / 0.00% x1.00
EURJPY 2019 - 2026 2,001 0.04% / 0.65% (fallback) 0.04% / 0.65% x1.00

On USDJPY the lots were about 45-50% too large in 2018-2021 and fell to about 1% in 2026, because the tester used the USDJPY rate of the day the test was run instead of the rate of each year. The direction depends on the rate when you run the test: with a rate lower than the historical one the lots would be too small.

EURJPY shows something else: on a cross pair the MT4 tester also books the profit with the current tick value, so the tick value formula matches the tester's own bookkeeping, and the library keeps it. The money result of such a backtest still uses today's conversion rate.

Limits

  • Cross pairs keep the tick value formula (see EURJPY above). TSL_Method() reports this.
  • Tested on one broker (Admirals, USD demo account). Symbols with unusual contract settings fall back to MODE_TICKVALUE through TSL_Method(); check them with the test EA before relying on them.
  • Swap and commission are not part of the risk calculation.
  • On a live chart the two methods are expected to differ only slightly (the library converts at the stop price, the terminal's tick value uses the current price). This was not measured; the tests above are tester runs.
Hotkeys: keyboard shortcuts for MQL4 experts and indicators, set in the inputs Hotkeys: keyboard shortcuts for MQL4 experts and indicators, set in the inputs

One include file that gives your EA or indicator keyboard shortcuts the user types into the inputs, such as Shift+B. Each press fires one action, Shift+B never fires on a plain B, and a shortcut that cannot work is refused at start with the reason.

Backtest Data Preflight: check broker bar history before a backtest Backtest Data Preflight: check broker bar history before a backtest

Check the first and last available bars and the gaps between bars for a date range before a backtest in the MetaTrader 4 Strategy Tester.

Three Colors Three Colors

Example: Moving Average indicator filling by different colors

MACD Sample MACD Sample

Classical MACD Sample.