Русский
preview
Neural Networks in Trading: Spatially Guided Aggregation of Market Events (STFlow)

Neural Networks in Trading: Spatially Guided Aggregation of Market Events (STFlow)

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

Introduction

The financial market is traditionally viewed as a sequence of price observations ordered over time. Classical models are based precisely on this representation: the market as a discrete time series, in which each new price observation is appended to the sequence. This perspective is convenient, time-tested, and elegant in its own way. However, with the growth of computing power and the shift toward algorithmic trading, it became clear that such a model reflects only the outer shell of market dynamics, leaving its internal structure out of the picture.

The modern market, especially on short time frames, is driven not by bars and candlesticks, but by events. Quote changes, the emergence of liquidity, aggressive volume absorption, and sharp shifts in the spread all occur asynchronously, unevenly, and often before the next bar has formed. In this sense, traditional candlestick aggregation is not so much a market model as a compromise between ease of analysis and loss of information. The higher the trading frequency, the higher the cost of this trade-off.

This is precisely where a key methodological problem arises: how can we describe and analyze the market if its primary dynamics are event-driven rather than frame-based?

Most neural network models used in trading have adopted architectural principles from time series and image processing. Recurrent networks, one-dimensional convolutions, and transformers — all of them, in one way or another, assume the presence of a regular time grid. Even when high-frequency data is used, the market is still represented using a fixed time step. This simplifies the calculations, but distorts the very nature of the data.

The event-driven market works differently. Information does not arrive on a schedule, but when something actually happens: during quiet periods, there is little data, while during bursts of activity, the stream becomes much denser. Thus, the density of information itself becomes a signal. To ignore this is to lose one of the key sources of market insight.

However, a purely event-based representation also has its limitations. The event stream is rich in temporal information but poor in spatial structure. A single event reveals almost nothing about the context — without understanding exactly where it occurred within the price structure, its significance is difficult to interpret. A familiar dilemma arises: temporal precision versus structural stability.

Virtually all trading models face the challenge of aggregation in one way or another: combining disparate signals into a coherent representation suitable for decision-making. Traditional approaches handle this problem in a crude manner: averaging, summation, and fixed windows. More advanced approaches use attention mechanisms or adaptive filters. But the fundamental problem remains: aggregation is usually not guided by market structure but imposed from outside by the model.

As a result, the model either loses local impulses by smoothing them out or overfits to noise, amplifying random fluctuations. This is particularly critical for financial markets. An aggregation error is not just a loss of accuracy — it is a direct path to instability in a trading system.

The STFlow framework, presented in the paper "Spatially-guided Temporal Aggregation for Robust Event-RGB Optical Flow Estimation," offers a different perspective on this problem. It is based on a simple yet fundamentally important idea: event aggregation must be spatially guided.

In STFlow, the data being analyzed is viewed not as a flat time series, but as a spatiotemporal flow, in which events shape the temporal dynamics, and the price structure defines the space in which these dynamics unfold. In other words, STFlow does not average events blindly; it aggregates them in the context of the current market structure. Spatial reference points — levels, ranges, and local price patterns — serve as a guiding framework within which the temporal flow of events takes on a meaningful form.

This approach is conceptually similar to how an experienced trader perceives the market. An experienced trader does not react to every tick, but considers exactly where it occurred: near a price level, it means one thing; away from any such level, it means something entirely different. STFlow formalizes this principle at the architectural level.

The first and most important advantage of STFlow is robustness. Spatially guided aggregation reduces the model's sensitivity to random noise and the non-uniformity of the event stream. During calm phases, the market does not overheat due to infrequent events; during phases of rapid price movement, information is not lost due to rigid time windows.

The second advantage is scale adaptability. STFlow naturally handles varying data densities. It does not require rigid temporal normalization. This is especially important for real-world markets, where market regimes can change within a single trading session.

The third advantage is structural interpretability. Spatial guides provide a better understanding of which specific market segments contribute to the final signal. This is not a black box completely detached from price, but a model closely linked to its geometry.

