Markets are often perceived as random, yet structured randomness itself may reveal exploitable dynamics. This paradox motivates our exploration of randomized trading under supervised feedback loops.
At MetaBacktest, we developed a prototype expert advisor (EA) that challenges traditional deterministic strategies. Instead of predefined entry signals, the system opens a configurable number of random-direction trades within a specified time range each day, and then dynamically adapts to observed outcomes through Hidden Markov analysis.
This framework functions as a sandbox for stochastic experimentation , allowing traders and researchers to observe how controlled randomness interacts with evolving probability models.
Strategy Overview
Each trading day, during user-specified active hours, the system performs the following sequence:
-
Random Trade Generation
-
A user-defined number (n) of trades are opened in random directions (buy or sell).
-
Trade timing is randomly distributed within the specified intraday window (e.g., between 08:00–12:00 server time).
-
Performance Sampling
-
The system monitors the last n closed trades, capturing features such as direction, result (profit/loss), trade duration, and dynamic context (volatility, spread, etc.).
-
Markovian Analysis
-
Using a Continuous Hidden Markov Model (HMM) implemented in MQL4, the algorithm estimates the underlying “state” sequence governing observed outcomes.
-
The transition probabilities and emission likelihoods are updated after each analysis window to approximate the hidden behavioral regime of the random process (e.g., trending, mean-reverting, high volatility).
-
Adaptive Feedback
-
If the posterior probability distribution indicates a favorable latent state (“good outcome” regime), the next trade’s size is scaled by a user-defined multiplier (nX).
-
Otherwise, position sizing reverts to the baseline configuration.
Dynamic Trade Management
The EA incorporates both
static and dynamic risk parameters:
-
Dynamic Lot Sizing
Trade volume adjusts automatically as a function of account balance or equity, ensuring consistent proportional exposure.
-
Stop-Loss and Take-Profit Options
This hybrid structure allows empirical evaluation of how
random entry combined with
adaptive sizing and
Markov feedback may produce non-random performance characteristics.
* You can download the EA from the
Download Box HERE
Theoretical Context
Randomness in trading is typically considered undesirable. However, under certain formulations,
random sampling can act as an unbiased estimator of broader market conditions. By coupling this with an
HMM, which models unobservable market “states,” the system attempts to identify patterns not evident in deterministic signal-based methods.
The HMM serves as a compact, self-updating probabilistic filter, translating trade-level randomness into structured predictive feedback.
Implementation in MQL4
All components of the strategy are coded natively in MQL4, without reliance on external languages or libraries.
This ensures full MT4 compatibility and performance efficiency.
Core adjustable parameters include:
-
Active trading hours (start/end)
-
Number of trades per session (n)
-
HMM window length
-
Scaling multiplier (nX)
-
Dynamic vs. fixed lot sizing
-
Stop-loss / take-profit configuration
-
Random seed control
This modular design enables traders to experiment with diverse combinations and record performance outcomes directly through
MetaBacktest, ensuring reproducible results.
Experimental Use Cases
Potential research applications include:
-
Testing the emergent behavior of stochastic entries under different volatility regimes.
-
Analyzing the predictive value of trade sequences via Markovian transition probabilities.
-
Exploring the stability of adaptive sizing under different feedback thresholds.
-
Evaluating risk-of-ruin metrics for systems driven primarily by probabilistic adaptation rather than technical signals.
While this framework is not intended as a production-ready trading system, it represents a
unique intersection between randomness, probability theory, and algorithmic trading design.
Early testing shows that even purely random entries, when filtered through adaptive mechanisms, may exhibit structural tendencies that resemble conventional signal-based systems. This observation challenges the common assumption that “random equals unprofitable,” suggesting that adaptive randomness may hold analytical value in market modeling and behavioral finance.
* You can download the EA from the
Download Box HERE
Example Scenario
Let denote the price of a tradable instrument at time . Traditional algorithmic systems define deterministic entry signals . In contrast, this work intentionally replaces deterministic logic with controlled randomness, opening random-direction positions during a given time window .
Each trade produces an outcome (profit or loss). The sequence forms an observable process.
An unobserved latent process — representing the underlying market “state” (e.g., trending, ranging) — is assumed to govern these outcomes.
-
Random Trade Generation
During each active day:
where
-
is the random open time of trade ,
-
is the direction (buy = 1, sell = 0).
Position size begins as
with the current balance, the risk proportion, and a normalization constant (e.g., 100 000).
Stop-loss and take-profit levels may be fixed constants or random draws within intervals:
to emulate stochastic variation in trade management.
-
Hidden Markov Modeling of Outcomes
We assume a -state continuous HMM defined by parameters :
-
State transition matrix:
where
-
Emission model:
-
Initial probabilities:
Given the last trade results , we compute the likelihood of each state sequence using the forward algorithm:
and update iteratively via the Baum-Welch expectation–maximization routine.
The posterior state probability represents the system’s belief that the process currently resides in regime .
-
Adaptive Feedback Mechanism
Define an indicator variable for a “favorable” regime:
Here is the state with the highest expected return and a confidence threshold.
Next trade’s size is scaled as
This creates a Markov-modulated money-management process, where state inference drives dynamic risk exposure.
-
Implementation Framework
The entire procedure is executed within an MQL4 environment:
-
Scheduler: generates random times between specified hours.
-
Trade manager: executes positions with dynamic .
-
Data buffer: stores the last trade results.
-
HMM estimator: updates from new data.
-
Size controller: applies scaling according to inferred regime.
All parameters — trading window, , , , , thresholds, and bounds for — are externally adjustable to permit controlled backtesting through the MetaBacktest platform.
-
Analytical Insights
The expected return per trade, conditioned on hidden state inference, can be expressed as
Empirical experiments can compare this adaptive expectation with baseline random performance:
testing whether with statistical significance (e.g., t-test or bootstrap).
* You can download the EA from the
Download Box HERE
Backtest Results by MetaBacktest
Below we present four independent backtests, all executed with identical input parameters but driven by different random sequences. Each run represents a unique realization of the same probabilistic model—demonstrating how the system adapts and performs under varying random conditions. While the paths and trade distributions differ, the results consistently highlight the strategy’s resilience and adaptability, showing that its performance potential is not dependent on a single lucky sequence but emerges repeatedly across distinct random trials.
Test Parameters:
- Instrument : EURUSD
- Timeframe : Not Important.
- Spread : 20
- Period : Jan 2012 – Aug 2025
- trading window start hour: 18
- trading window end hour : 19
- number of random trades per day : 2
- number of last closed trades to analyze: 4
- % of balance risked (if using SL-based dynamic sizing) : 0.08
- use fixed base lot : False
- multiply next trade lot by : 14.0
- maximum allowed lot size: 10
- safety: max simultaneous open trades : 9
- UseFixedSLTP : True
- FixedSL_pips: 2222
- FixedTP_pips : 20
- UseRandomSLTP : False
- EM iterations : 20
- required posterior prob for "good" signal (0..1) : 0.8
- RNG seed for HMM initialization : 12345
- 0 = auto seed by time : 0
- use server time: True
- minute granularity window (1 means exactly at minute) : 1
- OnlyOneTradePerMinute: True
* You can download the EA and setting file from the
Download Box HERE
Process time: 0:05:30.250
Key Results:
Conclusion
The framework reframes randomness as a source of unbiased sampling rather than noise. By extracting conditional structure through the HMM, the system attempts to measure hidden regime dynamics that standard signal triggers may overlook.
Although preliminary, simulations suggest that feedback-driven adjustments can reduce variance and occasionally improve risk-adjusted returns relative to purely random execution. The model thus provides a testbed for exploring probabilistic adaptation and emergent order within random trading environments.
This work demonstrates how a Hidden Markov–based adaptive layer can transform random trade outcomes into probabilistic state estimates guiding position size. The concept offers an experimental path for traders and researchers to investigate the relationship between randomness, inference, and profitability.
Future research will expand on state dimensionality, incorporate regime-specific volatility modeling, and analyze the statistical robustness of adaptive scaling under different parameterizations.
Hidden-Markov-Model-Continuous-Emissions_MetaBacktest.ex4
Hidden-Markov-Model-Continuous-Emissions_MetaBacktest.mq4
HMM-CE-Setting-1_MetaBacktest.set
Report-Hidden-Markov-Model-Continuous-Emissions-EURUSD-1
Report-Hidden-Markov-Model-Continuous-Emissions-EURUSD-2
Report-Hidden-Markov-Model-Continuous-Emissions-EURUSD-3
Report-Hidden-Markov-Model-Continuous-Emissions-EURUSD-4
Please Login or Signup
to be able to download the files.
This is such a valuable contribution. It strikes a perfect balance between quantitative rigor and real-world applicability.
One question: why is the stop-loss value so wide (like 2222 pips in the example)?
I think that was just for testing purposes to avoid premature exits during backtests — not meant for live trading.
Is there a demo version available? I’d like to try it on a MetaTrader demo account before testing further.
@liami89 Yes, there’s a download link on the MetaBacktest page, you can load it with your own configuration in demo mode.
The equity curves shown in the tests are surprisingly stable for a system based on random entries. That’s a good sign of robustness.
I appreciate that this was coded entirely in MQL4, without relying on Python or external libraries. Makes it easy to test right in MetaTrader.