Русский
preview
Neural Networks in Trading: Difference-Based Modeling of Market Microstructure (Conclusion)

Neural Networks in Trading: Difference-Based Modeling of Market Microstructure (Conclusion)

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

Introduction

Previous articles have shown that the key idea behind EDCFlow is to deliberately build on correlation analysis. The market, like the event data in the original problem statement, is not limited to stable correspondences between states. It is constantly changing, and these changes often carry the most valuable information.

The EDCFlow architecture is fundamentally built around representing the data being analyzed as a dense spatiotemporal stream of events. Events are aggregated into a voxel representation that preserves the temporal structure and density of activity, providing a basis for further motion analysis. A fundamental principle is established at this stage. The model does not work with abstract features, but rather with dynamics that are explicitly tied to time and space.

Further processing is organized into two parallel feature-analysis branches operating at different resolutions. High resolution is used to preserve fine-scale structure and local changes, whereas lower resolution is used to construct a correlation volume. This decision reflects the practical need to strike a balance between accuracy and computational efficiency. The correlation volume provides a stable basis for correspondences between time windows, but on its own, it is unable to capture subtle changes in dynamics, especially under conditions of rapid and uneven motion.

This is where a key element of the framework's architecture comes into play: a mechanism based on dense temporal difference maps. Instead of considering features in a static context, the model systematically analyzes the differences between feature representations aligned using the current motion estimate. To do this, at each iterative refinement step, high-resolution features are mapped to a common coordinate system using the current flow, after which difference maps are computed between different time slices. These maps are generated across several time scales, which makes it possible to account for both rapid pulses and more prolonged changes simultaneously.

The resulting difference features are processed using depth-wise convolutions, which allows for the efficient aggregation of spatiotemporal information without destroying the channel structure.

Next, the attention mechanism adaptively weights the contributions of difference maps at different scales. This allows the model to focus specifically on the changes that are most informative in the current context. It is important to emphasize that this block does not replace correlation features but works in parallel with them.

During the motion encoding stage, correlation features and temporal difference features are adaptively combined through a specialized module. This combination preserves the stability of global correspondences provided by correlation. At the same time, it increases sensitivity to local shifts detected through differences. The result is a coherent motion representation, in which structure and dynamics complement each other.

The final component of the architecture is an iterative flow update block, implemented as a recurrent module. It takes the current motion estimate and the combined motion features, then predicts a correction to refine the motion flow. This process is repeated several times, allowing the model to gradually, step by step, converge toward a stable estimate. This iterative approach closely reflects how market analysis works in practice, where an understanding of price movement develops through successive refinements as new information arrives.

The author's visualization of the EDCFlow framework is shown below.

Author's visualization of the EDCFlow framework

Thus, EDCFlow forms an integrated system. In this system, correlation provides the framework, while dense temporal difference maps bring it to life.


Correlation Encoder

Earlier, we examined in detail how dense temporal difference maps are constructed and analyzed within EDCFlow. The multiscale difference block we built allows us to see what is usually lost when data is smoothed. However, on its own, it does not provide a complete picture of motion. Now it is time to move on to the second pillar of the EDCFlow framework and examine how the framework handles feature correlations and why this particular approach is so crucial.

The correlation mechanism in EDCFlow is not a peripheral component or merely an auxiliary technique. It forms a stable framework for the motion representation, onto which difference features are then superimposed. Features at reduced spatial resolution are used to construct a compact correlation volume that encodes correspondences between event time windows. This approach allows for the efficient detection of structural displacements and matches without excessive computational costs, while maintaining sufficient information for further refinement of the motion.

An important point is that correlations in EDCFlow are not treated as static. At each step of iterative refinement, the current motion estimate guides selective correlation retrieval to obtain correlation features, thereby linking correlation analysis to the accumulated context. This makes it possible to gradually narrow down the range of possible correspondences and improve the accuracy of the motion representation. Correlation acts here as a stabilizing mechanism, keeping the model within the bounds of a coherent global structure and preventing the representation from breaking down in the presence of noise or sharp local spikes.

It is precisely in this form that correlation features become a natural companion to temporal differences. While difference maps respond sensitively to changes and impulses, the correlation volume ensures the continuity and consistency of motion over time. Using them together within a single iterative loop allows the framework to be both responsive and robust — a rare combination that is particularly valuable when working with market data streams.

We implement the approaches proposed by the authors of EDCFlow for handling feature correlations as a separate object, CNeuronCorrelationEncoder. Its presence in the architecture directly reflects the role that the correlation mechanism plays in the original framework. Here, correlation is treated as a full-fledged stage of motion encoding, with its own internal logic, state, and trainable parameters.

