Русский Português
preview
Neural Networks in Trading: Temporal Motion Aggregation (TMA)

Neural Networks in Trading: Temporal Motion Aggregation (TMA)

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

Introduction

The financial market is, in many ways, like a living organism. Its life pulses to the rhythm of trades, surges in liquidity, and shifts in market sentiment. Its breathing is irregular: at times it quickens under the pressure of news and emotional impulses, and at other times it seems to stop during long periods of waiting. Every moment here is filled with events, yet not every moment matters. Amid a stream of minute changes — microscopic price fluctuations, shifts in volume, and order crossings — form is lost, and the structure of movement becomes blurred. Traditional methods of analysis view this stream as a sequence of points, where time is merely a coordinate. But in reality, it is alive — sometimes condensing, sometimes spreading out, like the very breath of the market itself.

This variability is what makes financial time unique. It does not flow uniformly, as in classical time series. During periods of panic or frenzy, the market experiences entire eras in a matter of hours, whereas during calm phases, a single day can seem empty and serene, like a still, smooth sea. Such an irregular rhythm disrupts our usual notions of temporal causality. Prices, volumes, and spreads begin to interact in a nonlinear, asynchronous space, where every event triggers a whole network of consequences. This is precisely where the main challenge of modern market analysis lies: to look beyond merely recording changes and capture the dynamic form of movement, its hidden architecture.

It is interesting to note that a similar problem has long been addressed in the field of computer vision, particularly in research on event cameras. Unlike traditional sensors, which capture static frames, these cameras respond to changes in brightness — to motion, rather than to the image itself. Their data consists of a sequence of discrete events, each of which carries a tiny bit of information about what is happening. And the more intense the movement, the denser the flow of events becomes. Financial markets are structured in a remarkably similar way: quotes, orders, and the microstructure of trading — all of these are events that form a continuous but irregular stream of changes. Every transaction is like a flash of light in an event camera — a signal that the system has changed its state.

It was in this analogous domain that the TMA (Temporal Motion Aggregation) framework emerged, proposed by Haotian Liu and his co-authors in the paper "TMA: Temporal Motion Aggregation for Event-based Optical Flow". It was designed to extract motion from event data, but its principles turned out to be universal, capable of describing any dynamic system in which the temporal sequence of events is important. The essence of the TMA approach is not to view events as isolated, unrelated points, but to organize them into coherent temporal structures, revealing patterns of movement hidden beneath the surface of chaos. In this sense, TMA can be viewed as a kind of bridge between the physics of motion and the mathematics of time.

The TMA framework's algorithm is based on three interrelated mechanisms.

  1. The Event Splitting Strategy divides the event stream into temporal segments, much like an analyst divides trading history into micro-periods of activity. Each segment has its own rhythm — short bursts that reflect local market dynamics.
  2. The Linear Sampling Strategy performs temporal alignment by synchronizing events that occur at different times. This is similar to the process of normalizing financial data, in which signals from different assets or exchanges are aligned to a common time scale, thereby eliminating the effects of delays and offsets.
  3. The Motion Pattern Aggregation Module is the central component where all temporal segments are combined into a coherent picture of motion. Here, the noise fades away, and patterns emerge, like the contours of a current beneath the surface of the water.

Viewing the market through the lens of these ideas makes it clear that price is not simply a value, but a trajectory shaped by a multitude of micro-events. Every price change conveys information about capital flows, shifts in interest among market participants, reactions to news, and the struggle between liquidity and fear. TMA offers a tool for bringing this stream, scattered over time, together into a unified dynamic form. By dividing the events into time layers and aligning them by pace and direction. And then, by combining them into coherent motion, one can obtain what economists would call the market's true momentum — a structure that reveals the crowd's intent.

