Neural Networks in Trading: Mesh-Based Approximation of Event Streams as a Tool for Analyzing Price Patterns (Conclusion)
Introduction
The financial market is still commonly described as a time series: bars, time frames, fixed windows. This is an approach proven over decades. But it has one flaw, which becomes more and more noticeable over the years. The market does not run on clock time; it runs on events. At some points, more significant changes occur in a second than in an hour of a quiet Asian session, at others, time drags on and there is almost no information. Trying to force such dynamics into a uniform time grid inevitably leads either to a loss of detail or to an accumulation of noise. This fundamental problem motivates the EEMFlow framework.
The authors of EEMFlow propose abandoning the traditional view of data flow and viewing the market as a sequence of events, each of which brings about a change in the state of the system. It is not the price as such that is important, but the fact of movement itself, its direction, intensity, and local structure. This approach is well known to computer vision and robotics specialists, who have long worked with event cameras. But in the context of financial markets, it is only now truly coming into its own, as computing power allows for the processing of such flows in real time.
The key problem faced by any event-driven approach is the heterogeneity of data density. The market is uneven by nature. Bursts of activity are followed by periods of calm, and if all events are processed directly, the model will either choke in noise or become blind during quiet periods. EEMFlow solves this problem not by rough filtering or averaging, but by adaptation. The flow of events is first brought into a manageable form, where the density of information becomes a controlled parameter. This is a fundamental point. We do not throw away data or distort the market, but rather bring it to a form in which further analysis becomes meaningful and robust.
The framework's architecture is built around this idea. At the input is a raw stream of events formed from changes in the market state. Next comes the density adaptation stage, where the system learns to understand how much information actually needs to be stored in the current context. During periods of high activity, events are compressed into a more compact representation, preserving the structure of movement. In quiet moments, on the contrary, the system allows details to emerge without dissolving into aggressive averaging. This mechanism sets the rhythm for the entire architecture.
Once the flow of events has been brought to a manageable density, the EEMFlow architecture then proceeds to its core component — MeshFlow estimation. Here it is important to immediately establish the authors’ fundamental position. Unlike classical approaches to optical flow estimation, where the model refines local displacements step by step, moving from coarse to fine, EEMFlow is designed from the outset to capture global, large-scale motion. MeshFlow describes a coherent spatial deformation rather than minute local fluctuations. This is why the architecture is deliberately free from excessive depth. There is no aspiration here to squeeze out every pixel or every tick fluctuation. The task is different: to capture the structure of the movement as a whole, quickly and stably.
The authors base their approach on a three-level pyramidal feature encoder. It extracts representations from two adjacent event intervals corresponding to transitions from the previous state to the current one and from the current one to the next one. This symmetry looks almost old-fashioned against the backdrop of modern, redundant architecture, but this is precisely where the engineering maturity of the approach is evident. The model does not overfit to specific forms of movement and retains its generalization ability.
Next, a key transition occurs from features to movement. All extracted representations are first brought to a common resolution using average pooling. The authors deliberately choose an extremely compact spatial resolution, which allows the movement to be viewed at a coarse, structural scale.
The correlation of features is constructed as an inner product between feature vectors in adjacent states, taking into account possible displacements. The model effectively measures how well the current state is explained by the previous state under different motion hypotheses. Classical approaches use a dense square search space for this purpose, and increasing the radius of such a space quickly leads to an explosive increase in computational complexity. EEMFlow goes the other way. Instead of brute force, a sparse but geometrically intelligent sampling scheme is used — Dilated Feature Correlation.
The idea behind DFC is simple and elegant. Near the center, correlations are computed at densely sampled offsets to capture small displacements accurately. Sampling becomes sparser farther from the center. This allows the model to analyze large displacements and global deformations without incurring an avalanche-like increase in computational effort. For financial data, this is especially valuable. The market moves smoothly most of the time, but occasionally makes sharp jumps. DFC allows you to work equally confidently in both modes, without rebuilding the architecture or switching heuristics. The obtained correlation coefficients, formed at different levels of the pyramid, are combined with feature representations.
The next stage is clarification and restoration of details. Any compact approximation inevitably loses small elements, and it is these that often carry key information about a regime change or the origin of a pulse. In EEMFlow, this problem is addressed through confidence-guided detail recovery. Rather than mechanically filling in missing elements, the system assesses confidence across different regions of the representation Where the model is confident in the structure of the movement, the details are enhanced. Where confidence is low, the system behaves cautiously, not creating false signals. For financial data this is critical. Incorrect detailing is more dangerous than no detailing at all. One extra confident impulse may cost more than the missed opportunity.