The fourth advantage is versatility. STFlow is not tied to any specific market or time frame. It applies equally to futures, currencies, cryptocurrencies, and stocks, and scales from tick-level data to more aggregated representations.

Finally, an important practical aspect is compatibility with modern neural network architectures. STFlow does not conflict with attention mechanisms or convolutional blocks; on the contrary, it provides them with more meaningful input, thereby improving the efficiency of subsequent processing.


STFlow Architecture

The architecture of the STFlow framework is built around a central principle: the temporal aggregation of market events must be subordinate to the spatial structure of price, not the other way around. This defines both the overall structure of the framework and the purpose of each of its components. Unlike traditional neural network solutions, where aggregation is often a side effect of the architecture, in STFlow it is a deliberate, controllable process.

In general terms, STFlow can be viewed as a multi-level system that transforms a sparse stream of events into a stable spatiotemporal representation of the market. At the same time, each level does more than simply process data; it refines the context in which that data is interpreted.

To ensure that different modalities work together coherently during data analysis, the authors of the STFlow framework propose spatially guiding the temporal aggregation of events. The stream of market events is rich and informative in and of itself, but without a consistent context, it remains fragmented and difficult to interpret. Therefore, the architecture is based on the idea of relying on spatially stable features, which provide a framework for the subsequent aggregation of event signals.

The STFlow architecture divides data processing into two complementary streams from the outset. On the one hand, a spatial context is formed that captures the structure of price movements. On the other hand, a temporally dense stream of events reflecting the market's immediate reaction is processed. These two streams neither compete with each other nor are simply mixed together. On the contrary, one serves as a guiding framework, while the other provides dynamics.

The key challenge of the event-driven representation of the market lies in its sparsity and noisy nature. Individual events occur at irregular intervals. Their density varies sharply depending on the market regime, and on their own they convey almost no contextual information. To avoid blind aggregation, STFlow introduces a spatially stable guide based on price data enriched with events.

Price snapshots, despite being a familiar concept, are prone to distortion. Changes in liquidity, localized spikes in volatility, and microstructural noise can temporarily undermine their informational value. Event data, on the other hand, remain sensitive to activity even under adverse conditions. Combining these two sources makes it possible to stabilize the spatial context without complicating the architecture. To achieve this, a simplified event-price representation is used, in which both data sources are carefully linked within a single space.

Before being combined, price and event data are normalized so that their contributions are comparable. The price representation is normalized to a symmetric range, and the event stream is scaled relative to its maximum activity within the current observation period. This approach prevents one modality from dominating the other and maintains a balance between structure and dynamics.

After normalization, a joint representation is formed in which the current price snapshot is supplemented by a stream of events over a limited time window. The choice of this window is crucial. An interval that is too short deprives the model of the necessary context, while one that is too long blurs the spatial boundaries. In STFlow, the window length is aligned with the time scale of the target events, which ensures consistency in subsequent aggregation while simultaneously reducing the computational load.

The representation reflects the complementary nature of price and events. During periods when the price structure becomes unstable, events continue to signal actual market activity; conversely, in calm and liquid conditions, it is the geometry of price that sets the main context, while events merely clarify local dynamics. As a result, the spatial features extracted from the joint representation remain stable across a wide range of market regimes.

In the next step, features are extracted from successive joint representations, and a correlation volume is constructed that captures correspondences between market states at different points in time. This correlation volume reflects not only the aggregate price movement but also the stable spatial relationships formed by the context of events and prices. In the STFlow architecture, it serves as a guidance structure against which all subsequent temporal signals are interpreted.

It is important to emphasize that at this stage, we are no longer simply comparing states. The correlation volume covers the entire observation area and provides a global picture of market movement. It is precisely this that makes it possible to distinguish significant structural shifts from local noise and serves as the basis for guided aggregation of the event stream.

