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

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

MetaTrader 5 — Trading systems |
64 1
Dmitriy Gizlyk
Dmitriy Gizlyk

Introduction

The financial market breathes, contracts, bursts with momentum, and holds its breath in anticipation. It is precisely in these transitions that the key information about future movement is hidden. Most analysis and forecasting algorithms traditionally view the market as a sequence of states linked by their degree of similarity. They look for correlations, measure consistency, and assess how similar the current state is to the previous one. There is some logic to this, but there is also a limitation — the market’s turning points are precisely where its behavior changes.

The framework for difference-based modeling of market microstructure proposed in the paper "EDCFlow: Exploring Temporally Dense Difference Maps for Event-based Optical Flow Estimation" is based on this observation. It retains correlation as a source of a stable representation of motion, but supplements it with a temporally dense difference map between adjacent states of the flow. Thus, the analysis proceeds along two axes simultaneously — similarity between states provides context, while their differences reveal the point at which the dynamics change. This approach amplifies impulses and captures local changes in the structure of motion without waiting for statistical data to accumulate. A difference-based representation allows for a faster response to changes than when using only correlation-based methods.

If we think of the market as a flow, then classical correlation methods study the shape of the wave. The difference-based approach captures its breaks, acceleration, changes in direction, and sudden changes in the intensity of market activity. This is a fundamentally different perspective on dynamics. It is this very concept that forms the foundation of EDCFlow. It does not replace traditional methods, but rather enhances them, providing a more comprehensive and informative view of market movements.

Traditional flow models view the market as a sequence of states between which a correspondence is sought. This is like comparing two snapshots of a chart and assessing their similarity. This works well in stable market regimes, when movements are smooth, but begins to lag when impulses, sharp shifts in liquidity, and market regime changes occur. The difference-based augmentation allows these changes to be captured immediately, preserving important information about the market's microstructure.

An important advantage of the framework is its focus on micro-movements. This is not about the direction of the price in the usual sense, but about the nature of the movement — whether it is fast or sluggish, a sudden surge or a series of small steps, coordinated or marked by internal contradictions. Difference-based analysis captures these nuances directly, amplifying the impulses, making them noticeable, and responding to their emergence. This is especially important in short-term and intraday strategies, where even a delay of just a few bars reduces effectiveness.

EDCFlow serves as a representation layer for market dynamics. Infrastructure that shows the market as it really is. It's like switching from a standard candlestick chart to a trade stream. Candlesticks are convenient and familiar, but they hide important details, whereas the trade stream reflects the actual market dynamics. The difference-based framework performs a similar task for neural network-based models.

The difference-based augmentation of correlation also enhances resilience to changes in market regimes. Correlation assumes that patterns repeat, whereas a difference map captures the moment of change. This reduces the risk of algorithmic blindness during transitional phases, when most strategies cease to work. At the same time, the framework remains flexible. It can be used as an input layer for classical neural networks and recurrent models, enhancing any algorithm by providing a more informative representation of the market.

From a practical trading perspective, this approach is similar to the intuition of an experienced trader. A trader keeps the big picture of the market in mind (analogous to correlation) but makes decisions based on deviations and atypical movements (analogous to differences). EDCFlow formalizes this intuition, making it accessible to algorithms. At the same time, computational efficiency is maintained, and there is no need to abandon cumbersome correlation structures. The difference map merely supplements them, increasing the model's sensitivity to impulse moves and minimizing delays.


The EDCFlow Algorithm

The EDCFlow framework is based on an event stream representation in which each event is encoded with its coordinate, timestamp, and direction of change. This makes it possible to formalize the data stream and represent it as a spatiotemporal array. Each event in this array contributes not only to the nearest time interval but is also distributed across adjacent time slots, ensuring temporal density in the representation and allowing for the capture of even the slightest changes in market dynamics.

The main task is to estimate dense flow — that is, to predict state changes from the current moment to the next. To this end, the framework's authors propose considering two consecutive event segments: the current segment and the previous segment, which serves as a reference. The previous segment provides context, allowing the model to navigate the stream structure, while the current segment captures the latest changes — those that need to be analyzed. This approach strikes a balance between a stable market context and sensitivity to instantaneous changes.

