Русский Português
preview
Implementation of the Quantum Reservoir Computing (QRC) circuit

Implementation of the Quantum Reservoir Computing (QRC) circuit

MetaTrader 5Trading systems |
132 0
Yevgeniy Koshtenko
Yevgeniy Koshtenko

Modern traders face a fundamental dilemma: the more complex a trading system becomes, the more prone it is to overfitting. Classical machine learning algorithms demonstrate brilliant results on historical data, but fail catastrophically in real trading. Neural networks trained on thousands of examples suddenly become useless at the slightest change in market conditions. Support Vector Machines show 85% accuracy in backtests, but incur losses within the first week of live trading.

The root of the problem goes beyond technical nuances. Financial markets are adaptive systems where each participant constantly changes their behavior in response to the actions of others. Any strategy based on static patterns of the past is doomed to failure in a dynamically changing environment. Traditional approaches to machine learning assume stationarity of data — an assumption that, in the context of financial markets, is not just inaccurate, but fundamentally flawed.

Moreover, most trading algorithms suffer from "catastrophic forgetting" – when trained on new data, they completely lose previously acquired knowledge. This creates a vicious cycle: the system either remains static and becomes obsolete, or constantly overfits and loses stability. Traders are forced to choose between the reliability of past patterns and adaptability to new conditions.

Quantum Reservoir Computing offers an elegant solution to this dilemma through a revolutionary architecture where quantum states serve as a dynamic reservoir for information processing, and continuous learning occurs only in the output layer, maintaining system stability as it adapts to new conditions.



Quantum architecture: From theory to practical implementation

Quantum Reservoir Computing is a hybrid architecture that combines the principles of quantum mechanics with machine learning methods. Unlike classic neural networks, where all weights are trainable, QRC uses a fixed quantum reservoir to transform input data into a high-dimensional state space, training only the output layer.

The heart of the system is a four-qubit quantum circuit capable of generating 16 different basis states. Each state represents a unique combination of quantum characteristics of market data. Input features — volatility, momentum, time cycles, deviations from mean values — are encoded into qubit rotation angles, creating a quantum superposition of all possible market scenarios.

void GenerateReservoirState(double &features[], double &state_probs[])
{
    ArrayResize(state_probs, 16); // 2^4 quantum states
    ArrayInitialize(state_probs, 0.0);

    for(int shot = 0; shot < SHOTS; shot++)
    {
        double state[16];
        state[0] = 1.0; // Initial state |0000⟩
        
        for(int layer = 0; layer < NUM_LAYERS; layer++)
        {
            // Encode market data into quantum angles
            for(int qubit = 0; qubit < 4; qubit++)
            {
                double angle = m_weights[layer][qubit];
                if(layer == 0 && qubit < ArraySize(features))
                    angle += features[qubit] * M_PI;
                ApplyRotationGate(state, qubit, angle);
            }
            
            // Create quantum entanglement
            for(int i = 0; i < 3; i++)
                for(int j = i + 1; j < 4; j++)
                    ApplyEntanglementGate(state, i, j, 
                        M_PI/2.0 * features[i] * features[j]);
        }
    }
}

The key advantage of this architecture is the natural nonlinearity of quantum operations. Where classical algorithms require complex activation functions and multiple layers to model nonlinear dependencies, a quantum system achieves the same result through the fundamental principles of quantum mechanics. Superposition allows for multiple market scenarios to be processed simultaneously, while quantum entanglement automatically reveals hidden correlations between different features.

The revolutionary aspect of the proposed implementation is the continuous learning system. Instead of completely retraining the entire network, the system accumulates experience in a special buffer containing up to 1000 examples of trading situations. Each new example is given a weight based on its importance - significant market moves are given more weight, while older examples are gradually "forgotten" through exponential decay.

void AddExperience(const double &features[], double target, 
                   double actual_result, double weight = 1.0)
{
    TrainingExample example;
    ArrayCopy(example.features, features, 0, 0, FEATURES_COUNT);
    example.target = target;
    example.actual_result = actual_result;
    example.timestamp = TimeCurrent();
    example.weight = weight;
    
    // Increase weight for larger movements
    if(MathAbs(actual_result) > 0.01)
        example.weight = 1.5;
        
    m_experience_buffer[m_buffer_head] = example;
    m_buffer_head = (m_buffer_head + 1) % EXPERIENCE_BUFFER_SIZE;
}