From a perceptual standpoint, this represents a shift from the static logic of predictions to the dynamic logic of understanding. In traditional models, the past and the future are linked mechanically: the formula describes the relationship, and that is all there is to it. In TMA, time itself becomes a vehicle for meaning. Every new event does more than just add information; it redefines the context of previous events. Just as, in the market, a new surge in trading volume can completely change the interpretation of yesterday's price movement. This is not a linear chain, but a dynamic updating of cause-and-effect relationships, in which meaning emerges not from isolated facts, but from their coherence over time.

It can be said that TMA embodies the philosophy of temporal coherence, in which movement is not described but is experienced as a whole. This is especially important when it comes to financial data. Here, stable patterns emerge not from averages but from recurring activity patterns. Just as an experienced trader senses the market through the rhythm of the trade tape, the TMA model learns to recognize recurring motifs in the temporal flow. It does not look for static features — it captures movement.

This is precisely what makes the TMA approach so promising for the analysis of financial time series. It offers not just a new architecture for data processing, but a different perspective on the very concept of time. In it, time is not passive but active; not linear but multi-layered. Every event is not a point but a wave, and the interaction of these waves shapes the actual market dynamics.

If you look at the flow of quotes through this lens, you can see how trends form at the micro level. How bursts of activity coalesce into waves of movement, and how the noise of trading transforms into a meaningful rhythm. TMA makes this rhythm visible, transforming the market’s erratic breathing into a model capable of predicting the direction and intensity of its next breath.



The TMA Algorithm

In classical optical flow problems, the goal is to determine a dense displacement field u: ℝ² → ℝ² that maps each point (x, y) at time t₀ to its new position (x′, y′) at time t₁. Applying this idea to finance, we can say that the task of analyzing the data flow comes down to determining a market motion vector — a function that maps the state of price, volume, or volatility to a new state after a certain time interval.

Traditional models attempt to solve this problem by calculating the correlation between values in two time frames — which are, in a sense, snapshots of market activity. They assess the degree of similarity between patterns at different points in time to determine the direction and rate of change. However, this approach inevitably leads to limitations stemming from the nature of market data. They are discrete, asynchronous, and spatially sparse. A financial flow does not contain any explicit intensity — only a sequence of transactions, quotes, and orders. Therefore, attempts to construct a correlation structure produce unstable regions of correspondence and blurred motion boundaries. This results in less informative features and inaccurate assessments of the direction of capital flows.

The TMA framework takes a different approach to solving this problem. Instead of compressing data into frames and searching for matches in static snapshots, it takes advantage of the temporal continuity of the event stream. Financial data, like events in a visual model, contain a rich temporal structure. Every quote change is linked to a multitude of micro-events: the arrival of orders, an increase in volume, and changes in the spread. This sequential, fine-grained structure conveys much more information about the actual market dynamics than averaged spatial features. By utilizing this level of temporal detail, TMA reconstructs a continuous context of motion, yielding more accurate and expressive estimates of the direction and rate of change.

To preserve the temporal structure and simplify feature extraction, the event stream E is transformed into a three-dimensional temporal representation V(x, y, t). In its original formulation, TMA performs discretization along the time axis, dividing the stream into consecutive intervals and mapping events into a multidimensional representation. In a financial context, this is analogous to breaking down market flow into microslices of time, where each change in parameters (price, volume, or volatility) is recorded as an element of a multidimensional array.

Each event eₖ = (xₖ, pₖ, tₖ) can be viewed as a triad: a location (xₖ, yₖ), a timestamp tₖ, and the sign of the change pₖ = ±1, indicating the direction of movement (increase or decrease). Unlike fixed time frames, this format allows you to work with asynchronous streams without losing track of the sequence of market events.

The volume V(x, y, t) is constructed using time scaling and bilinear interpolation, with the latter helping to smooth the boundaries between adjacent time slices. If we denote the length of the time window by B and the number of events by Nₑ, then the volume is calculated as the weighted sum of all events, taking into account their temporal and spatial proximity.