class CNeuronCorrelationEncoder  :  public CNeuronSpikeConvBlock
  {
protected:
   uint                    iMaxDisplacement;
   int                     ibShifts;
   CNeuronBaseOCL          cCorrelation;
   CNeuronSpikeConvBlock   cWarpCorrs;
   CNeuronSpikeConvBlock   cWarpInps;
   CLayer                  cProjection;
   //---
   virtual int       CreateShifts(const uint max_displacement, int &count);
   //---
   virtual bool      feedForward(CNeuronBaseOCL *NeuronOCL) override;
   virtual bool      updateInputWeights(CNeuronBaseOCL *NeuronOCL) override;
   virtual bool      calcInputGradients(CNeuronBaseOCL *NeuronOCL) override;

public:
                     CNeuronCorrelationEncoder(void) {};
                    ~CNeuronCorrelationEncoder(void) {};
   //---
   virtual bool      Init(uint numOutputs, uint myIndex, COpenCLMy *open_cl,
                          uint dimension, uint units,
                          uint bottleneck, uint max_displacement,
                          ENUM_OPTIMIZATION optimization_type, uint batch);
   //---
   virtual int       Type(void) override const  {  return defNeuronCorrelationEncoder;   }
   //--- 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      SetOpenCL(COpenCLMy *obj)   override;
   virtual void      TrainMode(bool flag) override;
  };

Inheriting from CNeuronSpikeConvBlock establishes the basic context for working with event features and allows the correlation encoder to be integrated into the existing hierarchy of neural blocks without disrupting the overall architecture.

Within the class, the components responsible for the key stages of correlation analysis are clearly identified. The iMaxDisplacement parameter specifies the maximum displacement within which correspondences between features are sought, fully in line with the concept of a limited correlation window described in the authors' work. This is a key point: we do not construct a full, redundant correlation volume, but instead work in a local displacement space, which allows us to control computational complexity and maintain a focus on physically meaningful displacements.

The next important elements are the cWarpCorrs and cWarpInps blocks. They align the features with the current flow estimate. In the original model, correlation features are retrieved selectively, taking into account the displacement already predicted. Here, this idea is implemented directly in code. Correlations and input features are transformed into a common coordinate system, which allows them to be interpreted in a single space and used in subsequent motion encoding without logical discontinuities.

The cProjection projection layer completes the correlation encoding stage. Its task is to transform the resulting representation into a form suitable for subsequent combination with temporal difference features and transmission to the iterative update block. Here, correlation finally ceases to be a raw volume of correspondences and becomes a compact set of motion features, ready to work with other components of the framework.

The internal architecture of the object is defined during the initialization phase. And it is precisely the Init method that clearly demonstrates how the academic EDCFlow framework is translated into a rigorous engineering design. There are no arbitrary decisions here — every line of code reflects a specific architectural choice made by the framework's authors.

bool CNeuronCorrelationEncoder::Init(uint numOutputs, uint myIndex, COpenCLMy *open_cl,
                                     uint dimension, uint units,
                                     uint bottleneck, uint max_displacement,
                                     ENUM_OPTIMIZATION optimization_type, uint batch)
  {
   if(!CNeuronSpikeConvBlock::Init(numOutputs, myIndex, open_cl, 2 * bottleneck, 2 * bottleneck,
                                   dimension, units, 1, optimization_type, batch))
      return false;

Initialization begins with the method of the same name in the parent class, where the object's key parameters are set immediately and the base interfaces are created.

Next, a set of valid displacements is generated using CreateShifts.

   int count = 0;
   ibShifts = CreateShifts(max_displacement, count);
   if(ibShifts == INVALID_HANDLE)
      return false;
   iMaxDisplacement = max_displacement;

This is a direct reflection of the concept of a limited correlation window from the original EDCFlow paper. Instead of exhaustively enumerating all possible displacements, a compact set of shifts is created within the limit specified by max_displacement, which defines the correspondence search radius. The resulting number of displacements is used throughout the rest of the architecture and effectively determines the dimensionality of the correlation space. The maximum displacement parameter itself is also recorded here, and it becomes part of the object's state.

The next step is to initialize the cCorrelation object. It is responsible for storing the correlation volume.

   uint index = 0;
   if(!cCorrelation.Init(0, index, OpenCL, units * count, optimization, iBatch))
      return false;
   cCorrelation.SetActivationFunction(None);

The lack of an activation function in this block is no accident — the correlation volume is intended to convey raw correspondences without distortion.

Next, two symmetric alignment blocks appear in the architecture: cWarpCorrs and cWarpInps. The first one works with correlation features, while the second one works with the input features of the source stream.

   index++;
   if(!cWarpCorrs.Init(0, index, OpenCL, count, count, bottleneck, units, 1, optimization, iBatch))
      return false;
   index++;
   if(!cWarpInps.Init(0, index, OpenCL, dimension, dimension, bottleneck, units, 1, optimization, iBatch))
      return false;
   index++;

Both blocks use the same logic. The features are mapped to a common coordinate system based on the current motion estimate. This separation emphasizes the EDCFlow concept of processing different types of information in parallel so that they can then be matched directly, without additional normalization or heuristics.

The final part of the initialization process is dedicated to creating the cProjection projection block. It is assembled manually, allowing full control over its structure. First, a base neuron CNeuronBaseOCL is added, which takes the combined outputs of cWarpCorrs and cWarpInps as input. This layer serves as the point where the correlation and input representations converge, without introducing nonlinearities and while preserving the linear interpretation of the features.

   cProjection.Clear();
   cProjection.SetOpenCL(OpenCL);
   CNeuronBaseOCL*   neuron = NULL;
   CNeuronMSRes*     res_block = NULL;
//---
   neuron = new CNeuronBaseOCL();
   if(!neuron ||
      !neuron.Init(0, index, OpenCL, cWarpCorrs.Neurons() + cWarpInps.Neurons(), optimization, iBatch) ||
      !cProjection.Add(neuron))
     {
      DeleteObj(neuron)
      return false;
     }
   neuron.SetActivationFunction(None);
   index++;

Next, a residual block CNeuronMSRes is added to the projection. This block adaptively transforms the resulting representation, preparing it for further use in the iterative flow update loop.

   res_block = new CNeuronMSRes();
   if(!res_block ||
      !res_block.Init(0, index, OpenCL, units, 2 * bottleneck, 1, optimization, iBatch) ||
      !cProjection.Add(res_block))
     {
      DeleteObj(res_block)
      return false;
     }
//---
   return true;
  }