The EDCFlow architecture is built around three key stages. The first is feature extraction. The feature encoder generates a two-level representation of the data, allowing us to identify differences between states at high resolution while simultaneously constructing a low-resolution, aggregated representation for global analysis of the data stream. The context encoder adds additional information about the overall structure of the data, similar to how a trader assesses the big picture based on current market depth and volume dynamics.

The second stage is motion encoding. At low resolution, correlation features are retained and encoded through matching and spatiotemporal encoding. They are then scaled and combined with temporally dense changes captured by a multiscale difference layer. This allows the model to capture instantaneous impulses. These two complementary motion representations are combined through an attention layer that adaptively weights correlation and difference information. This mechanism makes the model sensitive to small movements, while preserving the overall flow structure.

The third stage is flow update. The residual flow is decoded using a GRU, which refines the current motion estimates based on the combined features. Motion encoding and flow updates are performed iteratively, allowing the model to gradually refine its prediction and account for the sequence of events at all levels.

Accurately capturing the market's temporal dynamics is a key step in the model's operation. The framework's authors divide the segment of the event stream being analyzed into several consecutive time windows. Each window captures local changes, and the previous segment is used as a reference. The result is a sequence of several time blocks, each containing unique information about how the market evolves. This structure allows the model to track the evolution of features over several consecutive time intervals.

A structured representation of the flow is created for each time block. Each event is distributed across the two nearest time slots, ensuring dense coverage. This creates a spatiotemporal representation of the flow, in which every microscopic detail is recorded and can be used for analysis. As a result, the model becomes highly sensitive to market impulses, sudden changes in liquidity, and abrupt shifts in market structure, which is particularly important for short-term and intraday strategies.

Next, an encoder with shared weights extracts features at two resolution levels. High resolution captures local, subtle changes — such as brief spikes in price or volume. Small but significant fluctuations. Low resolution produces a smoother, global representation of the flow that reflects the overall market trend. This two-level architecture allows the model to simultaneously account for both micro-movements and the market's macrostructure, striking a balance between sensitivity to noise and the preservation of global consistency.

To conserve computational resources and memory, a low-resolution 4D feature correlation tensor is generated to match features between the segment's first and last time windows. This tensor serves as a correspondence map between different points in time within the flow, enabling the identification of stable relationships between market segments and ensuring accurate matching. In a financial context, this means that the model can see how local changes relate to overall market dynamics and can identify patterns that are not apparent when data is simply averaged.

A context encoder, built using a similar architecture, adds information about the global structure of the flow. It captures stable market elements and forms the basis for subsequent updates to the predicted flow. Thus, the model simultaneously looks into the distance, assessing the big picture, and looks up close, noting every change.

To accurately predict motion, the framework's authors use high-resolution difference maps and a low-resolution correlation volume, combined into a single representation. This approach makes it possible to assess flow dynamics as effectively as possible and ensures a high degree of accuracy in forecasting short-term changes. The architecture is designed as an iterative scheme: at each iteration, the current motion estimate is refined, the search space is narrowed, and sensitivity to local impulses is increased.

The correlation encoder plays a key role in capturing long-term dependencies in the flow. Difference maps capture instantaneous changes between adjacent time windows, but do not provide a direct correspondence between distant segments. Low-resolution correlation coefficients solve this problem. They capture relationships between the beginning and end of a market segment, enabling the model to identify consistent patterns. In practice, this is achieved by constructing correlation matrices for each time window, followed by upscaling to a high resolution and encoding the features using convolutional blocks. This mechanism makes it possible to quickly and effectively account for local and global dependencies.

Multiscale encoding of temporal differences makes it possible to capture continuous market movements in great detail. To do this, the features of each time window are aligned with respect to the reference segment using the current flow estimate. Over short time intervals, the motion can be considered linear, which simplifies the calculation of dense difference maps. After the differences are calculated, channel dimensionality is reduced, which lowers memory requirements and speeds up computation. Spatial filtering is also added, which smooths out edges and highlights significant changes.

A multiscale sampling strategy is used to process movements of varying speeds. Rapid changes are recorded over short intervals, while slow changes are recorded over longer intervals. For each scale, a sequence of difference maps is generated and then processed by 3D convolutions that reconstruct spatiotemporal features and restore channels for further processing. This approach accounts for the diversity of market patterns and speeds up data integration into subsequent modules.