In other words, TMA does not consider each transaction or price change in isolation. It creates a continuous three-dimensional representation of market movement, where the axes represent price, time, and the direction of activity. It is a kind of temporal liquidity cube, within which one can observe trends taking shape — from the initial impulses of demand to the emergence of a sustained trend.

The TMA framework is built on architectural principles inherited from RAFT, but has been significantly reworked to handle event streams. Its architecture is based on three key mechanisms:

  • the event splitting strategy,
  • linear temporal alignment (linear lookup strategy)
  • the motion pattern aggregation module.
Together, these components unlock the potential of temporal continuity, ensuring accurate and stable reconstruction of dynamics within the trainable model.

If we apply this idea to the financial sector, TMA can be viewed as a system that analyzes the flow of market events (trades, orders, liquidity spikes) and transforms it into a map of coordinated capital movements. Unlike traditional models, which view data as a sequence of fixed frames (such as candlesticks or time bars), TMA perceives the market as a continuous video with a high frame rate, where each tick reflects the movement of market participants, and each microsignal conveys the direction of the liquidity flow.

The first component, Event Splitting Strategy, acts as an intelligent segmenter. Instead of condensing the stream of quotes into averaged temporal frames, it divides it into several overlapping time intervals, forming a series of intermediate representations. This separation preserves the rich intermediate dynamics — the subtle details of motion that are often lost with standard aggregation. The data stream E, covering the interval from t₀ to t₁, is divided into g equal segments with a step size of Δt, to which one additional reference segment from the interval (t₀ – Δt, t₀) is added. This results in a sequence of g+1 time slices, each reflecting a distinct rhythm of the market.

Each of these slices is then passed through a shared encoder (analogous to a market structure analyzer), which extracts vector representations from it — Fi ∈ ℝᴴ×ᵂ×ᶜ, where H and W define the spatial feature grid, and C defines the depth of the feature space. In a financial context, this can be interpreted as the transformation of micro-events into a multidimensional field of market features — a kind of activity map that reflects local and global fluctuations in participant interest.

In the next step, temporal correlations Ci are derived from all these representations; these correlations measure the degree of similarity between the initial and subsequent states of the flow.

where:

  • F₀ — features of the first time segment (the reference state of the market)
  • Fᵢ — the features of the corresponding segment at time tᵢ

This mechanism makes it possible to calculate not just the overall relationship between frames, but a temporally dense correlation field that captures exactly how local market structures change over time.

To draw an analogy, it is as if an analyst were not simply comparing daily candlesticks, but were observing every movement within them — the micro-fluctuations in market interest, how momentum forms, and how it flows from one price zone to another. Such densely sampled temporal correlation coefficients make it possible to detect even subtle shifts in market structures, identifying the start of a trend even before it becomes apparent in classical indicators.

The main difference between TMA and traditional approaches lies precisely in the temporal density of the analysis. While classical methods are limited to a single fixed pair of time points (the initial and final states), TMA considers a whole series of interconnected time segments. This makes it possible to track the continuous evolution of motion and take into account not only its direction but also the pattern of its change.

In a financial context, this paves the way for modeling the temporal structure of momentum — that is, for understanding how market energy propagates through a sequence of events. By dividing the flow into microsegments and correlating them at a high temporal density, TMA effectively constructs a dynamic map of capital flows — where every event and every transaction becomes an element of a complex temporal pattern from which the overall trend emerges.

This approach allows us to move beyond a flat view of the market as a set of independent bars. Instead, it reveals the depth of temporal interaction, where the past and the future are intertwined in a continuous process of shaping movement. As a result, the TMA framework is capable not only of predicting the direction of the market but also of understanding the logic of market flow, identifying hidden connections between moments and transforming them into a coherent field of dynamics.

The next step — the linear sampling strategy (Linear Lookup Strategy) — is a method for bringing all the dynamic processes recorded in the event stream to a common denominator on the timeline.