As a result, the initialization method creates a complete and logically coherent internal architecture for the object. The correlation volume, alignment operations, and projection block are arranged in a strict sequence that is fully consistent with the original EDCFlow architecture.

The correlation encoder's forward pass algorithm follows a clear, step-by-step structure, precisely reproducing the logical sequence of correlation feature processing defined in the EDCFlow architecture. The feedForward method builds a coherent motion representation step by step, mapping correlations and input features to a common coordinate system.

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

The forward pass begins with the processing of input features through the cWarpInps block. At this stage, the input representation is aligned based on the current motion estimate.

The next step is to calculate the correlation volume using the DilatedCorrelation function.

   if(!DilatedCorrelation(NeuronOCL, cCorrelation.AsObject(), ibShifts,
                          cWarpInps.GetWindow(), cWarpInps.GetUnits()))
      return false;

The correlation is computed not globally but over a predefined set of shifts, corresponding to the bounded displacement window used in the original work. The use of sparse, dilated shifts allows for efficient coverage of the search area without an exponential increase in computational complexity.

After the correlation volume has been generated, the second alignment stage is performed by the cWarpCorrs block. At this stage, the correlation features are mapped to the coordinate system defined by the current flow estimate.

   if(!cWarpCorrs.FeedForward(cCorrelation.AsObject()))
      return false;

This dual warping highlights an important aspect of the EDCFlow architecture: correlation is not a static correspondence table; rather, it dynamically adapts to the current motion estimate and is applied selectively, rather than in its entirety.

Next, the processing moves on to the cProjection projection block. First, the outputs of cWarpInps and cWarpCorrs are concatenated into a single feature tensor.

   CNeuronBaseOCL* curr = cProjection[0];
   CNeuronBaseOCL* prev = NULL;
//---
   if(!curr ||
      !Concat(cWarpInps.getOutput(), cWarpCorrs.getOutput(), curr.getOutput(),
              cWarpInps.GetFilters(), cWarpCorrs.GetFilters(), cWarpInps.GetUnits()))
      return false;
   prev = curr;

This is the point at which local input structures and global correlation correspondences are directly combined for the first time, without any intermediate heuristics. The resulting unified representation is sequentially processed through the projection layers, including a residual block that adaptively transforms the features and prepares them for use at the next level of the architecture.

   for(int i = 1; i < cProjection.Total(); i++)
     {
      curr = cProjection[i];
      if(!curr ||
         !curr.FeedForward(prev))
         return false;
      prev = curr;
     }

The output of the projection block is passed to the base CNeuronSpikeConvBlock, where it undergoes further processing within the framework's general computational loop.

   if(!CNeuronSpikeConvBlock::feedForward(prev))
      return false;
   if(!SumAndNormilize(NeuronOCL.getOutput(), Output, Output, cConv.GetFilters(), true, 0, 0, 0, 1))
      return false;
//---
   return true;
  }

The final step in the forward pass is to carefully merge the new representation with the current output state and then normalize it. This keeps feature scales stable and prevents scale imbalances from accumulating over repeated update iterations.

Thus, the feedForward method implements the complete correlation pathway of EDCFlow: from aligning input features and performing selective correlation retrieval to integrating the retrieved correlations with the input representation and passing the result to the shared iterative loop. This algorithm makes correlation an active participant in the motion refinement process, working in close coordination with temporal differences and the other components of the framework.

As a result, CNeuronCorrelationEncoder becomes a direct reflection of the EDCFlow correlation path in the code. It forms a stable structural framework for motion, which is then supplemented by temporally dense difference maps. This division of responsibilities makes the architecture transparent, manageable, and — most importantly — as close as possible to the framework authors' original vision, without simplifications or conceptual distortions.


Top-level object

Now that we have all the key components — the multiscale difference encoder CNeuronMultiScaleDifference, the correlation encoder CNeuronCorrelationEncoder, feature preparation blocks, and projection layers — we can move on to creating the top-level CNeuronEDCFlow object. This object forms a complete EDCFlow pipeline, integrating all the individual modules into a single, manageable, and sequential system.