Adaptive fusion through attention effectively combines correlation features and difference features. Correlation establishes a stable structure of market movement, while difference maps capture local impulses and sharp changes. Attention mechanisms combine the features into a unified representation of motion, with the model itself determining what to focus on. This is particularly important for intraday or high-frequency analysis, when impulses and noise can alternate rapidly.

The iterative flow update is performed using a GRU. It receives contextual features and fused motion features as input, calculates the residual flow, and refines the current estimate of market movement. Iteratively performing encoding and flow updates allows the model to gradually improve prediction accuracy by taking global trends and local impulses into account. Each iteration narrows the search area, making the model more accurate and responsive to real-time changes.

In practice, this is implemented as a sequential computational pipeline. Features for each time window are generated using encoders, and difference maps and a correlation tensor are created. The features are combined through an attention layer and fed into a GRU to compute the residual flow. Iterative refinement allows information about local changes and the global structure of the flow to be integrated smoothly, creating an adaptive and informative representation of the market. This approach makes it possible to directly use the results to generate trading signals, assess short-term changes, and make price movement forecasts.

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

Author's visualization of the EDCFlow framework


Implementation in MQL5

After a detailed examination of the theoretical foundations of the EDCFlow framework, it makes sense to move from abstractions to practice. The next step is to implement one possible configuration of the proposed approaches in MQL5. Here, theory ceases to be a neat model and becomes a working mechanism capable of processing the actual flow of market events.

We are deliberately choosing not to simply copy the architecture, but rather to adapt it to meet our needs. This is an engineering trade-off familiar to every trader: preserve the essence, eliminate the unnecessary, and reinforce what truly provides an advantage. As a result, EDCFlow is transformed from an academic framework into an applied model for analyzing market microstructure, suitable for optimization and subsequent integration into a trading system.

The Process of Calculating Differences

It makes sense to begin the practical implementation by organizing the core processes. This is where the foundation for all future work is laid. A key innovation of the EDCFlow framework is the use of state differences with varying offsets along the time axis. Essentially, we analyze not only where the market stands, but also exactly how it arrived at this point. At what speed. With what rhythm. And with what intermediate changes.

This approach almost automatically leads to a large number of similar operations. Differences are calculated for different time windows, with different lags, using the same data arrays. It's similar to a trader who monitors several time frames at once. The logic is the same, but there is a lot of data and even more computation. In a conventional CPU implementation, this kind of load quickly becomes a bottleneck. Especially when we are dealing not with retrospective analysis, but with a live market.

And we're actually planning to use the model in real time. This is a crucial point. There is no room here for lengthy deliberation or computationally intensive loops. Decisions must be made quickly, and calculations must be completed within strict time frames. Therefore, we need solutions that require minimal processing time for a large set of elementary operations.

In this context, using a GPU seems not only logical but practically the only option. A graphics processing unit is ideal for performing computations of the same type in parallel, such as calculating differences, correlations, and intermediate features. Tasks that run sequentially and take a long time on the CPU become a stream of simple, independent operations processed simultaneously on the GPU.

To implement difference-based analysis on the GPU, we create a new kernel in our OpenCL program. It is here that the idea of differences between states with different time offsets first takes concrete form in code. The DilatedDifference kernel serves as the workhorse of the entire architecture, performing large numbers of operations of the same type that are therefore ideally suited to parallel execution.

