Русский
preview
Neural Networks in Trading: Mesh-Based Approximation of Event Streams as a Tool for Analyzing Price Patterns (CDC Module)

Neural Networks in Trading: Mesh-Based Approximation of Event Streams as a Tool for Analyzing Price Patterns (CDC Module)

MetaTrader 5 — Trading systems |
135 0
Dmitriy Gizlyk
Dmitriy Gizlyk

Introduction

We are continuing our systematic and, importantly, thoughtful work on putting the ideas behind the EEMFlow framework into practice in algorithmic trading. The previous articles have laid a solid foundation: from defining the problem itself and explaining the rationale for transitioning to an event-driven market model, to implementing the key adaptive mechanisms responsible for stabilizing and structuring the data stream under analysis. Now is the logical time to take the next step. But before we delve into the next level of implementation, let's take a moment to calmly and clearly recall why we embarked on this journey in the first place. What is the fundamental strength of the EEMFlow framework, and what architectural concepts underlie it?

By its very nature, the modern financial market has long since ceased to be a smooth time series. It is discrete, non-uniform, and asynchronous. Periods of calm are suddenly followed by bursts of activity, and classical models, which are designed for a uniform time grid, either lose sensitivity or begin to perceive noise where a signal is actually forming. It is precisely this fundamental problem — the gap between actual market dynamics and the way they are formally described — that served as the starting point for this work. We have deliberately rejected the illusion of equal time and opted for an event-based representation, where the market is described not by the number of seconds, but by changes in its state.

This approach immediately reveals a new challenge. The event stream follows its own rules; its density varies by orders of magnitude, its distribution is non-stationary, and local spikes can completely dominate the global structure. Without adaptation, such a data stream either overloads the model or, conversely, becomes too sparse to be informative. This is where the core philosophy of EEMFlow comes into play: before evaluating anything, you need to get the data into a form that is actually usable. Do not smooth out the market too aggressively or normalize it based on averages; instead, learn to adapt dynamically to its current density and rhythm.

In previous articles, we took an in-depth look at the Adaptive Density Module. It solves a problem that classical trading systems typically try to work around with stopgap measures: volatility filters and heuristic limits. Here, the event density becomes a controllable variable. The model decides for itself how much information it needs at any given moment and on what scale that information should be processed. For the market, this means stability, and for the algorithm, it means predictable behavior.

It is important to emphasize that EEMFlow does not seek to predict the market. It strives to measure it accurately. This is a fundamentally different perspective, one that is close to the classical school of engineering. First, the framework's developers build a reliable measurement device, and only then does the model begin to draw conclusions. That is precisely why the framework's architecture appears, at first glance, to be understated and even conservative. There is no excessive depth for the sake of depth here, no decorative layers; each block serves a strictly defined function and logically follows from the previous one.

The basic architecture of EEMFlow is built around the sequential transformation of an event stream into a structured spatiotemporal representation. Events are aggregated, normalized by density, encoded at multiple levels, and gradually transformed into a motion flow. It is crucial to note that the processing is not based on absolute time coordinates, but on relative changes. This makes the architecture resilient to shifts in market regimes and naturally scalable.

Author's visualization of the EEMFlow framework

The concept of multi-level density processing deserves special attention. In EEMFlow, it is implemented as a system of interacting mechanisms that operate at both the global and local levels. This is where the framework proves its practical value: density adaptation allows computational resources to be reallocated to areas where the market is truly active, rather than wasting them on inactive areas.

An important advantage of EEMFlow, which gradually becomes apparent during implementation, is its modularity. The architecture allows for phased development without the need to rewrite parts that are already in use. We started with an event-based representation and implemented ADM. Each new component integrates seamlessly into the system, enhancing it rather than upsetting its balance.

The issue of interpretability is no less important. Despite its apparent complexity, EEMFlow remains transparent from an engineering perspective. We can always explain why the model is behaving this way at this moment. The density of events, the chosen scale, and the active features — all of these are observable and amenable to analysis. This is critical for real-world trading systems. The market does not forgive decisions made blindly, even if they look good in a backtester.

The next logical step in our work is to address detail completion. Once the event stream has been stabilized in terms of density, aligned by features, and transformed into a consistent spatiotemporal representation, the next, more nuanced task arises: reconstructing the local structure of motion where the data is incomplete, sparse, or contradictory. The market, like any event space, does not provide information uniformly. It leaves gaps, masks the true dynamics, and often hides important details precisely in those areas where the signal appears weak.