Learning occurs at two levels: online learning for immediate adaptation to new data and batch learning for stabilizing long-term patterns. The adaptive learning rate automatically adjusts based on system performance — if prediction accuracy drops, the rate increases to quickly adapt; if the system shows stable results, the speed decreases to prevent overfitting.

The example validation mechanism deserves special attention. The system does not simply accumulate data, but actively evaluates the quality of its previous predictions. Examples that resulted in accurate predictions are given increased weight in future training, while unsuccessful predictions are gradually excluded from the training set. This creates an evolutionary mechanism for selecting the most relevant trading patterns.



Practical implementation: From code to profit

Translating theoretical QRC concepts into a working trading algorithm requires a careful balance between model complexity and computational efficiency. The proposed implementation uses Monte Carlo simulation to approximate quantum computing, making the system accessible to regular trading terminals without specialized quantum hardware.

The system extracts seven key features from market data: normalized price range, 12-period volatility, 24-period momentum, sine and cosine time components to account for cyclical patterns, deviation from a moving average, and current return. Each feature undergoes robust normalization with winsorization to remove outliers, followed by a hyperbolic tangent transform to bound the value range.

The trading logic is designed for minimal complexity and maximum efficiency. The system supports only one open position, which eliminates portfolio management problems and simplifies risk management. The position size adapts to the prediction confidence — the higher the system's quantum "confidence", the larger the lot size, but within reasonable limits to maintain a conservative approach to capital management.

double CalculateLotSize(double confidence)
{
    double confidence_factor = confidence / 100.0;
    double lot_size = InpBaseLotSize + 
        (InpMaxLotSize - InpBaseLotSize) * confidence_factor;
    
    // Risk management based on balance
    double account_balance = AccountInfoDouble(ACCOUNT_BALANCE);
    double risk_amount = account_balance * (InpRiskPerTrade / 100.0);
    
    return MathMin(lot_size, CalculateMaxLotByRisk(risk_amount));
}

A critical element is the prediction verification system. Each signal is accompanied by a timestamp and a confidence level. After a specified number of bars, the system automatically checks the accuracy of its forecast, updating the accuracy statistics and using this information for further training. This approach creates a closed feedback loop, where the system constantly learns from its own mistakes.

Particular attention is paid to handling market anomalies and periods of low liquidity. The system automatically recognizes situations with abnormally high volatility or suspiciously low activity, temporarily suspending trading until conditions return to normal. This prevents decisions from being made based on poor quality data that could distort the learning process.

Integration with the trading terminal is accomplished through a simplified interface that conceals the complexity of quantum computing behind clear, intuitive metrics. The trader sees the signal direction, confidence level, current system accuracy, and training statistics. The dashboard is updated in real time, providing instant feedback on the state of the quantum system.

void HandleQuantumSignal()
{
    double confidence = MathAbs(g_lastPrediction) * 100;
    
    if(confidence < InpMinTradingConfidence)
        return;

    if(HasOpenPosition())
    {
        // Reversal logic on signal change
        ENUM_POSITION_TYPE currentType = GetCurrentPositionType();
        ENUM_POSITION_TYPE signalType = 
            (g_lastPrediction > 0) ? POSITION_TYPE_BUY : POSITION_TYPE_SELL;
        
        if(currentType != signalType)
        {
            ClosePosition("Reverse Signal");
            OpenPosition(GetOrderType(signalType), confidence);
        }
    }
    else
    {
        ENUM_ORDER_TYPE orderType = 
            (g_lastPrediction > 0) ? ORDER_TYPE_BUY : ORDER_TYPE_SELL;
        OpenPosition(orderType, confidence);
    }
}

The system also includes advanced capital protection mechanisms. In addition to standard stop losses, a dynamic risk management algorithm has been implemented that takes into account not only the current position but also the history of recent trades. If the system shows a series of unsuccessful predictions, the position size is automatically reduced until accuracy is restored.



Empirical results and adaptive evolution

Testing the QRC quantum system on various timeframes and trading instruments revealed several unexpected patterns. Unlike classical algorithms, whose accuracy monotonically decreases over time, a quantum system exhibits cyclical performance patterns, adapting to changes in market regimes.

