preview
Volatility Sizing Under Controlled Stress in MQL5 (Part 1): From Known Variance to Auditable Position Sizes

Volatility Sizing Under Controlled Stress in MQL5 (Part 1): From Known Variance to Auditable Position Sizes

MetaTrader 5 — Tester |
43 0
Maxell Agustin Aguiran
Maxell Agustin Aguiran

Contents

  1. Introduction
  2. The decision we will audit
  3. A controlled return stream
  4. Two estimators and one control
  5. How the source files work
  6. Run the MQL5 audit
  7. What the decisions show
  8. Checks and limits
  9. Conclusion


Introduction

Suppose an Expert Advisor forecasts next-bar volatility and adjusts exposure to meet a risk target. Before connecting that rule to orders, we need to check three things: whether the forecast is converted using the correct units, whether each decision uses only information available at that time, and how far the resulting conditional risk is from the target.

This article builds a repeatable MQL5 audit using synthetic returns with known next-bar variance. You will run rolling and EWMA variance estimators alongside a fixed-exposure control, then inspect a decision ledger that separates forecast-based sizing from the risk implied by the generator. The audit also tracks the effect of the exposure cap.

The test evaluates a sizing calculation under controlled conditions. It does not measure trading profitability or determine broker-ready volume: it excludes orders, fills, trading costs, and broker constraints. In real market data, the next-bar conditional variance used as the audit reference is not directly observable.

We take inspiration from FinStressTS (2026), which uses financial mechanisms to model and diagnose problems related to incorrect predictions in financial markets. The case discussed in the paper provides a basis to evaluate other approaches to model volatility outside of the constant-variance Gaussian case. We’ve developed an analogous, but smaller, single series position sizing system in MQL5. It is important to note that our code does not incorporate the paper’s benchmark or multi-asset returns generation component, and the authors of the paper do not mention our sizing estimates.

Other MQL5 articles cover related topics, including volatility models, stress testing with custom symbols, and artificial time series. Here, the key question is: what exposure is requested for bar t+1 given a variance estimate at the close of bar t, and how far is the resulting conditional risk from the target? The decision function can be reused in a subsequent EA by replacing the synthetic variance with a forecast of variance from the market. Because the next-bar variance of the generator is unobservable in historic or real-time data, the oracle audit criterion cannot be directly applied. Broker volume constraints and the manner in which orders are executed require specific implementation and testing.


The decision we will audit

Let r_t be a zero-mean log-return. Let h_(t+1) be the conditional variance for the next log-return provided by the generator. Assume that we estimated the conditional variance, denoted by estimated_h_(t+1), using the log-returns observed by the end of Bar t. We ask for a non-negative exposure with a unit notional amount. Our target next-bar standard deviation is 0.0075, or 0.75% of notional. Given a maximum exposure of 1.5, our sizing rule states:

exposure_(t+1) = min(1.5, target_sd / sqrt(estimated_h_(t+1)))

The square root is important. Variance is measured in squared return units and the target is standard deviation. Dividing the target standard deviation of 0.0075 by variance instead of its square root would result in a type of error known as a 'unit error' rather than an alternative way of specifying the size of the exposure. We have a native fixture in our system to check if the wrong expression produces a different answer from the right expression.

The conditional risk of the exposure is computed using the generator after exposure is selected.

The sizing function returns the next-bar standard deviation of the capped exposure, given a variance forecast. The audit calculates the next-bar conditional standard deviation as the capped exposure times the square root of the next-bar variance of the generator. Neither of these quantities is a realized loss, Value at Risk, expected shortfall, or the probability of loss in the given simulator.

oracle_risk_(t+1) = exposure_(t+1) * sqrt(h_(t+1))
deviation_(t+1)   = abs(oracle_risk_(t+1) - target_sd)