High temporal resolution in event data has long been regarded as the key to compensating for its sparsity and noisy nature. This claim has been confirmed by a number of recent studies in which temporally dense correlation volumes are used instead of a single correlation representation. This approach is based on an important observation: structural movement patterns exhibit temporal coherence, whereas noise — especially under adverse conditions — is typically random and uncorrelated. By aggregating correlation information across multiple time slices simultaneously, it is possible to amplify stable signals and suppress short-term distortions.

In the context of financial markets, this idea seems particularly natural. Real market movements do not occur instantly. Market impulses develop, subside, and transform while maintaining a degree of temporal coherence. Noise, on the other hand — random trades, isolated spikes, and small liquidity gaps — rarely exhibits such coherence. Consequently, temporal density becomes not a source of chaos but a filtering tool.

Based on this, STFlow does not treat the temporal flow of events as a homogeneous mass; instead, it breaks it down into a sequence of intermediate states, each of which captures market movement on its own local time scale. The event stream is divided into a reference representation and a series of target segments that evenly cover the interval under analysis. The initial segment is synchronized with the first price snapshot, and the final segment with the next one, ensuring consistency between the event and price components.

It is essential that all these segments be processed by the same feature encoder. This approach eliminates representation drift and ensures that differences between time slices reflect market dynamics rather than characteristics of the encoding. Thus, the model compares states on a like-for-like basis rather than comparing a set of disparate projections.

For each intermediate event segment, a correlation representation is constructed relative to the reference state. As a result, a set of temporally dense correlation volumes is formed, each of which contains information about local market movement within its own time interval. These correlation volumes have high temporal sensitivity and can detect even short-lived impulses.

However, there is a downside to this representation. Despite the abundance of temporal information, temporally dense correlations remain spatially sparse and unstable. They capture the dynamics but do not preserve the structure well. From a financial perspective, this is like a stream of ticks without any understanding of exactly where within the price range they occurred. Taken individually, these features do not provide a complete picture of the movement.

Once a spatially stable guidance structure and temporally dense correlation representations have been formed, the next fundamental question arises: how can these sources of information be combined so that they do not merely coexist, but actually reinforce one another? To this end, the authors of STFlow introduce the concept of spatiotemporal context, which serves as a link between market structure and market dynamics.

In this case, context is not limited to a set of supporting features. It reflects the overall state of the market over the interval under analysis. The spatial context derived from the price representation captures the geometry and local structural details of the current market state. The temporal context, formed on the basis of a stream of events, encompasses the dynamics of change between two consecutive states. Each of these components, taken individually, can improve the quality of motion estimation. However, their combined use remained underappreciated for a long time.

The authors of STFlow start from the premise that the market does not separate space and time: structure and dynamics coexist and constantly interact. Therefore, instead of using unimodal contextual features, a unified spatiotemporal context is introduced, which combines both aspects into a coherent representation. This context proves to be more informative and stable than either component on its own, as confirmed by experimental results.

A dedicated context encoder with mixed aggregation is used to generate this representation. Spatial contextual features are extracted from the current price snapshot, while temporal features are extracted from the event voxel covering the interval between two consecutive market states. These features are represented in the same feature space and have the same dimensionality, allowing them to be combined without distortion.

After the initial extraction, both feature sets are concatenated and fed into the mixed aggregation block. Its task is not simply to join the data, but to enable local and component-wise interactions, allowing the model to determine for itself which aspects of structure and dynamics are important at each point in space. Using a lightweight multilayer perceptron for processing, in combination with local convolution, ensures that information is propagated within the immediate neighborhood without compromising spatial integrity. The result is a spatiotemporal context that preserves the dimensionality of unimodal features but possesses significantly greater expressive power.

This context becomes a key element of the next stage — the guided aggregation of temporally dense event features. At this point, the architecture already includes two fundamentally different sources of information about market movements. On the one hand, there are spatially stable correlation representations formed on the basis of an event-price framework. On the other hand, there are temporally dense correlations that reflect the detailed dynamics of events. The goal is to integrate them into a single process for refining motion.