__kernel void DilatedDifference(__global const float* feature,
                                __global const int* shifts,
                                __global float* differences
                               )
  {
   const size_t main = get_global_id(0);
   const size_t sh = get_global_id(1);
   const size_t d = get_global_id(2);
   const size_t units = get_global_size(0);
   const size_t total_shifts = get_global_size(1);
   const size_t dimension = get_global_size(2);

The kernel's logic is extremely straightforward. Each computational thread corresponds to a specific market state, a specific time offset, and a specific dimension of the feature space. This three-dimensional index allows all combinations of states, lags, and features to be processed simultaneously without nested loops. The GPU is in its element here, performing thousands of simple subtraction operations in parallel, without unnecessary checks or delays.

The feature array contains the input features describing the market state, already prepared in the previous step. The shifts array specifies time offsets, effectively determining which states will be compared with one another. This is the key element of the difference-based approach. We don't just compare adjacent time points; we can specify an arbitrary lag structure tailored to the current task and the nature of the market.

Before calculating the difference, a basic check is performed to verify that the index is valid. If the offset state falls outside the valid bounds, the result is set to zero. This simple solution eliminates unnecessary branches in the main logic and makes the kernel's behavior predictable.

   const int slave = shifts[sh];
   if(slave < 0 || slave >= units)
     {
      differences[RCtoFlat(main, d, units, dimension, sh)] = 0;
      return;
     }

Next, the feature values are retrieved from global memory, with additional protection against invalid numbers. Under real-world market conditions, such checks are not a luxury but a necessity.

   float value_main = IsNaNOrInf(feature[RCtoFlat(main, d, units, dimension, 0)], 0);
   float value_slave = IsNaNOrInf(feature[RCtoFlat(slave, d, units, dimension, 0)], 0);

The calculation of the difference itself is extremely straightforward. The value of the offset state is subtracted from the value of the current state. No magic. Just pure math. It is precisely this simplicity that gives the approach its power. The output is a dense array of differences, where each cell reflects the change in a specific feature between two points in market time separated by a specified time lag.

   float result = value_main - value_slave;
//---
   differences[RCtoFlat(main, d, units, dimension, sh)] = result;
  }

It is important to note that this kernel scales almost linearly. Adding new offsets or increasing the dimensionality of features does not change the structure of the code; it merely expands the computational grid. This is critical for real-time operation, where the number of lags analyzed can be adjusted based on the market phase.

As a result, DilatedDifference becomes a fundamental building block of the entire EDCFlow implementation. It translates the concept of difference-based modeling from theory into practice. The market is no longer viewed here as a static sequence of states. It transforms into a dynamic field of change, where every movement, every shift, and every impulse is quantified — quickly, in parallel, and with minimal latency.

However, it is important to make a fundamental clarification here. Although the algorithm for computing differences does not contain any trainable parameters, this does not in any way relieve us of the need to implement proper backpropagation. We use differences not as an external analytical indicator, but as an internal component of the model being trained. This means that each such operator must be differentiable and must fit correctly into the overall computation graph. As we all know, the market doesn't forgive mistakes.

This is precisely why a separate OpenCL kernel, DilatedDifferenceGrad, is created to propagate gradients back to the original features. Its task is to accurately and efficiently accumulate the contributions of all temporal offsets to the total state gradient. Essentially, we're solving the inverse problem. While in the forward pass each state affected many differences, in the backward pass each difference must return its contribution to all the states involved.

__kernel void DilatedDifferenceGrad(__global const float* feature,
                                    __global float*       feature_gr,
                                    __global const int*   shifts,
                                    __global const float* differences_gr,
                                    const int total_shifts
                                   )
  {
   const size_t id = get_global_id(0);
   const size_t loc = get_local_id(1);
   const size_t d = get_global_id(2);
   const size_t units = get_global_size(0);
   const size_t total_loc = get_local_size(1);
   const size_t dimension = get_global_size(2);
//---
   __local float temp[LOCAL_ARRAY_SIZE];

The kernel's logic reflects this idea with the utmost clarity. For each state and each dimension of the feature space, we sequentially examine all specified offsets. If the current state served as the base state, its gradient increases. If it served as the offset state, its gradient decreases. This follows directly from the definition of the difference, without any heuristics or simplifications. The math here is as strict as a balance sheet: everything that was subtracted must be added back with the correct sign.

   float result = 0.0f;
   for(int sh = loc; sh < total_shifts; sh += total_loc)
     {
      const int offset = shifts[sh];
      int slave = id + offset;
      if(slave >= 0 && slave < units)
        {
         // id — main
         result += IsNaNOrInf(differences_gr[RCtoFlat(id, d, units, dimension, sh)], 0.0f);
         // id — slave
         result -= IsNaNOrInf(differences_gr[RCtoFlat(slave, d, units, dimension, sh)], 0.0f);
        }
     }

Special attention has been paid to performance. Gradients are accumulated across offsets using local memory and reduction within the work-group. This helps avoid atomic operations and unnecessary accesses to global memory, which is critical for real-time operation. This approach scales well and maintains a consistent speed even as the number of time lags and the dimensionality of the features increase.

   result = LocalSum(result, 1, temp);
   if(loc == 0)
      feature_gr[RCtoFlat(id, d, units, dimension, 0)] = result;
  }