The next-bar conditional variance h_(t+1) is provided only to the audit function and is not passed to the estimator or the sizing function. The manifest refers to the next-bar conditional variance (h_(t+1)) of the generator as “truth.” The long-run variance determines the initial variance and omega of the generator. EWMA also starts from the same long-run variance, and the fixed control is calibrated from it. This does not state anything about the next realized loss. The next return can be much larger or smaller than the conditional standard deviation. We capture the following: excess and shortfall risks, exposure changes, and how often the cap is bound. These are diagnostic of a given decision, and not of trading or investment performance.


A controlled return stream

There are two scenarios in Part 1. Both begin at long-run variance 0.0001, which represents a conditional standard deviation of 1%. In the constant case, that variance is used for every bar. In the clustered scenario, a scalar GARCH(1,1) iteration alters it:

r_t     = sqrt(h_t) * z_t
h_(t+1) = omega + alpha * r_t^2 + beta * h_t

with alpha = 0.08, beta = 0.90 and omega = (1- alpha- beta) * 0.0001 = 0.000002. Standard normal innovations are z_t. For both cases, the same innovations are generated for each seed. This reduces one type of noise when comparing the scenarios, and does not force the path generated by the scenarios to be the same.

The native application uses eight fixed seeds. Each seed is used to generate 800 bars, 200 of which are burn-in bars, for each of the two scenarios. The other 600 bars are used to make 600 evaluation decisions. The innovations are generated using the Xorshift32 RNG and post-processed using the Box-Muller Transform. It is assumed that Gaussian innovations occur. The return stream, although clustered, is still conditionally Gaussian with changing variance. This is not intended to mean that clustered returns are jointly Gaussian, or that returns of financial assets are normally distributed. Later installments will allow for other more extreme distributions and allow for regime shifts.

The code used is in VolatilitySizingCore.mqh. CScalarVarianceGenerator in this code updates the conditional variance after emitting the current return. The estimator observes the returned value and takes an action for the next bar. To create a record of the process and show when a decision is made, the ledger stores both observed_bar and sized_bar.


Two estimators and one control

The first estimator computes the mean squared return of the last 20 bars. The second estimator is an EWMA, defined by lambda = 0.94:

EWMA_variance_(t+1) = 0.94 * EWMA_variance_t + 0.06 * r_t^2

The second is an EWMA, which starts at a long-run variance of 0.0001. Both estimators update their values after a given bar has been observed. No return mean is estimated in this demonstration because the generator's conditional mean is zero, and mean estimation would entail adding an additional question to the test. The fixed control puts exposure at 0.75, which has a conditional risk of 0.75% given that variance is 0.0001. This special case is important for the interpretation of the constant variance case.

The informed control in the fixed exposure method is calibrated to the known variance of the generator. Therefore, we should expect that the result of the fixed exposure method in the constant case should not be read as an endorsement for fixed exposure methods in general. A known long-run variance of the generator is also involved in the construction of EWMA, and, in this case, that variance is not estimated.

The starting value of EWMA receives a direct weight of about 0.00000422 after 200 burn-in observations. At the first scored decision, which follows observation 201, the direct weight is about 0.00000397. Burn-in reduces this direct weight and makes the estimators ready. However, it does not constitute a sensitivity test or prove that all effects associated with initialization have been removed.

The core sizing function refuses to operate with nonpositive or nonfinite variance, target, or cap. The function returns the requested exposure, capped exposure, and risk estimate for the request. The function is simple:

//+------------------------------------------------------------------+
//| SizeForVariance - apply the exposure cap (excerpt)               |
//+------------------------------------------------------------------+
//--- SizeForVariance: Convert forecast variance to capped exposure
   const double standard_deviation=MathSqrt(forecast_variance);
   const double desired=target_standard_deviation/standard_deviation;
   // ...
   result.desired_exposure=desired;
   result.exposure=MathMin(desired,maximum_exposure);
   result.capped=(desired>maximum_exposure);
   result.estimated_risk=result.exposure*standard_deviation;

It is important to note that given a binding cap, the estimated risk may be less than the target. Reporting only the uncapped desired exposure would be misleading to the requestor. In a trading Expert Advisor (EA), several constraints must be satisfied, including lot size, volume step, tick value, available margin, and existing positions. Fills also must be considered. These constraints are outside the scope of this program and will be discussed in Part 3.