In the STFlow update branch, spatial correlation features serve as a guidance signal. They determine which displacements are structurally consistent and thereby guide the aggregation of temporal signals. Temporally dense event correlations, in turn, provide high sensitivity to short-term changes and allow for the precise localization of moments when the motion intensifies or weakens.

The aggregation process begins by sampling local correlation maps corresponding to the current motion estimate. For the spatial modality, this operation reduces to sampling from a stable correlation volume according to the current displacement estimate. For the event-based modality, the situation is more complex: each time segment covers its own interval, so a coordinated linear sampling strategy is used to ensure that time scales are correctly aligned.

The resulting correlation maps are converted into motion features. The spatial component encodes the stable structure and the general direction of motion. Event-based features form a sequence of temporal signals that detail the dynamics within individual portions of the interval. Taken individually, these features are incomplete, but together they provide a rich description of market motion.

The key point is that the aggregation of event-based features is guided by the spatial modality. To do this, a lightweight transformer cross-attention mechanism is used. Temporally dense event-based features serve as queries, while spatial features serve as keys and values. Thus, it is the spatial structure that determines which temporal signals are amplified and which are suppressed.

At the architectural level, this implements an intuitive principle. Events do not dictate the structure of motion; they merely refine it. The spatial context defines the shape and direction, while temporal signals fill that shape with details. The cross-attention mechanism facilitates this interaction at the level of individual representation elements, allowing for flexible adaptation to various market regimes.

The aggregated features are combined into a unified representation of motion and fed into the recurrent refinement module, where the motion estimate is successively refined. This iterative process allows for the gradual alignment of structure and dynamics, eliminating local errors and reinforcing stable patterns.

As a result, STFlow generates a representation of market motion in which the high temporal sensitivity of events is combined with the stability and interpretability of the spatial context. This completes the framework's architectural chain: from sparse events, through guided aggregation, to a coherent and robust description of market dynamics.

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

STFlow training follows classical correlation-based approaches, in which supervision is applied directly to the model output. The L1 distance between the predicted motion and the reference value is used as the loss function. Crucially, supervision is applied to all iterative outputs of the recurrent update block. Each ConvGRU iteration contributes to the final error, but with a decreasing weight. This approach disciplines the model. The model must produce an accurate motion estimate early in the refinement process, rather than bringing the result up to standard only at the end. The exponential decay coefficient gently shifts the focus toward later iterations without devaluing the intermediate ones.



Implementation in MQL5

After a thorough examination of the theoretical foundations of STFlow, it is time to come down from the lofty realm of concepts to a more down-to-earth — but no less interesting — level: practice. Next, we will move on to the practical part of this work, where we will examine one possible way to implement the framework's key ideas using MQL5. The focus will not be on a literal reproduction of the original architecture, but on a thoughtful adaptation of its principles to the specific nature of financial data.

It is important to define the scope from the outset. We are not trying to mechanically transfer computer vision solutions to trading as though simply replacing an image with a price chart. That path usually ends in disappointment. Instead, we are interested in transferring the underlying ideas: spatial stability, temporal signal density, guided aggregation, and cross-modal interaction — all of which constitute the intellectual core of STFlow. In the context of the market, these concepts take on a different — yet very tangible — meaning: price structure, the microdynamics of trade flow, asynchronous events, and their synchronization over time.

As noted earlier, it makes sense to view the STFlow framework as a multi-level signal processing system, in which each level performs a specific task and prepares the data for the next stage. That is precisely where both its strength and the difficulty of implementing it lie. Attempting to implement the entire system all at once, in a single step and without first breaking it down, will inevitably lead either to excessive complexity or to a loss of meaningful connections between the components.

That is precisely why the work that follows will be structured in the same sequential and hierarchical manner as the framework itself. We will move from simple to complex, carefully distinguishing between the different levels of processing. This approach not only reduces engineering risks but also provides a better understanding of each component's contribution to the final result.