Mathematically, linear sampling is based on the assumption that, within a short time window, changes in motion occur linearly — in other words, the trajectory changes uniformly between adjacent time slices. This makes it possible to divide the total displacement vector (u) into equal intervals and sample data at the intermediate points corresponding to these time steps. Thus, each correlation map is assigned a strictly defined time reference, which ensures synchronization during subsequent aggregation.

When viewed in the context of financial markets, linear sampling functions as an algorithm for normalizing market signals. In practice, different assets — and even different time periods for a single asset — may exhibit asynchronous movement: growth and correction phases are shifted in time, and responses to external events are delayed. The Linear Lookup Strategy in TMA serves as a tool for aligning these timing differences; it brings together movements occurring at different times, allowing them to be analyzed on a common time scale. This is similar to the process of adjusting price series for volatility or aligning them to a single time frame, which makes comparisons and interpretations more accurate.

From a technical standpoint, linear sampling performs temporal alignment of correlation maps — structures that contain information about the relationships between features from different temporal layers. Each of these volumes initially captures motion at its own pace, just as each financial instrument has its own rhythm of price changes. The purpose of sampling is to transform this disparate data into a coherent whole, where each element reflects the same instant in the dynamic process. As a result, the motion of objects becomes visible over time, not just in space.

To put it figuratively, linear sampling is like a conductor who brings order to an orchestra of temporal signals. Without it, each group of instruments — a separate correlation layer — would play at its own tempo, creating noise instead of harmony. But after temporal alignment, all elements move in sync, and the model can identify stable patterns that recur across different time intervals. It is precisely this property that makes TMA particularly sensitive to complex, subtle patterns of movement — whether they are the trajectories of objects in space or the micro-patterns of changes in price quotes.

The Motion Pattern Aggregation Module is the final — and perhaps the most elegant — element of the TMA architecture. Its purpose is to integrate the previously obtained temporal motion features into a single, coherent representation, where each temporal layer does not merely add data but makes a meaningful contribution to the overall picture of the dynamics. At first glance, it is simple — combine the features and update the flow estimate. But in reality, there is a delicate balance at play here —both between the different stages of motion in physics and between noise and signal in financial analysis.

In traditional architectures, such features are typically concatenated — stacked on top of one another — so that the model can synthesize all the accumulated information. However, this method treats all features the same, much like a market that does not distinguish between a morning surge in activity and an evening lull. The intermediate layers, which are always more numerous, begin to dominate, and their statistical weight can skew the final decision. The problem is that these intermediate features were derived using linear assumptions and manually applied shifts — their accuracy is limited.

The authors of the TMA framework addressed this with engineering elegance by introducing a cross-attention mechanism that allows motion to be weighted not equally, but according to its degree of alignment with the most recent, most reliable temporal state. The final feature (MFg) serves here as a benchmark, a reference point—much like the close of a trading day, which summarizes all preceding fluctuations and reflects the market’s overall dynamics.

Each intermediate layer (MFi) is compared to this final representation using an attention mechanism, in which cross-similarities are computed. Thus, TMA identifies precisely those motion patterns that are consistent with the latest stage — those that have withstood the evolution of the process and stood the test of time. In trading terms, this can be likened to filtering out noise: a large number of short-term signals are tested for stability relative to a longer-term trend. Only those patterns that maintain a direction and rhythm consistent with the overall movement are amplified, while random fluctuations are attenuated.

Technically, this process is implemented through a series of cross-attention blocks and subsequent nonlinear transformations (MLP), which refine and normalize the features without changing their dimensions. This compactness is important — it allows for increasing depth without overloading the model, just as an analyst can progressively refine a forecast without increasing the number of input variables. As a result, each updated feature (MFi) becomes not merely another snapshot of a time series, but a carrier of consistent and validated patterns.

Figuratively speaking, the motion pattern aggregation module acts as a synthesizer, transforming the polyphony of the time layers into a single melody. It listens to the past, checks the present, and produces an overall harmony in which every note matters. In financial analysis, this approach is similar to integrating signals from different time frames — minute, hourly, and daily — with priority given to those that remain consistent when moving to higher time frames. It is precisely this consistency across multiple time periods that ensures the reliability of the forecast.