How the source files work

Three MQL5 files are included with the source code. Each file has a distinct function: the decision rule, the experiment, or the small fixture. This allows the user to better understand how the source code works, rather than viewing it as a black box.

File

Purpose

VolatilitySizingCore.mqh

Reusable variance estimators, sizing decision, and controlled variance generator

SizingAudit.mq5

Paired scenario runner and per-decision audit writer

SizingAuditFixture.mq5

Small hand-calculated and timing checks

A shared header is included and separates the estimation and decision making code from the audit script. The generator is used only as a test input, and not as a source of market data for the sizing function. The sizing function and the audit script cannot place a trade. Scenario restrictions and privileged truth remain in the experiment and ledger.

In CVolatilitySizingCore::Observe, an observed return is squared and inserted in a ring buffer of size 20. The running sum subtracts the old entry once the buffer is full, so RollingVariance divides the sum of the last 20 squares by 20. It does not re-scan the entire history. The new square and the previous EWMA are used to update EWMA.

Ready prevents the rolling rule from sizing before 20 observations. The 200 bar burn-in ensures both methods are ready at the first reported decision. Because we work with means of squared-returns here, as opposed to sample variances about an estimated mean, we retain the zero-mean assumption.

The method named Observe displays the shared input and two memory rules:

//+------------------------------------------------------------------+
//| Observe - update the rolling ring and EWMA (excerpt)             |
//+------------------------------------------------------------------+
//--- Observe: Update the squared-return ring and EWMA state
   const int slot=m_seen%m_window;
   if(m_seen>=m_window)
      m_rolling_sum-=m_squared[slot];
   m_squared[slot]=squared;
   m_rolling_sum+=squared;
   m_ewma=m_lambda*m_ewma+(1.0-m_lambda)*squared;
   m_seen++;

CScalarVarianceGenerator::Step first shows the current variance, emits sqrt(h_t) * z_t, and finally updates the current variance with that return. During RunScenario, only the emission is sent to Observe. It uses each estimate to call SizeForVariance and write the request. WriteDecision then performs an audit-only calculation using the generator's next variance. It computes conditional risk, excess and shortfall, cap count, and exposure change. This ensures the ledger can report true variances, while keeping the estimator independent of report values. The control is set separately to 0.75 and written via the same audit function.

The intentionally small fixture allows for calculations to be performed manually. For testing, both Rolling and EWMA are fed three returns of our choosing. The test compares the variances and exposures with fixed expected values. It writes FAIL in case of a mismatch.

A second pair of Estimator instances is exposed to the same first two observations but different third observations. According to the check, the exposure recorded before the third observation must match. The check preserves the integrity of the decision at the cut-off point. In general, this is not a proof of impossibility of other paths the future may take.

VolatilitySizingCore.mqh

The public methods presented here constitute a reusable calculation interface. The generator is included for controlled tests, and the sizing function does not depend on it. Constructors set the object in an invalid state and it remains invalid until the Init method succeeds.

SizeForVariance

The function SizeForVariance returns a SizingDecision with respect to the variance of the forecast, the standard deviation of the target, and exposure limit. It doesn't allow nonpositive or non-finite inputs. It divides the target by the forecast standard deviation, and applies an upper bound. A valid result of the method is a request for a unit notional exposure, and not a broker lot size or a risk guarantee.

CVolatilitySizingCore constructor and Init

The constructor function takes no parameters. Init takes positive rolling window size, lambda in the range [0,1) and positive initial variance and returns a boolean. The function allocates and clears a ring buffer to store squared returns. It also resets the count to zero and sets the EWMA to the initial value. If validation or memory allocation fails, the object is set to an invalid state.

Observe

The Observe method is called with a zero-mean finite log-return and returns a boolean. It squares the return and pushes it onto the ring buffer. It replaces the oldest value in the ring buffer if it is full. It updates the running sum and EWMA and increments the count. The function rejects a nonfinite square and an invalid object state. It does not estimate a return mean or inspect a future value.