From a practical standpoint, this is particularly important in the context of financial markets. Here, predictability, controllability, and the ability to optimize specific areas are valued. A multi-level, step-by-step implementation allows us to adapt the concepts of STFlow to the real-world constraints of the trading environment without compromising the logic of the original approach. The result is not an abstract model as a whole, but a coherent system built up layer by layer — like a fine mechanical timepiece, where every gear is in its proper place and contributes to the overall result.

We will begin our work with the ICE (Image-Event Connection) module — it is this module that lays the foundation for the entire system and provides a stable spatial framework for subsequent processing. In the context of financial markets, ICE serves as a state map. It links the structural representation of price to event streams — sharp spikes in volume, anomalous trades, and other micro-impulses that occur asynchronously.

The module carefully normalizes both data sources, bringing them to a comparable scale, and creates a unified representation in which each price component is linked to the corresponding events. This makes it possible to identify consistent patterns even under conditions of high volatility or sparse data. As a result, ICE becomes the guidance structure that sets the direction for all subsequent aggregation of events and the formation of market motion features.

We implemented this module as the CNeuronCreateICEFlow object, which inherits the basic functionality of the event stream generation object while extending it to accommodate the specifics of ICE. Within this object, normalized price data and the event stream are combined to form a unified representation, where each price element corresponds to the relevant market micro-impulses.

class CNeuronCreateICEFlow :  public CNeuronCreateFlow
  {
protected:
   CNeuronBaseOCL       cConcat;
   //---
   virtual bool      feedForward(CNeuronBaseOCL *NeuronOCL) override;
   virtual bool      updateInputWeights(CNeuronBaseOCL *NeuronOCL) override;
   virtual bool      calcInputGradients(CNeuronBaseOCL *NeuronOCL) override;

public:
                     CNeuronCreateICEFlow(void) {};
                    ~CNeuronCreateICEFlow(void) {};
   //---
   virtual bool      Init(uint numOutputs, uint myIndex, COpenCLMy *open_cl,
                          uint stack_size, uint dimension,
                          uint patch_dimension, uint variables,
                          ENUM_OPTIMIZATION optimization_type, uint batch);
   //---
   virtual int       Type(void)   override const   {  return defNeuronCreateICEFlow;   }
   //--- methods for working with files
   virtual bool      Load(int const file_handle) override;
   //---
   virtual void      SetOpenCL(COpenCLMy *obj)   override;
   //---
   virtual bool      Clear(void) override;
  };

Object initialization in our ICE module is implemented to take into account all key parameters that affect stability and performance.

bool CNeuronCreateICEFlow::Init(uint numOutputs, uint myIndex, COpenCLMy *open_cl,
                                uint stack_size, uint dimension, uint patch_dimension, uint variables,
                                ENUM_OPTIMIZATION optimization_type, uint batch)
  {
   if(!CNeuronSpikePatchStak::Init(numOutputs, myIndex, open_cl, stack_size,
                                   2 * dimension, patch_dimension, variables, optimization_type, batch))
      return false;

The Init method specifies the output data dimensions, patch sizes, and data volumes, and enables OpenCL for accelerated computations.

First, the base stack of state embeddings is initialized with twice the dimensionality to ensure sufficient throughput for processing both price and event data.

Next, the internal components are created one by one. The cState object is designed to store data on the previous market state and current events, defined as the difference between two consecutive market states.

   uint index=0;
   if(!cState.Init(0, index, OpenCL, dimension * variables, optimization, iBatch))
      return false;
   cState.SetActivationFunction(None);

The cConcat concatenation block combines representations from two modalities.

   index++;
   if(!cConcat.Init(0, index, OpenCL, 2 * dimension * variables, optimization, iBatch))
      return false;
   cConcat.SetActivationFunction(None);
//---
   if(!Clear())
      return false;
//---
   return true;
  }

Furthermore, the activation function is disabled for both objects to ensure direct signal transmission without distortion. At the end, the object is cleaned up to ensure that the module starts in a clean and predictable state. This approach ensures proper operation even with high event stream density and allows processing to be safely scaled to handle large volumes of market data.

