Neural Networks in Trading: Mesh Approximation of Event Streams as a Tool for Analyzing Price Patterns (ADM Module)
Introduction
The EEMFlow framework was conceived from the outset as an attempt to take a mature approach to event data processing. Its authors start from a simple but often overlooked idea. The world — whether it is a physical scene or a financial market — does not unfold in discrete frames, but rather as a continuous flow of events. Price does not form candlesticks; it moves. Volume is not updated on a timer; it reacts. And that is precisely what makes the event-driven approach so appealing for problems where response speed, local motion structure, and robustness to nonstationarity are important.
In previous articles, we have already examined in detail how the ideas behind EEMFlow allow us to go beyond the conventional representation of the market. The framework's architecture is built around an event stream that preserves as much information as possible about the dynamics of the process. However, this stream requires extremely careful handling. Events are irregular. Their density varies by several orders of magnitude. And the statistics drift as market regimes change. Ignoring this means building fragility into the model from the outset.
This is exactly where EEMFlow demonstrates its key advantage. The framework's architecture is designed from the ground up to handle variable data density. Rather than dealing with the consequences of nonstationarity in the later stages, the authors shift the focus to the model's input. First, the data is converted into a robust, comparable representation, and only then does the process of extracting the motion structure begin.
In general terms, the EEMFlow architecture follows the classic, time-tested Encoder–Decoder framework with multiscale processing. However, beneath this apparent familiarity lies an important difference. Here, the encoder does not simply extract features, but works with an event space that has already been adapted. Correlation modules look not for density matches, but for consistency in motion. Reconstruction blocks recover details based on confidence in the local structure rather than on blind interpolation.
The central element of this logic is the Adaptive Density Module (ADM) — a module for density adaptation. It is this component that ties the raw events and the entire subsequent architecture together into a single whole. ADM ensures that the data entering the model has stable statistical properties, regardless of whether the system is in a quiet regime or undergoing a sharp momentum move. This is particularly important for financial markets. Here, regime changes are the norm, not the exception.
The ADM structure consists of two major components:
- Multi-Density Changer (MDC),
- Multi-Density Selector (MDS).