Ready and Observations

Both the functions, Ready and Observations, take no inputs and return a boolean and the observation count respectively. The Ready method returns true if the rolling window is full and the object is valid. Observations reports the count, regardless of readiness; neither assesses forecast quality.

RollingVariance and EWMAVariance

RollingVariance and EWMAVariance take no inputs and return variances or EMPTY_VALUE. The rolling variance estimator returns the average of the latest window of the squares of the returns. EWMA returns the value of the state which is updated for each new observation and requires at least one observation. Both are zero-mean estimators and are susceptible to outliers. Callers must verify readiness and check validity before usage.

CScalarVarianceGenerator constructor and Init

The constructor takes no arguments. The Init method is called with long-run variance, alpha and beta and returns a boolean. It sets the scalar GARCH recurrence with omega = (1-alpha-beta) * long-run variance. It requires LongRunVariance which is greater than 0 and Alpha and Beta which are non-negative and Alpha + Beta < 1. The component is a test case generator, not a fitted market model.

CScalarVarianceGenerator::Step

Step takes a finite innovation and output references for the observed return, current variance and next variance. It returns a success indicator. The generator returns the observed return using current variance and computes next GARCH variance, advancing state only after a valid result. The next variance is a privileged audit truth and is not to be sent to the estimator.

SizingAudit.mq5
CXorShiftNormal::Uniform, Init, and Next

The Init method accepts a seed and returns no value. Next and Uniform take no arguments and return samples from the standard-normal and standard-uniform distributions, respectively. Xorshift32 advances the internal state and Box-Muller converts two uniformly distributed numbers to a single normally distributed number. If a seed of zero is provided, the internal state is set to a fixed nonzero value. Repeatable (but neither cryptographically random nor a demonstration of market realism) sampling is provided for testing purposes.

ResetTotals

ResetTotals returns no value and takes an AuditTotals reference. Counts, deviations, turnover, and the prior-exposure flag are cleared so each method and path starts independently.

WriteDecision

WriteDecision accepts an open CSV file handle, scenario name, seed, bar data, method, estimate, decision and a totals reference. It returns a Boolean. It computes conditional risk, excess, shortfall, cap count, and exposure change for the next bar and writes to the CSV file. It rejects an invalid decision and reports a FileWrite failure. It only uses the generator truth value to write diagnostics in the audit file. If totals are updated before a write fails, the run is not complete.

WriteSummary

The WriteSummary function accepts a file handle, scenario name, seed, method and totals. It returns a Boolean. If there is at least one decision, diagnostic means are written for each seed. It does not pool seeds or perform a significance test.

The article performs a separate aggregation, averaging the eight seed means, with 600 decisions per seed. Cap counts are summed across the eight seeds and reported out of 4,800 decisions for each of the methods and scenarios.

RunScenario

RunScenario takes a scenario name, seed, innovation tape, and two file handles and returns a boolean. It replays the same tape with either constant or clustered variance and observes the returns. It skips burn-in and sizes rolling and EWMA requests. It writes the values and a fixed control to the file. It fails if there is an error during scenario initialization, calculation or file row writing. The scenario name is expected to be one of two names selected by OnStart.

WriteManifest

WriteManifest does not accept any input, and returns a boolean. It writes frozen settings to sizing_manifest.txt and reports an open file failure. Individual FileWriteString calls are not verified. The code, after closing the manifest, reopens it and verifies that its byte count and line contents are as expected. The code then returns a verification result.

OnStart

The script entry point is OnStart, which requires no inputs and returns no value. It opens files, draws eight fixed tapes, runs two scenarios, closes files, writes a status receipt, and reports PASS or FAIL. A receipt, if successfully written after this run, records this code path; independent replay and row counts verify arithmetic and output.

SizingAuditFixture.mq5
CheckNear

CheckNear takes a label, actual and expected values, and tolerance and returns nothing. It increments a failure count and prints FAIL if actual is non-finite or beyond the tolerance from expected. It performs the scalar comparison check only.