In the EEMFlow framework architecture, this problem is solved by the Confidence‑induced Detail Completion Module (CDC). Its role cannot be reduced to merely improving the appearance of the result. This is a crucial stage in which the model begins to consciously distinguish between regions of reliable motion and areas of uncertainty, and then carefully — without making aggressive assumptions — fills in the missing structure. This restores the system's integrity and allows the dynamic picture to remain continuous without distorting the underlying signal.

Today, we will focus on building and adapting this module using MQL5.



Architecture of the CDC Module

In the EEMFlow architecture, the Confidence-induced Detail Completion module is there neither by chance nor just for show. This is a solution to a very practical problem that inevitably arises in multilevel motion processing. During the upsampling stage, different motions begin to blend together, boundaries become blurred, and the local structure of the signal loses its clarity. This is particularly critical for trading analysis, since it is in zones of transition, acceleration, and regime change that the market most often prompts significant trading decisions.

CDC serves as a precise mechanism for refining the motion already obtained. It takes a lower-resolution flow as input and first upsamples it to the next level using simple bilinear interpolation. This is merely a draft, an initial approximation that deliberately makes no claim to accuracy. Next, two complementary branches come into play — self-correction and self-correlation. Each addresses its own part of the problem.

The self-correction branch operates locally and in an extremely pragmatic manner. It analyzes the aligned features of neighboring events and uses a dense convolutional structure to reconstruct the correct motion near boundaries and discontinuities. At the same time, a confidence map is created — a practical assessment of where the result is most vulnerable to errors. Essentially, the system itself flags the sections where it is unsure about the initial interpolation.

The second branch — the self-correlation branch — takes a broader view. Using the Self-Attention mechanism and a large receptive field, it searches the feature space for regions with similar dynamics and transfers this information to the problem areas. This is no longer a local repair, but a global comparison. If the market behaves similarly elsewhere, this structure can be used to refine the current motion.

The final result is derived from a weighted combination of these two representations. The corrected motion obtained through local correction and the refined motion flow enhanced by Self-Attention are carefully blended. The confidence map plays a decisive role here. Where the initial estimate is reliable, the system retains it. Where the probability of error is high, priority is given to the refined version. As a result, the motion is not rebuilt from scratch, but is gently supplemented exactly where it is truly needed.

Author's visualization of the CDC module

In the context of an event-based representation of the market, CDC is particularly appropriate. We do not impose unnecessary interpretations on the market, nor do we mechanically smooth out the signal. We allow the system to identify areas of uncertainty on its own and fill them in, drawing on the structure already observed in the data.


Flow Correction Block

We will begin our practical work with the flow self-correction block. This is a deliberate and conservative engineering decision. This is where the system develops the local sensitivity that will later determine the quality of motion recovery in areas of uncertainty. Before introducing attention and global comparison mechanisms, we need to train the model to carefully interpret an event's immediate surroundings and recognize boundaries, discontinuities, and subtle transitions between different dynamic regimes.

From a practical standpoint, this block is a perfect fit for the capabilities of MQL5. It is compact, has a predictable computational load, and scales well. We begin with a dense, sequential analysis of local features, laying the groundwork for further motion correction and the creation of a confidence map.

We deliberately encapsulate the entire self-correction process in a separate object. This is not merely a matter of implementation convenience, but a direct consequence of the architectural logic of CDC. The Self-Corrector branch must be autonomous, self-contained, and predictable in its behavior, since it is responsible for local motion correction and the formation of the confidence map. Encapsulating it in a separate block is therefore a natural step.

The CNeuronCDCSelfCorrector class integrates seamlessly into the familiar hierarchy, inheriting from CNeuronBatchNormOCL. This immediately establishes the appropriate operating context. No unnecessary heroics or manual buffer management — everything stays within the established computational pipeline.

class CNeuronCDCSelfCorrector :  public CNeuronBatchNormOCL
  {
protected:
   uint              iUnits;
   uint              iVariables;
   CLayer            cEstimator;
   //---
   virtual bool      feedForward(CNeuronBaseOCL *NeuronOCL) override;
   virtual bool      updateInputWeights(CNeuronBaseOCL *NeuronOCL) override;
   virtual bool      calcInputGradients(CNeuronBaseOCL *NeuronOCL) override;

public:
                     CNeuronCDCSelfCorrector(void) {};
                    ~CNeuronCDCSelfCorrector(void) {};
   //---
   virtual bool      Init(uint numOutputs, uint myIndex, COpenCLMy *open_cl,
                          uint window, uint &inside_dimensions[],
                          uint window_out, uint units_count, uint variables,
                          ENUM_OPTIMIZATION optimization_type, uint batch);
   //---
   virtual int       Type(void) override const  {  return defNeuronCDCSelfCorrector;   }
   //--- 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;
  };