TMA combines all three of its key components — event segmentation, linear sampling over time, and aggregation of consistent patterns — into a single computational workflow. Together, they form a framework that does more than simply compute the optical flow; it extracts the internal structure of motion by leveraging a wealth of temporal information. Essentially, the model learns to think in terms of time. It does not rely on static data; it understands the dynamics, just as an experienced trader senses the market's pulse rather than simply looking at the quotes on the screen.

This architecture demonstrates that, when the problem is properly framed, temporal continuity is not an obstacle but a source of additional information. It enables high accuracy even in the early stages of forecasting, when most models still require lengthy refinements. In a financial context, this is equivalent to making a reliable forecast based on the very first price movements, without waiting for confirmation from indicators.

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


Implementation in MQL5

After analyzing the theoretical foundations of the TMA framework, it makes sense to move on to the practical part, where we can see for ourselves how effectively the concepts described work in real-world conditions. We will explore one possible way to implement the proposed ideas using MQL5, drawing on our existing experience with integrating deep architectures into trading infrastructure.

As the framework's authors note, TMA is based on the RAFT architecture — a time-tested approach that has proven itself in solving optical flow problems. This is a significant advantage for us. We have not only familiarized ourselves thoroughly with this framework, but have also implemented it in our own library. As a result, we are starting the project from a very favorable position — we do not need to design the model from scratch; we simply need to adapt the existing code to the specific temporal processing approach proposed in TMA.

This approach can be compared to using a pre-built foundation to construct a new building. The foundation is solid and the infrastructure is in place, so we can focus all our attention on the superstructure — the unique mechanisms that set TMA apart: event stream partitioning, linear sampling in time, and cross-aggregation of motion patterns. Essentially, our task now is not to recreate the architecture, but to infuse it with the dynamics of time. That very temporal sensitivity is what makes TMA such a powerful analytical tool.

However, as we adapt TMA's approaches to the MQL5 environment, we will encounter quite a few pitfalls — both conceptual and purely technical. And this becomes clear right from the start. The authors of the original TMA framework propose segmenting the time stream into non-overlapping blocks of equal duration. At first glance, this is not a particularly difficult problem, especially if you have a fixed time window with a known number of elements. In our practice, we have used similar techniques on numerous occasions when analyzing historical data.

But in this case, things are a little different. The model we developed while studying the RAFT framework has a recurrent architecture. This means that at any given moment, it receives only a snapshot of the current market state — a single frame of price dynamics — rather than a long sequence of values. This approach significantly reduces the computational load. Each frame is processed only once, which makes the model stable and efficient. But this simplicity also has a downside — limited ability to segment along the time axis.

In classical TMA, the analysis is based on a holistic view of the temporal volume, in which each block of events is linked to the preceding and following blocks through a structure of temporal patterns. In our recurrent architecture, this connection is weaker. The model views the market not as a stream, but as a sequence of frames. Therefore, integrating TMA principles requires a special approach — we need to teach the model to perceive temporal depth while keeping it lightweight and fast.

In other words, we face a challenging task — to bring two worlds together. The world of RAFT, where information flows sequentially, like a river, and the world of TMA, where time is viewed as a structured volume, similar to a crystal. We need to find a way to combine these perspectives so that the market flow is not merely recorded but also meaningfully interpreted.

First, let's figure out why these segments are needed at all and how they are used in the TMA structure. The framework's authors propose dividing the temporal stream for reasons other than ease of processing. Each segment here represents a distinct snapshot of market dynamics, within which one can examine the interrelationships and patterns among the features that shape price behavior.

For each such block, a separate correlation map is constructed — a kind of snapshot of interactions over a specific time period. It tracks how the relationships between local features change, how coherently different regions of the price field move, and where temporal market inertia arises. Essentially, each segment becomes a mini-experiment in which the model assesses the nature of the current movement and its underlying logic.