CheckTrue

CheckTrue takes a label and a boolean expression and returns nothing. It increases the failure count and reports FAIL if the condition is false and reports PASS otherwise. The caller defines the condition; the helper does not prove the property.

OnStart

OnStart, the fixture entry point, takes no arguments and returns nothing. It runs hand-calculated generator, estimator, cap, invalid input, unit, and prefix tests. The results are saved in a file named fixture_result.txt. This test case is a focused example and not a comprehensive proof for all inputs.

verify_ledger.py

An optional Python checker is available to check exported CSV data. It can rebuild the experiment independently. This is not required to run or compile the MQL5 scripts.

close

close takes an exported value, expected value, and field label, and returns nothing. It raises AssertionError if the difference is greater than relative tolerance of 2e-10 and absolute tolerance of 2e-12. It performs the comparison and does not verify the source of the expectation.

uniforms

uniforms takes a nonzero seed and generates an unlimited stream of uniform values. For uniform random numbers it uses xorshift 32-bit state space and masked integers in Python. The zero seed case is avoided with a provided seed list; this is to validate the protocol and not to test randomness.

innovations

innovations takes a seed and generates 800 normally distributed values. It transforms the next pair of uniforms using Box-Muller. The length and the order are fixed in this program; changing the native draw protocol means changing this checker.

main

main takes no arguments, returns nothing, and prints PASS or fails with an assertion. It reads both CSV files, rejects duplicates among the decision and summary keys, rebuilds all paths, estimates, exposures, risks, timing indices, and turnover, and verifies 48 summary entries. This checker validates the numerical protocol, and does not validate broker/dealer orders or trade profits.


Run the MQL5 audit

Follow the instructions for ‘Download MQL5.zip’ and extract the MQL5 folder to the data folder launched by the File → Open Data Folder command in MetaTrader 5. The source code is in the MQL5/Scripts/SizingAudit directory and the MQL5/Include/SizingAudit directory. Optional Python checks are located in MQL5/Files/SizingAudit/Part1. The source code and tools are located in the archive and the data may be generated by running MQL5 programs. You have to compile the MQL5 programs on your computer, as the zip file contains no compiled programs (EX5).

The attached files include SizingAudit.mq5, SizingAuditFixture.mq5 and VolatilitySizingCore.mqh. Place the header file in the MQL5/Include/SizingAudit/ directory and the scripts in MQL5/Scripts/SizingAudit/ directory. Compile both scripts in MetaEditor and run SizingAuditFixture.mq5 first. If the fixture is successful, it should write PASS to fixture_result.txt located in the MQL5/Files directory. The fixture compares the sizes computed from the same prefix of observed returns and checks if different subsequent returns update later EWMA estimates. It also validates a three return tape, the exposure cap, and invalid inputs. It identifies the mistake of confounding variance and standard deviation.

Run the SizingAudit.mq5 program on any chart. The script does not access nor is it concerned with the chart prices, specific symbol or account. It creates 4 files in the MQL5/Files folder:

File

Purpose

sizing_manifest.txt

Frozen seeds, generator, timing, estimator, target, and cap

sizing_decisions.csv

One row for every scenario, seed, evaluation bar, and method

sizing_summary.csv

Per-seed summaries, without hiding the individual runs

sizing_status.txt

PASS/FAIL receipt; verify fresh outputs separately

The main function of this MQL5 script draws the complete innovation tape once per seed, and applies it to the two case scenarios. Once it observes bar t, it calculates two variance estimates, sizes for bar t+1, and writes rolling, EWMA, and fixed decisions to the ledger. Therefore it makes 8 * 2 * 600 * 3 = 28,800 decisions. No trade requests are made. The CSV file can be read by a verification script or be opened in a spreadsheet to be inspected.

Confirm a successful run by checking the terminal output and the newly generated CSV files. Create the folder MQL5/Files/SizingAudit/Part1/evidence, then copy sizing_decisions.csv and sizing_summary.csv into it. Preserve the outputs and receipts of previously executed scripts before rerunning.