The forward pass is the heart of the entire processing workflow, where market state data and event streams are combined into a consistent spatial-event representation. The feedForward method carefully implements this process step by step.

bool CNeuronCreateICEFlow::feedForward(CNeuronBaseOCL *NeuronOCL)
  {
   if(!CalcFlow(NeuronOCL))
      return false;

First, the CalcFlow helper method is called to extract the initial changes in the input signals. In the context of financial data, this can be understood as extracting primary market patterns, such as short-lived volume spikes, sharp price changes, and other micro-impulses that have not yet been integrated into a coherent representation. If something goes wrong at this stage, the method aborts execution and returns false.

Next, the key parameters are calculated: the window size and the sequence length. These values determine the depth and breadth of aggregation for events and market data, striking a balance between detail and the stability of the representation.

   uint dimension = cBlock.GetWindow() / 2;
   uint units = cBlock.GetUnits() * cBlock.GetVariables();

The next step is to call the concatenation method, which combines the current market state data with the events identified in the previous step into a single coherent representation. Price data is linked to events, forming a spatially consistent structure that is ready for normalization.

   if(!Concat(NeuronOCL.getOutput(), cState.getOutput(), cConcat.getOutput(),
              dimension, dimension, units))
      return false;
   if(!Normilize(cConcat.getOutput(), dimension))
     return false;

Normalization (Normilize) eliminates scale differences between streams by bringing all values into a comparable range. This is critical for financial data. A sharp spike in volume or a sudden price jump should not disrupt the overall structure.

It is particularly important to note that normalization uses the original, undoubled dimensionality, specified by dimension. This is a key point. It allows market state data and event data to be brought separately into a comparable form while preserving their internal structure and relationships. Combining these streams into a single tensor makes it possible to perform normalization simultaneously for both representations at the OpenCL context level. This approach not only conserves computational resources but also ensures scale consistency, which is critical for subsequent aggregation and the construction of a robust ICE representation.

In other words, we simultaneously preserve the distinction between streams and create a unified foundation for processing them together. This makes the entire system more stable and better able to adapt to sudden market spikes.

The result is passed to the method of the same name in the ancestor class, ensuring the creation of consistent embeddings and further signal propagation through the stack.

   return CNeuronSpikePatchStak::feedForward(cConcat.AsObject());
  }

As a result, each step of the forward pass method logically follows from the previous one: first, we identify the primary movements; then, we combine them with the current state, normalize them, and pass them on. This produces a stable, spatially consistent joint representation that serves as the basis for temporal aggregation and cross-modal integration.

The error gradient propagation algorithm is designed to correctly transmit the training signal through a joint representation of market data that combines the current state with the dynamics of recent events.

bool CNeuronCreateICEFlow::calcInputGradients(CNeuronBaseOCL *NeuronOCL)
  {
   if(!NeuronOCL)
      return false;

The calcInputGradients method begins by checking whether the NeuronOCL object is valid. If it is absent, further calculations are impossible, and the function immediately returns false.

Next, the method of the same name in the parent class is called, which propagates gradients at the neuron stack level, ensuring that the module interacts correctly with the rest of the STFlow architecture.

   if(!CNeuronSpikePatchStak::calcInputGradients(cConcat.AsObject()))
      return false;

Next, the window size and the sequence length are calculated.

   uint dimension = cBlock.GetWindow() / 2;
   uint units = cBlock.GetUnits() * cBlock.GetVariables();
   if(!DeConcat(NeuronOCL.getGradient(), cState.getGradient(), cConcat.getGradient(),
                dimension, dimension, units))
      return false;

The reverse concatenation method unpacks the gradients from the combined tensor back into separate streams: the current market state, stored in NeuronOCL, and the dynamics of recent events, stored in cState. It is important to note that the dynamics are calculated as the difference between the current and previous market states. Accordingly, the gradient received by the dynamics stream is passed in full to the object describing the current state, where it is added to the previously accumulated gradients.

   if(!SumAndNormilize(NeuronOCL.getGradient(), cState.getGradient(), NeuronOCL.getGradient(),
                       dimension, false, 0, 0, 0, 1))
      return false;
   Deactivation(NeuronOCL)
//---
   return false;
  }