The internal structure of the class reflects the module's functional role. The iUnits and iVariables parameters specify the dimensionality and expressive power of the local analysis. These parameters are not chosen arbitrarily. The sequence length and the number of channels directly determine how finely the block can distinguish between borderline motion states. The cEstimator object acts as a dense estimator — the very convolutional kernel that carefully extracts local patterns from the aligned features of neighboring events.

The key computational steps are encapsulated in methods that are standard for neural network architectures.

The initialization method deserves separate consideration because it is precisely here that the logic of the Self-Corrector architecture and its alignment with the original CDC concept are most clearly evident. This method does more than just create a set of internal layers. Step by step, it builds a dense corrective analyzer designed to work with the local structure of motion and gradually expand the context without losing resolution.

bool CNeuronCDCSelfCorrector::Init(uint numOutputs, uint myIndex, COpenCLMy *open_cl,
                                   uint window, uint &inside_dimensions[], uint window_out,
                                   uint units_count, uint variables,
                                   ENUM_OPTIMIZATION optimization_type, uint batch)
  {
   uint layers = inside_dimensions.Size();
   if(layers <= 0)
      return false;
   if(!CNeuronBatchNormOCL::Init(numOutputs, myIndex, open_cl, window_out * units_count * variables,
                                 batch, optimization_type))
      return false;
   activation = None;

Initialization begins with a check of the internal configuration. The inside_dimensions array specifies the depth and shape of the analyzer, and if it is empty, the module simply serves no purpose. This highlights an important point: the Self-Corrector is not a fixed block. Its expressive power is determined by a predefined architecture, not by a hard-coded number of layers.

Next, the parent class's initialization method is called. This is a key point. We immediately bring the entire block into a consistent data format compatible with the rest of CDC and the entire event-driven architecture. The activation function is intentionally disabled. The Self-Corrector should not distort the dynamics with container-level nonlinearities — all nonlinear transformations are concentrated within the estimator.

The main logic is centered on constructing the cEstimator sequence. Here we see a dense, almost classic architecture: convolution, normalization, concatenation, and so on, layer by layer. Each cycle expands the input window by adding new filters, which gradually broadens the local context. That is an important detail. Instead of a sudden increase in the receptive field, we get a gradual accumulation of information, which is ideal for handling motion boundaries and local discontinuities.

   iUnits = units_count;
   iVariables = variables;
//---
   CNeuronMultiWindowsConvWPadOCL*  conv = NULL;
   CNeuronBatchNormOCL*             norm = NULL;
   CNeuronBaseOCL*                  concat = NULL;
   uint index = 0;
   uint inp_window = window;
   uint windows[1] = { 3 * inp_window };
   for(uint i = 0; i < layers; i++)
     {
      conv = new CNeuronMultiWindowsConvWPadOCL();
      if(!conv ||
         !conv.Init(0, index, OpenCL, windows, inp_window, inside_dimensions[i],
                    iUnits, iVariables, optimization, iBatch) ||
         !cEstimator.Add(conv))
        {
         DeleteObj(conv)
         return false;
        }
      conv.SetActivationFunction(SoftPlus);
      index++;
      inp_window += conv.GetFilters();
      windows[0] =  3 * inp_window;
      norm = new CNeuronBatchNormOCL();
      if(!norm ||
         !norm.Init(0, index, OpenCL, conv.Neurons(), iBatch, optimization) ||
         !cEstimator.Add(norm))
        {
         DeleteObj(norm)
         return false;
        }
      norm.SetActivationFunction(None);
      index++;
      concat = new CNeuronBaseOCL();
      if(!concat ||
         !concat.Init(0, index, OpenCL, inp_window * iUnits * iVariables, optimization, iBatch) ||
         !cEstimator.Add(concat))
        {
         DeleteObj(concat)
         return false;
        }
      index++;
      concat.SetActivationFunction(None);
     }

Convolutional layers are created with padding enabled. This makes it possible to analyze motion without disrupting spatial consistency. The SoftPlus activation function was not chosen by chance. It maintains a smooth response and performs well near zero, which is critical when analyzing weak and borderline motion. This is not an aggressive nonlinearity, but rather a sound engineering compromise between sensitivity and stability.

Normalization follows each convolution. It stabilizes the distribution of features and makes training predictable, especially when event density is uneven. Next comes the concatenation layer, which combines the current and previously accumulated features into a single representation. This is where the Self-Corrector acquires its dense architecture. Information is not lost along the way; rather, it is accumulated and reused at every level.

The final convolutional layer completes the formation of the corrective representation and brings it to the specified size. It neatly completes the architecture without adding unnecessary operations or complicating the computation graph.

   conv = new CNeuronMultiWindowsConvWPadOCL();
   if(!conv ||
      !conv.Init(0, index, OpenCL, windows, inp_window, window_out,
                 iUnits, iVariables, optimization, iBatch) ||
      !cEstimator.Add(conv))
     {
      DeleteObj(conv)
      return false;
     }
//---
   return true;
  }