If you wish to execute the optional checks in Python, use Python 3.10 or newer, and set your working directory to MQL5/Files/SizingAudit/Part1. To check your exported decisions, run the command below.

python3 tools/verify_ledger.py

Figure 1: conditional standard deviation and the two estimates under one clustered path

Figure 1. The black line is the known next-bar conditional standard deviation for seed 104729 over evaluation bars 201–400. The green and orange lines are EWMA and rolling estimates made after observing each labeled bar. This is a view of the native MQL5 decision ledger, not an independent historical backtest.


What the decisions show

For each seed, we compute the mean absolute deviation of the generator’s implied conditional standard deviation of capped exposure from the 0.75% target. The value in the table is the mean of these eight means. Turnover is defined as the mean absolute change of capped exposure for the 600 evaluations. The mean is based on 600 evaluations, including 599 changes and an initial, or baseline, value of 0. An initial entry from a flat position is excluded. The model does not account for spread, commission, or slippage.

Mean absolute risk deviation is the sum of mean excess and mean shortfall, with both directional means calculated over all decisions, including zeros. It gives equal importance to errors made in overshooting and undershooting the target. Because of this, it does not reveal the direction of the error. The ranking of the various methodologies may change if one considers exceedance frequency, excess magnitude, or tail behavior, to name a few.

Scenario

Method

Mean absolute risk deviation

Mean exposure change

Capped decisions/4,800

Constant

Fixed 0.75

0.000000

0.000000

0

Constant

Rolling 20

0.001051

0.027203

8

Constant

EWMA 0.94

0.000806

0.022908

0

Clustered

Fixed 0.75

0.001698

0.000000

0

Clustered

Rolling 20

0.000773

0.029566

173

Clustered

EWMA 0.94

0.000534

0.025724

42

The table provides a descriptive comparison of two specified situations, using one GARCH parameter set and eight fixed seeds. There are no confidence intervals, analysis of parameter sensitivity, or results of initial-value sensitivity in the article. Per-seed ranges reported in the article are not to be confused with confidence intervals and are not measures of statistical robustness. No conclusions about a generally superior estimator may be drawn from these comparisons.

Per-seed mean absolute deviation (log-return SD units)

Scenario

Method

Minimum seed mean

Maximum seed mean

Constant

Fixed 0.75

0.000000000

0.000000000

Constant

Rolling 20

0.000915222

0.001329115

Constant

EWMA 0.94

0.000655644

0.001088367

Clustered

Fixed 0.75

0.001145149

0.002868763

Clustered

Rolling 20

0.000574366

0.000931408

Clustered

EWMA 0.94

0.000388768

0.000832059

Figure 2: comparison of risk deviations across both scenarios

Figure 2. Each bar averages eight per-seed mean deviations. The fixed control is exact in the constant case because its 0.75 exposure was chosen from the known 1% standard deviation. In this constant case, the adaptive rules change capped exposure, and the generator’s variance does not change. Under this particular clustered generator and parameter set, both adaptive methods reduce conditional-risk deviation, and EWMA has the smaller mean deviation of the two.

This result is only valid for the specific seeds, tuning constants and the conditional risk. The result does not prove that EWMA is the best estimate of volatility in other cases. The cap changes the exposure of 42 clustered EWMA decisions and 173 clustered rolling decisions. Individual excess risks can occur even with low average errors. The ledger differentiates excess and shortfall risks, and the combined absolute-deviation metric captures the total deviation. On the clustered paths, EWMA has a lower mean absolute deviation than rolling; however, in 3,275 of the 4,800 decisions of EWMA, the 0.75% conditional-standard-deviation target was exceeded, compared to 3,211 decisions for rolling. The frequencies represent the eight paths and should not be misconstrued as probabilities of a trading loss.

Direction of deviation (log-return SD units)

Scenario

Method

Mean excess

Mean shortfall

Above target/4,800

Frequency

Constant

Fixed 0.75

0.000000000