This ensures that the training signal takes into account both the stable structure of the market and the impact of recent events.

Finally, the Deactivation method completes the processing by deactivating the temporary activation functions and preparing the accumulated gradients for the next weight update step.

As a result, the entire error propagation process ensures accurate and consistent learning, with the module remaining both robust to noise and sensitive to market dynamics.

Thus, CNeuronCreateICEFlow serves as the foundation for an adapted STFlow system for financial markets. It creates a stable, normalized, and spatially consistent representation, which is then used at subsequent levels of temporal aggregation and cross-modal integration, providing a robust framework for the entire sequential, multi-level architecture.



Conclusion

We have only just taken our first steps. We familiarized ourselves with the theoretical aspects of the STFlow framework and began adapting its approaches to financial markets. Even at this stage, we can identify the system's key strengths. It is capable of forming a robust joint representation of the current market state and the dynamics of recent events, while remaining sensitive to micro-impulses and ensuring stable data processing.

As part of the practical work, the basic structure of the ICE module was implemented to consolidate these two streams and provide a solid foundation for further aggregation and analysis.

In the next article, we will continue implementing the framework by developing algorithms for temporal aggregation and cross-modal integration. This will enable a comprehensive, multi-level analysis of market flows.


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 for describing the system state and model architectures
5 NeuroNet.mqh Class Library Class library for building a neural network
6 NeuroNet.cl Library Code library for the OpenCL program

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

Attached files |
MQL5.zip (3518.68 KB)
Practical MQL5 Utilities (Part 1): Trade Journal Analytics Panel Practical MQL5 Utilities (Part 1): Trade Journal Analytics Panel
This article presents a read-only trade journal for MetaTrader 5 that groups account deals into positions and calculates closed-trade statistics, including profit factor, expectancy, drawdown, and win and loss streaks. It breaks the results down by entry hour and weekday, shows them in a chart panel, and exports the closed positions to a CSV file. The implementation covers HistorySelect, deal and position identifiers, closed-trade sorting, and object-based panel rendering.
Streaming Percentiles in MQL5: Testing the P-Square Algorithm on Real Tick Data Streaming Percentiles in MQL5: Testing the P-Square Algorithm on Real Tick Data
An EA can set spread and tick-gap thresholds by percentile without storing every tick. CPSquare implements the P-Square algorithm, and two order-independent classes serve as alternatives: CCountQuantile returns exact percentiles of rounded spreads, and CLogQuantile keeps a chosen relative error within a set range. Unit tests, mutation runs, and a Python consistency check cover the code. On EURUSD and XAUUSD ticks in time order, the P-Square estimates of high percentiles stayed far from the exact values.
Adaptive Bar Replay Tool in MQL5: Using MFE and MAE Percentile Analysis Adaptive Bar Replay Tool in MQL5: Using MFE and MAE Percentile Analysis
We implement a bar replay indicator in MQL5 that uses historical MFE and MAE percentiles to compute adaptive Stop Loss and Take Profit levels. The article covers data collection, excursion calculation, percentile interpolation, and an event-driven engine that replays candles and manages multiple simulated positions. Readers can test decisions against statistically derived risk thresholds rather than fixed offsets.
Building Your Own Expert Advisor (Part 9): Point-Based and Indicator Trailing Stops Building Your Own Expert Advisor (Part 9): Point-Based and Indicator Trailing Stops
This part extends the MQL5 risk management framework with two trailing stop methods: fixed points and an indicator line. A base class converts chart levels on Bid-built charts into stop prices and adds the current spread to sell stops so they align with Ask-triggered execution. The Series EA integrates these trails alongside the existing ATR and R-ladder options.