The result is a compact yet expressive analyzer capable of extracting local motion patterns and preparing data for the generation of a corrective flow and a confidence map.

Overall, the initialization method exemplifies the very approach that runs like a common thread throughout the entire EEMFlow framework architecture. No magic, no unnecessary complexity. Just the systematic, logically sound construction of a block that does exactly what is required of it. And it does so reliably. It is precisely these details that make up the working architecture of CDC in real-world trading applications.

The forward pass algorithm is implemented with great care and, importantly, fully reflects the architectural concept of dense local correction. There are no hidden transitions or implicit transformations here. Each step logically follows from the previous one and works toward a single goal — to form a stable, feature-rich representation of local motion.

bool CNeuronCDCSelfCorrector::feedForward(CNeuronBaseOCL *NeuronOCL)
  {
   CNeuronBaseOCL* residual = NeuronOCL;
   CNeuronBaseOCL* prev = residual;
   CNeuronBaseOCL* curr = NULL;
   if(!residual)
      return false;
//---
   uint count = iUnits * iVariables;
   uint res_window = residual.Neurons() / count;
   int total = cEstimator.Total();

The forward pass begins by obtaining a pointer to the source data object, which, in the context of CDC, serves as a residual representation. This is not just an input tensor, but a base flow onto which refinement information is subsequently added.

We immediately set the window dimensionality based on the number of channels and the sequence length so that all subsequent processing is performed in a consistent format. Performing this calculation at the start eliminates the need for unnecessary checks and recalculations within the loop.

Control is then passed to the cEstimator sequence, which, as a reminder, contains the entire dense structure of the Self-Corrector. Iterating through its internal layers implements the key principle of a dense connection.

   for(int i = 0; i < total; i++)
     {
      curr = cEstimator[i];
      if(!curr)
         return false;
      if(curr.Type() == defNeuronBaseOCL)
        {
         if(!Concat(residual.getOutput(), prev.getOutput(), curr.getOutput(),
                    res_window, prev.Neurons() / count, count))
            return false;
         residual = curr;
         res_window = curr.Neurons() / count;
        }
      else
         if(!curr.FeedForward(prev))
            return false;
      prev = curr;
     }

Checking the types of the sequence's components allows us to identify the concatenation objects. The current residual representation is combined with the previous result. This is a critical point. Instead of overwriting the information, we progressively expand the context, allowing each subsequent layer to work with an enriched set of features.

In all other cases, the layer performs a standard forward pass using the previous result as input. Handling these cases separately makes the code transparent and eliminates implicit dependencies. We always know exactly where convolution occurs, where normalization takes place, and where features are structurally combined.

As we move through the layers, the current residual representation is also updated. Its window gradually grows, reflecting the expansion of the local context. This is especially important for refining motion boundaries. The system does not make sudden jumps in scale, but gradually looks further and further afield while maintaining a connection to the original signal.

The final step of the forward pass is to call the method of the same name in the parent class. Here, the output of the dense estimator is normalized to a form compatible with the rest of CDC.

   if(!CNeuronBatchNormOCL::feedForward(prev))
      return false;
//---
   return true;
  }

This completes the formation of the correction flow and the confidence map without compromising the overall consistency of the computational graph.

As a result, the feedForward method implements exactly the behavior expected of Self-Corrector. Local analysis, dense accumulation of features, careful normalization, and the absence of aggressive transformations. Everything runs smoothly, predictably, and strictly according to the architecture. This code does not try to be flashy. It just does its job — and does it right.

Training a model is not a formal inverse operation, but rather a careful analysis of the inaccuracies that have occurred, while preserving the architectural logic of the dense analyzer. The calcInputGradients method performs precisely this error correction, passing the gradient signal back through the entire Self-Corrector structure step by step, without disrupting the accumulated connections or losing the local context.