But in the financial markets, time cannot be strictly divided into discrete units. Price movement is a continuous process without clear boundaries, in which each moment flows seamlessly into the next. Any artificial division inevitably leads to the loss of transitional phases, impulses, and microtrends — the very breath of the market that often determines a reversal or an acceleration in price movement.

We decided to move away from rigid discretization and propose a different approach — allowing the model to move along with the flow. Our solution is based on a recurrent architecture that was previously developed during the implementation of the RAFT framework. It allows us to perceive a time series not as a collection of isolated snapshots, but as a continuous narrative. Each new frame is not just a data point, but a natural continuation of the previous state. We place it in a recurrent stack, which stores the last few states—the observation window through which the model views the market.

This window glides along the timeline like a camera lens, constantly focused on the present, yet without losing the depth of context. At each step, correlations between the elements of the window are calculated, forming a multi-layered description of the current motion. However, the model does not recalculate everything from scratch: each frame is processed only once, and all subsequent updates are performed incrementally — only where new data has appeared. Old states gradually exit the stack, making room for new ones, but their influence persists in the accumulated correlation structures.

This approach naturally handles overlapping segments without unnecessary computational overhead. We are creating a dynamic system in which overlaps are not modeled artificially but arise organically, thanks to recurrent memory. Correlation maps serve as a kind of market pulse — they react to the slightest fluctuations, capturing micro-movements while maintaining the stability of the overall picture.

It could be said that the model begins to think like an experienced analyst: it does not view the market as a series of isolated bars, but rather sees it as a continuous flow of capital. Each new tick complements, rather than replaces, the previous observation, forming a comprehensive, dynamic picture.

As part of the practical implementation of the proposed approach, we are creating a new component — CNeuronMultScalStackCorrelBySegments — which serves as the central element in adapting TMA concepts to a recurrent architecture. Its task is to combine multiscale correlation with a segmentation mechanism while preserving the continuous flow of time. Simply put, it is a node where market dynamics are broken down into overlapping time segments and immediately synthesized back together — as an enriched representation of motion.

class CNeuronMultScalStackCorrelBySegments :  public CNeuronAddToStack
  {
protected:
   CNeuronMultiScaleStackCorrelation cCorrelation;
   //---
   virtual bool      feedForward(CNeuronBaseOCL *NeuronOCL) override;
   virtual bool      calcInputGradients(CNeuronBaseOCL *NeuronOCL) override;

public:
                     CNeuronMultScalStackCorrelBySegments(void) {};
                    ~CNeuronMultScalStackCorrelBySegments(void) {};
   //---
   virtual bool      Init(uint numOutputs, uint myIndex, COpenCLMy *open_cl,
                          uint segments, uint segment_size, uint dimension,
                          uint variables, uint levels,
                          ENUM_OPTIMIZATION optimization_type, uint batch);
   //---
   virtual int       Type(void)   override const   {  return defNeuronMultScalStackCorrelBySegments;   }
   //--- methods for working with files
   virtual bool      Save(int const file_handle) override;
   virtual bool      Load(int const file_handle) override;
   //---
   virtual void      SetOpenCL(COpenCLMy *obj) override;
   //---
   virtual void      SetActivationFunction(ENUM_ACTIVATION value) override;
   virtual bool      Clear(void) override;
   //---
   virtual uint      GetLevels(void) const { return cCorrelation.GetLevels(); }
   virtual uint      SetSegmentSize(void) const { return cCorrelation.GetStackSize(); }
  };

The class inherits the basic functionality from CNeuronAddToStack, which allows it to integrate seamlessly into the existing hierarchy of neural modules and use the previously implemented stack logic. An object of type CNeuronMultiScaleStackCorrelation is declared within the class to handle multiscale correlations within the current segment. This object forms the computational foundation, comparing relationships between successive states and creating the temporal fabric of motion on which subsequent predictions are based.