It is also important to note that this kernel is completely symmetric with respect to the forward pass. It does not introduce any new assumptions and does not alter the structure of the computational graph. This makes the model stable during training and allows difference-based layers to be integrated without restrictions into more complex architectures — with recurrent blocks, attention mechanisms, and iterative state updates.

As a result, we achieve an important practical outcome. Difference-based analysis in EDCFlow remains simple at its core, yet it plays a full-fledged role in the learning process. It doesn't just calculate market changes; it actively shapes the gradient field, influencing the tuning of the entire model. This is exactly the kind of situation where rigorous mathematics, sound engineering, and sound trading judgment all come together.

Depthwise convolution

The next point worth paying special attention to concerns the framework authors' choice of the DW-3DConvs mechanism — that is, three-dimensional depthwise convolutions. At first glance, this may seem like a minor technical detail, but this is precisely where the line is drawn between an architecture suitable for offline experiments and a model capable of working with the market in real time.

Three-dimensional convolution fundamentally expands upon the classical approach. It takes into account not only the spatial dimensions of the features, but also the time axis. In financial market terms, this means that the model stops analyzing isolated data snapshots and begins to work with a sequence of states. Price, volume, and derived features are treated as a continuous flow, in which not only magnitude but also the dynamics of change matter. It is precisely this perspective that aligns with the EDCFlow philosophy, in which market movement is described through the evolution of states rather than a set of static values.

The separation of channels inherent in the Depthwise approach solves several practical problems at once. The convolution is applied to each feature channel independently, without mixing them prematurely. This drastically reduces the number of parameters and computational operations. But, more importantly, it preserves the local characteristics of the signal. This is critical for trading. The market rarely moves in an averaged-out way. Trading decisions hinge on subtle shifts that can easily be lost through aggressive feature aggregation.

The framework's authors rightly point out that simply summing or concatenating difference maps of features results either in a loss of detail or in a sharp increase in computational complexity. In the first case, the model loses its sensitivity to local impulses. In the second case, it becomes too computationally demanding for practical use. DW-3DConvs strike a balance between these two extremes. They effectively aggregate multiscale motion features while preserving the spatiotemporal structure of the flow without overloading the processing pipeline.

In our implementation, we use a separate object integrated into the overall model pipeline to implement the Depthwise approach. To do this, we introduce a new class, CNeuronSpikeDepthWiseConv, which inherits from the spiking convolutional block and fits seamlessly into the existing hierarchy of neural components.

class CNeuronSpikeDepthWiseConv  :  public CNeuronSpikeConvBlock
  {
protected:
   CNeuronTransposeVRCOCL           cTranspose[2];
   CNeuronMultiWindowsConvWPadOCL   cDepthConv;
   CNeuronBatchNormOCL              cNorm;
   //---
   virtual bool      feedForward(CNeuronBaseOCL *NeuronOCL) override;
   virtual bool      updateInputWeights(CNeuronBaseOCL *NeuronOCL) override;
   virtual bool      calcInputGradients(CNeuronBaseOCL *NeuronOCL) override;

public:
                     CNeuronSpikeDepthWiseConv(void) {};
                    ~CNeuronSpikeDepthWiseConv(void) {};
   //---
   virtual bool      Init(uint numOutputs, uint myIndex, COpenCLMy *open_cl,
                          uint chanels_in, uint chanels_out,
                          uint depth_window, uint depth_step,
                          uint units, uint variables,
                          ENUM_OPTIMIZATION optimization_type, uint batch);
   //---
   virtual int       Type(void) override const  {  return defNeuronSpikeDepthWiseConv;   }
   //--- 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 void      SetActivationFunction(ENUM_ACTIVATION value) override { };
   virtual void      SetOpenCL(COpenCLMy *obj)   override;
   virtual void      TrainMode(bool flag) override;
  };

The class structure directly reflects the logic of DW-3DConvs, adapted for streaming market data processing. Transposition blocks are used at the input and output to convert the data into a format suitable for depthwise convolution and back again. This is an important point. In the Depthwise architecture, the order of dimensions is critical, and explicit control over tensor representations helps avoid hidden transformations and unnecessary data copies.