The Multi-Density Changer (MDC) is a basic yet fundamentally important component. Its task is simple to state but complex in practice: to transform the event stream so that differences in density no longer dominate the motion structure. MDC does not attempt to predict the market or add predictive logic; it does what good data engineers have traditionally done: brings chaotic input into a well-organized, controlled form.
In our previous work, we began the practical implementation of this particular module. And this is no coincidence. MDC is the foundation of ADM and, in fact, of the entire EEMFlow architecture. Without this module functioning properly, any subsequent operations — whether feature correlation or MeshFlow estimation — will begin to respond not to price movements but to changes in market activity. As a result, the model becomes sensitive to noise and loses robustness precisely when it is most needed — during market regime transitions.
In this article, we continue our work on ADM, building on the ideas presented in previous publications. Our focus remains on engineering. We do not aim to reproduce the original neural network in its entirety. On the contrary, we are gradually porting the architectural principles of EEMFlow to the MQL5 environment, adapting them to the requirements of real-world use.
Feature Selection Module
Once the Multi-Density Changer (MDC) has generated a multiscale representation of the event stream, we reach a fundamentally new stage. Here we have three parallel representations of the same market, each of which reflects its behavior in its own density regime. That is already a significant step forward. But the work of ADM does not end there. On the contrary — that is exactly where it really begins.
The market does not operate in three regimes at the same time. At any given moment, it tends toward one of them — sometimes gradually, sometimes abruptly. The system's task is not simply to have several representations available, but to select the currently relevant one without losing information or resorting to hard switching. In the EEMFlow architecture, this is precisely the role of the Multi-Density Selector (MDS).
While MDC addresses the question of how to represent a stream of events at different densities, MDS addresses a more nuanced — and perhaps more important — question: Which of these representations is most valuable right now?
From an engineering standpoint, MDS is a weighting mechanism. It does not discard scales or select one correct option. Instead, it forms a coherent, weighted representation in which the contribution of each density level is determined by the current state of the system. This approach appears neat, conservative, and — most importantly — robust. Exactly the way good trading models tend to behave.
In the original EEMFlow, MDS is implemented as a trainable module that evaluates the relevance of each density channel based on local features. However, when adapting this idea to the MQL5 environment, we continue to follow principles rather than copy blindly. It is important for us to preserve the very logic of the architecture: adaptability, continuity, and the absence of rigid thresholds.
It is of fundamental importance that MDS operates continuously. We do not define discrete market states such as a flat market, a trend, or high volatility. Instead, the system itself assesses which combination of densities best describes what is happening at any given moment. This approach aligns well with the event-driven nature of the data and spares us from artificial classifications that rarely stand up to the realities of the market.
It is worth emphasizing that MDS, like MDC, is not a predictive module. It does not attempt to predict the future direction of the price. Its task is far more modest and, at the same time, more fundamental — to correctly construct the input representation for the rest of the architecture. This is yet another example of how EEMFlow shifts intelligence from the upper layers of the network to the earliest stages of data processing.
To implement the functionality of the MDS module, we create a new object — CNeuronMDS. Its inclusion is no coincidence and reflects the role of MDS in the overall structure of the framework. This module is not a typical neuron in the classical sense. It works with multiple input representations simultaneously and performs selection at the level of density scales rather than individual features.
class CNeuronMDS : public CNeuronBaseOCL { protected: uint iDimension; uint iUnits; uint iVariables; CNeuronBaseOCL cConcat; CLayer cScores; CNeuronTransposeVRCOCL cTranspose; //--- virtual bool feedForward(CNeuronBaseOCL *NeuronOCL) override { return false; } virtual bool feedForward(CNeuronBaseOCL *NeuronOCL, CBufferFloat *SecondInput) override; virtual bool updateInputWeights(CNeuronBaseOCL *NeuronOCL) override { return false; } virtual bool updateInputWeights(CNeuronBaseOCL *NeuronOCL, CBufferFloat *second) override; virtual bool calcInputGradients(CNeuronBaseOCL *NeuronOCL) override { return false; } virtual bool calcInputGradients(CNeuronBaseOCL *NeuronOCL, CBufferFloat *SecondInput, CBufferFloat *SecondGradient, ENUM_ACTIVATION SecondActivation = None) override; public: CNeuronMDS(void) {}; ~CNeuronMDS(void) {}; //--- virtual bool Init(uint numOutputs, uint myIndex, COpenCLMy *open_cl, uint window, uint units_count, uint variables, ENUM_OPTIMIZATION optimization_type, uint batch); //--- virtual int Type(void) override const { return defNeuronMDS; } //--- methods for working with files virtual bool Save(int const file_handle) override; virtual bool Load(int const file_handle) override; //--- virtual void SetOpenCL(COpenCLMy *obj) override; //--- virtual bool WeightsUpdate(CNeuronBaseOCL *source, float tau) override; virtual void SetActivationFunction(ENUM_ACTIVATION value) override { }; };
Inheritance from CNeuronBaseOCL emphasizes that MDS is a full-fledged element of the computational graph, designed for execution in OpenCL. This architectural choice is justified: the selection and weighting operations are performed on tensor structures and must be as efficient as possible when processing streaming data. When processing market data as an event stream, this means robust performance both during periods of low activity and during times of sharp density spikes.
The internal parameters iDimension, iUnits, and iVariables define the geometry of the data being processed and enforce fixed shapes for the input and output representations. This is an important point. MDS does not work with abstract signals, but rather with pre-structured features generated by MDC. Any ambiguity regarding dimensions is unacceptable here, as it directly affects the correctness of subsequent calculations.
Weight generation is implemented through the cScores block of neural layers. It is at this stage that the relevance scores for the density representation are calculated for each individual feature. This fundamentally distinguishes MDS from crude global weighting mechanisms. The selector does not assign a single common factor to the entire density scale. On the contrary, it analyzes the contribution of each feature separately, forming a refined, locally adaptive weighting scheme.
This approach allows the system to account for the fact that different features behave differently across density regimes. Some of them remain informative even when the flow of events is sparse, while others reveal their value only under conditions of high market activity. MDS does not impose a one-size-fits-all solution, but rather carefully distributes confidence across density scales at the level of individual representation components.
From an engineering perspective, this means that the cScores block functions as a component-wise adaptation mechanism. As a result, the final representation is formed through a weighted combination, and each feature is assigned the contribution that best reflects the current state of the event stream.
It is precisely this level of detail that makes MDS a key component of ADM. It completes the transition from a multi-density description to a unified adaptive feature space, while maintaining sensitivity to the local structure of the data. For the subsequent correlation and estimation blocks, this means a stable and informative input, free from biases caused by changes in market density.
The initialization method sets all the key parameters for the selector's operation and, in essence, defines its internal architecture. It is here that it is finally determined how multi-density representations will be combined and how the relevance of each scale will be calculated with respect to individual features.
bool CNeuronMDS::Init(uint numOutputs, uint myIndex, COpenCLMy *open_cl, uint window, uint units_count, uint variables, ENUM_OPTIMIZATION optimization_type, uint batch) { if(!CNeuronBaseOCL::Init(numOutputs, myIndex, open_cl, window * units_count * variables, optimization_type, batch)) return false; activation = None;
The first step is to call the base initialization of the parent class. The size of the output space is defined as the product of the window size, the number of elements in the sequence, and the number of independent variables. The activation function is disabled at this level because the selector itself does not introduce any additional nonlinearity — its purpose is to redistribute feature importance.
Next, the internal parameters iDimension, iUnits, and iVariables are set. These values serve as the basis for all subsequent calculations and determine the geometry of the data at each stage of processing. Specifying dimensions in this explicit manner eliminates implicit assumptions from the module and makes its behavior completely deterministic.
iDimension = window; iUnits = units_count; iVariables = variables;
The next step is to initialize the data concatenation object.
uint index = 0; if(!cConcat.Init(0, index, OpenCL, 4 * Neurons(), optimization, iBatch)) return false; cConcat.SetActivationFunction(None);
Here, it is important to note one key point. The Multi-Density Selector receives data from two sources simultaneously. The first is the initial event representation received at the ADM input — that is, data that has not yet undergone density adaptation. The second is the multi-density representation already produced at the output of MDC. Thus, from the outset, MDS operates in the context of the original stream rather than in isolation from it.
In the first stage, these two sources are neither mixed nor weighted, but are carefully concatenated in a shared feature space. An extended representation is formed in which raw data and density variants of the same stream coexist in parallel. This decision may seem conservative, but that is precisely where its strength lies.
From an engineering perspective, concatenation is a way to preserve as much information as possible before the selection stage. MDS is able to assess the relevance of density scales not in the abstract, but based on the current state of the input event stream.
This is essential for proper adaptation. Under different market conditions, the same density transformations may behave differently. By maintaining access to the raw data, MDS avoids blind selection and generates weights based on the actual structure of the signal being analyzed.
Only after this stage — when all sources have been merged into a single, expanded space — does the calculation of relevance scores begin in the cScores block. This block is formed as a sequence of convolution and normalization operations. The first convolution expands the feature space, allowing for local relationships between density representations to be taken into account.
CNeuronConvOCL* conv = NULL; CNeuronBatchNormOCL* norm = NULL; CNeuronSoftMaxOCL* softmax = NULL; cScores.Clear(); cScores.SetOpenCL(OpenCL); index++; conv = new CNeuronConvOCL(); if(!conv || !conv.Init(0, index, OpenCL, 4 * iDimension, 4 * iDimension, iDimension, iUnits, iVariables, optimization, iBatch) || !cScores.Add(conv)) return false; conv.SetActivationFunction(None);
This is followed by batch normalization with the smooth nonlinearity SoftPlus, which ensures numerical stability without abrupt cutoffs.
index++; norm = new CNeuronBatchNormOCL(); if(!norm || !norm.Init(0, index, OpenCL, conv.Neurons(), iBatch, optimization) || !cScores.Add(norm)) return false; norm.SetActivationFunction(SoftPlus);
The second convolution restores the representation to the dimensionality corresponding to the original window, but now in the form of a compact set of scores.
index++; conv = new CNeuronConvOCL(); if(!conv || !conv.Init(0, index, OpenCL, iDimension, iDimension, 4, iUnits, iVariables, optimization, iBatch) || !cScores.Add(conv)) return false; conv.SetActivationFunction(None);
Re-normalization once again stabilizes the distribution of values, preparing the data for the final selection stage.
index++; norm = new CNeuronBatchNormOCL(); if(!norm || !norm.Init(0, index, OpenCL, conv.Neurons(), iBatch, optimization) || !cScores.Add(norm)) return false; norm.SetActivationFunction(SoftPlus);
The final element of cScores is the SoftMax layer. This is where the normalized relevance weights are calculated. And not globally across the entire scale, but for each feature separately. Setting the number of heads to iUnits*iVariables emphasizes the component-wise nature of the selection. Each feature is assigned its own confidence distribution across the density channels. This is a key aspect of the entire MDS architecture and a fundamental difference from crude mode-selection schemes.
index++; softmax = new CNeuronSoftMaxOCL(); if(!softmax || !softmax.Init(0, index, OpenCL, norm.Neurons(), optimization, iBatch) || !cScores.Add(softmax)) return false; softmax.SetHeads(iUnits * iVariables);
After the weights are calculated, the transposition object is initialized. It ensures that the dimensions are properly aligned before the weights are applied to the original features. Despite its technical nature, its role is critical: it is here that the correspondence between relevance scores and the structure of the input tensors is ensured. An error at this stage would negate all of the selector's adaptive logic.
index++; if(!cTranspose.Init(0, index, OpenCL, iUnits * iVariables, 4, iDimension, optimization, iBatch)) return false; cTranspose.SetActivationFunction(None); //--- return true; }
As a result, the initialization method produces a complete and self-contained MDS module that takes a multi-density representation of the event stream and transforms it into a unified, weighted feature space. At the same time, the adaptation occurs continuously, on a component-wise basis, and without abrupt switches between modes. This approach fits seamlessly into the philosophy of EEMFlow and creates a robust foundation for the architecture's subsequent correlation and estimation modules.
The Multi-Density Selector forward pass algorithm is implemented in the feedForward method. It is here that the analyzed data undergoes a step-by-step transformation into a unified, weighted representation of features that reflects the current state of the market.
bool CNeuronMDS::feedForward(CNeuronBaseOCL *NeuronOCL, CBufferFloat *SecondInput) { if(!NeuronOCL || !SecondInput) return false; if(!Concat(NeuronOCL.getOutput(), SecondInput, cConcat.getOutput(), iDimension, 3 * iDimension, iUnits * iVariables)) return false;
In the first stage, the method receives data from two sources: raw data fed into ADM, and a multi-density representation from MDC. These data are carefully combined using the concatenation function. The result is an expanded representation that preserves all density scales as well as the original information about the events. This combination enables MDS to evaluate the contribution of each density channel relative to the source stream, which is critical for adaptive selection.
Next, a sequence of calculations is performed using the cScores block. Each element of this block is applied sequentially to the previous result.
CNeuronBaseOCL* prev = cConcat.AsObject(); CNeuronBaseOCL* curr = NULL; for(int i = 0; i < cScores.Total(); i++) { curr = cScores[i]; if(!curr || !curr.FeedForward(prev)) return false; prev = curr; }
This implements the principle of component-wise weighting. Each feature is assigned its own relevance distribution across the density channels. Thanks to SoftMax, normalized weights are generated at the output, while BatchNorm and SoftPlus ensure the stability of numerical values, preventing sharp fluctuations when market activity changes.
After the operations in the cScores block are completed, the concatenated tensor — which combines the input data and the multi-density representation from MDC — is transposed.
if(!cTranspose.FeedForward(cConcat.AsObject())) return false; if(!MatMul(cTranspose.getOutput(), curr.getOutput(), Output, iDimension, 4, 1, iUnits * iVariables, true)) return false; //--- return true; }
This step ensures that the dimensions are properly aligned before performing matrix multiplication with the resulting relevance coefficients, so that each weight correctly influences the corresponding feature.
The final step of the forward pass is matrix multiplication of the transposed tensor output by the output of the cScores block. As a result, a final weighted representation is formed, in which each feature receives a contribution from each density scale in accordance with the relevance scores. This is the key output of MDS: a unified adaptive representation of the event stream, ready for further correlation processing and the construction of motion features.
As a result, CNeuronMDS completes the formation of an adaptive input representation for the subsequent blocks of the framework. After this processing, the event stream ceases to be merely a set of parallel scales and becomes a unified, consistent description of motion, ready for further processing. It is precisely at this stage that the EEMFlow architecture begins to fully demonstrate its key strength — robust adaptation to variable market density without losing structural information.
Adaptive Density Module
At this stage, we have already implemented two key submodules of the Adaptive Density Module:
- MDC, which forms a multi-density representation of the event stream,
- MDS, which provides adaptive weighting of these representations at the level of individual features.
From an engineering standpoint, this integration offers several important advantages. First, the entire adaptation process becomes deterministic and transparent: each input signal follows a strictly defined path, and the influence of each density channel is clearly defined. Second, this ensures robustness to changes in market regimes: whether the market is calm or experiencing a sharp surge in activity, the ADM output remains accurate and informative.
To combine the two submodules, we create a new CNeuronSpikeADM object that inherits from CNeuronMDS. This object serves as a unified wrapper for the Adaptive Density Module, combining a multi-density representation and a feature weighting mechanism within a single functional block.
class CNeuronSpikeADM : public CNeuronMDS { protected: CNeuronSpikeConvBlock cConv; CNeuronSpikeMDC cMDC; //--- virtual bool feedForward(CNeuronBaseOCL *NeuronOCL) override; virtual bool feedForward(CNeuronBaseOCL *NeuronOCL, CBufferFloat *SecondInput) override { return feedForward(NeuronOCL); } virtual bool updateInputWeights(CNeuronBaseOCL *NeuronOCL) override; virtual bool updateInputWeights(CNeuronBaseOCL *NeuronOCL, CBufferFloat *second) override { return updateInputWeights(NeuronOCL); } virtual bool calcInputGradients(CNeuronBaseOCL *NeuronOCL) override; virtual bool calcInputGradients(CNeuronBaseOCL *NeuronOCL, CBufferFloat *SecondInput, CBufferFloat *SecondGradient, ENUM_ACTIVATION SecondActivation = None) override { return calcInputGradients(NeuronOCL); } public: CNeuronSpikeADM(void) {}; ~CNeuronSpikeADM(void) {}; //--- virtual bool Init(uint numOutputs, uint myIndex, COpenCLMy *open_cl, uint window, uint units_count, uint variables, ENUM_OPTIMIZATION optimization_type, uint batch); //--- virtual int Type(void) override const { return defNeuronSpikeADM; } //--- methods for working with files virtual bool Save(int const file_handle) override; virtual bool Load(int const file_handle) override; //--- virtual void SetOpenCL(COpenCLMy *obj) override; //--- virtual bool WeightsUpdate(CNeuronBaseOCL *source, float tau) override; //--- virtual void SetActivationFunction(ENUM_ACTIVATION value) override { }; virtual void TrainMode(bool flag) override; virtual bool Clear(void) override; };
There are two key components within the object: cMDC and cConv. The first is responsible for constructing a multi-density representation of the event stream, replicating the functions of MDC, while the second is responsible for preprocessing and feature generation. Representations are selected using the parent class. Thus, the new object encapsulates the entire sequence of ADM operations: first, the event stream is transformed into parallel density channels; then, these channels undergo adaptive selection and form a coherent representation.
The initialization method sets all key operating parameters for the combined ADM unit and ensures that its internal components are initialized correctly.
bool CNeuronSpikeADM::Init(uint numOutputs, uint myIndex, COpenCLMy *open_cl, uint window, uint units_count, uint variables, ENUM_OPTIMIZATION optimization_type, uint batch) { if(!CNeuronMDS::Init(numOutputs, myIndex, open_cl, window, units_count, variables, optimization_type, batch)) return false;
First, the parent class is initialized, which defines the structure of the Multi-Density Selector, including the dimensions of the data being analyzed. Thus, MDS receives a ready-to-use configuration for component-wise weighting of density channels.
Next, two internal submodules are initialized. cConv is responsible for preprocessing the event stream, generating features for subsequent adaptive selection.
if(!cConv.Init(0, 0, OpenCL, window, window, window, units_count, variables, optimization, iBatch)) return false;
cMDC generates a multi-density representation by providing parallel density channels that will be evaluated and weighted by MDS.
if(!cMDC.Init(0, 1, OpenCL, window, window, units_count, variables, optimization, iBatch)) return false; //--- return true; }
Each of these components receives the same key parameters, which ensures consistency and compatibility in their computations.
As a result, the initialization method fully prepares the new object to function as a complete Adaptive Density Module: it combines MDC and MDS into a single processing pipeline.
The forward pass algorithm for the combined block is implemented in the feedForward method. It creates a sequential pipeline for processing the event stream by integrating all the key components.
bool CNeuronSpikeADM::feedForward(CNeuronBaseOCL *NeuronOCL) { if(!cConv.FeedForward(NeuronOCL)) return false;
In the first step, the method of the same name is called on cConv, which performs preliminary convolutional processing of the input data stream. This is where the fundamental features are formed, preparing events for subsequent multi-density decomposition.
Next, MDC is invoked to generate a multi-density representation of the event stream. This step ensures the creation of parallel density channels, each of which reflects market movement on its own scale.
if(!cMDC.FeedForward(cConv.AsObject())) return false;
Finally, control is passed to the parent class, which receives two inputs: the preliminary convolution result and the multi-density representation.
if(!CNeuronMDS::feedForward(cConv.AsObject(), cMDC.getOutput())) return false; //--- return true; }
Component-wise adaptive selection is implemented here. Each feature is assigned a relevance weight across all density channels, forming a single, consistent representation.
As a result, the feedForward method transforms disparate data streams into a unified, adaptive view of the event stream, ready for further processing. This approach ensures smooth adaptation to changes in market activity and maintains sensitivity to the local data structure, which is a key operating principle of EEMFlow.
Integration of ADM into the model
At this stage, we have implemented one of the key components of the EEMFlow framework — the Adaptive Density Module. This module combines multi-density transformation and adaptive feature selection to form a weighted representation of the event stream. Our work, of course, is not yet complete: we still have to adapt the remaining components of the framework. Nevertheless, it is important to note one key feature: the authors of EEMFlow emphasize the versatility of ADM and its ability to improve the performance of other models. This means that the module is not tied exclusively to a specific architecture but can be integrated into various models and strategies, improving their adaptability to fluctuating market density.
Consequently, in the next step, we will attempt to integrate the implemented ADM into one of the models discussed earlier and evaluate its effectiveness. This experiment will not only verify the correctness of the implementation but also demonstrate the practical value of the Adaptive Density Module in real-world event analysis scenarios.
We chose the BAT framework as the basis for the experiment. Its previously developed top-level object, CNeuronBAT, provides a flexible architecture that allows new components to be integrated with minimal changes to the existing structure. This makes BAT the ideal platform for testing ADM. Our module can be integrated as an additional preprocessing unit for the event stream without disrupting the core logic of feature engineering and risk management strategies. At the same time, maintaining compatibility with the other elements of BAT allows us to evaluate the impact of ADM on the model's performance under familiar conditions, using proven methods.
To carry out the planned experiment, we create a new object, CNeuronBATvADM, which inherits from CNeuronBAT. The main goal of this class is to integrate the Adaptive Density Module into the existing BAT structure.
class CNeuronBATvADM : public CNeuronBAT { public: CNeuronBATvADM(void) {}; ~CNeuronBATvADM(void) {}; //--- virtual bool Init(uint numOutputs, uint myIndex, COpenCLMy *open_cl, uint dimension, uint embed_size, uint stack_size, uint variables, ENUM_OPTIMIZATION optimization_type, uint batch); //--- virtual int Type(void) override const { return defNeuronBATvADM; } };
A distinctive feature of CNeuronBATvADM is that only the initialization method is overridden. This allows ADM to be added to the BAT computation pipeline during the configuration phase while retaining all other framework features. Thanks to this architectural simplicity, the new object serves as a flexible platform for experimentation.
It is worth noting how concise the initialization method is. In fact, its operation boils down to two key actions. First, the method of the same name in the parent class is called. This ensures that all inherited BAT structures are fully initialized.
bool CNeuronBATvADM::Init(uint numOutputs, uint myIndex, COpenCLMy *open_cl, uint dimension, uint embed_size, uint stack_size, uint variables, ENUM_OPTIMIZATION optimization_type, uint batch) { if(!CNeuronBAT::Init(numOutputs, myIndex, open_cl, dimension, embed_size, stack_size, variables, optimization_type, batch)) return false;
Next, a new CNeuronSpikeADM object — which represents the Adaptive Density Module we implemented — is added to the initialized data preparation block.
int index = cPrepare.Total(); CNeuronSpikeADM* amd = new CNeuronSpikeADM(); if(!amd || !amd.Init(0, index, OpenCL, embed_size, stack_size, variables, optimization, iBatch) || !cPrepare.Add(amd)) { DeleteObj(amd) return false; } //--- return true; }
It is included in the cPrepare block, forming a single sequence for processing the input stream. The concise code creates the object, initializes it with the required parameters, and immediately adds it to the pipeline, minimizing disruption to the existing architecture.
As a result, the initialization method creates a fully operational CNeuronBATvADM object, in which ADM is integrated as part of the data preparation process. This approach preserves all the capabilities of BAT while paving the way for experimental evaluation of the impact of the Adaptive Density Module on model performance, demonstrating the framework's practical flexibility and extensibility.
The changes to the model's architecture are also minimal — we are simply changing the object type. The complete code for all the objects and trainable models presented here is included in the attachment.
Testing
Trading policy training and its backtesting using historical data were carried out in several consecutive stages. The model was first trained offline using EURUSD exchange rate data on the H1 timeframe for the period from January 2024 to June 2025. This period served as a training ground. The model studied historical patterns, analyzed price dynamics and trading volumes, identified relationships between key features, and generated forecasts.
The next step — fine-tuning the model online in the MetaTrader 5 Strategy Tester — allowed the model to adapt to the real-time data stream. Here, it learned to handle the characteristics of a live market — remaining robust amid market noise, adjusting its actions when liquidity declined, and reacting instantly to sharp price spikes. This approach ensured a seamless integration of historical experience with current market signals, making trading decisions as timely and well-founded as possible.
The final test was conducted using data from July through October 2025, which was entirely new and had not been used previously in the training process. All of the model's parameters remained unchanged, which made it possible to objectively assess its ability to generalize and adapt to unfamiliar conditions.


During the testing period, the model showed steady growth in the account balance from USD 100 to USD 162, delivering an ROI of 62% with controlled drawdowns of up to 26.5%. Each trade added an average of about 1% to the account balance, which indicates a prudent approach to risk.
Trade statistics confirm stability: 55% of trades are profitable, with the best returns coming from downward price impulses; the average profit exceeds the average loss; and the Balance and Equity curves show smooth, step-like growth without sharp accelerations. Sharpe Ratio = 3.64 indicates high stability and low dispersion of returns.
Overall, the strategy has proven to be medium-term and statistically robust, with controlled risk and a sound equity structure. The results confirm that step-by-step training and the integration of adaptive modules enable the model to effectively analyze the market and make informed decisions in real time. However, the model needs to be tested more thoroughly before it is used in live trading.
Conclusion
As part of this work, one of the key components of the EEMFlow framework — the Adaptive Density Module — was implemented, combining a multi-density representation with adaptive feature weighting. Its integration into existing models, as demonstrated by BAT, has proven to be effective in practice. The module allows the system to account for different scales of market density and identify the most relevant features for the current situation.
Backtesting on historical data confirmed that the EEMFlow approach ensures the robustness, stability, and adaptability of trading decisions. The model demonstrates controlled growth in the account balance, a high Sharpe ratio, a positive expected return, and a structurally robust equity curve, reflecting the framework's ability to perform amid market noise and unpredictable price movements.
The main advantage of EEMFlow is its versatility and modularity. Individual components, such as ADM, can be easily integrated into various trading architectures, enhancing their adaptability and predictive accuracy. This opens up a wide range of opportunities for further research and strategy optimization, transforming the framework into an effective tool for building flexible and reliable autonomous trading systems.
Links
Software used in this article
| # | Name | Type | Description |
|---|---|---|---|
| 1 | Study.mq5 | Expert Advisor | Expert Advisor for offline model training |
| 2 | StudyOnline.mq5 | Expert Advisor | Expert Advisor for online model training |
| 3 | Test.mq5 | Expert Advisor | Expert Advisor for model testing |
| 4 | Trajectory.mqh | Class library | Structure describing the system state and model architectures |
| 5 | NeuroNet.mqh | Class library | Class library for building a neural network |
| 6 | NeuroNet.cl | Library | Code library for an OpenCL program |
Translated from Russian by MetaQuotes Ltd.
Original article: https://www.mql5.com/ru/articles/20646
Warning: All rights to these materials are reserved by MetaQuotes Ltd. Copying or reprinting of these materials in whole or in part is prohibited.
This article was written by a user of the site and reflects their personal views. MetaQuotes Ltd is not responsible for the accuracy of the information presented, nor for any consequences resulting from the use of the solutions, strategies or recommendations described.