preview
Self-Optimizing Expert Advisors in MQL5 (Part 21): Wavelet Denoising With Time-Lagged Independent Component Analysis (4)

Self-Optimizing Expert Advisors in MQL5 (Part 21): Wavelet Denoising With Time-Lagged Independent Component Analysis (4)

MetaTrader 5 — Examples |
24 0
Gamuchirai Zororo Ndawana
Gamuchirai Zororo Ndawana

This article addresses the engineering challenges traders face when building noise filters for algorithmic trading strategies. Inadequate filtering often results in poor performance during live trading execution. Our contribution through this discussion aims to help developers improve signal-to-noise ratios from an example case study of the EURUSD on the daily timeframe.

Independent Component Analysis (ICA) is a statistical method that separates mixed signals into a set of column vectors that are as statistically independent as possible. True signal and random noise are independent; hence, the ICA algorithm has the potential to denoise our time-lagged market data, giving us cleaner trading signals to work with.

In practice, we rarely employ the full ICA algorithm because it is computationally expensive. This approach searches for components that have minimum mutual information (MI), a metric that measures any form of dependence between variables. Minimizing MI ensures that our components are statistically independent. Unfortunately, MI is expensive to calculate, especially in high-dimensional cases.

This computational bottleneck is why most scientific libraries implement more efficient variants of the algorithm. Python libraries such as PICARD (Preconditioned Independent Component Analysis For Real Data) and scikit-learn (FastICA) bypass the costly task of calculating MI and instead work with intelligent approximations of independence. For this reason, we will use the scikit-learn implementation of FastICA. 

We will work with daily EURUSD exchange rates spanning almost 14 years. Our historical data will be partitioned into 3 equal sets for training, validation, and testing. All of our estimators, transformations, and clustering algorithms will only be fit on the training set; the remaining 2 sets will be reserved as out-of-sample test sets to help us approximate the effects of our proposed solution on a potentially representative sample of market behavior.

Building upon our previous implementation of a statistical noise filter using Time-Lagged Independent Component Analysis (TICA), this article outlines methods to refine the framework. These adjustments reduce our forecasting error and enhance structural robustness through two key technical improvements: 

  1. Expanding Lag Horizons for Macro-Market Analysis: Our baseline filter relies on lagged technical indicators spanning only five sequential historical time steps. While a narrow horizon accelerates initial model prototyping and iteration, it risks constraining the model to micro-market structures, which are inherently noisy. Increasing the lag horizon expands our model's visual field, allowing it to capture macro-market structures.
  2. Mitigating Residual Noise Passed by Moving Averages: Our current setup relies on moving averages to smooth raw market data, but we know that residual noise frequently bypasses these indicators. The current architecture maps independent component embeddings directly from these noisy moving average inputs without any prior treatment. To optimize performance, the framework should sanitize the indicator data first. The ICA manifold should be built on denoised readings. This optimization directly enhances all downstream tasks within the trading application.

To achieve the first objective, our MQL5 data retrieval script was modified. The inputs previously dedicated to raw historical prices were replaced with lagged moving average inputs spanning 10, 20, 30, 40, 60, and 80 days. These additional inputs were selected to broaden our model's field of view.

For the second objective, the moving average readings are sanitized using the Discrete Wavelet Transform (DWT)—a mathematically principled algorithm widely utilized for signal denoising, data compression, and harmonic analysis. From a pool of candidate wavelets, the optimal-performing transformation was selected to denoise the moving average inputs. 

Our current solution can be illustrated to the reader by the following schematic diagram. The moving average indicator is currently the only filter between our ICA manifold and the noisy market data we are working with. We currently accept all the indicator's limitations, but we can do better than this. 


Figure 1: A schematic illustration of our current statistical noise filter.

We must make attempts to denoise the moving average inputs before constructing our ICA manifold. For this task, we have selected the wavelet transform. Wavelet transformations can be broadly grouped into two families, continuous and discrete. Our discussion focuses only on the discrete type. Applying this denoising technique makes our piecewise approach more robust to market noise. We are effectively creating a deep computational graph that meaningfully filters market data before attempting to make any predictions.


Figure 2: Our proposed solution will make our manifold more robust to any market noise bypassing the moving average filter.

In our case study, our proposed solution appeared to have improved our ability to forecast smoothed returns by 4% on average. However, this case study was limited to a single symbol and a single time frame. More robust estimates may be obtained from repeating this exercise over more symbols on varying time frames. At this point, we were keen to realize the benefits of wavelet denoising in our MetaTrader 5 terminal. Unfortunately, the PyWavelets library currently lacks native Open Neural Network Exchange (ONNX) support. PyWavelets relies on compiled C and other low-level libraries. These compiled libraries exist as machine code; hence, their computational steps cannot be traced and exported as a standard ONNX graph. To mitigate this limitation, a surrogate model was engineered to approximate the wavelet transformation from noisy moving average inputs.


Getting Started in MQL5

Our first objective is to revise the data collection script. Previous analysis indicated that moving averages provide a richer set of inputs for the model. Consequently, all raw price inputs will be omitted and replaced with moving average readings across broader horizons. The previous input set was limited to a 5-day historical span, which may constrain the model to learning noisy microeconomic structures. In total, the introduction of 6 new historical lag points provides our model with an entirely different structure of inputs. 

Compile the script on your machine, and then drag and drop the script onto your symbol of choice. The script accepts inputs specifying how many bars of historical data should be written to a file; we selected 3650 historical days, which is roughly equal to 14 years of historical market data. Our script is fixed to the daily time frame. This is the time frame that we will use throughout our analysis.

//+------------------------------------------------------------------+
//|                                                  ICA Filtering 2 |
//|                                      Copyright 2026, CompanyName |
//|                                       http://www.companyname.net |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property script_show_inputs

//+------------------------------------------------------------------+
//| Inputs                                                           |
//+------------------------------------------------------------------+
input group "File Properties"
input int size = 3650; //Number of Bars

input group "Technical Indicators"
input int MA_PERIOD = 5; //MA Period
input ENUM_MA_METHOD MA_TYPE = MODE_EMA; //MA Type

//--- File name
string ma_period = (string) MA_PERIOD;
string ma_type = EnumToString(MA_TYPE);
string file_name = Symbol()+ " " + ma_period + " Period" + " " + ma_type + " ICA Noise Filter 2.csv";

//--- Technical indicators
int      ma_h,ma_l,ma_o,ma_c,file_handle;
double   ma_h_reading[],ma_l_reading[],ma_o_reading[],ma_c_reading[];

//--- Fixed variables
int const total_lags = 90;
ENUM_TIMEFRAMES TIME_FRAME = PERIOD_D1;