bool CNeuronCDCSelfCorrector::calcInputGradients(CNeuronBaseOCL *NeuronOCL)
  {
   if(!NeuronOCL)
      return false;
//---
   if(!CNeuronBatchNormOCL::calcInputGradients(cEstimator[-1]))
      return false;

The procedure begins at the top level. First, the input gradients for the last element of cEstimator are computed using the batch normalization mechanism. This is an important step. It is here that the error is brought to a consistent scale so that further propagation does not amplify random spikes or mask significant deviations. Essentially, the signal returns from the space of output estimates to the dense correction analyzer in a cleaned-up form.

Next, the backward pass through the cEstimator layers begins in strict reverse order. Each layer analyzes the contribution of its outputs to the total error using a standard mechanism for computing hidden gradients.

   CNeuronBaseOCL* next = cEstimator[-1];
   CNeuronBaseOCL* curr = NULL;
   CNeuronBaseOCL* residual = NULL;
   uint count = iUnits * iVariables;
//---
   for(int i = cEstimator.Total() - 2; i >= 0; i--)
     {
      curr = cEstimator[i];
      if(!curr ||
         !curr.CalcHiddenGradients(next))
         return false;

However, the key feature becomes apparent when processing concatenation layers. Here, backpropagation is not straightforward, since the output was formed by combining several feature streams.

When a layer responsible for concatenation is encountered, the gradients are carefully redistributed. Part of the error is attributable to newly formed features, and part to a previously accumulated residual representation.

      if(curr.Type() == defNeuronBaseOCL && i > 0)
        {
         int concat_win = curr.Neurons() / (int)count;
         if(!!residual)
            if(!SumAndNormilize(curr.getGradient(), residual.getPrevOutput(), curr.getGradient(),
                                concat_win, false, 0, 0, 0, 1))
               return false;
         next = cEstimator[i - 1];
         if(!next)
            return false;
         int prev_win = next.Neurons() / (int)count;
         if(!DeConcat(curr.getPrevOutput(), next.getGradient(), curr.getGradient(),
                      concat_win - prev_win, prev_win, count))
            return false;
         residual = curr;
         Deactivation(next);
         i--;
        }
      else
         next = curr;
     }

To do this, the gradients are first summed, taking the residual flow into account, and then deconcatenation is performed to return the corresponding error components to the previous level. This is a critical point: it is precisely here that the dense structure of the architecture is preserved and correct training of all levels at once — not just the final layers — is ensured.

In addition, if necessary, the previous layer is deactivated. This underscores the fact that the Self-Corrector is not a linear chain; it contains nested nonlinear transformations, and each of them must be correctly undone during the backward pass. The code does this explicitly, without any hidden assumptions, which is particularly important in the context of complex event dynamics.

After the backward pass through cEstimator is complete, the gradients are passed to the source data object from which the correction began. Here, the possible presence of an activation function and a residual connection is again taken into account.

   if(!NeuronOCL.CalcHiddenGradients(next))
      return false;
   if(!!residual)
     {
      if(NeuronOCL.Activation() != None)
         if(!DeActivation(NeuronOCL.getOutput(), residual.getPrevOutput(),
                          residual.getPrevOutput(), NeuronOCL.Activation()))
            return false;
      if(!SumAndNormilize(NeuronOCL.getGradient(), residual.getPrevOutput(), NeuronOCL.getGradient(),
                          NeuronOCL.Neurons() / count, false, 0, 0, 0, 1))
         return false;
     }
//---
   return true;
  }

If the residual flow contributed to the result, its contribution is added back through summation. This completes the learning cycle by feeding the error information back into the original representation of the flow.

As a result, calcInputGradients implements not just a standard backward pass, but a precise, architecturally consistent mechanism for training a dense correction module. The error is not mechanically propagated backward, but is meaningfully distributed across all levels of local analysis. This is precisely what allows the Self-Corrector to gradually learn to distinguish between true motion boundaries and random artifacts, without losing stability or overfitting to noise.


Confidence-Induced Detail Completion Module

In the next step, we move from local analysis to a complete spiking implementation of CDC. It is here that the disparate components — self-correction, correlation search, and confidence masking — are brought together into a single computational node. The CNeuronSpikeCDC class serves as such a node and is, in essence, a practical implementation of the entire concept of Confidence-induced Detail Completion in an event-driven format.