class CNeuronEDCFlow :  public CNeuronSpikeConvBlock
  {
protected:
   CLayer                        cPrepare;
   CLayer                        cFeatureEncoder[2];
   CLayer                        cConextEncoder;
   CNeuronMultiScaleDifference   cDiffEncoder;
   CNeuronCorrelationEncoder     cCorrelation;
   CLayer                        cCorrelationUpsampling;
   CLayer                        cFlow;
   //---
   virtual bool      feedForward(CNeuronBaseOCL *NeuronOCL) override;
   virtual bool      updateInputWeights(CNeuronBaseOCL *NeuronOCL) override;
   virtual bool      calcInputGradients(CNeuronBaseOCL *NeuronOCL) override;

public:
                     CNeuronEDCFlow(void) {};
                    ~CNeuronEDCFlow(void) {};
   //---
   virtual bool      Init(uint numOutputs, uint myIndex, COpenCLMy *open_cl,
                          uint dimension_in, uint units_in, uint bottleneck,
                          uint dimension_out, uint units_out,
                          uint &shifts[], uint max_displacement,
                          ENUM_OPTIMIZATION optimization_type, uint batch);
   //---
   virtual int       Type(void) override const  {  return defNeuronEDCFlow;   }
   //--- 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      SetOpenCL(COpenCLMy *obj)   override;
   virtual void      TrainMode(bool flag) override;
//---
   virtual CBufferFloat   *getWeights(void) override;
  };

Inheritance from CNeuronSpikeConvBlock provides a common interface for working with event streams and integrating with other neural blocks. Within the object, logical blocks are defined that mirror the architecture of the original framework:

  • cPrepare performs initial processing of the input event stream, preparing it for multiscale processing.
  • cFeatureEncoder[0] and cFeatureEncoder[1] form feature encoding branches, each responsible for extracting specific spatiotemporal information at a different resolution. This step directly echoes the idea behind the original work: multiscale feature extraction allows for the simultaneous capture of local impulses and global patterns.
  • cConextEncoder aggregates the global context, maintaining the stability of the motion estimate and ensuring the consistency of the spatiotemporal representation.

  • cDiffEncoder constructs temporally dense difference maps, capturing local changes and dynamic shifts in the stream of events.

  • cCorrelation implements the correlation pathway discussed earlier: constructing the correlation volume, aligning features, and projecting them.

  • cCorrelationUpsampling increases the resolution of the correlation prediction, synchronizing it with high-resolution features from the difference blocks and feature encoders. Thus, local and global correspondences are brought into the same space, ready for final fusion.

  • cFlow is responsible for predicting the final motion flow. At this stage, all the extracted features — differences, correlations, and global context — are combined, and a final motion estimate is generated through successive processing layers.

The initialization method forms the basis of the high-level pipeline, transforming individual computational blocks into a single, coordinated system. If we imagine the event stream as dynamic market activity, then feature preparation acts like an analyst who first takes in the data, normalizes it, and organizes it into a coherent system so that subsequent modules can operate without losing information.