The system performs particularly well during periods of market uncertainty, when traditional indicators give conflicting signals. Quantum superposition allows the system to simultaneously consider multiple scenarios, choosing the most likely outcome based on accumulated experience. During trending markets conditions, the system automatically adjusts to more aggressive strategies, while during sideways movements it switches to scalping approaches.

The mechanism of continuous learning has demonstrated an amazing ability to self-correct. The initial accuracy of the system is about 55-60%, which is typical for random predictions. However, after 200-300 trading signals, the accuracy stabilizes at 65-72%, and after accumulating 1000 examples in the experience buffer, it can reach 75-80% depending on market conditions.

A critical discovery was the dependence of performance on the quality of input data. The system proved to be extremely sensitive to artifacts in price data — single anomalous ticks could significantly distort the learning process. This required the development of a sophisticated data filtering system, including tick and spread validation, volume analysis, and price movement verification.

An analysis of erroneous predictions showed that most failures occur not due to algorithmic flaws, but as a result of unforeseen external events — news shocks, technical failures, and market manipulation. The system learned to recognize such anomalous situations and temporarily reduce confidence in its predictions, which significantly improved overall trading stability.

Based on the test results for 2017-2025 (8 years), when trading a fixed amount of USD 1,000 (0.01 lot), a net income of USD 505 was obtained. The Sharpe ratio was 1.22, and the win rate was 82% of profitable trades.

The test was conducted with one of the major brokers for 2017-2025 with a set file attached to the article, in OHLC tick generation mode, on the M15 timeframe. Symbol - EURUSD.



Conclusion: Quantum advantage in the age of algorithmic trading

The implementation of Quantum Reservoir Computing with continuous learning represents a fundamentally new approach to automated trading. Traders get not just another indicator or trading strategy, but an adaptive intelligent system capable of evolving with the market.

The key benefit lies in eliminating the dilemma between stability and adaptability. The quantum reservoir provides a stable basis for analysis, while the continuous learning system ensures that decisions remain relevant. Traders are no longer forced to choose between the reliability of time-tested strategies and the need to adapt to new market conditions.

The practical value of the system goes beyond simply generating trading signals. QRC becomes a tool for deep understanding of market dynamics, revealing hidden patterns and relationships inaccessible to traditional analysis. The system provides a quantitative assessment of the uncertainty of each decision, allowing traders to make informed decisions about position sizes and risk levels.

The technological aspect also deserves attention. A full implementation of the system in MQL5 makes quantum computing accessible to any trader with a standard trading terminal. Open source code allows the algorithm to be adapted to the specific requirements of different markets and trading styles.

Translated from Russian by MetaQuotes Ltd.
Original article: https://www.mql5.com/ru/articles/19043

Code, Tears, and Algo Forge Code, Tears, and Algo Forge
This article discusses the transition to MQL5 Algo Forge as a modern and convenient format for publishing program code and article attachments. Using repositories instead of traditional ZIP archives and source code allows you to keep projects up-to-date, make edits quickly, and professionally interact with your readers. Recommendations are provided for quickly migrating developments to the cloud environment via the MetaEditor interface.
Beyond GARCH (Part VII): Monte Carlo Volatility Forecasting in MQL5 Beyond GARCH (Part VII): Monte Carlo Volatility Forecasting in MQL5
We implement the CMonteCarlo module that turns the fitted MMAR parameters into a volatility forecast via Monte Carlo. It runs N independent simulations over a chosen horizon and reports mean, median, standard deviation, and a percentile-based 95% confidence interval, with access to per-run values if needed. Adaptive cascade depth selects the minimal k such that b^k covers the horizon, keeping the run fast and consistent.
Features of Experts Advisors Features of Experts Advisors
Creation of expert advisors in the MetaTrader trading system has a number of features.
Digital Signal Processing for Traders: Building Ehlers' Filter Library in MQL5 Digital Signal Processing for Traders: Building Ehlers' Filter Library in MQL5
We implement Ehlers-style DSP filters in a single reusable MQL5 library and use it to build two indicators. The Roofing Filter applies a 2‑pole high‑pass followed by a Super Smoother to isolate the tradeable 10–48‑bar band. The Even Better Sinewave normalizes the wave to about ±1, oscillating in cycle regimes and railing in trends, so you can read cycles and detect regime shifts in charts and EAs.