It is important to emphasize that the entire EEMFlow architecture was originally designed with efficiency in mind. This is not an academic monster that requires a server rack. On the contrary, each module is minimalist in nature. They do exactly what they are supposed to do and no more.
Another important advantage of EEMFlow is its modularity. The architecture is not closed in on itself. Each processing stage can be analyzed, modified and optimized separately. This is a rare quality for modern neural network frameworks, which often appear as a black box. Here we have a transparent chain of transformations. From raw event to structured representation of movement. For practical trading, this means the ability to control the system's behavior and adapt it to a specific market, instrument, or trading style.
In previous works we assembled and tested the ADM module and analyzed the logic of event density adaptation. We showed how the computing processes are built inside the CDC module. Step by step, we have built a solid foundation on which we can confidently build, without having to constantly return to the basic assumptions.
Today, continuing the practical adaptation of the EEMFlow framework to the trading environment, we move on to the next logical step - building the MeshFlow estimation algorithms. It is here that disparate events begin to coalesce into a coherent picture of market movement, and the framework's architecture is revealed in its full, practical form.
Dilated Feature Correlation
We start working with the MeshFlow estimation algorithms by building the Dilated Feature Correlation module. This is the very node where abstract feature representations are first transformed into measurable information about movement. The framework's authors start from a simple but important idea. Features in neighboring states should be compared not only at one point, but also taking into account possible shifts in some neighborhood. In this case, the density of such displacements must be non-uniform. Near the analyzed element it is maximum, and as it moves away from the center it gradually becomes rarefied. This approach allows for the simultaneous accurate recording of small movements and large displacements without incurring excessive computational overhead.
From a practical point of view, this means that a large number of correlations need to be calculated in parallel. Therefore, we immediately transfer the entire process to the OpenCL program. In doing so, we deliberately avoid hard-coding the logic for selecting neighboring states within the kernel itself. Instead, a simpler and more universal path has been chosen that fits well with the EEMFlow philosophy.
We use a static vector of relative displacements. It is generated once on the main program side, is fully controlled by the top-level logic and is then transferred to the OpenCL context memory. The kernel does not know how exactly these offsets were chosen and according to what rule they were formed. It just goes through them sequentially and calculates the correlation. This approach minimizes kernel complexity, simplifies debugging, and allows for easy reconfiguration of the search space without changing the OpenCL code. Essentially, we move the strategy into the control code, and leave the calculations as clean as possible.
The DilatedCorrelation kernel logic seems surprisingly simple and at the same time very well-thought-out. It does exactly one thing: it measures how well one feature state matches another given the offset. And it does this immediately for all possible displacements, in parallel and without unnecessary assumptions.
__kernel void DilatedCorrelation(__global const float* feature, __global const int* shifts, __global float* correlations, const int dimension ) { const size_t main = get_global_id(0); const size_t loc = get_local_id(1); const size_t sh = get_global_id(2); const size_t units = get_global_size(0); const size_t total_loc = get_local_size(1); const size_t total_corr = get_global_size(2);
The kernel algorithm is built around a three-dimensional problem space. And each work-item in this space is uniquely defined by a triple of indices.
The first dimension of global space corresponds to the basic element. This is the reference position relative to which the movement is evaluated. In terms of MeshFlow, a specific mesh cell or feature array element for which we want to understand how it relates to neighboring states. Each value of this index defines its own starting point, and all further calculations are tied to it.
The second dimension, local, is used to parallelize calculations by feature dimension. Each thread in the workgroup processes only a part of the components of the feature vector. This means that the same base element and the same offset are processed simultaneously by multiple threads, each of which contributes to the final correlation. This technique allows us to effectively implement a scalar product in parallel form without going beyond the scope of a simple and stable scheme.
The third dimension of global space defines the displacement hypothesis. Here, each thread selects one specific relative offset from a pre-prepared set. There is no logic for forming the search area within the kernel. The work-item simply takes its offset, restores the sign and thus determines which neighboring element the base element should be compared with. Thus, for each basic element, all admissible hypotheses of motion are considered in parallel, from the nearest to the more distant, but already sparse ones.
__local float temp[LOCAL_ARRAY_SIZE]; //--- const int slave = shifts[sh >> 1] * ((sh & 1) ? -1 : 1); if(slave < 0 || slave >= units) { if(loc == 0) correlations[RCtoFlat(main, sh, units, total_corr, 0)] = 0; return; }
Once the thread has determined the base element and the offset state, it checks that the index is correct. If the bias is outside the acceptable range, the corresponding correlation is considered zero. This decision is of fundamental importance. The algorithm does not attempt to replace data or reflect indexes, but honestly records the absence of an acceptable match. For further EEMFlow steps, this is much safer than artificial boundary padding.
If the pair of elements is valid, the thread proceeds to the main part of the work. It sequentially iterates over its part of the feature space, multiplies the components of the base and shifted features, and accumulates the partial sum.
float result = 0.0f; for(int d = loc; d < dimension; d += total_loc) { float value_main = IsNaNOrInf(feature[RCtoFlat(main, d, units, dimension, 0)], 0); float value_slave = IsNaNOrInf(feature[RCtoFlat(slave, d, units, dimension, 0)], 0); result += IsNaNOrInf(value_main * value_slave, 0); }
All operations are performed with protection against incorrect values. This type of control may not look impressive, but it is precisely this that makes the system's behavior stable when working with real, imperfect data.
When all threads in a local group have completed computing their partial sums, local reduction occurs. The partial results are combined into one final correlation value for a particular base element — shift pair. This value already represents a holistic measure of the similarity of two states, and not a set of fragments.
result = LocalSum(result, 1, temp); //--- if(loc == 0) correlations[RCtoFlat(main, sh, units, total_corr, 0)] = result; }
The result is written once and in a strictly deterministic manner. Only one thread in the group stores the resulting correlation in the output array. The other threads have already completed their work at this point. Thanks to this, the scheme does not require complex synchronization and does not create write conflicts.
If you look at the algorithm as a whole, it becomes clear that it perfectly matches the Dilated Feature Correlation philosophy. We do not scan a dense square area blindly. We only test for biases that are pre-determined to be significant. Near the center they are densely located, and farther away they are sparsely located. The kernel remains universal. It works equally well with both narrow and broad search scopes. The only difference is in the content of the displacement vector.
As is easy to see, the correlation calculation algorithm itself is extremely honest and even somewhat ascetic. It has no weights, coefficients, or hidden parameters that could be adjusted during the learning process. It simply does its job - measures the similarity of features at given offsets. However, this is where the calm ends. We use this mechanism not in isolation, but as part of a learning model. This means that we must integrate it into the overall optimization loop and ensure correct propagation of error gradients.
At first glance, the correlation error may indeed sound strange. Correlation is not a prediction, not a probability, and not the output of a classifier. This is just an intermediate measure of similarity. But in the context of the entire EEMFlow architecture, it plays a key role. It is on the basis of these correlations that values are formed, from which MeshFlow is then generated. This means that any error in the model output inevitably passes through the correlation coefficients. If we want the model to learn, we must be able to draw the gradient back from the MeshFlow error to correlations, and then to the features of states themselves.
The task here is formulated quite clearly. For pairs of states that actually correspond to each other and form a valid movement, the correlation should strengthen. For all other pairs, the correlation should be weakened. In other words, we do not train the correlation operator itself. But we train the feature space so that the correlation in it behaves correctly. This is a fundamental point. The algorithm remains fixed, but the environment in which it operates is gradually deformed towards a more expressive and separable representation.
From a mathematical point of view, it all comes down to propagating the gradient through the dot product operation. Each correlation value is the sum of pairwise products of the components of the feature vectors. Therefore, the gradient of one feature directly depends on the value of another. If the correlation is too high where the motion is incorrect, the gradient will tend to reduce the consistency of these features. If the model underestimates the similarity, the gradient, on the contrary, will push the features towards each other. There is no magic here. There is a strict, symmetrical connection between the states.
It is also important that the gradients are distributed not across one pair of elements, but across the entire set of displacements at once. The same feature is involved in calculating correlations for different motion hypotheses. This means that the resulting gradient is the result of the combined pressure from many correlations. This is how a stable representation of movement is formed. Not through a single lucky match, but through consistency across different scales and directions.
A practical implementation of the error gradient distribution algorithm is presented in the DilatedCorrelationGrad kernel. It is useful to think of it as a logical continuation of direct correlation, rather than as something separate and complicated. Essentially, a mirror image is happening here. If in the forward pass we collected correlations from features, now we distribute the accumulated error back across the same features, strictly following the same displacement geometry.
__kernel void DilatedCorrelationGrad(__global const float* feature, __global float* feature_gr, __global const int* shifts, __global const float* corr_gr, const int total_corr ) { const size_t id = get_global_id(0); const size_t loc = get_local_id(1); const size_t d = get_global_id(2); const size_t units = get_global_size(0); const size_t total_loc = get_local_size(1); const size_t dimension = get_global_size(2);
The algorithm again relies on a three-dimensional problem space. Each flow is simultaneously fixed by the base element, by the component of the feature vector, and by the local position within the work group. Each work-item computes a partial contribution to the gradient of one feature component of one element.
The work-item first obtains the element index id and the feature-component index d. This identifies the target element and feature dimension. We know for which state and which feature dimension the gradient is currently being calculated. The thread does not attempt to analyze the individual offset further. On the contrary, it goes through consistently across the entire set of correlations carefully collecting the contribution from each of them.
__local float temp[LOCAL_ARRAY_SIZE]; //--- float result = 0.0f; for(int sh = loc; sh < total_corr; sh += total_loc) { const int offset = shifts[sh >> 1]; const int sign = (sh & 1) ? -1 : +1; // id — main int slave = id + sign * offset; if(slave >= 0 && slave < units) { float g = corr_gr[RCtoFlat(id, sh, units, total_corr, 0)]; result += IsNaNOrInf(g * feature[RCtoFlat(slave, d, units, dimension, 0)], 0.0f); }
Each correlation corresponds to some offset encoded in the shifts array. As in the forward pass, the sign of the offset is restored on the fly. This allows for a compact representation of the search space and preserves symmetry. The flow then considers two fundamentally different roles that the current element can play.
In the first case, the current element acts as a base element. Then the shifted element is calculated as slave. If such an index is valid, the work-item takes the gradient of the corresponding correlation and multiplies it by the feature value of the shifted element. This is a direct consequence of the derivative of the scalar product: the contribution to the gradient of one vector is proportional to the components of the other.
In the second case, the current element plays the role of the offset element, and the base element is on the other side of the offset. Then the index of the base element is calculated as main. If it is also admissible, the contribution to the gradient is calculated in a similar way.
// id — slave int main = id - sign * offset; if(main >= 0 && main < units) { float g = corr_gr[RCtoFlat(main, sh, units, total_corr, 0)]; result += IsNaNOrInf(g * feature[RCtoFlat(main, d, units, dimension, 0)], 0.0f); } }
Thus, each feature receives a contribution both as a supporting and as a displaced one, which is completely consistent with the symmetry of the correlation operation.
All such contributions are accumulated in a local result variable. It is important to understand the scale of what is happening. The same feature is involved in dozens, and sometimes hundreds, of correlations — with different biases and in different roles. The resulting gradient is the total pressure from the entire correlation structure. This is precisely why learning is robust: feature updating is determined not by a single coincidence, but by collective coordination of movement.
After a thread has iterated over all the offsets, its partial result is not yet final. Each thread in a local group processes only a portion of the correlations, so a local reduction is performed where partial sums are combined into a single total. This again happens in local memory, quickly and without accessing global resources.
result = LocalSum(result, 1, temp); if(loc == 0) feature_gr[RCtoFlat(id, d, units, dimension, 0)] = result; }
The final step is extremely careful. Only one thread of the workgroup writes the result to the feature gradient array. This eliminates write conflicts and maintains deterministic computations. For each feature component of each element, we obtain exactly one gradient value that is fully consistent with all correlations in which this element participated.
Looking at the algorithm as a whole, it becomes clear that it perfectly closes the learning loop. Direct correlation measures the consistency of features under different offsets. The backward pass, in turn, adjusts the features themselves so that the desired correlations are strengthened and the unnecessary ones are weakened. In this case, no trainable parameters are added. We do not complicate the model, but only force its features to gradually take a form in which the correlation operator begins to work in the right direction.
This is the strength of the approach. Correlation remains a simple, interpretable, and computationally efficient operator. And learning occurs where it is truly justified - in the feature space. That is exactly how Dilated Feature Correlation is organically integrated into the EEMFlow learning architecture without breaking its philosophy and maintaining a strict connection between the geometry of movement and the optimization process.
Top-level Object
The next logical step is to move up a level and construct a top-level object — CNeuronSpikeEEMFLow. It is here that the disparate algorithmic elements we have been working with consistently before come together to form a coherent, meaningful architecture. While the previous stages resembled fine-tuning individual components, we now have a fully assembled mechanism ready to work as a fully functional component of the learning model.
The CNeuronSpikeEEMFLow class inherits from CNeuronSpikeCDC, and this is a fundamentally important point. We do not abandon the previously established logic for processing event data and the temporal structure. On the contrary, we rely on it as a solid foundation. The new class neatly extends the core functionality by adding a level of spatio-temporal analysis through MeshFlow mechanisms and extended feature correlation.
class CNeuronSpikeEEMFLow : public CNeuronSpikeCDC { protected: uint iMaxDisplacement; int ibShifts; CLayer cPrepare; CLayer cEncoder[3]; CNeuronBaseOCL cCorrelations[3]; CNeuronBaseOCL cConcat[3]; CLayer cDecoder[4]; //--- virtual bool DilatedCorrelation(CNeuronBaseOCL* feature, CNeuronBaseOCL* correlations, uint dimension, uint units); virtual bool DilatedCorrelationGrad(CNeuronBaseOCL* feature, CNeuronBaseOCL* correlations, uint dimension, uint units); //--- virtual bool feedForward(CNeuronBaseOCL *NeuronOCL) override; virtual bool updateInputWeights(CNeuronBaseOCL *NeuronOCL) override; virtual bool calcInputGradients(CNeuronBaseOCL *NeuronOCL) override; public: CNeuronSpikeEEMFLow(void) : ibShifts(INVALID_HANDLE) {}; ~CNeuronSpikeEEMFLow(void) {}; //--- virtual bool Init(uint numOutputs, uint myIndex, COpenCLMy *open_cl, uint dimension, uint embed_size, uint stack_size, uint variables, uint max_displacement, ENUM_OPTIMIZATION optimization_type, uint batch); //--- virtual int Type(void) override const { return defNeuronSpikeEEMFLow; } //--- methods for working with files virtual bool Save(int const file_handle) override; virtual bool Load(int const file_handle) override; //--- virtual bool WeightsUpdate(CNeuronBaseOCL *source, float tau) override; virtual bool Clear(void) override; //--- virtual void SetActivationFunction(ENUM_ACTIVATION value) override { }; virtual void SetOpenCL(COpenCLMy *obj) override; virtual void TrainMode(bool flag) override; virtual CBufferFloat *getWeights(void) override; };
The internal structure of a class starts with the control parameters. The iMaxDisplacement variable sets the maximum radius of displacements taken into account when constructing correlations. In fact, this is the boundary of the search area within which the model analyzes possible movement. The higher this value, the wider the algorithm's range of vision, but the higher the computational load. There are no random decisions here - the range is set explicitly and completely controls the trade-off between the expressiveness of the model and its efficiency.
The ibShifts field stores a buffer descriptor with a static set of relative offsets. This is the key element of the whole Dilated Feature Correlation structure. The offset vector is generated once on the main program side and then used by all OpenCL kernels. This approach avoids complex neighbor selection logic within kernels and makes computations predictable, stable, and highly scalable.
Next comes a set of dynamic arrays that form the main computational chain. The cPrepare block performs preliminary preparation of the data to be analyzed. Its task is to bring event features into a consistent form, align dimensions and form a compact representation suitable for further processing. This is a classic, time-tested step, without which it is difficult to talk about the stable operation of the entire model.
The cEncoder[3] array implements a multi-level encoder. Each level operates at its own scale and extracts features of varying degrees of generalization. Together they form a hierarchical representation of the input event stream. This approach has proven itself in motion analysis tasks: large structures are captured at the upper levels, and more local dependencies at the lower levels.
The cCorrelations[3] objects occupy a central place in the architecture. This is where the calculation of extended correlations for each encoder level is performed. The results of the correlation analysis are sent to the cConcat[3] blocks.
The final element of the computing path is the cDecoder[4] array. The decoder gradually transforms the internal compact representation back into the target value space. This stepwise return avoids abrupt and unstable transformations, maintaining the stability of training and the predictability of output estimates.
The initialization method is essentially the moment when the EEMFlow architecture turns into a working design from an abstract structure. Here, the entire computational path is carefully assembled step by step: from the preparation of event features to multi-level MeshFlow estimation. And it is important to emphasize that this is not just a set of calls to the same methods of internal components, but a well-thought-out sequence in which every detail is in its place.
bool CNeuronSpikeEEMFLow::Init(uint numOutputs, uint myIndex, COpenCLMy *open_cl, uint dimension, uint embed_size, uint stack_size, uint variables, uint max_displacement, ENUM_OPTIMIZATION optimization_type, uint batch) { uint inside_dimensions[] = {32, 32, 32, 16, 8}; if(!CNeuronSpikeCDC::Init(numOutputs, myIndex, open_cl, embed_size, inside_dimensions, dimension, stack_size, variables, optimization_type, batch)) return false;
The method's operation begins with the initialization of the base part through the method of the same name of the parent class. This way we can immediately integrate EEMFlow into the event pipeline already familiar to the reader. Pre-defined internal dimensions are used, which determine the depth and capacity of the intermediate representations. This solution seems conservative, but it is precisely these fixed proportions that ensure the stability and reproducibility of experiments - a quality that is extremely valuable when working with market data.
Next, the cPrepare preparatory block is formed. Its task is to bring the analyzed flow into a form convenient for further analysis of the movement. First, batch normalization is applied, which equalizes the feature statistics. This is a sort of a morning tool fine-tuning before starting serious work.
CNeuronCreateFlow* stack = NULL; CNeuronBatchNormOCL* norm = NULL; CNeuronSpikeADM* adm = NULL; CNeuronMultiWindowsConvWPadOCL* padconv = NULL; CNeuronSpikeConvBlock* conv = NULL; CNeuronSpikeCDC* cdc = NULL; //--- uint index = 0; cPrepare.Clear(); cPrepare.SetOpenCL(OpenCL); norm = new CNeuronBatchNormOCL(); if(!norm || !norm.Init(0, index, OpenCL, dimension * variables, iBatch, optimization) || !cPrepare.Add(norm)) { DeleteObj(norm) return false; } index++;
A stream of states is then created using CNeuronCreateFlow, which organizes the temporal structure of the data.
stack = new CNeuronCreateFlow(); if(!stack || !stack.Init(0, index, OpenCL, stack_size, dimension, embed_size, variables, optimization, iBatch) || !cPrepare.Add(stack)) { DeleteObj(stack) return false; } index++;The preparatory stage is completed by the ADM module, which is already familiar from the previous articles. It is responsible for the adaptive modulation of events and emphasizes the relevant features.
adm = new CNeuronSpikeADM(); if(!adm || !adm.Init(0, index, OpenCL, embed_size, stack_size, variables, optimization, iBatch) || !cPrepare.Add(adm)) { DeleteObj(adm) return false; } index++;
The formation of the displacement array deserves special attention. Here the idea of Dilated Feature Correlation is put into practice. Instead of generating offsets on the fly inside OpenCL kernel, we form a compact set of relative steps in advance. Dense displacements remain near zero and become more sparse as they move away.
int shifts[]; if(ArrayResize(shifts, max_displacement) <= 0) return false; uint count = 0; for(uint i = 0; i < max_displacement; i++) { if(i > 2 && bool(i & 1)) continue; shifts[count] = (int)(i + 1); count++; } if(ArrayResize(shifts, count) < (int)count) return false; ibShifts = OpenCL.AddBufferFromArray(shifts, 0, count, CL_MEM_READ_ONLY); if(ibShifts == INVALID_HANDLE) return false; iMaxDisplacement = max_displacement;
This vector is loaded into OpenCL memory once and then reused throughout all levels of the pyramid. This solution saves computing resources and makes the algorithm's behavior completely deterministic.
After this, the main part begins - the construction of a three-level hierarchy Encoder → Correlation → Decoder. At each level, Encoder is created first. It consists of several convolutional blocks with padding, normalization and soft nonlinearity. These layers gradually compact the representation, reduce the number of elements in the sequence and simultaneously increase the expressiveness of features. Here the model learns to see movement not in details, but in larger, more stable structures.
uint window_in = embed_size; uint window_out = 16; uint units_in = stack_size; uint units_out = (units_in + 1) / 2; uint windows[] = { 3 * window_in }; //--- for(int i = 0; i < 3; i++) { cEncoder[i].Clear(); cDecoder[i].Clear(); cEncoder[i].SetOpenCL(OpenCL); cDecoder[i].SetOpenCL(OpenCL); //--- Encoder padconv = new CNeuronMultiWindowsConvWPadOCL(); if(!padconv || !padconv.Init(0, index, OpenCL, windows, 2 * window_in, window_out, units_out, variables, optimization, iBatch) || !cEncoder[i].Add(padconv)) { DeleteObj(padconv) return false; } padconv.SetActivationFunction(SoftPlus); index++; norm = new CNeuronBatchNormOCL(); if(!norm || !norm.Init(0, index, OpenCL, padconv.Neurons(), iBatch, optimization) || !cEncoder[i].Add(norm)) { DeleteObj(norm) return false; } norm.SetActivationFunction(None); index++; windows[0] = 3 * window_out; for(int j = 0; j < 2; j++) { padconv = new CNeuronMultiWindowsConvWPadOCL(); if(!padconv || !padconv.Init(0, index, OpenCL, windows, window_out, window_out, units_out, variables, optimization, iBatch) || !cEncoder[i].Add(padconv)) { DeleteObj(padconv) return false; } padconv.SetActivationFunction(SoftPlus); index++; norm = new CNeuronBatchNormOCL(); if(!norm || !norm.Init(0, index, OpenCL, padconv.Neurons(), iBatch, optimization) || !cEncoder[i].Add(norm)) { DeleteObj(norm) return false; } norm.SetActivationFunction(None); index++; } conv = new CNeuronSpikeConvBlock(); if(!conv || !conv.Init(0, index, OpenCL, window_out, window_out, window_out, units_out, variables, optimization, iBatch) || !cEncoder[i].Add(conv)) { DeleteObj(conv) return false; } index++;
The next step for each level is to initialize the correlation block. This is where extended correlations between states are calculated given the specified offsets. The output size directly depends on the number of offsets and the size of the sequence being analyzed. This highlights a key MeshFlow feature: we do not try to reconstruct motion at the level of individual pixels or events, but work with a coarser, but more informative mesh.
if(!cCorrelations[i].Init(0, index, OpenCL, count * units_out * variables, optimization, iBatch)) return false; cCorrelations[i].SetActivationFunction(None);
The correlation results are combined with the original features in the cConcat block. This is the moment when local information and global displacements meet in a single representation. The model is given the ability to compare what we have at the moment and where it is shifting without losing context.
index++; if(!cConcat[i].Init(0, index, OpenCL, (2 * window_out + count)*units_out * variables, optimization, iBatch)) return false; cConcat[i].SetActivationFunction(None); index++;
The decoder mirrors the structure of the encoder, but works in the opposite direction. It gradually restores dimensions, increases temporal resolution, and returns features to a space compatible with subsequent levels or the final output. The same proven techniques are used: convolutional blocks, normalization, soft activations. No sudden jumps. Everything happens smoothly and predictably.
//--- Decoder padconv = new CNeuronMultiWindowsConvWPadOCL(); if(!padconv || !padconv.Init(0, index, OpenCL, windows, window_out, window_out, units_out, variables, optimization, iBatch) || !cDecoder[i].Add(padconv)) { DeleteObj(padconv) return false; } padconv.SetActivationFunction(SoftPlus); index++; norm = new CNeuronBatchNormOCL(); if(!norm || !norm.Init(0, index, OpenCL, padconv.Neurons(), iBatch, optimization) || !cDecoder[i].Add(norm)) { DeleteObj(norm) return false; } norm.SetActivationFunction(None); index++; padconv = new CNeuronMultiWindowsConvWPadOCL(); if(!padconv || !padconv.Init(0, index, OpenCL, windows, window_out, 2 * window_in, units_out, variables, optimization, iBatch) || !cDecoder[i].Add(padconv)) { DeleteObj(padconv) return false; } padconv.SetActivationFunction(SoftPlus); index++; norm = new CNeuronBatchNormOCL(); if(!norm || !norm.Init(0, index, OpenCL, padconv.Neurons(), iBatch, optimization) || !cDecoder[i].Add(norm)) { DeleteObj(norm) return false; } norm.SetActivationFunction(None); index++; windows[0] = 3 * window_in; for(int j = 0; j < 2; j++) { padconv = new CNeuronMultiWindowsConvWPadOCL(); if(!padconv || !padconv.Init(0, index, OpenCL, windows, window_in, window_in, units_in, variables, optimization, iBatch) || !cDecoder[i].Add(padconv)) { DeleteObj(padconv) return false; } padconv.SetActivationFunction(SoftPlus); index++; norm = new CNeuronBatchNormOCL(); if(!norm || !norm.Init(0, index, OpenCL, padconv.Neurons(), iBatch, optimization) || !cDecoder[i].Add(norm)) { DeleteObj(norm) return false; } norm.SetActivationFunction(None); index++; } conv = new CNeuronSpikeConvBlock(); if(!conv || !conv.Init(0, index, OpenCL, window_in, window_in, window_in, units_in, variables, optimization, iBatch) || !cDecoder[i].Add(conv)) { DeleteObj(conv) return false; } index++;
Starting from the second level, an additional CDC block is incorporated into the decoder. This allows us to re-take into account the event dynamics after the correlation analysis, strengthening the temporal consistency of the features. This solution seems particularly appropriate in the context of trading data, where not only the magnitude of the move is important, but also its time structure.
if(i > 0) { cdc = new CNeuronSpikeCDC(); if(!cdc || !cdc.Init(0, index, OpenCL, window_in, inside_dimensions, window_in, units_in, variables, optimization, iBatch) || !cDecoder[i].Add(cdc)) { DeleteObj(cdc) return false; } } index++; //--- window_in = window_out; window_out = 2 * window_in; units_in = units_out; units_out = (units_in + 1) / 2; windows[0] = 3 * window_in; }
After completing three pyramidal levels, cDecoder[3] is formed. This block creates an initial top-level stream initialized to zero values. The minimum CNeuronBaseOCL is used without activation. This sets a neutral starting point from which the lower levels begin to refine MeshFlow step by step.
cDecoder[3].Clear(); cDecoder[3].SetOpenCL(OpenCL); CNeuronBaseOCL* neuron = new CNeuronBaseOCL(); if(!neuron || !neuron.Init(0, index, OpenCL, window_in * units_in * variables, optimization, iBatch) || !cDecoder[3].Add(neuron)) { DeleteObj(neuron) return false; } neuron.SetActivationFunction(None); neuron.Clear(); //--- return true; }
As a result, the initialization method acts as both an architect and a foreman. It does not merely create objects, but builds a logically coherent, balanced system. Every solution, from sparse displacements to multi-level decomposition, aims to preserve maximum motion information at a reasonable computational cost. It is in this initialization that the EEMFlow philosophy is clearly felt: minimum redundancy, maximum useful signal and strict calculation discipline.
The forward pass algorithm implemented in the feedForward method demonstrates the work of the entire EEMFlow architecture in a coherent and strictly ordered form. At this stage, previously initialized modules begin to interact with each other, forming a single computational MeshFlow estimation flow.
bool CNeuronSpikeEEMFLow::feedForward(CNeuronBaseOCL *NeuronOCL) { CNeuronBaseOCL* prev = NeuronOCL; CNeuronBaseOCL* curr = NULL; CNeuronSpikeConvBlock* conv = NULL; //--- for(int l = 0; l < cPrepare.Total(); l++) { curr = cPrepare[l]; if(!curr || !curr.FeedForward(prev)) return false; prev = curr; }
The forward pass starts with the cPrepare preparation pipeline. The analyzed state is sequentially transmitted through all layers of preparation. Each layer takes the output of the previous one, updating the representation of the original data. Here, normalization, formation of a temporal structure and adaptive modulation of features are performed. By the end of this stage, the flow has already been brought to a stable and consistent form, suitable for motion analysis.
Then control passes to Encoders. Processing is organized according to the levels of the pyramid. At each level, the input representation passes through all layers of the corresponding Encoder.
for(uint i = 0; i < cEncoder.Size(); i++) { for(int l = 0; l < cEncoder[i].Total(); l++) { curr = cEncoder[i][l]; if(!curr || !curr.FeedForward(prev)) return false; prev = curr; } if(prev.Type() != defNeuronSpikeConvBlock) return false; conv = prev; if(!DilatedCorrelation(prev, cCorrelations[i].AsObject(), conv.GetFilters(), conv.GetUnits()*conv.GetVariables())) return false; }
In the process, the temporal resolution decreases and the features become more generalized. Checking the output layer type ensures that the output of the encoder is CNeuronSpikeConvBlock, since it forms the features in the format necessary for correlation analysis.
After completing each Encoder operation, the extended correlation calculation is performed. Calling DilatedCorrelation generates a correlation representation of the current level using encoder features, a given set of offsets, and dimensionality parameters. The resulting correlations are stored separately and do not change the main data stream. Thus, at this stage, an additional source of information about possible shifts between states is formed.
After processing all Encoder levels, decoding begins. The passage is organized in reverse order - from the upper level of the pyramid to the lower one. At each level, three data streams are first combined: the features of the corresponding Encoder, the output of the higher-level decoder and the correlation representation of the current level. Concatenation is performed with explicit calculation of dimensions, which eliminates ambiguities and hidden transformations.
CNeuronMultiWindowsConvWPadOCL* padconv = NULL; for(int i = int(cDecoder.Size()) - 2; i >= 0; i--) { if(!cDecoder[i][0] || cDecoder[i][0].Type() != defNeuronMultiWindowsConvWPadOCL) return false; if(!cEncoder[i][-1] || !cDecoder[i + 1][-1]) return false; //--- padconv = cDecoder[i][0]; uint units = padconv.GetUnits() * padconv.GetVariables(); uint window1 = cEncoder[i][-1].Neurons() / units; uint window2 = cDecoder[i][-1].Neurons() / units; uint window3 = cCorrelations[i].Neurons() / units; if(!Concat(cEncoder[i][-1].getOutput(), cDecoder[i + 1][-1].getOutput(), cCorrelations[i].getOutput(), cConcat[i].getOutput(), window1, window2, window3, units)) return false; prev = cConcat[i].AsObject();
The combined stream is passed to the decoder of the current level. All its layers are processed sequentially.
for(int l = 0; l < cDecoder[i].Total(); l++) { curr = cDecoder[i][l]; if(!curr) return false; if(curr.Type() == defNeuronSpikeCDC) if(!SumAndNormilize(cEncoder[i - 1][-1].getOutput(), prev.getOutput(), prev.getOutput(), ((CNeuronSpikeCDC*)curr).GetWindow(), false, 0, 0, 0, 1)) return false; if(!curr.FeedForward(prev)) return false; prev = curr; } }
If CDC block occurs in the chain, an additional summation operation is performed with the output of the previous Encoder. This step combines the current representation with the predicted dynamics, producing a consistent predicted flow for subsequent processing.
This process is repeated for each level of the pyramid. The MeshFlow is formed gradually, through successive refinements, rather than through a one-time regression. Each level adds its own contribution, based on features, correlations, and the already accumulated representation of the movement.
At the final stage, the resulting flow is summed with the output of the preparatory cPrepare block. This ensures that the final assessment is consistent with the original event representation.
if(!SumAndNormilize(cPrepare[-1].getOutput(), prev.getOutput(), prev.getOutput(), GetWindow(), false, 0, 0, 0, 1)) return false; if(!CNeuronSpikeCDC::feedForward(prev)) return false; //--- return true; }
After this, execution is transferred to the method of the same name of the parent class, which completes the forward pass within the general event framework.
Thus, the EEMFlow forward pass is a strictly deterministic sequence of operations in which each level performs a clearly defined function. The architecture sequentially moves from coarse motion estimates to more detailed ones, maintaining the stability of calculations and the logical integrity of the entire process.
As a result, we have before us not just another class, but a key node of the entire EEMFlow implementation. This is where event data, spatial correlations, and learning mechanisms converge. The architecture looks strict and even a little conservative. But, as in financial markets, it is precisely these decisions that often prove the most robust. Each element has its place, performs a clearly defined role, and together with the others forms a solid foundation for the further development and practical application of the framework.
The complete code of the class and all its methods is provided in the attachment.
Test
The final stage of the work involves training and testing the model on real historical data. The architecture of the trained models almost completely repeats the approaches described in our previous publications. The main innovation is the introduction of the EEMFlow concepts to the Environment State Encoder.
Thus, the model retains the proven structure of feature processing and event dynamics, while gaining the ability to accurately account for global and local biases through extended correlations. All key elements, including preparatory blocks, pyramidal encoders and decoders, and correlation modules, are integrated into a single system, ensuring consistency and stability of the forecast flow.
A full and detailed description of the architectural solution for the trained models is provided in the attachment, allowing for the replication and scaling of the approach for further experimentation and performance analysis.
The work began with offline training on historical data for EURUSD M1 from January 2024 to June 2025. At this stage, the model developed the ability to identify recurring market patterns, analyze price dynamics and trading volumes, and identify relationships between key features for accurate forecasting. As a result, an internal understanding of the market was formed that combined rigorous mathematical processing of data with the identification of patterns in time series.
The next step was online fine-tuning in the MetaTrader 5 strategy tester. The model was adapted to a real-world data stream, taking into account market noise, liquidity fluctuations, and sharp price spikes. This approach allowed us to integrate accumulated historical experience with current market dynamics, ensuring timely and informed trading decisions.
The final check was carried out on data from July to October 2025, completely new and not previously used in the training process. All model parameters were kept unchanged, which allowed us to objectively evaluate its ability to generalize and adapt to unfamiliar market conditions.

The results of trading system testing demonstrate the high efficiency and stability of the proposed approach. The test showed a positive net profit of 56.1 % with a maximum balance and equity drawdowns of 11% and 15.7%, respectively.
Analysis of key ratios confirms the quality of the trading logic: Profit Factor is 1.61, Recovery Factor — 2.42, and the average profit per trade is 0.79, which indicates a positive mathematical expectation of the strategy.
Trading activity was distributed evenly. Of the 71 trades, 62% were profitable, short trades had a higher win rate (69%) than long trades (54%). The ratio of the average winning trade to the average losing trade is close to 1:1, and the advantage is achieved through a high percentage of profitable trades. Winning and losing streaks remained short and manageable, providing a comfortable risk profile.
The Balance/Equity curve demonstrates a smooth, monotonic increase in capital without sharp collapses, and the deposit load did not exceed 25 %, which confirms the robustness and adaptability of the strategy. Overall, the tested trading system demonstrated statistical stability, positive mathematical expectation, and effective risk control, making it suitable for use in algorithmic trading with the possibility of scaling and further optimization.
Conclusion
In this work, we adapted the EEMFlow framework using MQL5 was implemented, which made it possible to integrate the concepts of extended feature correlation and pyramidal encoding into the architecture of trainable trading models. Constructed MeshFlow estimation algorithms provide a consistent and accurate representation of market dynamics, accurately accounting for both local and global shifts in price flows.
The practical implementation included both offline training on historical data and online tuning under real-time price feed conditions, which allowed the model to adapt to market noise, changes in liquidity, and sharp price spikes. Final tests on previously unused data confirmed the strategy's high stability: the model demonstrates positive mathematical expectation, moderate drawdowns, and high trading efficiency across a variety of market conditions.
EEMFlow integration into the existing architecture opens up prospects for further optimization, scaling, and application in algorithmic trading, confirming the practical value of the methods developed by the framework's authors.
Links
Programs used in the 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 | System state and model architecture description structure |
| 5 | NeuroNet.mqh | Class library | Library of classes for creating a neural network |
| 6 | NeuroNet.cl | Code Base | OpenCL program code library |
Translated from Russian by MetaQuotes Ltd.
Original article: https://www.mql5.com/ru/articles/20704
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.
Dmitry, hello!
Thank you for the new work!
I’ve run your expert advisor in its original form (logs aren’t taken into account). The STFS error level remains at 1600+. Is this normal? Or do the features need to be normalised after all?
Good afternoon, Vladimir.
The STFS error rate, by and large, has little impact on the model’s trading performance. We use it at the initial stage of training to focus the state encoder’s attention as much as possible on features that provide the most information about future price movements. This is the supervised learning stage on a pseudo-ideal trajectory (Self-Supervised Learning).
In the second stage — online training in the strategy tester (StudyOnline.mq5) — STFS is no longer used. We then adjust the model’s parameters based on the performance of completed trades — this is known asreinforcement learning.
I’ve noticed that during training, the graphics card is underutilised — it’s only running at 5–10 per cent, even though it has plenty of resources. As far as I understand, this is because the data is being processed strictly one bar at a time (Batch Size = 1).
I’d like to seek your advice as the author:
I’d be very grateful for any advice on where to look. I’d like to make the most efficient use of the hardware. My questions may not be entirely accurate, as I’m using LLM for interaction, but I think you’ll understand that anyway. Thank you!
Thank you for the articles!
I’m trying to compile the code in the EEMFlow directory in the zip archive linked in your post. But I’m not sure where to find the Neuronet.mqh and Neuronet.cl files. Sorry if this is a silly question.
Thank you for the articles!
I’m trying to compile the code in the EEMFlow directory in the zip archive linked in your post. But I’m not sure where to find the Neuronet.mqh and Neuronet.cl files. Sorry if this is a silly question.
Hello,
You can find these files in the NeuroNet_DNG directory within the zip file.
Dmitry, thank you for your feedback. I appreciate your interest.
I’ve noticed that during training, the graphics card is underutilised — it’s only running at 5–10 per cent, even though it has plenty of resources. As far as I understand, this is because the data is being processed strictly one bar at a time (Batch Size = 1).
I’d like to seek your advice as the author:
I’d be very grateful for any advice on which direction to look in. I’d like to make the most efficient use of the hardware. My questions may not be entirely accurate, as I’m using LLM for interaction, but I think you’ll understand that anyway. Thank you!
Good afternoon, Vladimir.
Initially, everything was designed with a focus on online operation within the terminal, and such mechanisms were not envisaged. Implementing them would require significant modifications to both the library itself and the training programmes. In the library, this is primarily due to the size of the data buffers. Whilst maintaining the volume of parameters being trained, it will be necessary to increase the storage buffers for raw data, intermediate values and results several-fold. Furthermore, on the training programme side, it will be necessary to create a correspondingly larger set of raw data and target values.
However, during operation, such large data buffers will be excessive. Consequently, we arrive at the need for separate organisation of the training and operational processes.