The central element is the cDepthConv object, which is responsible for convolution along the time dimension with padding. This is where the concept of independent processing of feature channels is implemented. Each channel is analyzed within its own temporal context, without being prematurely combined with other features. For financial flows, this means that the model can separately track the dynamics of price, volume, or derived characteristics while preserving their individual patterns of movement.

The initialization method sets the block's key parameters and, in essence, defines its internal architecture. It is here that the abstract concept of Depthwise is transformed into a concrete computational scheme.

bool CNeuronSpikeDepthWiseConv::Init(uint numOutputs, uint myIndex, COpenCLMy *open_cl,
                                     uint chanels_in, uint chanels_out,
                                     uint depth_window, uint depth_step,
                                     uint units, uint variables,
                                     ENUM_OPTIMIZATION optimization_type, uint batch)
  {
   if(!CNeuronSpikeConvBlock::Init(numOutputs, myIndex, open_cl, chanels_in, chanels_in,
                                   chanels_out, units, variables, optimization_type, batch))
      return false;

The first step is to transfer control to the parent class. This allows the new object to be integrated immediately into the overall model pipeline and to inherit all the necessary infrastructure. Importantly, the numbers of input and output channels are set at this stage so that the Depthwise operation preserves dimensional consistency. We deliberately maintain the symmetry of the channels, emphasizing the independent processing of each feature.

Next, two transposition blocks are initialized sequentially. The first one prepares the data for depthwise convolution by reordering the dimensions.

   uint index = 0;
   if(!cTranspose[0].Init(0, index, OpenCL, variables, units * depth_step,
                                        chanels_in, optimization, iBatch))
      return false;
   cTranspose[0].SetActivationFunction(None);

This is a purely technical point, but one of fundamental importance. In the Depthwise architecture, an incorrect dimension order inevitably leads either to reduced performance or to a distortion of the intended meaning of the computations.

The second transposition block performs the inverse transformation, converting the data back to the format expected by the rest of the model.

   index++;
   if(!cTranspose[1].Init(0, index, OpenCL, variables, chanels_in, units,
                                                   optimization, iBatch))
      return false;
   cTranspose[1].SetActivationFunction(None);
   index++;

Both blocks operate without any activation functions, since their sole purpose is to represent the data accurately, without introducing any nonlinearities.

Configuring the cDepthConv object is a key part of the initialization process. This is where you specify the time window size and the depth step, which determine which specific segments of the time series will be aggregated.

   uint windows[] = { depth_window };
   if(!cDepthConv.Init(0, index, OpenCL, windows, depth_step, 1, units,
                         chanels_in * variables, optimization, iBatch))
      return false;
   cDepthConv.SetActivationFunction(None);
   index++;

Each channel is processed independently, while taking into account the temporal structure of the data. In the context of financial markets, this means that the model analyzes the evolution of each feature over a given time interval without mixing it with other channels at this stage. This type of isolation is particularly valuable when working with difference features, where it is important to preserve the shape of local motion.

After the convolution, the normalization block must be initialized. Its role is difficult to overstate. Difference features and temporal features are highly variable, and without normalization, training quickly becomes unstable. Including normalization directly within the depthwise block helps stabilize the distribution of activations and ensures that gradients are propagated correctly in subsequent training stages. This decision is based on practical experience rather than theory, and it directly affects the model's stability when working with real market data.

   if(!cNorm.Init(0, index, OpenCL, cDepthConv.Neurons(), iBatch, optimization))
      return false;
//---
   return true;
  }

As a result, the initialization method produces a complete, self-contained module. It knows exactly how many channels to process and what time window to use.

The feedForward method is responsible for organizing the forward pass, and its structure clearly reflects the philosophy of the entire block. No magic — just a strict sequence of transformations, in which each step plays its own clearly defined role.