class CNeuronSpikeCDC  :  public CNeuronSpikeConvBlock
  {
protected:
   CNeuronCDCSelfCorrector       cEsimator;
   CNeuronBaseOCL                cFlowCorrector;
   CNeuronRelativeSelfAttention  cFlowCorrelation;
   CNeuronBaseOCL                cFlowMask;
   CNeuronBaseOCL                cFlow;
   //---
   virtual bool      feedForward(CNeuronBaseOCL *NeuronOCL) override;
   virtual bool      updateInputWeights(CNeuronBaseOCL *NeuronOCL) override;
   virtual bool      calcInputGradients(CNeuronBaseOCL *NeuronOCL) override;

public:
                     CNeuronSpikeCDC(void) {};
                    ~CNeuronSpikeCDC(void) {};
   //---
   virtual bool      Init(uint numOutputs, uint myIndex, COpenCLMy *open_cl,
                          uint window, uint &inside_dimensions[],
                          uint window_out, uint units_count, uint variables,
                          ENUM_OPTIMIZATION optimization_type, uint batch);
   //---
   virtual int       Type(void) override const  {  return defNeuronSpikeCDC;   }
   //--- 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;
  };

Inheritance from CNeuronSpikeConvBlock immediately establishes the appropriate scale. We no longer work with a separate correction filter; instead, we integrate CDC into the overall spiking pipeline, where each block must be compatible with event dynamics and operate on a sparse, irregular stream. This is not a cosmetic adaptation, but an architectural transition to a full-fledged event-driven model.

The internal structure of the class reflects the logic of the original framework almost exactly, but in a form that is convenient for practical implementation. The cEstimator object encapsulates the self-correcting branch, which we just discussed in detail. This is a local analyst responsible for refining motion and generating a confidence map. It operates within the immediate neighborhood of events and lays the foundation for all subsequent decisions.

The cFlowCorrector object serves as the link between local correction and the final flow. The corrected displacements pass through this object and are then compared with the global motion structure. There is no independent logic here — it is simply a neat container that ensures data consistency and the correct integration of the correction signal into the overall flow.

The cFlowCorrelation branch implements a self-correlation mechanism. This is Self-Attention, which is focused not on aggressively amplifying features, but on identifying coherent dynamic structures within an expanded context. It allows the model to peek at similar motions and use them to refine problem areas without disrupting the local geometry of the flow.

The object is initialized in such a way that all internal components immediately take their strictly defined places in the overall computational flow. There is no improvisation or dynamic assembly on the fly here. The CDC architecture is fully defined during the initialization phase, which makes the module's behavior predictable and easy to analyze.

bool CNeuronSpikeCDC::Init(uint numOutputs, uint myIndex, COpenCLMy *open_cl,
                           uint window, uint &inside_dimensions[], uint window_out,
                           uint units_count, uint variables,
                           ENUM_OPTIMIZATION optimization_type, uint batch)
  {
   if(!CNeuronSpikeConvBlock::Init(numOutputs, myIndex, open_cl, window, window, window_out,
                                   units_count, variables, optimization_type, batch))
      return false;

The process begins with the basic initialization of the parent class. With this step, we immediately integrate CDC into the overall spiking pipeline, specifying a uniform window format, channel dimensionality, and execution parameters.

Next, the internal components are initialized sequentially. First, cEstimator — that is, the self-correcting branch — is created.

   uint index = 0;
   if(!cEsimator.Init(0, index, OpenCL, window, inside_dimensions, 2 * window, units_count,
                      variables, optimization, iBatch))
      return false;

It is passed the initial window, the internal layer configuration, and the extended output window. In this way, we prepare this block in advance to work with an enriched local context. It becomes the source of two key entities — corrected motion and a confidence map — although they have not yet been separated.

The next element is cFlowCorrector. Its input dimensionality is half the output dimensionality of Self-Corrector, reflecting the division of information into flow components. Here, the activation function is deliberately disabled. This unit should not interpret the data; its purpose is to pass the corrected motion on without distortion.

   index++;
   if(!cFlowCorrector.Init(0, index, OpenCL, cEsimator.Neurons() / 2, optimization, iBatch))
      return false;
   cFlowCorrector.SetActivationFunction(None);

After that, cFlowCorrelation is initialized. This is an implementation of the Self-Attention mechanism.

   index++;
   if(!cFlowCorrelation.Init(0, index, OpenCL, window, (window + 3) / 4, units_count * variables,
                             4, optimization, iBatch))
      return false;

In architectural terms, this is precisely the broad perspective that complements local corrections with a global comparison of motion.

Next, cFlowMask is created. This block generates a confidence mask, which is why sigmoid activation was chosen for it.

   index++;
   if(!cFlowMask.Init(0, index, OpenCL, cFlowCorrector.Neurons(), optimization, iBatch))
      return false;
   cFlowMask.SetActivationFunction(SIGMOID);

The mask values must lie within a bounded range and be interpreted as weights rather than hard decisions. This is a key element that allows CDC to operate in a soft rather than binary manner, accounting for uncertainty.

The final step in the initialization process is cFlow. It takes input with the same dimensionality as the correction flow and generates the corrected flow. The activation function has been disabled again to preserve the linearity of the mixing and avoid introducing unnecessary nonlinearities in the final stage.

   index++;
   if(!cFlow.Init(0, index, OpenCL, cFlowCorrector.Neurons(), optimization, iBatch))
      return false;
   cFlow.SetActivationFunction(None);
//---
   return true;
  }

