Neural Networks in Trading: Difference-Based Modeling of Market Microstructure (Difference Block)
Introduction
In the previous article, we laid the groundwork: we explored the concept of EDCFlow, traced its origins, and carefully applied its academic logic to the context of financial markets. Now is the perfect time to take a step forward and put what we have learned into practice. That is precisely where a theory either begins to work or remains nothing more than a beautiful illustration.
The EDCFlow framework was originally developed as a response to the limitations of traditional approaches to event stream analysis. Its authors rejected the simplistic view of motion as a sequence of states linked solely by correlation. Instead, they proposed viewing the flow as a dynamic tapestry of change, in which value lies not only in the similarities between states but also in their differences. Sometimes, the differences matter most.
In the context of financial markets, this idea sounds almost trite. An experienced trader intuitively knows that the market is characterized not only by its states, but also by the transitions between them — whether abrupt or gradual, accelerating or decelerating, through a series of micro-movements or a single impulse. It is precisely this "how" that eludes most traditional models, which are stuck in a world of smoothed indicators and averaged representations.
EDCFlow offers a different perspective. It does not reject correlation; on the contrary, it uses it as a stable framework, but supplements it with temporally dense difference maps that capture local changes between adjacent fragments of the stream. Taken together, this creates a representation in which the market ceases to be a static surface and begins to resemble a living environment with internal tensions, impulses, and zones of turbulence.
From an architectural standpoint, the EDCFlow framework appears clean and well-thought-out. There are no random blocks or decorative elements here — each component serves a specific purpose, and together they form a coherent computational pipeline.
It is based on multi-level feature extraction. The data stream is first converted into a spatiotemporal representation, where different resolution levels correspond to different scales of motion. Large-scale structures provide context, while small-scale structures capture local deviations. This principle is well known from classic convolutional architectures, but in EDCFlow it is used not for the sake of depth per se, but to separate dynamics across scales.
Next, the correlation mechanism comes into play. It ensures stability. It is this very market memory that allows the model to understand which states are interconnected and which price movements are a continuation of an already observed trend. Correlation smooths out the chaos, provides a framework, and prevents the representation from breaking down into noise.
But this is precisely where EDCFlow takes a fundamental step in a different direction. In addition to the correlation features, Difference Maps are included — dense maps of the differences between adjacent time segments. These maps do more than simply calculate the difference in values; they encode changes in the structure of motion, its direction, intensity, and local heterogeneity. Where correlation says this is similar, the difference clarifies: but it has changed like this.
This is particularly valuable for a financial data stream. The market may retain its overall structure while changing the nature of its movements; volatility may increase without a change in the trend; liquidity may dry up in certain areas without disrupting the overall picture. It is precisely these states that often precede significant events — and it is precisely these that are difficult to detect through classic features.
Correlation features and difference features are combined through an attention mechanism. This is not a concession to fashion, but an engineering necessity. Attention in EDCFlow acts as an adaptive filter. It allows the model to decide on its own which features are more important in the current context: when to rely on a stable structure, and when to rely on a sudden local change. As a result, the representation neither becomes static nor fluctuates without reason. It adapts.
The final component of the architecture is an iterative mechanism for refining motion. Instead of making a single prediction, the model repeatedly updates its representation, adjusting it each time based on the accumulated context. This approach works particularly well with financial data, where price movements are rarely instantaneous and complete. More often, it is a process that unfolds over time, with pullbacks, pauses, and false moves.
It is important to emphasize that the strength of EDCFlow lies not in any single component, but in its balance. Correlation provides stability, differences provide sensitivity, multiscale analysis provides depth, and iterative processing provides accuracy. Together, they form an architecture that seeks to understand the market rather than simply guess what it will do.
The author's visualization of the EDCFlow framework is shown below.