//+------------------------------------------------------------------+
//| Our script execution                                             |
//+------------------------------------------------------------------+
void OnStart()
  {

//--- initialize indcators
   ma_h = iMA(Symbol(),TIME_FRAME,MA_PERIOD,0,MA_TYPE,PRICE_HIGH);
   ma_l = iMA(Symbol(),TIME_FRAME,MA_PERIOD,0,MA_TYPE,PRICE_LOW);
   ma_o = iMA(Symbol(),TIME_FRAME,MA_PERIOD,0,MA_TYPE,PRICE_OPEN);
   ma_c = iMA(Symbol(),TIME_FRAME,MA_PERIOD,0,MA_TYPE,PRICE_CLOSE);

   if(ma_h == INVALID_HANDLE || ma_l == INVALID_HANDLE ||ma_o == INVALID_HANDLE ||ma_c == INVALID_HANDLE)
     {
      //--- We failed to load the indicators
      Comment("Failed to load Technical Indicators: ",GetLastError());
      return;
     }

   else
     {
      //---Write to file
      file_handle=FileOpen(file_name,FILE_WRITE|FILE_ANSI|FILE_CSV,",");

      for(int i=size+1;i>=1;i--)
        {

         //--- Update indicator values
         //--- High MA
         if(CopyBuffer(ma_h,0,i,total_lags,ma_h_reading) > 0)
           {
            ArraySetAsSeries(ma_h_reading,true);
           }

         else
           {
            Print("Failed to copy the moving average high buffer");
            return;
           }

         //--- Open MA
         if(CopyBuffer(ma_o,0,i,total_lags,ma_o_reading) > 0)
           {
            ArraySetAsSeries(ma_o_reading,true);
           }

         else
           {
            Print("Failed to copy the moving average open buffer");
            return;
           }

         //--- Low MA
         if(CopyBuffer(ma_l,0,i,total_lags,ma_l_reading) > 0)
           {
            ArraySetAsSeries(ma_l_reading,true);
           }

         else
           {
            Print("Failed to copy the moving average low buffer");
            return;
           }

         //--- Close MA
         if(CopyBuffer(ma_c,0,i,total_lags,ma_c_reading) > 0)
           {
            ArraySetAsSeries(ma_c_reading,true);
           }

         else
           {
            Print("Failed to copy the moving average close buffer");
            return;
           }



         //--- Fill in the column names
         if(i == size+1)
           {
            FileWrite(file_handle,
                      //--- Time
                      "Time",
                      //--- Indicators
                      "MA O",
                      "MA H",
                      "MA L",
                      "MA C",
                      //--- Indicators lag 1
                      "MA O Lag 1",
                      "MA H Lag 1",
                      "MA L Lag 1",
                      "MA C Lag 1",
                      //--- Indicators lag 2
                      "MA O Lag 2",
                      "MA H Lag 2",
                      "MA L Lag 2",
                      "MA C Lag 2",
                      //--- Indicators lag 3
                      "MA O Lag 3",
                      "MA H Lag 3",
                      "MA L Lag 3",
                      "MA C Lag 3",
                      //--- Indicators lag 4
                      "MA O Lag 4",
                      "MA H Lag 4",
                      "MA L Lag 4",
                      "MA C Lag 4",
                      //--- Indicators lag 5
                      "MA O Lag 5",
                      "MA H Lag 5",
                      "MA L Lag 5",
                      "MA C Lag 5",
                      //--- Indicators lag 10
                      "MA O Lag 10",
                      "MA H Lag 10",
                      "MA L Lag 10",
                      "MA C Lag 10",
                      //--- Indicators lag 20
                      "MA O Lag 20",
                      "MA H Lag 20",
                      "MA L Lag 20",
                      "MA C Lag 20",
                      //--- Indicators lag 30
                      "MA O Lag 30",
                      "MA H Lag 30",
                      "MA L Lag 30",
                      "MA C Lag 30",
                      //--- Indicators lag 40
                      "MA O Lag 40",
                      "MA H Lag 40",
                      "MA L Lag 40",
                      "MA C Lag 40",
                      //--- Indicators lag 60
                      "MA O Lag 60",
                      "MA H Lag 60",
                      "MA L Lag 60",
                      "MA C Lag 60",
                      //--- Indicators lag 80
                      "MA O Lag 80",
                      "MA H Lag 80",
                      "MA L Lag 80",
                      "MA C Lag 80"
                     );
           }

         //--- Fill in the column values
         else
           {
            FileWrite(file_handle,
                      iTime(_Symbol,TIME_FRAME,i),
                      //--- Indicators
                      ma_o_reading[0],
                      ma_h_reading[0],
                      ma_l_reading[0],
                      ma_c_reading[0],
                      //--- Indicators lag 1
                      ma_o_reading[1],
                      ma_h_reading[1],
                      ma_l_reading[1],
                      ma_c_reading[1],
                      //--- Indicators lag 2
                      ma_o_reading[2],
                      ma_h_reading[2],
                      ma_l_reading[2],
                      ma_c_reading[2],
                      //--- Indicators lag 3
                      ma_o_reading[3],
                      ma_h_reading[3],
                      ma_l_reading[3],
                      ma_c_reading[3],
                      //--- Indicators lag 4
                      ma_o_reading[4],
                      ma_h_reading[4],
                      ma_l_reading[4],
                      ma_c_reading[4],
                      //--- Indicators lag 5
                      ma_o_reading[5],
                      ma_h_reading[5],
                      ma_l_reading[5],
                      ma_c_reading[5],
                      //--- Indicators lag 10
                      ma_o_reading[10],
                      ma_h_reading[10],
                      ma_l_reading[10],
                      ma_c_reading[10],
                      //--- Indicators lag 20
                      ma_o_reading[20],
                      ma_h_reading[20],
                      ma_l_reading[20],
                      ma_c_reading[20],
                      //--- Indicators lag 30
                      ma_o_reading[30],
                      ma_h_reading[30],
                      ma_l_reading[30],
                      ma_c_reading[30],
                      //--- Indicators lag 40
                      ma_o_reading[40],
                      ma_h_reading[40],
                      ma_l_reading[40],
                      ma_c_reading[40],
                      //--- Indicators lag 60
                      ma_o_reading[60],
                      ma_h_reading[60],
                      ma_l_reading[60],
                      ma_c_reading[60],
                      //--- Indicators lag 80
                      ma_o_reading[80],
                      ma_h_reading[80],
                      ma_l_reading[80],
                      ma_c_reading[80]
                     );
           }
        }

     }
//--- Close the file
   FileClose(file_handle);
  }
//+------------------------------------------------------------------+

Analyzing Our Market Data in Python

We are now ready to start analyzing our market data in Python; let us first import the libraries we need.

#Import our standard Python libraries
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

Read in the market data.

#Read in our historical market data
data = pd.read_csv("/ENTER/YOUR/PATH/HERE/EURUSD 5 Period MODE_EMA ICA Noise Filter 2.csv")

Set a fixed horizon for our forecasting task. Our current forecasting horizon has been carried over from our previous discussion; it is not necessarily the best we can do and is by no means guaranteed to be optimal. We only carry over this fixed parameter for consistency with our previous discussion and rapid prototyping of ideas.

#Define our forecast horizon
HORIZON = 5

Label the data using our surrogate target. This will also serve as a proxy to help us measure the efficiency of our proposed solution.

#Label the historical market data
data['Target'] = data['MA C'].shift(-HORIZON) - data['MA C']
data['Target Bin'] = 0

data.loc[data['Target'] > 0,'Target Bin'] = 1
data.dropna(inplace=True)
data

Let us visually inspect the distribution of the target to make sure our surrogate target is not imbalanced. In Figure 3, we have prepared a kernel density plot that shows us the distribution of the 2 target classes in our dataset. Our dataset is not evenly distributed between the 2 classes; we can observe that there are slightly more bearish labels, 0, than there are bullish labels, 1. However, the discrepancy here is not wide enough to be considered problematic; we can still learn meaningful relationships even though the 2 classes are slightly imbalanced.

#Let us observe how well balanced our target is
sns.kdeplot(data['Target Bin'])

Figure 3: Our surrogate target appears to be slightly imbalanced.

We must group the inputs the model accepts and the prediction targets. 

#Now group the inputs
X = data.iloc[:,1:-2].columns
#And the targets
y = data.iloc[:,-2:].columns

Let us partition our dataset into training, validation, and test sets. We will only fit our models on the train set and then evaluate the impact of the changes we have made on the held-out validation and test sets.