Ultimately, the initialization method assembles CDC into a cohesive, balanced module. Each component is assigned a specific role, a consistent dimensionality, and a predetermined place in the chain.

The forward pass algorithm is strictly sequential and, importantly, logically transparent. There are no hidden workarounds here — every step reflects the original idea behind Confidence-induced Detail Completion and carefully adapts it to the spiking environment.

bool CNeuronSpikeCDC::feedForward(CNeuronBaseOCL *NeuronOCL)
  {
   if(!cEsimator.FeedForward(NeuronOCL))
      return false;

The process begins by calling a forward pass for the flow correction branch. This is the starting point for the entire module. At this stage, an initial representation of motion is formed, already enriched with an internal reliability estimate. In effect, we obtain a dense signal that has not yet been separated, in which information about the flow itself and confidence in it coexist in the same space.

The next step is to explicitly separate these entities. Using DeConcat, the estimator's output is split into two streams: the flow to be corrected, cFlowCorrector, and the confidence mask, cFlowMask. The dimensionality is not calculated in the abstract but is derived strictly from the convolutional block's parameters: the length of the sequence being analyzed, the number of variables, and the window size. This highlights the architectural discipline: CDC does not exist separately from the pipeline; it is seamlessly integrated into it.

   uint count = cConv.GetUnits() * cConv.GetVariables();
   uint window = cConv.GetWindow();
   if(!DeConcat(cFlowCorrector.getOutput(), cFlowMask.getOutput(),
                cEsimator.getOutput(), window, window, count))
      return false;
   dActivation(cFlowCorrector)
   dActivation(cFlowMask) 

After deconcatenation, each of the streams undergoes its own activation stage. For the motion being corrected, this is essentially a formality, since activation is disabled there. For the confidence mask, however, the sigmoid function is essential: it maps the data into an interpretable space of weights, where each value is a measure of confidence. Here, CDC begins to function as a sophisticated probabilistic mechanism rather than a binary filter.

Next, we carefully add the flow correction values to the original features being analyzed, forming an alternative corrected flow. This step is critically important: it allows us to combine the local correction made by Self-Corrector with the original information without discarding important details, while smoothly suppressing noise.

  if(!SumAndNormilize(cFlowCorrector.getOutput(), NeuronOCL.getOutput(),
                       cFlowCorrector.getOutput(), window, false, 0, 0, 0, 1))
      return false;

Essentially, we create an intermediate flow that already incorporates the corrections made and preserves the structural integrity of the original signal.

After that, the corrected flow is fed into cFlowCorrelation. This is where the Self-Attention mechanism comes into play. It analyzes spatiotemporal relationships within the window and identifies coherent motion structures. This is particularly valuable in the context of event-driven trading: the market rarely moves in isolation, and correlation patterns are often more important than local spikes.

   if(!cFlowCorrelation.FeedForward(cFlowCorrector.AsObject()))
      return false;

It is important to emphasize the fundamental difference between our implementation and the framework's original version. In the original version, Self-Correlation is based on the Self-Attention mechanism, which searches the feature space for regions with motion identical to that in the problem area of the original flow. In other words, attention is applied to the raw flow before correction, and the model attempts to reconstruct details from the original, unrefined data.

In our implementation, we apply the Self-Attention mechanism to the corrected flow. In other words, the attention mechanism now operates on locally refined values, where some of the noise and artifacts have been removed by the Self-Corrector. This offers two advantages at once. First, the search for matches becomes more accurate, since the correction has already aligned the key features of motion. Second, the final attention map reflects trusted information, which increases the stability of the subsequent combination step.

The resulting correlation features are then carefully integrated with the flow being analyzed through a weighted combination, with the confidence mask providing the weights. This is not simply tensor multiplication: each element of the corrected flow is scaled according to the confidence level assigned by the Self-Corrector.

   if(!GateElementMult(NeuronOCL.getOutput(), cFlowCorrelation.getOutput(),
                       cFlowMask.getOutput(), cFlow.getOutput()))
      return false;

Thus, details are not added everywhere, but only where the system is truly confident in their accuracy. This is the practical implementation of the Confidence-induced approach — rigorous, economical, and without unnecessary noise.

The final step is to transfer control to the parent class. At this stage, CDC is fully integrated into the overall spiking pipeline, passing on a refined, weighted, and architecturally consistent representation of the flow.

   if(!CNeuronSpikeConvBlock::feedForward(cFlow.AsObject()))
      return false;
//---
   return true;
  }