However, up until now, we have been talking mainly about principles. It is time to move to the implementation level, because that is where the real work begins. Any architecture, no matter how elegant it may appear on paper, must be adapted to the actual computing environment and to the constraints of the language, memory, and execution time.
In this article, we will focus on a single but crucial element — the Multi-Scale Difference Layer. This is the very mechanism that transforms the concept of difference maps from an abstract formula into a practical tool. It is responsible for extracting changes at various scales and ensuring that these changes are computed quickly, correctly, and without leaking future information.
For financial markets, multiscale analysis is not a luxury but a necessity. The market always operates across several time horizons at once. What looks like noise at one scale may be the beginning of a price move at another. And vice versa. The Multi-Scale Difference Layer captures this multiscale structure without blending it into a single averaged signal.
Scale Emphasis Module
Let's start by working on the Multi-Scale Attention module. At this point, it is important to establish the right emphasis from the outset and avoid misleading associations. Within the EDCFlow framework, the attention mechanism differs fundamentally from the Self-Attention mechanism we are familiar with from previous work. This is not about universally comparing everything with everything or searching for global dependencies within a sequence. This approach is excessive for dense streaming data and, more importantly, computationally expensive.
The framework's authors propose a more restrained, practical solution. Multiscale attention in EDCFlow operates not on elements, but on representation scales. Its task is not to reinterpret the entire stream, but to carefully weight the contributions of difference features obtained at different temporal and spatial levels.
While Self-Attention aims to construct a global picture of interrelationships, attention here serves as an adaptive regulator. It determines when smooth market movements call for a longer time horizon and when abrupt local shifts require finer resolution.
This approach is well aligned with the nature of market data. Markets are rarely homogeneous. Short-term impulses and more persistent movements can coexist in the market at the same time. The multiscale attention mechanism allows this to be taken into account without complicating the architecture or compromising stability.
From a practical standpoint, this offers several advantages at once. First, the computational load is reduced compared to classical Self-Attention. Second, attention becomes locally meaningful — it operates on already structured features rather than on raw states. Finally, the model gains additional flexibility without sacrificing the causality and temporal correctness of the analysis.
Our implementation of the approaches described above is contained in the specialized class CNeuronMultiScaleExcitation. This is a key computational component where the concept of multiscale attention, proposed by the authors of EDCFlow, is put into practice. There are no pairwise comparisons of the elements of the tensor being analyzed here. And there is no global attention across the entire sequence. Instead, a more restrained and practical excitation mechanism is used, operating at the scale level.
class CNeuronMultiScaleExcitation : public CNeuronBaseOCL { protected: CLayer cExcitation; //--- virtual bool feedForward(CNeuronBaseOCL *NeuronOCL) override; virtual bool updateInputWeights(CNeuronBaseOCL *NeuronOCL) override; virtual bool calcInputGradients(CNeuronBaseOCL *NeuronOCL) override; public: CNeuronMultiScaleExcitation(void) {}; ~CNeuronMultiScaleExcitation(void) {}; //--- virtual bool Init(uint numOutputs, uint myIndex, COpenCLMy *open_cl, uint dimension, uint units, uint scales, uint bottleneck, ENUM_OPTIMIZATION optimization_type, uint batch); //--- virtual int Type(void) override const { return defNeuronMultiScaleExcitation; } //--- 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 central element of the class is the cExcitation block. It is this component that is responsible for generating the weights used to scale the features obtained at different resolution levels. In effect, this block acts as an adaptive controller. It amplifies informative scales and attenuates less important ones based on the current context of the stream. It places emphasis where it matters, so to speak.
The initialization of the module is entirely contained within the Init method. What is important here is not so much to follow every line of code as it is to understand the logic behind the design of the computational pipeline.
bool CNeuronMultiScaleExcitation::Init(uint numOutputs, uint myIndex, COpenCLMy *open_cl, uint dimension, uint units, uint scales, uint bottleneck, ENUM_OPTIMIZATION optimization_type, uint batch) { if(!CNeuronBaseOCL::Init(numOutputs, myIndex, open_cl, dimension * units * scales, optimization_type, batch)) return false;
In the first step, control is passed to the method of the same name in the parent class. Next, the internal cExcitation pipeline is created. This pipeline implements the attention mechanism. The architecture is built step by step, without any hidden magic.
cExcitation.Clear(); cExcitation.SetOpenCL(OpenCL); CNeuronSpikeConvBlock* conv = NULL; CNeuronTransposeOCL* transp = NULL; CNeuronSoftMaxOCL* softmax = NULL; uint index = 0; //--- [Scale, Unit, Dimension] transp = new CNeuronTransposeOCL(); if(!transp || !transp.Init(0, index, OpenCL, scales, units * dimension, optimization, iBatch) || !cExcitation.Add(transp)) { DeleteObj(transp) return false; } index++;
First, transposition is performed. The original representation is transformed so that scale occupies a separate axis. This is a technical but important step. Attention in EDCFlow operates across scales, not across time steps or individual elements. We are literally restructuring the data so that scale becomes the subject of analysis.
The next block is a convolutional block. This is where the initial processing of the scales takes place. A narrow kernel is used, and there is no spatial mixing. This is a careful aggregation of information within each channel. Essentially, we are preparing the data for compression.
//--- [Unit, Dimension, Scale] conv = new CNeuronSpikeConvBlock(); if(!conv || !conv.Init(0, index, OpenCL, scales, scales, 1, dimension * units, 1, optimization, iBatch) || !cExcitation.Add(conv)) { DeleteObj(conv) return false; } index++;
Next comes a key step—the bottleneck transformation. The dimensionality of the features is intentionally reduced. This is a classic, time-tested technique. It reduces the computational load and forces the model to extract only truly meaningful information. In the context of attention, this is particularly important: weights should be derived from a compact, stable representation, rather than from noise.
//--- [Unit, Dimension] conv = new CNeuronSpikeConvBlock(); if(!conv || !conv.Init(0, index, OpenCL, dimension, dimension, bottleneck, units, 1, optimization, iBatch) || !cExcitation.Add(conv)) { DeleteObj(conv) return false; } index++;
After the bottleneck layer, the features are expanded again. Here, the model returns from the compressed space to a representation that once again contains information about all scales. But now these are no longer the original features; rather, they are an assessment of their relative importance.
//--- [Unit, Bottleneck] conv = new CNeuronSpikeConvBlock(); if(!conv || !conv.Init(0, index, OpenCL, bottleneck, bottleneck, scales * dimension, units, 1, optimization, iBatch) || !cExcitation.Add(conv)) { DeleteObj(conv) return false; } index++;
At this stage, SoftMax is applied. Its role is crystal clear and practical. It normalizes the attention weights across scales, transforming them into an interpretable distribution. Each scale is assigned its own influence coefficient, and the sum of these coefficients is strictly controlled. No arbitrary amplification — only relative priorities.
//--- [Unit, Dimension, Scale] softmax = new CNeuronSoftMaxOCL(); if(!softmax || !softmax.Init(0, index, OpenCL, conv.Neurons(), optimization, iBatch) || !cExcitation.Add(softmax)) { DeleteObj(softmax) return false; } softmax.SetHeads(dimension * units); index++;
It is important to note the setting for the number of heads. Here, attention is effectively distributed across all channels of the representation. This is not multi-head attention in the transformer sense, but rather a careful division of responsibility: each channel receives its own scale weights without mixing with its neighbors.
The final transposition restores the data to its original format [Scale, Unit, Dimension].
//--- [Unit, Dimension, Scale] transp = new CNeuronTransposeOCL(); if(!transp || !transp.Init(0, index, OpenCL, units * dimension, scales, optimization, iBatch) || !cExcitation.Add(transp)) { DeleteObj(transp) return false; } index++; //--- [Scale, Unit, Dimension] return true; }
The module is complete. The result is a set of weights that can be directly applied to multiscale features.
In summary, this attention mechanism:
- operates strictly locally across scales,
- does not violate the principle of causality,
- avoids the quadratic complexity of Self-Attention,
- is fully consistent with the logic of EDCFlow.
After initializing the object, we move on to building the forward pass algorithm, which is implemented in the feedForward method. Unlike the initialization phase, where the architecture is defined and connections between objects are established, the logic here is extremely concise and, importantly, easy to read. This is exactly the kind of situation where the code speaks for itself.
bool CNeuronMultiScaleExcitation::feedForward(CNeuronBaseOCL *NeuronOCL) { CNeuronBaseOCL* prev = NeuronOCL; CNeuronBaseOCL* curr = NULL; for(int i = 0; i < cExcitation.Total(); i++) { curr = cExcitation[i]; if(!curr || !curr.FeedForward(prev)) return false; prev = curr; }
The method begins by sequentially passing the data to be analyzed through the internal cExcitation pipeline. We do not perform any additional transformations or intervene in the process. Each layer receives the output from the previous layer and returns its own result. This linear pass highlights the module's central idea: attention is formed as a function of already prepared multiscale features, without side branches or hidden states.
The variable prev points to the current data source at each step, while curr points to the active excitation layer. This approach eliminates ambiguity and makes the order of operations clear. From an engineering standpoint, this is an important point: the attention mechanism should not be more complex than the problem it solves.
After completing the pass through all layers of cExcitation, we obtain the attention weight tensor. Next comes the key operation: element-wise multiplication (ElementMult) of the original input features by the computed excitation coefficients. No summation, no channel recombination. Every scale, every unit, and every dimension is scaled strictly by its own weight.
if(!ElementMult(NeuronOCL.getOutput(), prev.getOutput(), Output)) return false; //--- return true; }
This is precisely where the fundamental difference from Self-Attention becomes apparent. We do not reconstruct the representation or create new connections between elements. We merely adjust the amplitude of existing features, amplifying informative scales and suppressing less important ones. This is a subtle yet extremely effective operation.
As a result, the CNeuronMultiScaleExcitation module functions as an intelligent filter. It does not alter the signal's form, but rather adjusts its significance. It is a carefully balanced compromise between expressiveness and computational discipline. It does exactly what is required within EDCFlow — it allows the model to sense which scale of movement matters most right now.
Multiscale Difference Block
Next, we move up a level in the EDCFlow framework's architectural hierarchy and proceed to build the Multi-Scale Difference block, which works not with weights but with the dynamics of the data stream itself.
While the multiscale attention module answers the question of which scale to trust right now, the Multi-Scale Difference module answers a more fundamental question — what exactly has changed. This is a logical extension of the architecture. First, we learned how to weight scales. Now we are learning to extract meaningful differences from them.
It is important to note that in EDCFlow, the difference representation is not a side effect or an auxiliary feature. It has equal standing with correlation and forms a separate feature branch. The framework's authors deliberately avoid the idea of a single, universal description of motion. Instead, they distinguish between the stable structure and local changes, allowing the model to handle them separately.
Multi-Scale Difference is based on a simple yet fundamental observation. Market changes manifest themselves differently at different scales. What appears to be noise over a short time horizon may be part of a directional move over a longer one. Conversely, a local impulse can be completely lost in the smoothed representation. Therefore, differences are computed at multiple scales while preserving the independence of those scales.
From an architectural standpoint, this block generates a set of difference maps, each of which corresponds to its own scale. It is of fundamental importance that the calculation of differences does not violate causality. Only data already available is used, without any lookahead. When it comes to financial data, this is not just a formality, but a basic requirement.
The CNeuronMultiScaleDifference class is the central component of the Multi-Scale Difference module's implementation. It is integrated into the main feature processing pipeline and performs two key functions: it computes structured difference features across multiple scales and evaluates their significance using built-in multiscale attention. This approach provides a seamless integration of the core concepts of EDCFlow: dense difference maps and adaptive scale weighting.
class CNeuronMultiScaleDifference : public CNeuronSpikeConvBlock { protected: uint iaShifts[]; int ibShifts; //--- CLayer cBottleneck; CLayer cExcitation; CLayer cProjection; //--- virtual bool feedForward(CNeuronBaseOCL *NeuronOCL) override; virtual bool updateInputWeights(CNeuronBaseOCL *NeuronOCL) override; virtual bool calcInputGradients(CNeuronBaseOCL *NeuronOCL) override; public: CNeuronMultiScaleDifference(void) {}; ~CNeuronMultiScaleDifference(void) {}; //--- virtual bool Init(uint numOutputs, uint myIndex, COpenCLMy *open_cl, uint dimension, uint units, uint bottleneck, uint &shifts[], ENUM_OPTIMIZATION optimization_type, uint batch); //--- virtual int Type(void) override const { return defNeuronMultiScaleDifference; } //--- 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; };
Architecturally, the class is divided into three blocks:
- cBottleneck — compresses the analyzed representation into a compact feature space, filtering out noise and reducing the computational load for subsequent operations.
- cExcitation — contains a CNeuronMultiScaleExcitation object that implements multiscale attention. It receives difference maps for all shifts and adaptively amplifies the most informative scales, generating appropriate weights for each feature.
- cProjection — returns the processed difference features to the original feature space, enabling their integration with the other branches of the framework (correlation and context).
The initialization of internal components and the construction of the object's architecture are handled in the Init method. At this stage, the complete computational pipeline for the Multi-Scale Difference block is created, and key parameters are configured.
bool CNeuronMultiScaleDifference::Init(uint numOutputs, uint myIndex, COpenCLMy *open_cl, uint dimension, uint units, uint bottleneck, uint &shifts[], ENUM_OPTIMIZATION optimization_type, uint batch) { if(!CNeuronSpikeConvBlock::Init(numOutputs, myIndex, open_cl, bottleneck, bottleneck, dimension, units, 1, optimization_type, batch)) return false;
First, the base class is initialized; this class already implements the creation of the base interfaces. Next, the number of scales, scales, is determined from the shift array shifts, which is copied into the local array iaShifts.
int scales = int(shifts.Size()); if(scales == 0 || ArrayResize(iaShifts, scales) < scales || ArrayCopy(iaShifts, shifts, 0, 0, scales) < scales) return false; ibShifts = OpenCL.AddBufferFromArray(iaShifts, 0, scales, CL_MEM_READ_ONLY); if(ibShifts == INVALID_HANDLE) return false;
The ibShifts parameter stores a pointer to this array in the OpenCL context's memory, providing direct access to the data on the GPU without unnecessary copying. This improves performance and ensures consistency in computations across layers.
Next, three logical blocks are constructed one after another. To ensure proper operation, all containers are first cleared and then bound to the OpenCL context so that operations are performed directly on the GPU.
cBottleneck.Clear(); cExcitation.Clear(); cProjection.Clear(); cBottleneck.SetOpenCL(OpenCL); cExcitation.SetOpenCL(OpenCL); cProjection.SetOpenCL(OpenCL);
The first of these — cBottleneck — compresses the analyzed features into a compact representation, filtering out noise and reducing the computational load on subsequent layers. At the implementation level, three key layers are created within cBottleneck. First, a depth-wise convolution block is formed, which processes the data being analyzed by carefully aggregating the information across all spatial and temporal dimensions. It reduces the number of features while preserving structurally significant signals, much like an experienced analyst distinguishes truly important market events from random fluctuations.
CNeuronMultiWindowsConvWPadOCL* padconv = NULL; CNeuronSpikeDepthWiseConv* dwconv = NULL; CNeuronSpikeConvBlock* conv = NULL; CNeuronBaseOCL* neuron = NULL; CNeuronMultiScaleExcitation* excitation = NULL; CNeuronTransposeOCL* transpose = NULL; uint index = 0; //--- Bottleneck uint units_out = (units + 1) / 2; dwconv = new CNeuronSpikeDepthWiseConv(); if(!dwconv || !dwconv.Init(0, index, OpenCL, dimension, bottleneck, 5, 2, units_out, 1, optimization, iBatch) || !cBottleneck.Add(dwconv)) { DeleteObj(dwconv); return false; } index++;
The next layer applies convolutions with padding, creating local representations of features at multiple scales simultaneously.
uint windows[] = { 3 * bottleneck }; padconv = new CNeuronMultiWindowsConvWPadOCL(); if(!padconv || !padconv.Init(0, index, OpenCL, windows, bottleneck, bottleneck, units_out, 1, optimization, iBatch) || !cBottleneck.Add(padconv)) { DeleteObj(padconv) return false; } index++;
This technique enhances the model's ability to capture changes spanning different ranges in time and across features, laying the groundwork for subsequent analysis of differences.
The final layer of the block integrates all the obtained representations into a coherent, compact feature space.
conv = new CNeuronSpikeConvBlock(); if(!conv || !conv.Init(0, index, OpenCL, bottleneck, bottleneck, bottleneck, units_out, 1, optimization, iBatch) || !cBottleneck.Add(conv)) { DeleteObj(conv) return false; } index++;
The output of cBottleneck is a preprocessed and structured signal, ready for calculating difference maps and subsequent multiscale weighting. Each line of code responsible for creating and adding layers ensures that components are correctly connected to the pipeline and verifies that they have been successfully initialized, which is critical for stable operation when processing financial data streams.
The next block, cExcitation, receives difference features as input and applies adaptive amplification to them across scales. First, a base neuron is created, which forms the structure for storing all difference maps, taking into account the number of scales and output units.
//--- Excitation neuron = new CNeuronBaseOCL(); if(!neuron || !neuron.Init(0, index, OpenCL, conv.Neurons()*scales, optimization, iBatch) || !cExcitation.Add(neuron)) { DeleteObj(neuron) return false; } neuron.SetActivationFunction(None); index++;
Setting the activation function to None emphasizes the importance of purely linear information transfer without distortion at this stage.
Next, a key component is added — CNeuronMultiScaleExcitation — which implements multiscale attention. It receives input features and differences, generates weights for each scale, and amplifies the most informative changes, allowing the model to focus on meaningful patterns rather than noise.
excitation = new CNeuronMultiScaleExcitation(); if(!excitation || !excitation.Init(0, index, OpenCL, bottleneck, units_out, scales, (bottleneck + 1) / 2, optimization, iBatch) || !cExcitation.Add(excitation)) { DeleteObj(excitation) return false; } index++;
In the context of analyzing financial data streams, this is similar to the work of an analyst who immediately identifies key impulses and trends amid a multitude of random fluctuations.
Next, a feature transposition layer is created to align the data dimensions correctly for the subsequent convolutional layer.
transpose = new CNeuronTransposeOCL(); if(!transpose || !transpose.Init(0, index, OpenCL, bottleneck * units_out, scales, optimization, iBatch) || !cExcitation.Add(transpose)) { DeleteObj(transpose) return false; } index++;
This ensures that the difference maps and their scales are properly aligned, which is critical for the accuracy of the calculations.
The final layer of the block integrates all scale representations into a coherent and compact feature space.
conv = new CNeuronSpikeConvBlock(); if(!conv || !conv.Init(0, index, OpenCL, scales, scales, 1, transpose.GetCount(), 1, optimization, iBatch) || !cExcitation.Add(conv)) { DeleteObj(conv) return false; } index++;
This step completes the processing in cExcitation, producing a final output in which each difference is weighted according to its significance, and the multiscale information is organized for transmission to the next block, Projection.
The cProjection block performs the final phase of feature processing, mapping the features back into a representation space compatible with the rest of the framework. At this stage, the outputs of the Excitation block are integrated with the initial representation, creating a data structure that is ready for further use. First, a base neuron is created.
//--- Projection neuron = new CNeuronBaseOCL(); if(!neuron || !neuron.Init(0, index, OpenCL, conv.Neurons(), optimization, iBatch) || !cProjection.Add(neuron)) { DeleteObj(neuron) return false; } neuron.SetActivationFunction(None); if(!neuron.SetGradient(conv.getGradient(), true)) return false; index++;
The next step is to create a depth-wise convolutional block, which performs additional feature aggregation, expanding the feature space and strengthening the structural consistency of the difference maps.
dwconv = new CNeuronSpikeDepthWiseConv(); if(!dwconv || !dwconv.Init(0, index, OpenCL, bottleneck, 2 * bottleneck, 5, 1, units_out, 1, optimization, iBatch) || !cProjection.Add(dwconv)) { DeleteObj(dwconv); return false; } //--- return true; }
It is worth noting the unconventional use of depth-wise convolution here. In the Bottleneck block, we reduced the feature dimension and halved the sequence length. Now the task is the opposite — we need to restore the original scale of the data. To do this, channel-independent grouping is first applied, which aligns the current value of a feature with its neighbors along the time axis, creating local dependencies between consecutive elements. The feature space is then doubled in size, effectively creating additional elements of the sequence that are aligned both in the feature space and along the time axis. This technique allows for the accurate reconstruction of the structure of the original data stream, preserving the informative value of the difference maps and correctly integrating them into subsequent processing.
Thus, cProjection completes the construction of the output tensor for the Multi-Scale Difference module. The features have been prepared, adaptively weighted, and projected into a consistent space, ready for further use in the analysis. Each line of code here serves both a technical purpose — initializing the layers — and a conceptual one — preserving the consistency, scale, and information content of the features for reliable analysis of financial data streams.
Each inner layer is added to the corresponding container (cBottleneck, cExcitation, cProjection), and the initialization is checked for correctness. At this stage, the module's architecture is fully formed, and the computational pipeline is ready for a forward pass and training.
As a result, the initialization method creates a structured, fully differentiable pipeline that combines multiscale differences and an adaptive attention mechanism, ensuring efficient processing of financial data streams while preserving causality and enabling scalability on the GPU.
The forward pass algorithm is implemented in the feedForward method and reflects the sequential logic of feature processing across three main blocks: Bottleneck, Excitation, and Projection.
bool CNeuronMultiScaleDifference::feedForward(CNeuronBaseOCL *NeuronOCL) { CNeuronBaseOCL* prev = NeuronOCL; CNeuronBaseOCL* curr = NULL;
The method begins with a simple but important step: setting up pointers to the current source and the active layer. The variable prev initially points to the NeuronOCL data stream being analyzed, while curr is used to process each internal layer sequentially. This approach makes the computational process transparent. At every step, we know exactly where we are getting the data from and where we're sending it — as if we were watching the flow of a river carrying information.
Processing begins with the Bottleneck block, where the input features pass through a sequence of convolutional layers. Some of them perform channel-independent tracking of changes in features, while others analyze patterns within a single time step.
//--- Bottleneck for(int i = 0; i < cBottleneck.Total(); i++) { curr = cBottleneck[i]; if(!curr || !curr.FeedForward(prev)) return false; prev = curr; }
Each layer receives the output of the previous layer, compresses and structures the data, and filters out noise. In terms of financial analysis, this is similar to the work of an experienced analyst who distinguishes random fluctuations from significant impulses, creating a compact, clean representation of events that is ready for detailed analysis.
In the next step, the DilatedDifference method generates change maps between time steps for all specified shifts. Here, we do not just calculate differences; we create a structured representation in which each change retains its association with a specific scale. It is similar to how an experienced trader examines both short-term spikes and long-term trends while keeping the two distinct.
//--- Excitation curr = cExcitation[0]; if(!curr) return false; uint dimension = cConv.GetWindow(); uint units = prev.Neurons() / dimension; if(!DilatedDifference(prev, curr, ibShifts, dimension, units)) return false; prev = curr; for(int i = 1; i < cExcitation.Total(); i++) { curr = cExcitation[i]; if(!curr || !curr.FeedForward(prev)) return false; prev = curr; }
Next, the difference maps pass through the remaining cExcitation layers, including the built-in CNeuronMultiScaleExcitation module. This block adaptively weights each scale, amplifying informative changes and suppressing less relevant ones. Visually, it's similar to adjusting lenses. Minor noise fluctuations become less noticeable, while genuine market movements become more clearly visible. This mechanism allows the model to focus on meaningful patterns and avoid overinterpreting random signals.
In the final stage, the Projection block combines the processed differences with the compressed representation from the Bottleneck block, performing summation and normalization.
//--- Projection curr = cProjection[0]; if(!curr || !SumAndNormilize(cBottleneck[-1].getOutput(), prev.getOutput(), curr.getOutput(), dimension, true, 0, 0, 0, 1)) return false; prev = curr; for(int i = 1; i < cProjection.Total(); i++) { curr = cProjection[i]; if(!curr || !curr.FeedForward(prev)) return false; prev = curr; }
Each Projection layer processes the output of the previous layer, preparing the data for integration with the rest of the architecture.
Final normalization and merging with the output of the parent class CNeuronSpikeConvBlock produce a stable, ready-to-use feature representation.
if(!CNeuronSpikeConvBlock::feedForward(prev)) return false; if(!SumAndNormilize(NeuronOCL.getOutput(), Output, Output, cConv.GetFilters(), true, 0, 0, 0, 1)) return false; //--- return true; }
Here, the model seems to sum up the analysis, bringing together insights into the structure and dynamics of the stream into a single picture.
The entire procedure is structured as a linear, deterministic flow. The data passes through the layers sequentially. Each step is logically justified and serves a specific purpose. The forward pass transforms a raw stream of events into an informative, structured representation of changes. Each scale retains its significance, and every change is evaluated in relation to its context. This process enables the model to identify patterns, distinguish true signals from noise, and lay the groundwork for further analysis and forecasting.
Conclusion
In this article, we demonstrated the practical implementation of key approaches from the EDCFlow framework, focusing on the Multi-Scale Difference module. The implementation demonstrated how sequential feature compression, the calculation of differences across multiple scales, and adaptive multiscale attention enable the formation of a structured and informative representation of streaming data. Each block — Bottleneck, Excitation, and Projection — plays a clearly defined role in a sequence that spans filtering and compression, identifying significant changes, and restoring the original dimensionality and integrating the features into the target representation space.
The implemented algorithm demonstrates how combining modern deep learning methods with attention mechanisms and difference analysis can transform a stream of events into an informative, structured representation.
Overall, the proposed implementation allows the EDCFlow framework's approaches to be adapted to specific tasks involving the analysis of multiscale financial data streams, ensuring efficient, stable, and scalable information processing.
References
- EDCFlow: Exploring Temporally Dense Difference Maps for Event-Based Optical Flow Estimation
- Other articles in this series
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: /ru/articles/20760
Warning: All rights to these materials are reserved by MetaQuotes Ltd. Copying or reprinting of these materials in whole or in part is prohibited.
This article was written by a user of the site and reflects their personal views. MetaQuotes Ltd is not responsible for the accuracy of the information presented, nor for any consequences resulting from the use of the solutions, strategies or recommendations described.