The class is initialized using the Init method, which sets the key parameters: the number of segments, their size, the dimensionality of the feature space, the number of variables, the number of scaling levels, and the optimization type. It constructs the environment in which the neuron will operate and also defines the rules for processing temporal structures.

bool CNeuronMultScalStackCorrelBySegments::Init(uint numOutputs, uint myIndex, COpenCLMy *open_cl,
                                                uint segments, uint segment_size, uint dimension,
                                                uint variables, uint levels,
                                                ENUM_OPTIMIZATION optimization_type, uint batch)
  {
   if(!CNeuronAddToStack::Init(numOutputs, myIndex, open_cl, segments, segment_size * levels,
                                                                    variables, optimization_type, batch))
      return false;
   if(!cCorrelation.Init(0, 0, OpenCL, segment_size, dimension, variables, levels, optimization, iBatch))
      return false;
   SetActivationFunction(None);
//---
   return true;
  }

The first step is to call the method of the same name in the parent class, which creates a stack to store correlation data within a specified number of segments. This approach allows a neuron to analyze not only short-term fluctuations but also to take longer time horizons into account. This is particularly important in the context of financial data: after all, price movements are not a single, instantaneous impulse, but rather the result of a complex interplay of signals with different time scales.

Next, a cCorrelation object is initialized; this object is responsible for calculating the correlations between the analyzed features within a segment. The result is an internal structure in which each level is processed independently, but all results are aggregated into a single correlation field. In effect, a kind of memory map is formed, reflecting the relationships between different segments of the time series. This allows the model to view the market not as a series of unrelated frames, but as a living system in which the past and the present continuously interact.

It is worth noting that the activation function is disabled. This is done intentionally: at this stage, it is important for us to obtain a clear, mathematically precise picture of the correlations, undistorted by nonlinear transformations. Activation functions will be applied later — in situations where the model must not only measure connections but also identify patterns within them.

Thus, the Init method establishes not only technical parameters but also the conceptual foundation for a new approach to time series processing. Thanks to this, the framework is able to view the market across multiple time scales simultaneously, while remaining efficient in terms of computational resources. It is precisely this feature that paves the way for developing more flexible, adaptive, and predictable trading strategies.

In our implementation, the forward pass algorithm serves as the central element linking dynamic correlation processing with the recurrent information accumulation mechanism. In the feedForward method, we essentially combine two processing operations  — the analysis of local relationships within a time segment and the sequential generation of a continuous stream of data that reflects the market’s dynamic pulse.

bool CNeuronMultScalStackCorrelBySegments::feedForward(CNeuronBaseOCL *NeuronOCL)
  {
   if(!cCorrelation.FeedForward(NeuronOCL))
      return false;
   if(!CNeuronAddToStack::feedForward(cCorrelation.AsObject()))
      return false;
//---
   return true;
  }

In the first stage, the method of the same name in the internal cCorrelation object is called, which initiates the calculation of correlations between the features of the current state and the data accumulated within the segment. This is where a correlation map is generated — a kind of snapshot of the market's internal structure over a specified time interval. It identifies which relationships dominate, where movements become more synchronized, and where trends begin to diverge. This is an instantaneous X-ray image of the local state, allowing the model to capture the nature of the interaction between forces at that moment.

The results are then placed into a recurrent stack, which serves as the model's memory. It stores the last few correlation maps. With each new step, the stack is updated: new information is added to it, and old data is gradually pushed out. This creates an effect of overlapping segments — where each new state takes the previous one into account, forming a smooth temporal continuum without the need to recalculate the entire data set.

This mechanism gives the model flexibility and adaptability. It no longer views the market as a collection of independent frames, but rather as a continuous process. Each point in time influences the next. This makes it possible to track not only local correlations but also their dynamics — how the relationships between features strengthen, weaken, or change direction as the price moves.