0.000000000

0

0.00%

Constant

Rolling 20

0.000721042

0.000330057

2,750

57.29%

Constant

EWMA 0.94

0.000536076

0.000270187

2,841

59.19%

Clustered

Fixed 0.75

0.000664486

0.001033209

1,465

30.52%

Clustered

Rolling 20

0.000612095

0.000160889

3,211

66.90%

Clustered

EWMA 0.94

0.000407391

0.000126528

3,275

68.23%

The reported deviation is due to the variance estimate as well as the 1.5 exposure cap. Desired exposure and capped exposure are compared using the same set of returns, estimates and next-bar variance to understand the reason for the deviation. For a given decision, the cap effect is the capped absolute deviation minus the uncapped absolute deviation. A negative value shows that clipping reduces the absolute deviation for that decision.

On these clustered paths, the mean absolute deviation is 0.000815 before the cap and 0.000773 after the cap for rolling. For EWMA, the mean absolute deviation is 0.000538 before the cap and 0.000534 after the cap. This accounts for the mechanical effect of the cap on frozen requests.

However, separate variance-forecast and constraint errors are not identified by this effect. A binding cap means the forecast-based desired exposure is greater than 1.5, while the generator-implied target is unattainable only if 1.5 times oracle_next_sd is less than 0.0075. No scored decision on the aforementioned paths satisfies the above-mentioned infeasibility condition, although there are forecast-based requests that have been capped. In this context, the removal of a cap does not mean that trades will be executed or that the return path will take a different course.

Before cap, After cap and Change are means over all 4,800 decisions per scenario and method, including decisions where the cap does not bind.

Mechanical cap effect (log-return SD units)

Scenario

Method

Capped decisions

Before cap

After cap

Change

Constant

Rolling 20

8

0.001053765

0.001051100

-0.000002665

Constant

EWMA 0.94

0

0.000806262

0.000806262

0.000000000

Clustered

Rolling 20

173

0.000815217

0.000772984

-0.000042234

Clustered

EWMA 0.94

42

0.000538270

0.000533918

-0.000004351

Generator-implied target feasibility

Scenario

Infeasible bars/4,800

Minimum next variance (squared-return units)

Constant

0

0.000100000000

Clustered

0

0.000027833687

Figure 3: capped decisions by seed under the clustered generator

Figure 3. Cap counts differ across seeds even with the same estimator settings. The eight-seed total in the table is useful for a compact comparison, while the per-seed view shows how unevenly the cap is reached on these finite paths.

The fixed control illustrates a useful lesson as well. The adaptive rules, on the clustered paths in question, outperform the fixed rule in terms of mean absolute deviation. Mean exposure change is determined on frictionless paths and does not include, for example, spread, commission, slippage or the cost of rebalancing. It, therefore, does not demonstrate if an incremental reduction in deviation from the conditional standard deviation target is justified by the additional trading activity.


Checks and limits

I verified the scripts by compiling and running them in a separate instance of MetaTrader 5. There were no reported errors or warnings with the compilation of the scripts. The native fixture returned PASS, and the main script wrote PASS. It also generated 28,800 decision steps and 48 per-seed summary rows.

I replayed the ledger for every seed outside of MQL5 and compared the results to those printed by the script. Innovations, GARCH recursions, rolling and EWMA estimates, exposures, cap flags, and conditional-risk calculations were in agreement with the results captured in CSV within the checker’s stated floating-point tolerances. This replay checks whether the numbers exported by the script agree with the expected output, even if the script generates a PASS statement.

Compiler success, along with PASS and independent replay, help verify examples and the correctness of the procedures used in the numerical calculation. These checks do not guarantee full test-case coverage, model validity for capital markets, statistical or economic significance of the results, or practical suitability of the sizing standards. The generator’s known variance can be used to develop a controlled test, but agreement with that reference does not in itself constitute evidence that the method is suitable for unknown variance cases.