bool CNeuronSpikeDepthWiseConv::feedForward(CNeuronBaseOCL *NeuronOCL)
  {
   if(!cTranspose[0].FeedForward(NeuronOCL))
      return false;

The forward pass begins with the first transposition. The cTranspose[0] block receives a pointer to the source data object and converts the data into a format suitable for depthwise convolution over time. It's like carefully organizing your desk before analyzing a chart: everything is in its place, nothing extra, and no rush.

Control is then passed to the cDepthConv object. This is where the key depthwise convolution operation takes place. Each channel is processed independently, but with consideration for the temporal context. The model does not combine features prematurely, but carefully tracks how each of them evolves within a specified time window.

   if(!cDepthConv.FeedForward(cTranspose[0].AsObject()))
      return false;

After the convolution is performed, the data is converted back to its standard representation using the second transpose block, cTranspose[1]. This reverse step restores the result to a form compatible with the rest of the model's architecture.

   if(!cTranspose[1].FeedForward(cDepthConv.AsObject()))
      return false;

Formally, the operation is simple, but conceptually it closes the local processing loop of the Depthwise block, making it transparent to external components.

The next step is normalization, which stabilizes the distribution of features, smooths out sharp spikes, and evens out the scale. When working with market data, where volatility spikes are the norm rather than the exception, this step acts as a shock absorber. It reduces the model's sensitivity to noise without suppressing useful movements.

   if(!cNorm.FeedForward(cTranspose[1].AsObject()))
      return false;

The forward pass concludes with channel mixing. Depthwise convolution fundamentally works in isolation. Each channel is processed independently. This is a deliberate and justified step. We first allow the model to carefully extract the local temporal dynamics of each feature without the features distorting one another. A classic, cautious approach. First, understand each instrument, and only then put together an ensemble.

But the market is an interconnected system. And at this stage, it's time for synthesis. Calling the method of the same name in the parent class serves as the point where everything comes together. Here, temporal dynamics cease to be a set of isolated responses and become a joint feature space. The channels begin to talk to each other. Carefully, without chaos, under the control of learnable parameters.

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

As a result, the forward pass method appears compact, almost austere. But behind this conciseness lies carefully considered engineering logic. Every step is justified. Each call is in its proper place. The algorithm scales well, is easy to debug, and, most importantly, keeps temporal feature processing interpretable.

The CNeuronSpikeDepthWiseConv object serves as a practical implementation of the concepts behind DW-3DConvs. It retains the key advantages of the approach — efficiency, preservation of motion details, and scalability. At the same time, it adheres to the trading model's strict architectural requirements.


Conclusion

The EDCFlow framework offers a fundamentally new approach to the analysis of market microstructure. Its main advantage is that it is not limited to traditional state correlation. It supplements this correlation with a difference map, making it possible to identify subtle dynamic changes in the market that traditional approaches often overlook. This is especially important for real-time analysis, where every fraction of a second and every change in volume can be critical.

The framework's architecture has been carefully designed to strike a balance between accuracy and computational efficiency. Using difference features in conjunction with correlation provides a richer and more informative view of market movements, while depthwise convolutions allow for the precise aggregation of multiscale features without losing local details.

At this stage, we have merely laid the foundation for building the future model, and we will resume work on it in the next article.


Links


Software used in this article

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

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

Attached files |
MQL5.zip (3486.55 KB)
Last comments | Go to discussion (1)
Alextronov
Alextronov | 11 Jan 2026 at 01:12
What does this look like on the graph?
Features of Custom Indicators Creation Features of Custom Indicators Creation
Creation of Custom Indicators in the MetaTrader trading system has a number of features.
Detrended Cross-Correlation Analysis (DCCA) for Pairs-Trading Pair Selection Under Nonstationarity Detrended Cross-Correlation Analysis (DCCA) for Pairs-Trading Pair Selection Under Nonstationarity
A complete, native MQL5 toolkit for Detrended Cross-Correlation Analysis: engine, validator, basket scanner, and a reference spread-trading EA. The engine produces a scale-by-scale rho_DCCA(s) curve and a band-mean score to rank pairs, contrasted with a standard Pearson correlation. The article details the box-detrending approach and shows real Strategy Tester results to illustrate how the gate integrates into trade decisions.
Features of Experts Advisors Features of Experts Advisors
Creation of expert advisors in the MetaTrader trading system has a number of features.
Implementing a Zone-Aware Rollover Window Gate in MQL5 Implementing a Zone-Aware Rollover Window Gate in MQL5
CTradeWindows blocks EA entries during the daily rollover spread spike. Each window is a clock time in a zone such as New York, so it follows that zone through DST. CSpreadProfile learns the windows from tick spreads and saves them to a file that an EA can load. Unit tests and Strategy Tester runs on one server show that a window fixed in server time misses the spike in weeks when the US and EU DST dates differ.