As a result, the forward pass does not look like a series of disjointed operations, but rather like a single, coherent logical chain. Each block does exactly what is expected of it. No more, no less. It is precisely this restrained engineering rigor that makes CDC suitable for real-world trading systems. Here, a mistake is not just an abstract concept — it is real, tangible money.

The transition to CNeuronSpikeCDC marks a qualitatively new phase. We go beyond individual corrective techniques and build a mature event-driven module capable of handling uncertainty and reconstructing the structure of motion in a form suitable for real-world trading applications.

We've done a lot of work today, and now it is time to let our thoughts settle. In the next article, we will complete our implementation of the approaches used in the EEMFlow framework by fully implementing its key components and evaluating their practical effectiveness using historical market data.


Conclusion

The work carried out allowed us to delve deeply into the architecture of the EEMFlow framework and successfully implement its key components using MQL5. At this stage, we have successfully implemented a CDC module that includes a Self-Corrector, integration of the Self-Attention mechanism for the corrected flow, and weighted signal merging via a confidence mask. This module ensures the coordinated generation of the final corrected flow by processing local and global motion features. The implementation validates the logical integrity of the architecture and the engineering maturity of the approach.

Although a final assessment of the framework's effectiveness can only be made after all stages of testing on historical data have been completed, its potential value can already be noted. The implementation in MQL5 demonstrates the predictability of the components' behavior, while the modular architecture opens up extensive opportunities for further optimization, scaling, and application in real-world market scenarios.


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 Model testing Expert Advisor
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/20677

Attached files |
MQL5.zip (3457.64 KB)
Building Your Own Expert Advisor (Part 8): ATR and R-Multiple Trailing Stops Building Your Own Expert Advisor (Part 8): ATR and R-Multiple Trailing Stops
We add TrailingStop.mqh: a trailing engine plus pluggable methods for the Series EA. Each method proposes a level; the engine decides if and when to send it, enforcing protective direction, minimum step, stops level and freeze level. Included methods are ATR trailing and an R‑multiple ladder, with optional break‑even as a floor. The result is per‑tick, safer stop management under broker constraints.
Building a Modular Pre-Trade Execution Filter Engine in MQL5 Building a Modular Pre-Trade Execution Filter Engine in MQL5
The article presents a modular pre-trade execution filter for MQL5 as an object-oriented include class. It validates quote freshness, aligns order filling with broker capabilities, applies a rollover freeze window, and detects spread outliers using rolling statistics with a hard cap. An on-chart diagnostic indicator and an EA template with reproducible telemetry show integration and help reduce execution frictions in live trading.
Reading Parquet Natively in MQL5: Thrift, Snappy and Dictionary Decoding into matrix Without CSV Reading Parquet Natively in MQL5: Thrift, Snappy and Dictionary Decoding into matrix Without CSV
This article shows how to read Apache Parquet files directly in MQL5 without DLLs: a native Thrift Compact Protocol decoder for footer metadata, a native Snappy block decompressor, and a hybrid RLE/bit‑packing decoder for definition levels and dictionary indices. We assemble numeric columns into a matrix with an optional null mask. Scope: flat schemas, INT32/INT64/FLOAT/DOUBLE, UNCOMPRESSED/SNAPPY, DataPageV1, first row group. The result avoids CSV conversions and preserves nulls and types.
Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 11): A Real Stroke Engine Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 11): A Real Stroke Engine
The engine learns to draw lines by stroking arbitrary paths with width, cap and join styles, miter limiting, and dashes. The stroker outputs overlapping geometry that the non-zero rule welds during fill, so no new raster code is required. In practice, you can render solid or dashed outlines with predictable caps and joins for chart series, widgets, and other UI shapes.