The generator’s zero conditional mean is the same as the mean assumption of the estimators, and the experiment utilizes only Gaussian innovations. Part 1 does not test mean misspecification, regime shifts, jumps, leverage effects, volatility asymmetry, serially correlated innovations, or innovations with heavy tails. Heavy-tailed innovations, injected outliers and regime shifts are not evaluated in Part 1.

These tests allow us to reproduce and check the results of a controlled example. Lot steps, margin, tick value, contract size, account type and/or mode, existing positions, and filled orders are not taken into account for this unit-notional calculation. Therefore, these results do not serve as a validation of a broker’s executable volume. Results do not show that a strategy is profitable. The conditional variance shown by the results is not directly observable in the historical data of the financial markets. In part two, we will keep the decision ledger of part one, and introduce transient outliers and heavy-tailed distributions. In Part 3, we will be able to test our decision in the Strategy Tester and check requested, filled and held exposure on a self-defined symbol.


Conclusion

We have traced each sizing decision from an observed return through a variance estimate and capped exposure to an audit of next-bar conditional risk. The supplied fixture checks selected calculations and timing cases; an independent replay checks the exported ledger against the experiment's numerical protocol.

The result is a reusable MQL5 sizing function and a reproducible audit that produces 28,800 decision rows and 48 per-seed summaries. The ledger lets you inspect individual decisions, compare rolling and EWMA sizing with fixed exposure, and measure how the exposure cap affects risk deviation.

On the tested clustered paths, EWMA had a lower mean absolute risk deviation than rolling sizing: 0.000534 versus 0.000773. But it exceeded the target more often: 68.23% of decisions versus 66.90%. A smaller average deviation therefore does not mean fewer overshoots. These results describe the specified generator, seeds, and settings; they do not establish that either estimator is generally superior or suitable for live trading. They provide a controlled baseline for testing changes to a sizing rule before connecting it to trading operations.

Files

File

Location

Purpose

VolatilitySizingCore.mqh

MQL5/Include/SizingAudit

Shared rolling/EWMA estimators, sizing decision and controlled variance generator.

SizingAudit.mq5

MQL5/Scripts/SizingAudit

Paired constant/clustered runner and per-decision audit writer.

SizingAuditFixture.mq5

MQL5/Scripts/SizingAudit

Hand-calculated estimator, unit, cap and timing checks.

verify_ledger.py

MQL5/Files/SizingAudit/Part1/tools

Independently replays 28,800 decisions and 48 Part 1 summaries.

MQL5.zip

MQL5

Archive with source files and verification tools in their terminal folder structure. Extract its MQL5 folder into the MetaTrader 5 data folder. Compile the source locally; no EX5 files are included.

Attached files |
SizingAudit.mq5 (16.49 KB)
verify_ledger.py (6.87 KB)
MQL5.zip (10.21 KB)
Features of Custom Indicators Creation Features of Custom Indicators Creation
Creation of Custom Indicators in the MetaTrader trading system has a number of features.
Practical Modules from Other Languages in MQL5 (Part 10): The configparser module from Python Practical Modules from Other Languages in MQL5 (Part 10): The configparser module from Python
Configuration is an essential part of almost every software application. Instead of hardcoding settings directly into the source code, developers can store them in configuration files, making programs easier to customize, maintain, and reuse. In this article, we will see how INI files work and implement an MQL5-friendly interface for reading, accessing, modifying, and writing configuration data similarly to Python's builtin module called configparser.
Features of Experts Advisors Features of Experts Advisors
Creation of expert advisors in the MetaTrader trading system has a number of features.
Aggregating Multi-Broker Tick Feeds into a Synthetic Mid-Price in MQL5 Aggregating Multi-Broker Tick Feeds into a Synthetic Mid-Price in MQL5
This article shows how to aggregate quotes from multiple brokers in MQL5 via a simple file‑based bridge. Publisher EAs write bid, ask, and volume per tick; a timer-driven master EA validates inputs, excludes stale feeds, and produces a volume-weighted synthetic mid-price. The EA publishes the series to a custom symbol you can chart and test; the design was exercised on three broker demo accounts.