#Partition the dataset into training, validation and test sets
#Define the train segment
train_start = 0
train_end   = int(((data.shape[0] * (1/3)) // 1))

#Define the validation segment
validation_start = train_end + HORIZON
validation_end =  int(((data.shape[0] * (2/3)) // 1))

#Define the test segment
test_start = validation_end + HORIZON
test_end   = data.shape[0]

#Create the partitions
train, validation , test = data.iloc[train_start:train_end,:], data.iloc[validation_start:validation_end,:] , data.iloc[test_start:test_end,:]



Brief Introduction to Wavelets

A wavelet is a localized mathematical function defined by specific structural constraints. Unlike traditional sine and cosine functions that oscillate infinitely, wavelets are localized in both time and frequency. Wavelets exist in various families, each designed to capture distinct localized patterns within a dataset.

Once a specific mother wavelet is selected, the wavelet is stretched and shifted along the time axis. At each point, the transform calculates coefficients that quantify the correlation between the localized data segment and the scaled, shifted mother wavelet. Mathematically, the wavelet transform generalizes the Fourier transform by utilizing localized basis functions instead of infinite sinusoids. This approach provides exceptional computational efficiency and simultaneous time-frequency resolution, allowing for the isolation of dominant underlying structures masked by high-frequency noise.

Discrete wavelets are defined for tasks involving data that is periodically sampled, usually by digital sensors. For this reason, we will only work with discrete wavelets in our discussion. The current version of the PyWavelets library implements five discrete wavelet families. Each wavelet family possesses distinct characteristics optimized for specific applications.

Notably, of the five discrete wavelet families we can work with, three share a common contributor in mathematician Ingrid Daubechies. A Fellow of the IEEE since 1993, Daubechies transformed wavelet theory from abstract mathematics into a cornerstone principle of signal processing.

Her work enables wavelets to process discontinuous data containing spikes and sudden jumps. This capability is critical for quantitative trading models, as financial markets frequently exhibit gaps rather than continuous price transitions. Within our shortlist, the 'db' family is named in her honor, while the 'coif' and 'sym' families represent further contributions by Daubechies to modern wavelet theory.

Ingrid Daubechies

Figure 4: Ingrid Daubechies has made many significant contributions to the field of wavelet theory.


Performing Wavelet Denoising

To perform wavelet denoising, the necessary computational libraries must first be initialized.

#Import our wavelet denoising libraries
import pywt
from skimage.restoration import denoise_wavelet

A complete list of all available wavelets can be obtained from the PyWavelets library. As we have mentioned earlier, the library supports both continuous and discrete time wavelets, but we will only work with discrete wavelets.

#A complete list of all supported wavelet families
pywt.wavelist()

Wavelets exist in families. In the PyWavelets package, only 5 families of wavelets are discrete. We will randomly sample members of each family to create a pool of 17 candidate transformations we could apply to our dataset. It is necessary for us to keep in mind that this small sample of wavelets do not necessarily represent the best possible solution. We only picked a few wavelets for demonstrational purposes. However, considering how inexpensive these transformations are to apply, readers with sufficient time and compute may consider performing a brute force search over all the discrete wavelet transforms. This would be more robust than the solution we are demonstrating in our limited case study.

#Our shortlist of wavelet transformations 
wavelet_families = ['coif1','coif4','coif6','coif10','coif17','db1','db8','db22','db12','db20','dmey','haar','sym2','sym14','sym5','sym10','sym17']

The next step requires implementing a function that returns a denoised wavelet signal. This function accepts a noisy input signal and the name of the mother wavelet as parameters.

We mentioned earlier that at each time step, the wavelet algorithm assigns a coefficient to score how well the current data segment correlates with the stretched and shifted mother wavelet. There are multiple strategies one can implement to decide how these scores should be assigned. PyWavelets currently supports two assignment strategies, BayesShrink and hard thresholding.

Hard thresholding sets all coefficient values below a designated threshold to zero; however, this approach is generally discouraged as it loses critical information by rigidly enforcing sparsity. Conversely, the BayesShrink method calculates optimal, adaptive threshold levels for distinct data segments, enforcing sparsity on a case-by-case basis. We will select the BayesShrink strategy.

Important parameters, such as wavelet levels, have a strong influence on the results we will obtain. Unfortunately, there is no single setting for this parameter that simultaneously satisfies all of our 17 candidate wavelet transformations. Therefore, we were faced with two options: we could either iterate through different level settings for each wavelet transform we wish to apply, but this would significantly increase the complexity of our search space. Instead, we opted to keep this parameter fixed at a level of 1. This compromise simplified our search procedure considerably, and moreover, a level setting of 1 was acceptable by almost all of our wavelets.

We will also implement a utility function that will return a denoised wavelet dataset. The function accepts the original noisy dataset and the name of the mother wavelet as its input parameters and returns a wavelet-transformed copy of the original dataset.

#Define a function to return a wavelet denoised signal to us
def wavelet_denoise(input_signal,wavelet_family='db1'):
    #Perform wavelet denoising using the user defined family of wavelet denoising
    clean_signal = denoise_wavelet(input_signal,method='BayesShrink',sigma=None,wavelet=wavelet_family,wavelet_levels= 1 ,rescale_sigma=True,mode='soft')
    #Return the clean signal
    return(clean_signal)

#Create a function to return a denoised wavelet dataset
def return_denoised_wavelet_dataset(user_data,user_wavelet='db1'):
    denoised_wavelet_dataset = user_data.copy()

    for col in denoised_wavelet_dataset.columns:
        denoised_wavelet_dataset[col] = wavelet_denoise(input_signal=user_data[col],wavelet_family=user_wavelet)

    return(denoised_wavelet_dataset.copy())

We can now load the statistical tools we need to assess the changes we are about to make.

#Let us now asses the changes we have made
from sklearn.neighbors import KNeighborsRegressor as KNR
from sklearn.model_selection import cross_val_score,TimeSeriesSplit
from sklearn.metrics import root_mean_squared_error as RMSE

Let us also define a time-series cross-validation object and implement a utility function that will return the cross-validated score our model obtained. The function accepts the model to be evaluated, the model's input, the prediction target, the name of the scoring method to be used, and a cross-validation object as its parameters. Once the cross-validation procedure has been completed, the absolute value of the model's performance is averaged and returned to the calling context.

#Define our time series cross-validation object
tscv = TimeSeriesSplit(n_splits=5,gap=HORIZON)

#Define a function to return the cross validated score for our model
def return_cross_val_score(model,model_inputs,model_target,scoring_method,cv_method):
    #Return our average performance levels
    score = np.mean(np.abs(cross_val_score(estimator=model,X=model_inputs,y=model_target,cv=cv_method,n_jobs=-1,scoring=scoring_method)))
    return(score)

Lastly, before performing our analysis, we will need a matrix to store our cross-validated error results and a utility function that will return an instance of the model we will use in our trading application.

#Create a matrix to store our CV results
cv_train_matrix = np.zeros((5,len(wavelet_families)))
cv_train_matrix = pd.DataFrame(cv_train_matrix,columns=wavelet_families)

#Create a matrix to store our CV results
cv_test_matrix = np.zeros((5,len(wavelet_families)))
cv_test_matrix = pd.DataFrame(cv_test_matrix,columns=wavelet_families)

#Our evaluation model
def evaluation_model():
    return(KNR(n_jobs=-1))

Let us now cross-validate the discrete wavelet transformations we have available. Our analysis will be performed in a time series split. The wavelet transformation will only be applied to the training partition, and the error rates will be measured on the test partition.

for i,(train_index,test_index) in enumerate(tscv.split(train)):
    #Fold number
    print(f'Fold {i+1}')

    #define training and test sets
    train_start = train_index[0]
    train_end   = train_index[-1]
    test_start  = test_index[0]
    test_end    = test_index[-1]

    train_X = train.loc[train_start:train_end,X]
    train_y = train.loc[train_start:train_end,y[0]]

    test_X = train.loc[test_start:test_end,X]
    test_y = train.loc[test_start:test_end,y[0]]
    
    #Evaluate each wavelet transform 
    for j in np.arange(len(wavelet_families)):
        
        #Select the candidate wavelettransform
        candidate_wavelet = wavelet_families[j]

        #Apply candidate wavelet transform
        candidate_train_X = return_denoised_wavelet_dataset(train_X,user_wavelet=candidate_wavelet)

        #Create a wavelet approximator
        candidate_wavelet_approximator = evaluation_model()

        #Fit the wavelet approximator
        candidate_wavelet_approximator.fit(train_X,candidate_train_X)

        #Create the final return model
        candidate_return_approximator = evaluation_model()

        #Fit the return model
        candidate_return_approximator.fit(candidate_wavelet_approximator.predict(train_X),train_y)

        #Store the candidate model predictions
        candidate_train_predictions = candidate_return_approximator.predict(candidate_wavelet_approximator.predict(train_X))
        candidate_test_predictions = candidate_return_approximator.predict(candidate_wavelet_approximator.predict(test_X))

        #Store the candidate error results
        cv_test_matrix.iloc[i,j] = RMSE(test_y,candidate_test_predictions)
        cv_train_matrix.iloc[i,j] = RMSE(train_y,candidate_train_predictions)
        
        #Apply the candidate wavelet on the training partition
        print(f'Evaluating {candidate_wavelet}')
        
    
    #End of training session
    print(f'End of Fold {i+1}')
    print('\n')
    
print('Done')

Fold 1

Evaluating coif1

Evaluating coif4

...

We will conveniently store the name of the best-performing mother wavelet. Our best-performing wavelet in this setup was the 'sym17' wavelet transformation.

#Identify the best wavelet family
best_wavelet = wavelet_families[np.argmin(cv_test_matrix.describe().loc['mean',:].values)]
best_wavelet

'sym17'

We can now visualize our results. In machine learning, the training error is always lower than the test error. What we are interested in is the relationship between the two curves. If our training error keeps falling, while our test error continues to rise, this is normally interpreted as a sign of overfitting. Meaning that our model is learning too much of the noise in the train set. However, in our example, our test error rises and then falls to its lowest levels while our training error remains almost unchanged. This may be an indicator that our model is learning meaningful patterns without overfitting to the training set.

plt.plot(cv_train_matrix.loc[:,best_wavelet],color='green')
plt.plot(cv_test_matrix.loc[:,best_wavelet],color='red')
plt.legend(['Train','Test'])
plt.grid()


Figure 5: The best performing wavelet transformation we found was the 'sym17' wavelet.


How Does Wavelet Denoising Affect Our Spectral Clusters?

We also want to evaluate the impact of wavelet denoising on the spectral clusters identified in our dataset. Previously, we applied the spectral clustering algorithm directly to the lagged moving average inputs and achieved optimal performance using eight clusters. We will now assess whether clustering the wavelet-transformed data instead yields superior performance. Let us start by first importing the libraries we need and then creating a matrix to store our cross-validated error results.

#Let us recalibrate the Spectral Clusters
from sklearn.cluster import SpectralClustering as SC
from sklearn.preprocessing import OneHotEncoder as OHE

#Create a matrix to store our cross-validated results
cv_test_matrix = np.zeros((5,10))
cv_test_matrix = pd.DataFrame(cv_test_matrix)

cv_train_matrix = np.zeros((5,10))
cv_train_matrix = pd.DataFrame(cv_train_matrix)

Spectral clustering becomes expensive as we look for numerous clusters in the dataset. For this reason, we will limit our search to a maximum of 10 clusters. We will record the error levels produced by a model that forecasts future smoothed market returns, given the identified spectral cluster. We will start by recording our performance when we cluster the training data in its original form.

for i,(train_index,test_index) in enumerate(tscv.split(train)):
    #Fold number
    print(f'Fold {i+1}')

    #define training and test sets
    train_start = train_index[0]
    train_end   = train_index[-1]
    test_start  = test_index[0]
    test_end    = test_index[-1]

    train_X = train.loc[train_start:train_end,X]
    train_y = train.loc[train_start:train_end,y[0]]

    test_X = train.loc[test_start:test_end,X]
    test_y = train.loc[test_start:test_end,y[0]]

    #We want to test a maximum of 10 clusters
    for j in np.arange(10):
        #Total clusters
        clusters = int(j+1)
        
        #Initialize the clustering object
        spectral_encoder = SC(n_clusters=clusters,random_state=0,eigen_solver='arpack',n_components=None,n_jobs=-1,n_init=30,affinity='rbf',n_neighbors=30,assign_labels='cluster_qr')
        
        #Learn spectral clusters
        spectral_encoder.fit(train_X)
        
        #Initialize the one hot encoder
        ohe_encoder = OHE(sparse_output=False)
        
        #One hot encode the spectral clusters
        spectral_clusters = pd.DataFrame(spectral_encoder.labels_,columns=['Cluster'])
        clusters_train = pd.DataFrame(ohe_encoder.fit_transform(spectral_clusters))

        #Create a model to approximate spectral clustering
        clustering_model = evaluation_model()
        
        #Create a model to reconstruct returns
        returns_model = evaluation_model()
        
        #Evaluate our new performance levels
        clustering_model.fit(train_X,clusters_train)

        returns_model.fit(clustering_model.predict(train_X),train_y)

        cv_train_matrix.iloc[i,j] = (RMSE(train_y,returns_model.predict(clustering_model.predict(train_X))))
        cv_test_matrix.iloc[i,j] = (RMSE(test_y,returns_model.predict(clustering_model.predict(test_X))))
          
print('Done')

Not only that, but we can visualize our results using a violin plot. From the plot, we can observe a general trend: increasing the number of clusters appears to reduce our error levels. On the original dataset, we achieved optimal performance from 5 clusters.

sns.violinplot(cv_test_matrix)

Figure 6: On the original dataset, spectral clustering achieved optimal performance with just 5 clusters.

We will now repeat the same exercise, but this time around we will cluster the wavelet-denoised dataset. A new matrix has been created to store the error levels recorded as we iterate from 1 to 10 clusters. The time series split function provides us with training and test partitions from our original train set. We apply the wavelet transformation on the training partition of our dataset and fit a surrogate model to approximate this transformation. From there, we measure the error levels produced on the test partition when our surrogate clustering model is applied to the approximated wavelet transformed test set. The results have been visualized using the violin plot in Figure 7. Detailed results are captured in the table beneath the violin plot.

cv_test_wavelet_matrix = np.zeros((5,10))
cv_test_wavelet_matrix = pd.DataFrame(cv_test_wavelet_matrix)

cv_train_wavelet_matrix = np.zeros((5,10))
cv_train_wavelet_matrix = pd.DataFrame(cv_train_wavelet_matrix)

for i,(train_index,test_index) in enumerate(tscv.split(train)):
    #Fold number
    print(f'Fold {i+1}')

    #define training and test sets
    train_start = train_index[0]
    train_end   = train_index[-1]
    test_start  = test_index[0]
    test_end    = test_index[-1]

    train_X = train.loc[train_start:train_end,X]
    train_y = train.loc[train_start:train_end,y[0]]

    test_X = train.loc[test_start:test_end,X]
    test_y = train.loc[test_start:test_end,y[0]]

    #We want to test a maximum of 10 clusters
    for j in np.arange(10):
        #Total clusters
        clusters = int(j+1)
        
        #Initialize the clustering object
        spectral_encoder = SC(n_clusters=clusters,random_state=0,eigen_solver='arpack',n_components=None,n_jobs=-1,n_init=30,affinity='rbf',n_neighbors=30,assign_labels='cluster_qr')

        #Wavlet training set
        wavelet_train_cv = return_denoised_wavelet_dataset(train_X,best_wavelet)

        #Create a model to approximate the wavelet transformation
        wavelet_model = evaluation_model()

        #Fit the wavelet approximator
        wavelet_model.fit(train_X,wavelet_train_cv)

        #Store the approximated wavelet transformation
        approximated_wavelet = pd.DataFrame(wavelet_model.predict(train_X))
        
        #Learn spectral clusters
        spectral_encoder.fit(approximated_wavelet)
        
        #Initialize the one hot encoder
        ohe_encoder = OHE(sparse_output=False)
        
        #One hot encode the spectral clusters
        spectral_clusters = pd.DataFrame(spectral_encoder.labels_,columns=['Cluster'])
        clusters_train = pd.DataFrame(ohe_encoder.fit_transform(spectral_clusters))

        #Create a model to approximate spectral clustering
        clustering_model = evaluation_model()
        
        #Create a model to reconstruct returns
        returns_model = evaluation_model()
        
        #Evaluate our new performance levels
        clustering_model.fit(approximated_wavelet,clusters_train)

        returns_model.fit(clustering_model.predict(approximated_wavelet),train_y)
        
        cv_train_wavelet_matrix.iloc[i,j] = RMSE(train_y,returns_model.predict(clustering_model.predict(wavelet_model.predict(train_X))))
        cv_test_wavelet_matrix.iloc[i,j] = RMSE(test_y,returns_model.predict(clustering_model.predict(wavelet_model.predict(test_X))))
          
print('Done')


Figure 7: Spectral clustering on the wavelet denoised dataset appears to reach optimal performance at 10 clusters.

In the table below, we present the error levels produced by the two clustering approaches. We observed that the lowest error levels were obtained by applying spectral clustering to the approximated wavelet denoised dataset.

Methodology Error Levels
Applied spectral clustering on the wavelet denoised dataset 0.011886264183507925
Applied spectral clustering on the dataset in its original form 0.012327809330290956

We recorded a 3% improvement in clustering error when we performed our clustering on the approximated wavelet dataset. Our results are limited to this case study; a fresh run of this methodology on your symbol of interest may yield different results.

(((control_clustering - wavelet_clustering) / control_clustering) * 100)

np.float64(3.581700000000004)

We will now reconstruct the ideal clustering setup we observed. 

#Let us store the best results we have found 
clusters = np.argmin(cv_test_wavelet_matrix.describe().loc['mean',:]) + 1
spectral_encoder = SC(n_clusters=clusters,random_state=0,eigen_solver='arpack',n_components=None,n_jobs=-1,n_init=30,affinity='rbf',n_neighbors=30,assign_labels='cluster_qr')
spectral_encoder.fit(wavelet_train)
ohe_encoder = OHE(sparse_output=False)
spectral_clusters = pd.DataFrame(spectral_encoder.labels_,columns=['Cluster'])
clusters_train = pd.DataFrame(ohe_encoder.fit_transform(spectral_clusters))
train = train.join(spectral_clusters)

The number of days that belong to each cluster is skewed in favor of cluster 8. This implies that clusters 1 and 4, which have the smallest populations, may be the most challenging for our surrogate model to identify.

#Visualize the distribution of the ideal number of clusters
sns.histplot(spectral_clusters,bins=clusters)


Figure 8: Cluster 1 has the smallest population and may be difficult to approximate correctly.


Recalibrating Cluster Statistics

In our previous discussion, we employed the econometric statistics associated with each cluster to dynamically adjust our market exposure. We want to understand how our new clustering setup affects the market statistics associated with each spectral cluster. However, we must keep in mind that the statistics associated with clusters 1 and 4 must be interpreted with a pinch of salt. Due to the small population of these 2 clusters, the statistics we are trying to learn about this cluster may be distorted.

In Figure 9 below, we have created a bar plot to help us visualize the risk of the returns associated with each cluster. We can see that clusters 3, 4, and 6 appear to have below-average risk levels. However, clusters 1, 2, and 5 appear to be associated with the most volatile returns.

#We will store important cluster stats in these variables
cluster_risk    = []
cluster_return  = [] 

#Learn the risk and return statitics associated with each cluster
for i in np.arange( clusters ):
  #Append cluster statistics
  cluster_risk.append(train.loc[train['Cluster'] == i,'Target'].std())
  cluster_return.append(train.loc[train['Cluster'] == i,'Target'].mean())

#Visualize the risk level of each cluster
sns.barplot(cluster_risk,palette='bright')


Figure 9: Clusters 1, 2, and 5 appear to be associated with the most market risk.

When we consider the expected return associated with each cluster, we observe that cluster 2 appears to be wildly associated with bearish returns. As we have already discussed, clusters with small populations may have distorted statistics, as appears to be the case in Figure 10. Nevertheless, we will copy these updated statistics into our Expert Advisor to help us dynamically manage our risk tolerance levels based on the spectral clusters we have identified in the wavelet-denoised input data.

#Visualize the returns associated with each cluster
sns.barplot(cluster_return,palette='bright')


Figure 10: Most clusters appear to be strongly associated with bearish returns.


Optimizing Our ICA Transformation For Wavelet Denoised Inputs

We need to recalibrate our ICA transformation to accommodate the wavelet transformation we have applied to our training data. To achieve this end, we can create a pipeline that allows us to tune the ICA algorithm in a supervised manner. The performance of our KNeighborsRegressor will be our supervisory signal for selecting optimal ICA parameters.

Define the input parameters we want to search and the values we will consider. We will allow anywhere from 2 to 15 ICA components and also allow for non-linear effects to be modeled by iterating through different cost functions the algorithm supports, such as cubic and exponential cost functions. We are optimizing the ICA algorithm over the wavelet dataset. 

In our current setup, we permit 100 optimization iterations. The number of optimization iterations we allow is an important tuning parameter that holds significant influence over the results we will obtain. This number represents a tradeoff between computational considerations and the quality of the results found. Allowing more iterations costs more time but produces better quality results. We have selected 100 iterations due to our computational constraints. Readers with a larger computational budget are highly encouraged to increase this important hyperparameter to yield better quality results.

#Let us now see how wavelet denoising affects our ICA manifold
from sklearn.decomposition import FastICA as FICA
from sklearn.pipeline import Pipeline
from sklearn.model_selection import RandomizedSearchCV

#Create a new pipeline
pipe = Pipeline([('ica',FICA(random_state=0,max_iter=300,w_init=None)),('knr',KNR(n_jobs=-1))])

#Define the parameter distribution we want to search over
param_dist = {
              'ica__n_components':[2,3,4,5,6,7,8,9,10,11,12,13,14,15],
              'ica__tol':np.logspace(-10,2,10),
              'ica__algorithm':['parallel','deflation'],
              'ica__whiten':['arbitrary-variance','unit-variance'],
              'ica__fun':['logcosh','exp','cube'],
              'ica__whiten_solver':['svd','eigh']
             }

#Configure the random search
rscv = RandomizedSearchCV(pipe,param_distributions=param_dist,
                          n_iter=100,
                          cv=tscv,
                          scoring='neg_mean_squared_error',
                          n_jobs=-1)

#Perform the search for optimal ICA parameters
rscv_res = rscv.fit(wavelet_train,train.loc[:,'Target'])

Store the optimal settings we found for our wavelet-denoised ICA manifold and validate that all our matrices are of the same shape.

#Store the optimal estimator on the wavelet denoised training set
optimal_encoder = FICA(whiten_solver='svd',whiten='arbitrary-variance',tol=np.float64(1e-06),n_components=15,fun='cube',algorithm='deflation')

#Store the optimal denoised ICA manifold obtained from our optimal encoder
sanitized_ica_manifold = pd.DataFrame(optimal_encoder.fit_transform(wavelet_train))
sanitized_ica_manifold.shape[0]

1214

Calculate the growth in each ICA component and store the manifold growth in its own matrix. Check the shape of the matrix and ensure it matches the shape of the denoised ICA manifold.

sanitized_ica_manifold_growth = sanitized_ica_manifold.iloc[:,:].shift(-HORIZON) - sanitized_ica_manifold.iloc[:,:]
sanitized_ica_manifold_growth.shape[0]

1214

Our training dataset should also be of the same number of rows as the two matrices we have just considered.

train.shape[0]

1214

All our input matrices have the same number of rows. Therefore, we can now start learning to approximate the wavelet transform and our sanitized ICA embeddings.

wavelet_train.shape[0]

1214

The matrix that stores the growth in our ICA manifold has non-numeric values in its last few rows. We will drop all those rows and ensure that the same adjustment is made to all the other matrices we are working with.

#Make sure all the matrices align
train = train.iloc[:-HORIZON,:]
wavelet_train = wavelet_train.iloc[:-HORIZON,:]
sanitized_ica_manifold = sanitized_ica_manifold.iloc[:-HORIZON,:]
sanitized_ica_manifold_growth = sanitized_ica_manifold_growth.iloc[:-HORIZON,:]
clusters_train = clusters_train.iloc[:-HORIZON,:]

Initialize the models we need for our noise filter. 

#Prepare our chain of models
wavelet_encoder = KNR()
denoised_ica_manifold = KNR()
ica_manifold_growth = KNR()
returns_reconstruction = KNR()
spectral_clustering = KNR()

Our first model learns to approximate the 'sym17' wavelet transformation from raw moving average inputs. This surrogate model sits close to the root of our computational graph. The estimated wavelets are stored in a matrix and passed down the network of models. 

Note: Excluding the last model, each model's predictions are stored and passed down the computational network. Therefore, to avoid boring the reader, we will not continue to repeat the same information regarding the output of each model.

wavelet_encoder.fit(train.loc[:,X],wavelet_train)
wavelet_encoder_predictions = pd.DataFrame(wavelet_encoder.predict(train.loc[:,X]))

The second model estimates the ICA manifold from the approximated wavelet signals. 

denoised_ica_manifold.fit(wavelet_encoder_predictions,sanitized_ica_manifold)
sanitized_ica_manifold_predictions = pd.DataFrame(denoised_ica_manifold.predict(wavelet_encoder_predictions))

Our third model forecasts the growth in the ICA manifold, given approximations of the manifold's current state.

ica_manifold_growth.fit(sanitized_ica_manifold_predictions,sanitized_ica_manifold_growth)
sanitized_ica_manifold_growth_predictions = ica_manifold_growth.predict(sanitized_ica_manifold_predictions)

The fourth model learns to estimate smoothed market returns, given the expected growth in the ICA manifold. This is the leaf of our computational tree.

returns_reconstruction.fit(sanitized_ica_manifold_growth_predictions,train.loc[:,y[0]])

Our last model learns to identify which spectral cluster we are currently in, given approximated wavelet signals.

spectral_clustering.fit(wavelet_encoder_predictions,clusters_train)



Estimating The Error in Our Computational Graph

Let us now try and estimate the total error associated with our complete computational graph. Since we have already fit each model on its training set, we will evaluate the performance of our chain of models on the validation set. To do so, we will simply execute our computational graph in its correct order, starting with the surrogate wavelet model. Its predictions on the validation set will be passed down the chain until we obtain the final forecasted market return from the last model that predicts smoothed market returns. We will record the error produced by our solution and repeat the exercise for our control setup. 

#Evaluate the error of our solution on the validation set
validation_predictions = returns_reconstruction.predict(ica_manifold_growth.predict(denoised_ica_manifold.predict(wavelet_encoder.predict(validation.loc[:,X]))))
#Record the error produced by our proposed solution
solution_validation_error = RMSE(validation[y[0]],validation_predictions)

#Setup a control model on the training set and evaluate its error levels on the validation set
validation_control_model = KNR()
validation_control_model.fit(train.loc[:,X],train[y[0]])
validation_control_predictions = validation_control_model.predict(validation.loc[:,X])
control_validation_error = RMSE(validation[y[0]],validation_control_predictions)
Methodology Observed Error
Solution: Our cascade framework of models 0.016563594122666777
Control: A single model working on its own to forecast price 0.01714961640965423

We calculated a 3% improvement over the control setup on the validation set when using our piecewise solution.

#Calcualte the percentage improvement
((control_validation_error - solution_validation_error) / control_validation_error) * 100

3.417116004166466

Lastly, let us also assess our performance on the second held-out set, the test set. We will store our solution's predictions over the test set.

#Store our solution's predictions on the test set
test_predictions = returns_reconstruction.predict(ica_manifold_growth.predict(denoised_ica_manifold.predict(wavelet_encoder.predict(test.loc[:,X]))))
#Observe our solution's test error
solution_test_error = RMSE(test[y[0]],test_predictions)

#Store our control predictions on the test set
test_control_model = KNR()
test_control_model.fit(train.loc[:,X],train[y[0]])
test_control_predictions = test_control_model.predict(test.loc[:,X])
#Observe the control test error
control_test_error = RMSE(test[y[0]],test_control_predictions)
Methodology Observed Error
Solution: Our cascade framework of models 0.011412252217700751
Control: A single model working on its own to forecast price 0.012008844036169364

We calculated a 4% improvement over the control setup on the test set. Let the reader recall that both the control and the solution demonstrated were only fit on the training set. However, our results have only been applied to a single symbol on a single time frame. The reader will benefit from revising our suggested solution over their chosen symbols and time frames.

#Calculate the percentage improvement
((control_test_error - solution_test_error) / control_test_error) * 100

4.967937102619882



Exporting Our Models to ONNX Format

Open Neural Network Exchange (ONNX) is an open-source industry protocol for building and deploying machine learning models in a model-agnostic way. Each computational step taken by the model is represented as a node in an ONNX computational graph, and the output of the computation is represented as an edge in the graph. ONNX allows us to export our statistical models from our Python training framework and import them directly into our MQL5 Expert Advisor.

#Import the ONNX library
import onnx
from skl2onnx.common.data_types import FloatTensorType
from skl2onnx import convert_sklearn

The input and output shape of each model should be specified. This can be done easily by fetching the number of columns in the matrices used to construct each model. 

wavelet_encoder_initial_types = [('float_input',FloatTensorType([1,train.loc[:,X].shape[1]]))]
wavelet_encoder_final_types = [('float_output',FloatTensorType([1,wavelet_train.loc[:,:].shape[1]]))]

denoised_ica_encoder_initial_types = [('float_input',FloatTensorType([1,wavelet_encoder_predictions.shape[1]]))]
denoised_ica_encoder_final_types = [('float_output',FloatTensorType([1,sanitized_ica_manifold_predictions.shape[1]]))]

denoised_ica_forecast_initial_types = [('float_input',FloatTensorType([1,sanitized_ica_manifold_predictions.shape[1]]))]
denoised_ica_forecast_final_types = [('float_output',FloatTensorType([1,sanitized_ica_manifold_predictions.shape[1]]))]

returns_reconstruction_initial_types = [('float_input',FloatTensorType([1,sanitized_ica_manifold_predictions.shape[1]]))]
returns_reconstruction_final_types = [('float_output',FloatTensorType([1,1]))]

spectral_clustering_initial_types = [('float_input',FloatTensorType([1,wavelet_encoder_predictions.shape[1]]))]
spectral_clustering_final_types   = [('float_output',FloatTensorType([1,clusters_train.shape[1]]))]

Each ONNX model is converted to its ONNX prototype, and the input and output types are encoded to the model's prototype. Finally, we save each ONNX file to disk using the ONNX save method.

onnx_proto = convert_sklearn(wavelet_encoder,initial_types=wavelet_encoder_initial_types,final_types=wavelet_encoder_final_types,target_opset=12)
onnx.save(onnx_proto,'EURUSD ICA WAVELET KNR.onnx')

onnx_proto = convert_sklearn(denoised_ica_manifold,initial_types=denoised_ica_encoder_initial_types,final_types=denoised_ica_encoder_final_types,target_opset=12)
onnx.save(onnx_proto,'EURUSD ICA ENCODER KNR.onnx')

onnx_proto = convert_sklearn(ica_manifold_growth,initial_types=denoised_ica_forecast_initial_types,final_types=denoised_ica_forecast_final_types,target_opset=12)
onnx.save(onnx_proto,'EURUSD ICA FORECAST KNR.onnx')

onnx_proto = convert_sklearn(returns_reconstruction,initial_types=returns_reconstruction_initial_types,final_types=returns_reconstruction_final_types,target_opset=12)
onnx.save(onnx_proto,'EURUSD ICA RR KNR.onnx')

onnx_proto = convert_sklearn(spectral_clustering,initial_types=spectral_clustering_initial_types,final_types=spectral_clustering_final_types,target_opset=12)
onnx.save(onnx_proto,'EURUSD WAVELET SC KNR.onnx')



Implementing Our Expert Advisor in MQL5

To start building our trading application, let us first import the ONNX resources we need. At this point, our application relies on 5 ONNX models.

//+------------------------------------------------------------------+
//|                                              ICA Filtering 4.mq5 |
//|                                  Copyright 2026, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2026, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"

//+------------------------------------------------------------------+
//| Resources                                                        |
//+------------------------------------------------------------------+
#include <Trade\Trade.mqh>
CTrade Trade;

//+------------------------------------------------------------------+
//| Resources                                                        |
//+------------------------------------------------------------------+
#resource "\\Files\\ICA Filtering\\EURUSD ICA ENCODER KNR.onnx" as const uchar onnx_ica_proto[];
#resource "\\Files\\ICA Filtering\\EURUSD ICA FORECAST KNR.onnx" as const uchar onnx_ica_forecast_proto[];
#resource "\\Files\\ICA Filtering\\EURUSD ICA WAVELET KNR.onnx" as const uchar onnx_wavelet_proto[];
#resource "\\Files\\ICA Filtering\\EURUSD ICA RR KNR.onnx" as const uchar onnx_returns_proto[];
#resource "\\Files\\ICA Filtering\\EURUSD WAVELET SC KNR.onnx" as const uchar onnx_cluster_proto[];

A handful of commonly used global variables are defined. These global variables store important information that is used throughout our application. These variables store information such as handlers to our ONNX models, the predictions made by our ONNX models, and technical indicator readings, just to name a few. We will also define the input and output shapes of our ONNX models as constant integer types.

//+------------------------------------------------------------------+
//| Global variables                                                 |
//+------------------------------------------------------------------+
//--- Application variables
long        onnx_ica_model,onnx_returns_model,onnx_cluster_model,onnx_ica_forecast_model,onnx_wavelet_model;
vectorf     onnx_graph_inputs,onnx_wavelet_outputs,onnx_ica_outputs,onnx_ica_forecast_outputs,onnx_return_outputs,onnx_cluster_outputs;
datetime    time_stamp;
int         atr_handler,o_ma_handler,c_ma_handler,h_ma_handler,l_ma_handler;
double      atr[],o_ma[],c_ma[],h_ma[],l_ma[],bid,ask;

//--- Fixed application variables
const int         graph_inputs = 48;
const int         ica_outputs = 15 ;
const int         ica_forecast_inputs = 15 ;
const int         ica_forecast_outputs = 15 ;
const int         returns_outputs = 1;
const int         cluster_outputs = 8 ;
const int         historical_values = 90;

We must also store the updated spectral cluster statistics. These statistics will help us dynamically adjust our risk exposure based on the expected risk and return associated with the cluster we are in.

//--- Statistical market variables
double cluster_returns[] = {0.0012047324253865455,-0.011432701477044612,0.0027930822608866262,-0.0010313170931057624,0.00011972025127285056,-0.0003135222092631602,0.0005737483036545992,-0.001496773172390616};

double cluster_risk[]    = {0.013951328385895731,0.011875753968549497,0.007068905176934451,0.009744014859514304,0.01115806313804597,0.00718261643483689,0.010576829734559255,0.010567107478261664};

double average_cluster_risk = 0.01026557739707472;

When our application receives updated price levels, our computational graph must be executed in the correct order. The ONNX model that approximates our wavelet transform sits closest to the root of our graph and is therefore executed first. From there, the models are each executed in turn, and each model's output is passed down the network until our final prediction has been made.

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//--- Update our time reading
   time_stamp = iTime(Symbol(),PERIOD_D1,1);
   static datetime previous_time_stamp;

   if(previous_time_stamp != time_stamp)
     {
      //--- Update the time stamp
      previous_time_stamp = time_stamp;

      //--- Fetch updated indicator readings
      if(!UpdateMarketData())
        {
         Print("An error occurred while trying to update indicator readings: ",GetLastError());
         return;
        }

      //--- Prepare the inputs for our ONNX models
      if(!FetchModelData())
        {
         Print("An error occurred while trying to fetch our ONNX model data: ");
         return;
        }

      //--- Obtain wavelet denoised inputs
      if(!OnnxRun(onnx_wavelet_model,ONNX_DEFAULT,onnx_graph_inputs,onnx_wavelet_outputs))
        {
         Print("Failed to approximate wavelet denoise: ",GetLastError());
         return;
        }

      //--- Approximate our ICA embeddings
      else
         if(!OnnxRun(onnx_ica_model,ONNX_DEFAULT,onnx_wavelet_outputs,onnx_ica_outputs))
           {
            Print("Failed to approximate ICA embeddings: ",GetLastError());
            return;
           }

         //--- Forecast future ICA embeddings growth
         else
            if(!OnnxRun(onnx_ica_forecast_model,ONNX_DEFAULT,onnx_ica_outputs,onnx_ica_forecast_outputs))
              {
               Print("Failed to forecast ICA embeddings: ",GetLastError());
               return;
              }

            //--- Identify the cluster we are in
            else
               if(!OnnxRun(onnx_cluster_model,ONNX_DEFAULT,onnx_wavelet_outputs,onnx_cluster_outputs))
                 {
                  Print("Failed to identify Spectral Cluster: ",GetLastError());
                  return;
                 }

               else
                 {
                  //--- Forecast smoothed market returns from approximate ICA embeddings
                  if(!OnnxRun(onnx_returns_model,ONNX_DEFAULT,onnx_ica_forecast_outputs,onnx_return_outputs))
                    {
                     Print("Failed to forecast market returns: ",GetLastError());
                     return;
                    }

                  else
                    {
                     if(PositionsTotal() == 0)
                        {
                           SetupPosition();   
                        }
                    }
                 }
     }
  }
//+------------------------------------------------------------------+

We shall now define the method responsible for fetching our model's input data. Our computational graph expects 48 inputs.

//+------------------------------------------------------------------+
//| Fetch the input data for our computational graph                 |
//+------------------------------------------------------------------+
bool FetchModelData(void)
  {
//--- Setup model inputs
//--- Inputs for our computational graph
   onnx_graph_inputs[0] = (float) o_ma[0];
   onnx_graph_inputs[1] = (float) h_ma[0];
   onnx_graph_inputs[2] = (float) l_ma[0];
   onnx_graph_inputs[3] = (float) c_ma[0];
//--- Lag 1
   onnx_graph_inputs[4] = (float) o_ma[1];
   onnx_graph_inputs[5] = (float) h_ma[1];
   onnx_graph_inputs[6] = (float) l_ma[1];
   onnx_graph_inputs[7] = (float) c_ma[1];
//--- Lag 2
   onnx_graph_inputs[8] = (float) o_ma[2];
   onnx_graph_inputs[9] = (float) h_ma[2];
   onnx_graph_inputs[10] = (float) l_ma[2];
   onnx_graph_inputs[11] = (float) c_ma[2];
//--- Lag 3
   onnx_graph_inputs[12] = (float) o_ma[3];
   onnx_graph_inputs[13] = (float) h_ma[3];
   onnx_graph_inputs[14] = (float) l_ma[3];
   onnx_graph_inputs[15] = (float) c_ma[3];
//--- Lag 4
   onnx_graph_inputs[16] = (float) o_ma[4];
   onnx_graph_inputs[17] = (float) h_ma[4];
   onnx_graph_inputs[18] = (float) l_ma[4];
   onnx_graph_inputs[19] = (float) c_ma[4];
//--- Lag 5
   onnx_graph_inputs[20] = (float) o_ma[5];
   onnx_graph_inputs[21] = (float) h_ma[5];
   onnx_graph_inputs[22] = (float) l_ma[5];
   onnx_graph_inputs[23] = (float) c_ma[5];
//--- Lag 10
   onnx_graph_inputs[24] = (float) o_ma[10];
   onnx_graph_inputs[25] = (float) h_ma[10];
   onnx_graph_inputs[26] = (float) l_ma[10];
   onnx_graph_inputs[27] = (float) c_ma[10];
//--- Lag 20
   onnx_graph_inputs[28] = (float) o_ma[20];
   onnx_graph_inputs[29] = (float) h_ma[20];
   onnx_graph_inputs[30] = (float) l_ma[20];
   onnx_graph_inputs[31] = (float) c_ma[20];
//--- Lag 30
   onnx_graph_inputs[32] = (float) o_ma[30];
   onnx_graph_inputs[33] = (float) h_ma[30];
   onnx_graph_inputs[34] = (float) l_ma[30];
   onnx_graph_inputs[35] = (float) c_ma[30];
//--- Lag 40
   onnx_graph_inputs[36] = (float) o_ma[40];
   onnx_graph_inputs[37] = (float) h_ma[40];
   onnx_graph_inputs[38] = (float) l_ma[40];
   onnx_graph_inputs[39] = (float) c_ma[40];
//--- Lag 60
   onnx_graph_inputs[40] = (float) o_ma[60];
   onnx_graph_inputs[41] = (float) h_ma[60];
   onnx_graph_inputs[42] = (float) l_ma[60];
   onnx_graph_inputs[43] = (float) c_ma[60];
//--- Lag 80
   onnx_graph_inputs[44] = (float) o_ma[80];
   onnx_graph_inputs[45] = (float) h_ma[80];
   onnx_graph_inputs[46] = (float) l_ma[80];
   onnx_graph_inputs[47] = (float) c_ma[80];


//--- Validate inputs are not empty
   if(onnx_graph_inputs.Sum() == 0)
     {
      Print("Inputs total equals zero. Something went wrong.");
      return(false);
     }

   return(true);
  }

The method responsible for loading our ONNX models must also be extended to initialize our wavelet model, validate its input shape, and prepare the model's input and output vectors. 

//+------------------------------------------------------------------+
//| Prepare our ONNX models for inferencing                          |
//+------------------------------------------------------------------+
bool LoadOnnxModels(void)
  {
//--- ONNX Models
   onnx_ica_model     = OnnxCreateFromBuffer(onnx_ica_proto,ONNX_DEFAULT);
   onnx_returns_model = OnnxCreateFromBuffer(onnx_returns_proto,ONNX_DEFAULT);
   onnx_cluster_model = OnnxCreateFromBuffer(onnx_cluster_proto,ONNX_DEFAULT);
   onnx_ica_forecast_model = OnnxCreateFromBuffer(onnx_ica_forecast_proto,ONNX_DEFAULT);
   onnx_wavelet_model = OnnxCreateFromBuffer(onnx_wavelet_proto,ONNX_DEFAULT);

//--- Validate the ONNX model handlers
   if(onnx_wavelet_model == INVALID_HANDLE)
     {
      Print("Failed to load the ONNX Wavelet model: ",GetLastError());
      return(false);
     }

   else
      if(onnx_ica_model == INVALID_HANDLE)
        {
         Print("Failed to load the ONNX ICA model: ",GetLastError());
         return(false);
        }

      else
         if(onnx_ica_forecast_model == INVALID_HANDLE)
           {
            Print("Failed to load the ONNX ICA forecast model: ",GetLastError());
            return(false);
           }

         else
            if(onnx_cluster_model == INVALID_HANDLE)
              {
               Print("Failed to load the ONNX Spectral Clustering  model: ",GetLastError());
               return(false);
              }

            else
               if(onnx_returns_model == INVALID_HANDLE)
                 {
                  Print("Failed to load the ONNX returns reconstruction model: ",GetLastError());
                  return(false);
                 }


//--- Validate the ONNX model shapes
   ulong onnx_wavelet_input_shape[] = {1,graph_inputs};
   ulong onnx_wavelet_output_shape[] = {1,graph_inputs};
   ulong onnx_graph_input_shape[] = {1,graph_inputs};
   ulong onnx_ica_output_shape[] = {1,ica_outputs};
   ulong onnx_returns_output_shape[] = {1,returns_outputs};
   ulong onnx_cluster_output_shape[] = {1,cluster_outputs};

   if(!OnnxSetInputShape(onnx_wavelet_model,0,onnx_wavelet_input_shape))
     {
      Print("Failed to set the correct input shape for our ONNX wavelet model.");
      return(false);
     }


   if(!OnnxSetOutputShape(onnx_wavelet_model,0,onnx_wavelet_output_shape))
     {
      Print("Failed to set the correct output shape for our ONNX wavelet model.");
      return(false);
     }


   if(!OnnxSetInputShape(onnx_ica_forecast_model,0,onnx_ica_output_shape))
     {
      Print("Failed to set the correct input shape for our ONNX forecast model.");
      return(false);
     }

   if(!OnnxSetOutputShape(onnx_ica_forecast_model,0,onnx_ica_output_shape))
     {
      Print("Failed to set the correct output shape for our ONNX forecast model.");
      return(false);
     }

   if(!OnnxSetInputShape(onnx_cluster_model,0,onnx_graph_input_shape))
     {
      Print("Failed to set the correct ONNX Spectral Clustering model input shape: ",GetLastError());
      return(false);
     }


   if(!OnnxSetOutputShape(onnx_cluster_model,0,onnx_cluster_output_shape))
     {
      Print("Failed to set the correct ONNX Spectral Clustering model output shape: ",GetLastError());
      return(false);
     }

   if(!OnnxSetInputShape(onnx_ica_model,0,onnx_graph_input_shape))
     {
      Print("Failed to set the correct ONNX ICA model input shape: ",GetLastError());
      return(false);
     }


   if(!OnnxSetOutputShape(onnx_ica_model,0,onnx_ica_output_shape))
     {
      Print("Failed to set the correct ONNX ICA model output shape: ",GetLastError());
      return(false);
     }


   if(!OnnxSetInputShape(onnx_returns_model,0,onnx_ica_output_shape))
     {
      Print("Failed to set the correct ONNX smoothed returns model input shape: ",GetLastError());
      return(false);
     }

   if(!OnnxSetOutputShape(onnx_returns_model,0,onnx_returns_output_shape))
     {
      Print("Failed to set the correct ONNX smoothed returns model output shape: ",GetLastError());
      return(false);
     }

//--- Prepare ONNX model I/O
   onnx_graph_inputs = vectorf::Zeros(graph_inputs);
   onnx_ica_outputs = vectorf::Zeros(ica_outputs);
   onnx_return_outputs = vectorf::Zeros(returns_outputs);
   onnx_cluster_outputs = vectorf::Zeros(cluster_outputs);
   onnx_ica_forecast_outputs = vectorf::Zeros(ica_outputs);
   onnx_wavelet_outputs = vectorf::Zeros(graph_inputs);
//--- Everything went well
   return(true);
  }

Finally, when our application is no longer in use, we will free up all resources that were previously reserved for our application's resources. This is good practice for MQL5 programming, especially if the user intends to run multiple EAs at once.

//+------------------------------------------------------------------+
//| Free up all resources we are no longer using                     |
//+------------------------------------------------------------------+
bool ReleaseResources(void)
  {

   if(!OnnxRelease(onnx_wavelet_model))
     {
      Print("An error occurred when releasing the ONNX Wavelet model: ",GetLastError());
      return(false);
     }

   if(!OnnxRelease(onnx_ica_forecast_model))
     {
      Print("An error occurred when releasing the ONNX ICA Forecast model: ",GetLastError());
      return(false);
     }

   if(!OnnxRelease(onnx_cluster_model))
     {
      Print("An error occurred when releasing the ONNX Cluster model: ",GetLastError());
      return(false);
     }

   if(!OnnxRelease(onnx_ica_model))
     {
      Print("An error occurred when releasing the ONNX ICA model: ",GetLastError());
      return(false);
     }

   if(!OnnxRelease(onnx_returns_model))
     {
      Print("An error occurred when releasing the ONNX Smoothed Returns model: ",GetLastError());
      return(false);
     }

   if(!IndicatorRelease(atr_handler))
     {
      Print("An error occurred while trying to release the ATR Indicator: ",GetLastError());
      return(false);
     }

   if(!IndicatorRelease(o_ma_handler))
     {
      Print("An error occurred while releasing the Open Moving Average Indicator");
      return(false);
     }

   if(!IndicatorRelease(l_ma_handler))
     {
      Print("An error occurred while releasing the Low Moving Average Indicator");
      return(false);
     }

   if(!IndicatorRelease(h_ma_handler))
     {
      Print("An error occurred while releasing the High Moving Average Indicator");
      return(false);
     }

   if(!IndicatorRelease(c_ma_handler))
     {
      Print("An error occurred while releasing the Close Moving Average Indicator");
      return(false);
     }
   return(true);
  }
//+------------------------------------------------------------------+


Backtesting Our Trading Application

Now that we have implemented the necessary changes to our trading application, we are now ready to analyze how well the application trades on out-of-sample data. We will load our trading application and test it over a 5-year period spanning 2020 until the time of writing. 


Figure 11: Preparing to backtest our application.

We want to emulate realistic backtest conditions for our trading application. Therefore, we set our modeling conditions to use real historical ticks during the entire test. This may take a while, as the requested historical data must be retrieved from your broker over the network. Lastly, selecting random delay settings mimics the uncertainty of real trading scenarios. Our backtest will be conducted on a swap-free trading account, with an initial deposit of $1000. Our leverage settings are set to 1:100, and our application will only be allowed to place a single trade at a time. Each trade will be fixed to the minimum lot size, and the entire test runs over an out-of-sample period our models were not trained on.

Figure 12: Our backtest conditions have been selected to emulate real trading scenarios.

A detailed statistical analysis of our trading performance has been captured in Figure 13 below. Our average and largest profits were both larger than their counterpart losses over the 5-year duration of our backtest. 48.84% of the trades placed were losing trades; this is modestly below average and is by no means the holy grail of trading strategies. Our profit factor is marginally above neutral levels.

Statistical Table

Figure 13: A detailed statistical summary of our backtest performance over our 3-year out-of-sample window.

We can also visualize a graph, depicting the change in account balance over time during our backtest window. No strategy is perfect; we can still observe periods of fluctuating equity, where our strategy appeared to be stuck in unfavorable conditions. However, the long-run trend in the account balance appears to be positive. Our results should only be considered over the limited conditions of our test. Readers that repeat this exercise on different symbols and timeframes will most likely produce results that differ from what we have presented here.

Equity Curve

Figure 14: A graph representing the change in account balance over the duration of our backtest.


Conclusion

After reading this article, the reader will gain a reproducible framework for filtering market noise by creating a computational graph that attempts to incrementally filter out noise with each computational layer.

Our approach is intended to be interpretable at each step, providing the reader with a flexible solution that has many tuning parameters to increase or reduce complexity to match the task at hand.

Additionally, all the artifacts attached to this article can be locally reproduced by the reader for rapid development and testing purposes. Ultimately, this article demonstrates to the reader how to combine different algorithms to create an effective ensemble noise filter. 

While our trading strategy has its strengths, we must also take time to consider potential pitfalls in our current configuration. The reader should be aware that our current strategy relies heavily on approximated representations of functions we could not implement. The error in these approximations can cascade down our computational graph, especially during volatile market conditions. This is likely the biggest blind spot of our trading application and the primary cause of the drawdown periods observed in our out-of-sample backtest. If the reader possesses enough computational power and historical data, a longer backtest period is encouraged before considering live deployment.

Lastly, the reader should also be aware that our strategy relies heavily on assumptions made about the distribution econometric statistics observed across the 10 spectral clusters we identified. Although it was not stated, we implicitly assumed that this distribution remains stationary as we move forward in time. This assumption allowed us to rapidly prototype the sophisticated engineering solution we presented. However, the sophistication of such solutions is of little comfort if the underlying assumptions are violated.

File Name File Description
ICA Filtering 4.mq5 This file is located in the Experts folder. It is the trading application that we built with a more robust statistical noise filter.
ICA Filtering 2.mq5  Located in the Scripts folder, this is the MQL5 script we wrote to fetch our historical lagged moving average indicator inputs.
EURUSD ICA WAVELET KNR.onnx  The ONNX model that learns to approximate the wavelet denoise algorithm. All the ONNX files are located inside the Files folder.
EURUSD ICA ENCODER KNR.onnx We relied on this ONNX model to learn a representation of the ICA algorithm. The model accepts wavelet-denoised inputs and outputs approximate ICA embeddings.
EURUSD ICA FORECAST KNR.onnx Our ONNX model responsible for forecasting the growth in the ICA manifold.
EURUSD ICA RR KNR.onnx This ONNX model learns to reconstruct the smoothed market returns, given forecasted growth in the ICA manifold.
EURUSD WAVELET SC KNR.onnx We employed this model to serve as an approximation of the spectral clustering algorithm. It helps us manage our position size and risk levels.
Wavelet Denoising ICA Components.ipynb The Jupyter notebook we used to perform our market analysis. The Notebook is located inside the Files folder, in its own standalone Notebook folder.


Attached files |
MQL5.zip (1272.07 KB)
Dirichlet Process Mixtures: How Many Market Regimes Are There, and Does the Answer Mean Anything? Dirichlet Process Mixtures: How Many Market Regimes Are There, and Does the Answer Mean Anything?
Most regime tools ask for a fixed number of states. This article implements a Dirichlet process mixture for MQL5 with truncated stick-breaking and varying coordinate ascent, so the cluster count is inferred from data and the evidence bound is monitored each iteration. The package includes a nine-file library, an out-of-sample indicator that scores each bar, a six-level test suite, and a shuffle-based null control to judge how much the recovered count means.
Neural Networks in Trading: Mesh Approximation of Event Streams as a Tool for Analyzing Price Patterns (ADM Module) Neural Networks in Trading: Mesh Approximation of Event Streams as a Tool for Analyzing Price Patterns (ADM Module)
The article presents an implementation of the Adaptive Density Module (ADM), a key component of the EEMFlow framework, using MQL5. It examines the steps involved in building and combining the MDC and MDS submodules, as well as integrating ADM into the existing BAT trading model. Backtesting results on historical EURUSD data show robust growth in the account balance, controlled drawdowns, and a highly stable equity curve.
Features of Experts Advisors Features of Experts Advisors
Creation of expert advisors in the MetaTrader trading system has a number of features.
Counting Breaches Is Not Backtesting: Six Tests for a Loss Limit Counting Breaches Is Not Backtesting: Six Tests for a Loss Limit
We present a dependency-free MQL5 library that tests risk limits instead of simply using them. It grades any loss limit with six coverage tests, validates the battery on synthetic data, compares four standard forecasters on EURUSD daily history, and feeds the verdict back into position sizing.