bool CNeuronEDCFlow::Init(uint numOutputs, uint myIndex, COpenCLMy *open_cl,
                          uint dimension_in, uint units_in, uint bottleneck,
                          uint dimension_out, uint units_out,
                          uint &shifts[], uint max_displacement,
                          ENUM_OPTIMIZATION optimization_type, uint batch)
  {
   if(!CNeuronSpikeConvBlock::Init(numOutputs, myIndex, open_cl, bottleneck, bottleneck,
                                   dimension_out, units_out, 1, optimization_type, batch))
      return false;
//---
   for(uint i = 0; i < cFeatureEncoder.Size(); i++)
     {
      cFeatureEncoder[i].Clear();
      cFeatureEncoder[i].SetOpenCL(OpenCL);
     }
   cPrepare.Clear();
   cConextEncoder.Clear();
   cCorrelationUpsampling.Clear();
   cFlow.Clear();
   cPrepare.SetOpenCL(OpenCL);
   cConextEncoder.SetOpenCL(OpenCL);
   cCorrelationUpsampling.SetOpenCL(OpenCL);
   cFlow.SetOpenCL(OpenCL);
//---
   CNeuronBaseOCL*               neuron = NULL;
   CNeuronBatchNormOCL*          norm=NULL;
   CNeuronCreateFlow*            stack = NULL;
   CNeuronSpikeADM*              adm = NULL;
   CNeuronSpikeDepthWiseConv*    dw_conv = NULL;
   CNeuronSpikeConvBlock*        conv = NULL;
   CNeuronTransposeOCL*          transp = NULL;
   CNeuronMultiScaleExcitation*  excitation = NULL;
   CNeuronSpikeConvGRU2D*        gru = NULL;
   uint index = 0;
//--- Prepare
   norm = new CNeuronBatchNormOCL();
   if(!norm ||
      !norm.Init(0, index, OpenCL, dimension_in, iBatch, optimization) ||
      !cPrepare.Add(norm))
     {
      DeleteObj(norm)
      return false;
     }
   index++;
   stack = new CNeuronCreateFlow();
   if(!stack ||
      !stack.Init(0, index, OpenCL, units_in, dimension_in, dimension_in, 1, optimization, iBatch) ||
      !cPrepare.Add(stack))
     {
      DeleteObj(stack)
      return false;
     }
   index++;
   adm = new CNeuronSpikeADM();
   if(!adm ||
      !adm.Init(0, index, OpenCL, dimension_in, units_in, 1, optimization, iBatch) ||
      !cPrepare.Add(adm))
     {
      DeleteObj(adm)
      return false;
     }
   index++;

Next come multiscale feature encoders, which can be compared to a group of observers simultaneously capturing small fluctuations and global trends: one sees local impulses, while another sees broad trends.

//--- Feature Encoder HD
   uint units = (units_in + 1) / 2;
   dw_conv = new CNeuronSpikeDepthWiseConv();
   if(!dw_conv ||
      !dw_conv.Init(0, index, OpenCL, dimension_in, dimension_in, 5, 2, units, 1, optimization, iBatch) ||
      !cFeatureEncoder[0].Add(dw_conv))
     {
      DeleteObj(dw_conv)
      return false;
     }
   index++;
   units = (units + 1) / 2;
   dw_conv = new CNeuronSpikeDepthWiseConv();
   if(!dw_conv ||
      !dw_conv.Init(0, index, OpenCL, dimension_in, bottleneck, 5, 2, units, 1, optimization, iBatch) ||
      !cFeatureEncoder[0].Add(dw_conv))
     {
      DeleteObj(dw_conv)
      return false;
     }
   index++;
   if(!cDiffEncoder.Init(0, index, OpenCL, bottleneck, units, bottleneck, shifts, optimization, iBatch))
      return false;
   index++;

These analysis branches create a rich and informative feature representation in which each signal has its place and receives due attention.

//--- Feature Encoder LD
   units = (units + 1) / 2;
   dw_conv = new CNeuronSpikeDepthWiseConv();
   if(!dw_conv ||
      !dw_conv.Init(0, index, OpenCL, bottleneck, 2 * bottleneck, 5, 2, units, 1, optimization, iBatch) ||
      !cFeatureEncoder[1].Add(dw_conv))
     {
      DeleteObj(dw_conv)
      return false;
     }
   index++;
   if(!cCorrelation.Init(0, index, OpenCL, 2 * bottleneck, units, bottleneck, max_displacement,
                                                                         optimization, iBatch))
      return false;
   index++;
   dw_conv = new CNeuronSpikeDepthWiseConv();
   if(!dw_conv ||
      !dw_conv.Init(0, index, OpenCL, 2 * bottleneck, 2 * bottleneck, 5, 1, units, 1, optimization, iBatch) ||
      !cCorrelationUpsampling.Add(dw_conv))
     {
      DeleteObj(dw_conv)
      return false;
     }
   index++;

The context encoder builds a global picture of motion, linking local spikes and long-term changes, much like an experienced trader who assesses the market as a whole rather than individual instruments.

//--- Conext Encoder
   units = (units_in + 1) / 2;
   dw_conv = new CNeuronSpikeDepthWiseConv();
   if(!dw_conv ||
      !dw_conv.Init(0, index, OpenCL, dimension_in, dimension_in, 10, 2, units, 1, optimization, iBatch) ||
      !cConextEncoder.Add(dw_conv))
     {
      DeleteObj(dw_conv)
      return false;
     }
   index++;
   units = (units + 1) / 2;
   dw_conv = new CNeuronSpikeDepthWiseConv();
   if(!dw_conv ||
      !dw_conv.Init(0, index, OpenCL, dimension_in, bottleneck, 10, 2, units, 1, optimization, iBatch) ||
      !cConextEncoder.Add(dw_conv))
     {
      DeleteObj(dw_conv)
      return false;
     }
   index++;

The difference encoder captures the dynamics between successive states of the flow — like tracking price changes on one-minute charts to identify impulses and predict the next move.

The correlation pathway identifies stable relationships between time windows, linking past events to current trends. Its role can be compared to that of an algorithm for finding recurring patterns on a chart. It helps us understand how certain changes affect others, providing a comprehensive understanding of the structure of movement. In this process, correlations and local features are combined and passed through adaptive amplification and integration blocks, where each element is assigned the correct weight and influence, just as if an analyst were deciding which signal is more important for the forecast.

The final flow prediction block carefully integrates all levels of information — local and global features, difference maps, correlations, and context.

//--- Flow
   neuron = new CNeuronBaseOCL();
   if(!neuron ||
      !neuron.Init(0, index, OpenCL, 4 * bottleneck, optimization, iBatch) ||
      !cFlow.Add(neuron))
     {
      DeleteObj(neuron)
      return false;
     }
   neuron.SetActivationFunction(None);
   index++;
   excitation = new CNeuronMultiScaleExcitation();
   if(!excitation ||
      !excitation.Init(0, index, OpenCL, bottleneck, units, 4, (bottleneck + 1) / 2,
                                                            optimization, iBatch) ||
      !cFlow.Add(excitation))
     {
      DeleteObj(excitation)
      return false;
     }
   index++;
   conv = new CNeuronSpikeConvBlock();
   if(!conv ||
      !conv.Init(0, index, OpenCL, 4 * bottleneck, 4 * bottleneck, bottleneck, units,
                                                           1, optimization, iBatch) ||
      !cFlow.Add(conv))
     {
      DeleteObj(conv)
      return false;
     }
   index++;
   dw_conv = new CNeuronSpikeDepthWiseConv();
   if(!dw_conv ||
      !dw_conv.Init(0, index, OpenCL, bottleneck, bottleneck, 3, 1, units, 1, optimization, iBatch) ||
      !cFlow.Add(dw_conv))
     {
      DeleteObj(dw_conv)
      return false;
     }
   index++;
   gru = new CNeuronSpikeConvGRU2D();
   if(!gru ||
      !gru.Init(0, index, OpenCL, units, bottleneck, bottleneck, optimization, iBatch) ||
      !cFlow.Add(gru))
     {
      DeleteObj(gru)
      return false;
     }
   index++;
   transp = new CNeuronTransposeOCL();
   if(!transp ||
      !transp.Init(0, index, OpenCL, units, bottleneck, optimization, iBatch) ||
      !cFlow.Add(transp))
     {
      DeleteObj(transp)
      return false;
     }
   index++;
   conv = CNeuronSpikeConvBlock();
   if(!conv ||
      !conv.Init(0, index, OpenCL, units, units, units_out, bottleneck, 1, optimization, iBatch) ||
      !cFlow.Add(conv))
     {
      DeleteObj(conv)
      return false;
     }
   index++;
   transp = new CNeuronTransposeOCL();
   if(!transp ||
      !transp.Init(0, index, OpenCL, bottleneck, units_out, optimization, iBatch) ||
      !cFlow.Add(transp))
     {
      DeleteObj(transp)
      return false;
     }
//---
   return true;
  }