In the context of financial data, this type of architecture is particularly valuable. After all, the market rarely moves in a straight line — more often than not, it fluctuates, returning to levels it has already reached and gradually forming new patterns of behavior. The feedForward method serves as the mechanism that allows our model to sense these fluctuations without losing its historical momentum. It makes it possible to analyze not only the market's current state, but also its evolution — that is, how the market remembers its own past and uses that memory to shape its current movement.

This is precisely where the proposed approach differs from the classical implementation of TMA. We do not recompute the entire stream; instead, we move through it step by step, preserving context and avoiding redundant computations.

Overall, the CNeuronMultScalStackCorrelBySegments class represents a new stage in the architecture's development — a transition from static processing to dynamic market perception. It allows for the construction of a chain of temporal relationships while maintaining computational efficiency and adapting the TMA methodology to the characteristics of the recurrent approach. The complete code for this class and all of its methods is provided in the attachment.


Conclusion

We have only just turned the first page of a major project — adapting the TMA framework to address financial market challenges using MQL5. Today we explored its theoretical foundations and began putting the authors’ ideas into practice. And the deeper we delve into the TMA architecture, the clearer it becomes: this is not just another method for processing time-series data, but an entire concept capable of transforming the approach to financial market analysis.

The greatest strength of TMA lies in its ability to extract information not from individual frames, but from the flow of time itself. It views movement as a continuous process in which every minute detail bears the imprint of the past and the shadow of the future. This approach is particularly valuable in the financial sector, where context and the sequence of events often matter more than individual figures.

In our implementation, which is based on recurrent processing, we were able to maintain computational efficiency while giving the model a sense of history — the ability to account for overlapping segments without incurring unnecessary computational costs. In fact, TMA, combined with MQL5, takes on the qualities of a living market observer capable of detecting patterns even where traditional methods see only noise.


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/20189

Attached files |
MQL5.zip (3280.15 KB)
Building a PDF Creation Library in MQL5 (Part 3): The Byte-Exact Writer Building a PDF Creation Library in MQL5 (Part 3): The Byte-Exact Writer
The article presents CPdfBuffer and CPdfWriter, a minimal MQL5 pair that derives all offsets from the output buffer instead of hand-maintaining numbers. CPdfWriter records object starts, writes a fixed-width cross-reference table and trailer, and ensures structural consistency. The result passes Part 2's validator, and a ready-to-use script converts arbitrary text to a paginated PDF.
Trading Strategy Beyond Raw Volume: Using Transformed Volume Change for Trading Trading Strategy Beyond Raw Volume: Using Transformed Volume Change for Trading
The article develops a volume-change strategy that transforms tick or real volume with Ln(volume+1), differences it bar to bar, and applies arctan to produce a bounded, scale‑independent signal. A threshold drives entries, with selectable gates for positive, negative, or bi‑directional signals and candle‑based confirmation. An MQL5 Expert Advisor implements the logic and supports fixed TP/SL, N‑candle exits, or both, enabling straightforward testing and deployment.
Using the MQL5 Economic Calendar for News Filter (Part 5): The Tier the Calendar Does Not Have Using the MQL5 Economic Calendar for News Filter (Part 5): The Tier the Calendar Does Not Have
This part extends the news filter with an ordered tier scale that adds a special tier above the broker's High, per‑event time windows, and one classifier shared by live calendar data and historical CSV. A rule table (with optional CSV overrides) promotes or demotes specific releases and can set custom windows. A diagnostic script prints your broker's calendar, event codes, and server time so your rules match what the terminal actually reports.
Color Harmony Algorithm (CHA) Color Harmony Algorithm (CHA)
We take a closer look at the Color Harmony Algorithm (CHA) — a meta-heuristic optimization method based on Munsell's theory of color harmony. We explore the structure of the hue circle, harmony templates, the alternation between the concentration and dispersion phases, and the role of solution memory. From a theoretical framework to a working implementation in MQL5 and unbiased testing on a standard benchmark.