The result is a unified, coherent motion representation, in which each signal plays a role in generating the forecast and makes its own contribution.

The architecture is designed so that data passes through the entire pipeline sequentially. However, each module remains flexible and adaptive, allowing it to process complex, high-frequency event streams without losing accuracy.

As a result, CNeuronEDCFlow becomes a fully-fledged system. Each block performs a strictly defined function, and the combined operation of all components creates a precise, stable, and efficient motion model. This pipeline transforms disparate computational operations into a cohesive architecture capable of analyzing event streams at a level close to that of the real market, providing a reliable and informative assessment of market dynamics.

The forward pass algorithm can be viewed as a complex analytical process in the market, where each block plays its own role. The results combine to form a complete picture of the movement. At the input stage, we have a stream of events — much like the stream of price fluctuations and trading volumes in the market, which is still unstructured and chaotic.

bool CNeuronEDCFlow::feedForward(CNeuronBaseOCL *NeuronOCL)
  {
   CNeuronBaseOCL* prev = NeuronOCL;
   CNeuronBaseOCL* curr = NULL;
//--- Prepare
   for(int i = 0; i < cPrepare.Total(); i++)
     {
      curr = cPrepare[i];
      if(!curr ||
         !curr.FeedForward(prev))
         return false;
      prev = curr;
     }

First, the signal passes through the cPrepare preprocessing block. Here, the data is normalized, distributed, and structured. You can think of this as an analyst's initial filter, which removes noise and aligns signals, allowing them to be processed further without distortion. At this stage, a basic representation of the flow is formed, ready for multiscale analysis.

Next, the feature encoders come into play, acting as a team of observers. Some track local impulses — sharp price spikes and short-term fluctuations. Others take a broader view, tracking long-term trends and patterns. As a result, the signal takes on a multi-layered structure: fine details are preserved, and overall trends are taken into account. The channels are gradually compressed, creating a compact yet informative feature representation.

//--- Feature Encoder
   for(uint fe = 0; fe < cFeatureEncoder.Size(); fe++)
     {
      for(int i = 0; i < cFeatureEncoder[fe].Total(); i++)
        {
         curr = cFeatureEncoder[fe][i];
         if(!curr ||
            !curr.FeedForward(prev))
            return false;
         prev = curr;
        }
     }

The next step is the context encoder cConextEncoder. It provides a broad perspective on the event stream, aggregating global dependencies and connections between features. You could compare this to an analyst who evaluates the entire market as a whole.

//--- Context Encoder
   prev = cPrepare[-1];
   for(int i = 0; i < cConextEncoder.Total(); i++)
     {
      curr = cConextEncoder[i];
      if(!curr ||
         !curr.FeedForward(prev))
         return false;
      prev = curr;
     }

Next, the motion encoders are activated. cDiffEncoder generates temporal difference maps by tracking signal changes between consecutive states, as if recording the speed and direction of impulses on a chart.

//--- Motion Encoder
   if(!cDiffEncoder.FeedForward(cFeatureEncoder[0][-1].AsObject()))
      return false;
   if(!cCorrelation.FeedForward(cFeatureEncoder[1][-1].AsObject()))
      return false;

In parallel, cCorrelation identifies stable relationships between time windows—as if we were looking for recurring market patterns, linking the past to the present. The results of the correlation analysis are then passed through the cCorrelationUpsampling block to increase their resolution so that they can be correctly combined with the other features.

   prev = cCorrelation.AsObject();
   for(int i = 0; i < cCorrelationUpsampling.Total(); i++)
     {
      curr = cCorrelationUpsampling[i];
      if(!curr ||
         !curr.FeedForward(prev))
         return false;
      prev = curr;
     }

In the final stage, all features are brought together in the cFlow block. Here, local patterns, global dependencies, difference maps, and correlations are integrated into a unified motion representation.

   curr = cFlow[0];
   uint units = cDiffEncoder.GetUnits();
   uint bottleneck = cDiffEncoder.GetFilters();
   if(!curr ||
      !Concat(cFeatureEncoder[0][-1].getOutput(), cConextEncoder[-1].getOutput(),
              cDiffEncoder.getOutput(), prev.getOutput(), curr.getOutput(),
              bottleneck, bottleneck, bottleneck, bottleneck, units))
      return false;
   prev = curr;
   for(int i = 1; i < cFlow.Total(); i++)
     {
      curr = cFlow[i];
      if(!curr ||
         !curr.FeedForward(prev))
         return false;
      prev = curr;
     }

Successive layers carefully process the data, amplifying key signals and preserving spatiotemporal relationships. It's as if several analytical tools were working together to produce a final forecast of market movements.

Finally, the signal is passed to the parent class, which summarizes the results, ensuring consistency with the overall architecture and preparing the output for subsequent computations or training.

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

The forward pass algorithm ensures consistent, end-to-end data processing. Each block plays its own role, and the combined work of all components creates an accurate, informative, and stable motion representation that fully embodies the EDCFlow concept.


Testing

We have completed the work of developing our own interpretation of the approaches proposed by the authors of the EDCFlow framework and have implemented them using MQL5. The theoretical aspects and architectural solutions have now taken on a thoroughly practical form. And the logical next step is to test their actual effectiveness in solving trading problems. This is where the architecture must prove its worth — not on paper, but under real market conditions.

As in previous studies, we are building a trading model capable of independently analyzing market conditions and making decisions without rigidly defined rules. It is important to note, however, that integrating EDCFlow does not require a complete overhaul of the trading system's architecture. We implement the approaches proposed by the framework's authors in a targeted manner — specifically in the Environment Analysis Encoder — by replacing only the last layer of the previously used model with a new top-level object, CNeuronEDCFlow.

This approach ensures the continuity of the experiments and the validity of the comparisons between results. It allows us to isolate the contribution of EDCFlow as a tool for extracting and interpreting complex spatiotemporal market relationships. The complete architecture of the trainable models is provided in the attachment and is available for self-study.

The experimental part of our work began with an offline training phase using historical data for the EURUSD currency pair on the M1 timeframe, covering the period from January 2024 to June 2025. At this stage, the model operated in a steady, controlled manner, gradually building a basic understanding of the market structure. It learned to recognize recurring patterns, track price movements, analyze volume distribution, and identify stable relationships between key features. Gradually, a holistic representation of the market took shape within the model.

After offline training was completed, the model was transferred to the MetaTrader 5 Strategy Tester for the online fine-tuning phase. Here, the conditions were much closer to a real trading environment. The data stream was no longer static: it contained market noise, sharp price moves, and shifts in market regimes. In this mode, the model adapted to the current dynamics, carefully adjusting its internal representations without disrupting previously established patterns. This approach made it possible to link accumulated historical experience with current market conditions, resulting in more balanced and timely trading decisions.

The final stage of the evaluation was conducted using data from July through October 2025, which was entirely new and had not been used previously in the training process. All model parameters remained unchanged, which is essential for an objective assessment of the model's performance. Under these conditions, the model's ability to generalize accumulated knowledge, correctly interpret unfamiliar market situations, and maintain stability when operating outside the training sample was tested. It was this stage that made it possible to assess the practical applicability of the proposed approach and its readiness for use in a real-world trading environment.

Based on the test results, the financial outcome was positive. With an initial deposit of 100 USD, the model ended the period with a net profit of 23.51 USD, which corresponds to a return of approximately 23.5%. This is not an aggressive return, but it is a solid result. This is especially significant given that the strategy was not optimized for a specific historical period and operated by generalizing previously learned patterns. Even at this stage, it is clear that the model is capable of extracting useful information from market dynamics and converting it into a positive expected value.

The ratio of gross profit to gross loss was moderate. With a total profit of 182.09 USD and losses of 158.58 USD, the Profit Factor was approximately 1.15. This value cannot be described as high, but it consistently exceeds one and confirms the presence of a positive expected value.

The risk metrics were the most revealing part of the results. The maximum balance drawdown reached 37%, while the maximum equity drawdown was nearly 46%. This discrepancy between balance and equity indicates that the model holds losing positions for extended periods and experiences significant intra-trade fluctuations. Essentially, this is an aggressive position-holding approach: the model stays in the trade through adverse price fluctuations, relying on the validity of the identified pattern. This aligns well with the EDCFlow architecture, which focuses on analyzing the structure of motion. At the same time, however, it emphasizes the need for stricter risk control at the trading logic level.

The model's trading activity was low. Only 33 trades were executed over the entire period. The model does not react to every local impulse but prefers to enter the market only when there is a clearly defined movement structure. That said, the percentage of profitable trades was less than 50%; however, this is offset by the ratio of average profit to average loss. The average winning trade is substantially larger than the average losing trade, creating an asymmetric return profile characteristic of strategies focused on riding price moves rather than frequent entries.

However, the ability to recover from drawdowns remains a weakness. The Recovery Factor is significantly below one, which means that the current level of profit does not offset the depth of past drawdowns. This once again underscores the fact that we are dealing with a research model.

Taken together, the results obtained allow us to draw a cautious but positive conclusion. The model is functional and has a positive expected value. The EDCFlow encoder does indeed form an informative representation of market dynamics that is sufficient for making trading decisions. However, in its current form, the strategy requires improved risk management, limits on equity drawdowns, and more carefully designed logic for exiting losing positions.


Conclusion

We went through the entire process carefully and systematically. From the theoretical concepts developed by the authors of EDCFlow to their practical implementation using MQL5 and rigorous testing on real historical data. Without simplifications. Without tweaking the model to obtain the desired result. This is exactly how complex models intended for use in a live market should be tested.

The experiment demonstrated the key point: the proposed architectural approaches really do work. The model is capable of forming a meaningful representation of market dynamics, identifying recurring patterns, and making trading decisions without relying on hand-crafted heuristics. A positive expected value, appropriate behavior, and the absence of signs of overfitting confirm the viability of the chosen approach.

At the same time, testing provided a sobering assessment of the weaknesses. High drawdown and a low Recovery Factor make it clear that the architecture for analyzing the market environment is strong, but the risk management module needs refinement. This is a normal stage in the development of any complex trading system. The market does not forgive overconfidence, but it generously rewards discipline.

Another point is worth emphasizing. We deliberately did not chase after impressive numbers. Our goal is to understand the model's behavior and its response to noise, liquidity, and sharp price movements. And in that sense, the results obtained are more valuable than any aggressive optimization. They provide a solid foundation for further development.


Links


Software used in this article

# Name Type Description
1 Study.mq5 Expert Advisor Expert Advisor for offline model training
2 StudyOnline.mq5 Expert Advisor Expert Advisor for online model training
3 Test.mq5 Expert Advisor Expert Advisor for model testing
4 Trajectory.mqh Class library Structure describing the system state and model architectures
5 NeuroNet.mqh Class library Class library for building a neural network
6 NeuroNet.cl Library Code library for the OpenCL program

Translated from Russian by MetaQuotes Ltd.
Original article: /ru/articles/20799

Attached files |
MQL5.zip (3517.81 KB)
Implementing Golden-File Regression Tests for Expert Advisors in MQL5 Implementing Golden-File Regression Tests for Expert Advisors in MQL5
Golden-file testing compares the trade decisions of a modified Expert Advisor with an accepted run, so an unintended logic change appears as changed decisions. CDecisionRecorder writes each recorded request with run context and a tick hash, and CGfFile refuses truncated or malformed files. CGoldenCompare pairs rows by time and returns a verdict that separates changed decisions from different settings or ticks. Random execution delay made the tested runs differ, so compare runs with the same fixed delay or none.
Your Take Profit Is a Guess Until You Log MFE: Building an Excursion Recorder in MQL5 Your Take Profit Is a Guess Until You Log MFE: Building an Excursion Recorder in MQL5
A compact MFE/MAE recorder in pure MQL5 samples excursion while a position is open and writes one CSV row per closed position, measured in R and frozen at entry. A companion script prints a reach-rate table per asset class: the share of trades that ever reached each level. In a 226-position sample, three of the four classes never reached the 3R target the system was using. Use it to test whether a target is reachable before trusting it.
Gating Trades with the Wald-Wolfowitz Runs Test: An O(1) Randomness Filter for Bar Direction Gating Trades with the Wald-Wolfowitz Runs Test: An O(1) Randomness Filter for Bar Direction
A rolling Wald–Wolfowitz runs-test engine classifies recent bar direction as persistent, alternating, or indistinguishable from noise before any entry logic is applied. The package includes full MQL5 source, a chart indicator, a three-mode Expert Advisor (Gated, No gate, Placebo), validation scripts, and an audit log. An 18‑run Strategy Tester matrix with fixed window and critical value, plus a null‑rate calibration on real history, shows how a regime gate changes trade frequency and drawdown.
Building a HalfTrend Channel Indicator in MQL5 Building a HalfTrend Channel Indicator in MQL5
This article builds a HalfTrend Channel indicator in MQL5 that combines rolling price extremes with a HalfTrend baseline and a Wilder‑smoothed ATR(100) to form adaptive channel boundaries. It explains the trend‑state machine, ATR smoothing, and the logic for detecting close‑price crossings of the bands. The result helps you study confirmed directional shifts and price behavior around a volatility‑adjusted reference line.