preview
Modular Indicator Architecture in MQL5 (Part 2): Standard Smoothing Methods as Interchangeable Modules

Modular Indicator Architecture in MQL5 (Part 2): Standard Smoothing Methods as Interchangeable Modules

MetaTrader 5 — Examples |
73 0
Vladislav Boyko
Vladislav Boyko

Introduction

The framework currently has two modules: CAppliedPrice and CSma. This article adds one for each of the other three standard moving averages: EMA, SMMA, and LWMA. Before the first of them, we fix a bug in CSma, extract a common base class for all smoothing methods, and make the smoothing method selectable at runtime. Finally, we optimize the LWMA module, whose straightforward implementation loops over the whole averaging window for every bar.

The article also explains the smoothing methods that the modules implement. It gives their formulas, works through examples, and compares the four: how they weight the bars, what they need for their first value, and what a full calculation costs.

In Part 1, I promised that this article would put the framework to work: new indicators, ready-made modules combined into more complex ones, and an AlgoForge project template. I planned to start by completing the set of standard moving averages, the building blocks behind a large share of indicators. That alone took the whole article. Combining modules and the project template will have to wait for later parts of the series. The template in particular benefits from the delay. Projects created from a template inherit its structure, so any later change to the framework's foundation would have to be repeated in each of them. The work continues in the same evolution repository, where the tag article-part1 marks the state of the code at the end of Part 1.

Fixing a Bug in CSma

The CSma module of Part 1 has a bug. It appears only in a rare case when the chart has exactly as many bars as the module requires, which for our indicator is the SMA period. The first OnCalculate() call then works as intended, and the next one ends with a critical error, "array out of range", after which the terminal stops the indicator.

Here is the body of CSma::onCalculate() as Part 1 left it:

int recalcStartIdx = prepareBeforeCalculating(rates_total, prev_calculated);
if(rates_total - prev_calculated > 1)
  {
   computeValueAtDrawBegin(source);
   recalcStartIdx++;
  }
for(int i = recalcStartIdx; i < rates_total; i++)
   buffer[i] = buffer[i - 1] + (source[i] - source[i - period]) / period;

The loop is a recurrence: it derives each value from the previous one, so the first value, the one at drawBegin, has to come from elsewhere. That first value is the seed of the recurrence, and computeValueAtDrawBegin() computes it.

Suppose the chart has exactly 5 bars and the indicator runs with its default period of 5. CSma then requires 5 bars, and drawBegin is 4, the index of the current bar. The figure below is a flowchart of the code above, with the routes that two OnCalculate() calls take through it. The first call is on the left, and the next one, a current bar update, is on the right:

Flowchart of Part 1's CSma::onCalculate() with the routes of the first two OnCalculate() calls

Both calls start the calculation at bar 4, which is drawBegin, and take different routes from there:

  1. On the first call, the difference rates_total - prev_calculated is greater than 1, so the body of the if statement runs: the seed is written to bar 4, and the start index, recalcStartIdx, becomes 5. The chart has no bar 5, so the loop does not run.
  2. On the second call, the difference is 0, and the body of the if statement is skipped. Nothing increments the start index, so it stays 4, and the loop runs for bar 4. There, the recurrence reads source[i - period], which is the element at index −1, and the terminal reports the error.

Every calculation that starts at drawBegin has to compute the seed and start the loop at the next bar. The condition of the if statement, however, does not ensure this, as the second call shows.

The fix tests the start index itself: the seed is computed whenever recalcStartIdx <= drawBegin holds, and the index is then set to drawBegin + 1.

While working on the fix, I also saw a chance to shorten two names, and I did so in a separate commit: prepareBeforeCalculating() became prepareCalculation(), and recalcStartIdx became calcStartIdx.

I expected later modules to need the same test, so I gave it a name, isFullCalculation, and moved it into a new overload of prepareCalculation() in the base class:

//+------------------------------------------------------------------+
//| Base class for all sub-indicators. Extracts common traits and    |
//| handles routine boilerplate                                      |
//+------------------------------------------------------------------+
class CSubIndiBase
  {
protected:
   //--- Determines calculation start index; clears buffers on full calculation
   int prepareCalculation(const int rates_total, const int prev_calculated)
     {
      int calcStartIdx;
      switch(rates_total - prev_calculated)
        {
         case 0:
         case 1:
            calcStartIdx = prev_calculated - 1;
            break;
         default:
            calcStartIdx = drawBegin;
            clearLeftFromDrawBegin();
            break;
        }
      return calcStartIdx;
     }

   //--- Overload for recurrent/stateful indicators: reports if drawBegin is calculated
   int prepareCalculation(const int rates_total, const int prev_calculated, bool& isFullCalculation)
     {
      const int calcStartIdx = prepareCalculation(rates_total, prev_calculated);
      isFullCalculation = calcStartIdx <= drawBegin;
      return calcStartIdx;
     }
  };

Code #1 | SubIndiBase.mqh | refactor: add prepareCalculation overload with isFullCalculation flag

The first function is the one from Part 1, under its new name. The second is the new overload: it calls the first one and reports through isFullCalculation whether the calculation covers the bar at drawBegin. If it does, every value of the buffer from drawBegin to the current bar is computed, which makes it a full calculation.

With the overload, CSma::onCalculate() takes this form:

//+------------------------------------------------------------------+
//| Sub-indicator calculating Simple Moving Average using recurrence |
//+------------------------------------------------------------------+
class CSma : public CSubIndiBase
  {
public:
   //--- Calculates SMA values using seed + recurrence formula
   void onCalculate(const int rates_total, const int prev_calculated, const double& source[])
     {
      bool isFullCalculation;
      int calcStartIdx = prepareCalculation(rates_total, prev_calculated, isFullCalculation);
      if(isFullCalculation)
        {
         computeValueAtDrawBegin(source);
         calcStartIdx = drawBegin + 1;
        }
      for(int i = calcStartIdx; i < rates_total; i++)
         buffer[i] = buffer[i - 1] + (source[i] - source[i - period]) / period;
     }
  };

Code #2 | Sma.mqh | refactor: add prepareCalculation overload with isFullCalculation flag

The isFullCalculation flag is for modules that need separate logic for a full calculation, as CSma does to compute the seed. The other module of Part 1, CAppliedPrice, computes every bar in the same way, so it has no use for the flag and still calls the two-argument overload.

The flowchart below shows how the new overload and CSma::onCalculate() handle an OnCalculate() call:

Flowchart of the new overload of prepareCalculation() and of CSma::onCalculate()

As the second OnCalculate() call of our example showed, a calculation can be a full one even when the difference rates_total - prev_calculated indicates only a current bar update or a new bar. This happens in one rare case: at the previous call, the chart had exactly as many bars as the module requires. The comparison of calcStartIdx with drawBegin covers this case too, and the flowchart draws it as the orange arrow that leaves the comparison.


Extracting CSmoothingBase

In Part 1, while building the framework, we implemented a basic SMA sub-indicator. The MQL5 ENUM_MA_METHOD enumeration specifies four methods: SMA, EMA, SMMA, and LWMA. The remaining three are the obvious next step. Before we can assemble complex indicators from ready-made modules, we need the modules they are most often built from. Many standard indicators also let the user pick the smoothing method: iStochastic(), iEnvelopes(), and iAlligator() all take an ENUM_MA_METHOD parameter.

It also pays to do this now, while the framework lives in a single repository. Take ATR, which in Wilder's original definition relies on his smoothing method. The smoothing could be written right inside the ATR module, but sooner or later all smoothing methods would need a common foundation anyway. Extracting it then would mean repeating the same refactoring in every project created from the template, which is also why the template can wait. Today, the refactoring only has to be done once.

Before diving into the implementation of new algorithms, let's extract a common base class for all smoothing methods—CSmoothingBase. First, this will allow us to work polymorphically with any smoother through a unified interface. Second, pulling shared functionality up into a base class eliminates code duplication, keeping the concrete smoothing classes short.

The diagram shows the hierarchy we are heading for; so far, only CSma exists.

Class diagram of the hierarchy of the smoothing modules under CSmoothingBase

Almost any smoothing operation takes a single input data series (the source array) and produces a single output series (the smoothed values). While certain algorithms may require intermediate buffers, those remain an internal implementation detail of the specific class. Externally, a smoothing module exposes exactly one result array. This has three consequences for the design:

  1. The onCalculate() method signature is the same for all of them. This allows us to declare a pure virtualonCalculate() method in CSmoothingBase, establishing a unified public contract.
  2. We can pull the public buffer[] array directly up into the base class.
  3. With the buffer in the base class, CSmoothingBase can implement the clearBuffersAt() hook once, for all derived classes.

For now, we leave aside the few algorithms that take or produce more than one series.

Here is the resulting class:

//+------------------------------------------------------------------+
//| Abstract base class for all smoothing sub-indicators             |
//+------------------------------------------------------------------+
class CSmoothingBase : public CSubIndiBase
  {
protected:
   //--- Hook implementation: clears all buffers at a given bar
   void clearBuffersAt(int barIdx) override { buffer[barIdx] = emptyValue; }

   //--- Validates and corrects the smoothing period against minPeriod
   static int correctPeriod(int period, bool mute = false, int minPeriod = 2)
     {
      if(period >= minPeriod)
         return period;
      if(!mute)
         PrintFormat(__FUNCTION__": invalid period value (%i); corrected to %i", period, minPeriod);
      return minPeriod;
     }

public:
   //--- Calculation interface implemented by concrete smoothing methods
   virtual void onCalculate(const int rates_total, const int prev_calculated, const double& source[]) = 0;

public:
   double    buffer[]; // output buffer with calculated smoothed values
protected:
   CSmoothingBase(int a_barsRequired) : CSubIndiBase(a_barsRequired, EMPTY_VALUE) {}
  };

Code #3 | SmoothingBase.mqh | refactor: introduce CSmoothingBase for smoothing sub-indicators

In the constructor, I hardcoded emptyValue to EMPTY_VALUE, so derived classes do not have to pass this parameter: it is unlikely we will ever need a custom empty value for smoothing methods.

The correctPeriod() method was also moved into the base class to avoid duplicating the validation logic: most smoothing methods rely on an averaging period from the input parameters. Because the minimum allowed period may vary across algorithms, a minPeriod parameter was added to the method.

CSma now derives from CSmoothingBase and loses its own buffer, clearBuffersAt(), and correctPeriod() (see Sma.mqh).


Selecting the Smoothing Method at Runtime

Next, the user needs a way to choose the smoothing method. The first change is a new method field in the CIndiParamsBase parameter class:

//+------------------------------------------------------------------+
//| Base structure for indicator parameters, decoupling core logic   |
//| from global input variables                                      |
//+------------------------------------------------------------------+
class CIndiParamsBase
  {
public:
   ENUM_APPLIED_PRICE applyTo;
   ENUM_MA_METHOD     method;
   int                period;
  };

Code #4 | IndiParamsBase.mqh | feat: add smoothing method input parameter

In InputsAndRelated.mqh, I declared a new input variable, inpMethod. Since the indicator is no longer exclusively an SMA, I also renamed the period parameter label from "SMA period" to just "Period". Placing inpMethod between the period and applied price follows the conventional order familiar to MetaTrader 5 users. The CIndiParams constructor assigns this new input variable to the corresponding field in the parameter object:

input(name="Period")   int                inpPeriod  = 5;
input(name="Method")   ENUM_MA_METHOD     inpMethod  = MODE_SMA;
input(name="Apply to") ENUM_APPLIED_PRICE inpApplyTo = PRICE_CLOSE;

//+------------------------------------------------------------------+
//| Concrete params class that captures global input variable values |
//+------------------------------------------------------------------+
class CIndiParams : public CIndiParamsBase
  {
public:
   //--- Populates params from global input variables
   CIndiParams()
     {
      period = inpPeriod;
      method = inpMethod;
      applyTo = inpApplyTo;
     }
  };

Code #5 | InputsAndRelated.mqh | feat: add smoothing method input parameter

The screenshot below shows the indicator's Inputs tab, where the drop-down list of the new parameter offers the four methods of the ENUM_MA_METHOD enumeration:

Inputs tab of the indicator in MetaTrader 5 with the list of the Method parameter open

Now that the settings include the method and CSmoothingBase defines the common interface, the root CIndicator object can use its smoothing sub-indicator polymorphically.

Previously, CIndicator held a CSma object as a member. The class of a member object is fixed at compile time, but now the user picks the smoothing method in the input parameters at runtime. CIndicator therefore has to create the object dynamically and hold it through a pointer to the base class, CSmoothingBase*.

//+------------------------------------------------------------------+
//| Root indicator object. Wires all sub-indicators together,        |
//| eliminating the need for global state                            |
//+------------------------------------------------------------------+
class CIndicator : public CIndicatorBase
  {
public:
   //--- Executes sub-indicators in dependency order
   void onCalculateImpl(const int rates_total, const int prev_calculated, const double& open[], const double& high[], const double& low[],
                        const double& close[], const datetime& time[]) override
     {
      appliedPrice.onCalculate(rates_total, prev_calculated, open, high, low, close);
      smoothing.onCalculate(rates_total, prev_calculated, appliedPrice.buffer);
     }

private:
   CAppliedPrice   appliedPrice; // applied price data source
   CSmoothingBase* smoothing;    // smoothing sub-indicator
public:
   CIndicator(const CIndiParamsBase& params)
      : appliedPrice(params.applyTo)
     {
      switch(params.method)
        {
         case MODE_SMA:
            smoothing = new CSma(params.period, appliedPrice.barsRequired);
            break;
         default:
            PrintFormat(__FUNCTION__": method %s not implemented; falling back to SMA", EnumToString(params.method));
            smoothing = new CSma(params.period, appliedPrice.barsRequired);
            break;
        }
      SetIndexBuffer(0, smoothing.buffer, INDICATOR_DATA);
      SetIndexBuffer(1, appliedPrice.buffer, INDICATOR_CALCULATIONS);
      PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, smoothing.emptyValue);
     }

   ~CIndicator()
     {
      delete smoothing;
     }
  };

Code #6 | Indicator.mqh | feat: switch CIndicator to dynamic CSmoothingBase pointer

In the CIndicator constructor, dynamic instantiation is handled by a switch statement on params.method. The MODE_SMA case instantiates CSma. Dedicated cases for the remaining smoothing methods will be added as their classes are implemented. The default branch handles any methods that are not yet ready: it logs a warning via PrintFormat() and falls back to CSma. This keeps the indicator fully functional at every intermediate development stage.

CIndicator owns the smoothing sub-indicator and manages its lifecycle. Because the object is allocated dynamically with new, CIndicator requires a destructor to properly release it with delete.

The onCalculateImpl() method now calls smoothing.onCalculate() through the base class virtual interface.


Exponential Moving Average

The next smoothing method in the ENUM_MA_METHOD enumeration is the Exponential Moving Average (MODE_EMA).

Unlike in the Simple Moving Average, where all bars within the averaging window carry equal weight, weights in an EMA decrease exponentially into the past. The degree of influence of more recent values is determined by the smoothing factor:

α = 2 period + 1

The recurrence formula for the EMA calculation links the current source value to the previous indicator value:

EMA i = Source i ⋅ α + EMA i − 1 ⋅ ( 1 − α )

Just as with the SMA in Part 1, we will base our algorithm on the implementation that ships with MetaTrader 5: the ExponentialMAOnBuffer() function from Include/MovingAverages.mqh. Here is that algorithm, adapted to our object model:

//+------------------------------------------------------------------+
//| Sub-indicator calculating Exponential Moving Average (EMA)       |
//+------------------------------------------------------------------+
class CEma : public CSmoothingBase
  {
public:
   //--- Calculates EMA values using seed + recurrence formula
   void onCalculate(const int rates_total, const int prev_calculated, const double& source[]) override
     {
      bool isFullCalculation;
      int calcStartIdx = prepareCalculation(rates_total, prev_calculated, isFullCalculation);
      if(isFullCalculation)
        {
         buffer[drawBegin] = source[drawBegin];
         calcStartIdx = drawBegin + 1;
        }
      for(int i = calcStartIdx; i < rates_total; i++)
         buffer[i] = source[i] * smoothFactor + buffer[i - 1] * (1.0 - smoothFactor);
     }

private:
   const double smoothFactor; // smoothing factor (2 / (period + 1))
public:
   CEma(int a_period, int sourceBarsRequired)
      : CSmoothingBase(sourceBarsRequired),
        smoothFactor(2.0 / (1.0 + correctPeriod(a_period)))
     {}
  };

Code #7 | Ema.mqh | feat: implement CEma smoothing sub-indicator

We pass sourceBarsRequired directly to the CSmoothingBase constructor without increasing the minimum bar requirement. Unlike the SMA, which requires a window of period bars to accumulate the initial sum, the EMA algorithm does not need additional bars. The source value at the first available bar serves as the seed ( EMA drawBegin = Source drawBegin), and the recurrence starts from it.

Because the calculation relies solely on smoothFactor, CEma computes that factor once in the constructor and stores it instead of the period.

The last step is to wire the new module into the root CIndicator object. In Indicator.mqh, we include the Ema.mqh header and add the MODE_EMA case to the switch statement in the CIndicator constructor:

#include "Ema.mqh"

//+------------------------------------------------------------------+
//| Root indicator object. Wires all sub-indicators together,        |
//| eliminating the need for global state                            |
//+------------------------------------------------------------------+
class CIndicator : public CIndicatorBase
  {
public:
   CIndicator(const CIndiParamsBase& params)
      : appliedPrice(params.applyTo)
     {
      switch(params.method)
        {
         case MODE_SMA:
            smoothing = new CSma(params.period, appliedPrice.barsRequired);
            break;
         case MODE_EMA:
            smoothing = new CEma(params.period, appliedPrice.barsRequired);
            break;
         default:
            PrintFormat(__FUNCTION__": method %s not implemented; falling back to SMA", EnumToString(params.method));
            smoothing = new CSma(params.period, appliedPrice.barsRequired);
            break;
        }
      SetIndexBuffer(0, smoothing.buffer, INDICATOR_DATA);
      SetIndexBuffer(1, appliedPrice.buffer, INDICATOR_CALCULATIONS);
      PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, smoothing.emptyValue);
     }
  };

Code #8 | Indicator.mqh | feat: implement CEma smoothing sub-indicator


Setting the Plot Label Dynamically

Our indicator can now plot not only a simple moving average, but an exponential one as well. Before we move on to SMMA and LWMA, there is a visual flaw to fix. With inpMethod set to MODE_EMA, both the Data Window and the line's tooltip still show "SMA".

The reason traces back to Part 1: when the indicator calculated exclusively the simple moving average, we hardcoded the plot label via a preprocessor directive in the main program file:

#property indicator_label1 "SMA"

The #property directives define static indicator properties at compile time. When the user selects the calculation algorithm at runtime, such a static definition cannot reflect the choice.

In MQL5, most indicator properties have corresponding runtime functions for dynamic configuration (see Connection between Indicator Properties and Corresponding Functions). In particular, the indicator_labelN property is optional: if the indicator line's label depends on input parameters, it should be configured dynamically during initialization using the PlotIndexSetString() function.

Therefore, we remove the obsolete indicator_label1 directive from the main Evolution.mq5 file. The label configuration moves to where it architecturally belongs—into the CIndicator constructor.

It is CIndicator that acts as an adapter between our modular object model and the MetaTrader 5 terminal runtime. Its constructor already binds the buffers via SetIndexBuffer() and configures the empty value via PlotIndexSetDouble(). The smoothing modules (CSma, CEma), meanwhile, remain "pure" mathematical objects isolated from indicator-level properties.

To construct the label, let's extract the method name from the ENUM_MA_METHOD enumeration. Because all standard moving average constants share the five-character prefix MODE_ (MODE_SMA, MODE_EMA, MODE_SMMA, MODE_LWMA), we can strip it using StringSubstr(EnumToString(params.method), 5) and combine the name with the averaging period:

//+------------------------------------------------------------------+
//| Root indicator object. Wires all sub-indicators together,        |
//| eliminating the need for global state                            |
//+------------------------------------------------------------------+
class CIndicator : public CIndicatorBase
  {
public:
   CIndicator(const CIndiParamsBase& params)
      : appliedPrice(params.applyTo)
     {
      //--- Instantiate smoothing sub-indicator
      switch(params.method) { ... }
      //--- Bind indicator buffers
      SetIndexBuffer(0, smoothing.buffer, INDICATOR_DATA);
      SetIndexBuffer(1, appliedPrice.buffer, INDICATOR_CALCULATIONS);
      //--- Configure smoothing plot
      PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, smoothing.emptyValue);
      string methodStr = StringSubstr(EnumToString(params.method), 5);
      PlotIndexSetString(0, PLOT_LABEL, StringFormat("%s(%d)", methodStr, params.period));
     }
  };

Code #9 | Indicator.mqh | refactor: set plot label dynamically based on smoothing method

The screenshot below shows the result with inpMethod set to MODE_EMA and the period set to 14:

Chart in MetaTrader 5 with the label EMA(14) in the Data Window and in the line's tooltip

The Data Window and the tooltip now display a label that matches the settings—such as "EMA(14)" or "SMA(5)". Moreover, adding SMMA and LWMA will not require any changes to the label setup code.


Smoothed Moving Average

The third smoothing method defined in the ENUM_MA_METHOD enumeration is the Smoothed Moving Average (MODE_SMMA).

This technique was introduced by J. Welles Wilder Jr. in 1978. Wilder used this smoothing algorithm in several of his indicators—most notably the Relative Strength Index (RSI), Average True Range (ATR), and Average Directional Index (ADX). SMMA is also known under various aliases: Wilder's Smoothing, Wilder's Moving Average, Running Moving Average (RMA), or Modified Moving Average (MMA).

Exponential Smoothing in Disguise

SMMA is a variation of exponential smoothing. It relies on the same recurrence formula as the EMA we built earlier:

Method Smoothing Factor ( α) Recurrence Formula
EMA α = 2 period + 1 EMA i = Source i ⋅ α + EMA i − 1 ⋅ ( 1 − α )
SMMA α = 1 period SMMA i = Source i ⋅ α + SMMA i − 1 ⋅ ( 1 − α )

As the table shows, the formula itself is identical—the only distinction lies in the smoothing factor. Wilder used a simpler and smaller value, so with the same period his average reacts more slowly.

Equating the two smoothing factors ( 2 P EMA + 1 = 1 P SMMA) yields an algebraic equivalence:

P EMA = 2 ⋅ P SMMA − 1

An SMMA with period N provides the same degree of exponential dampening as an EMA with period 2 N − 1. For instance, the standard 14-period smoothing that Wilder applied in his RSI produces an exponential response curve identical to that of a 27-period EMA.

The Classic Fractional Form

Although SMMA can be expressed using α, Wilder originally presented the formula in its classic fractional form.

Substituting Wilder's α = 1 period into the general recurrence relation:

SMMA i = Source i ⋅ 1 period + SMMA i − 1 ⋅ ( 1 − 1 period )

and combining the terms over a common denominator yields:

SMMA i = SMMA i − 1 ⋅ ( period − 1 ) + Source i period

Intuitively, this formula computes a weighted average of two numbers: for a 14-period average, it takes the previous smoothed value 13 times ( period − 1), adds the current source value once, and divides the total by 14 ( period).

This is the exact formula implemented in SmoothedMAOnBuffer(), rather than the recurrence relation with α. Our CSmma module will follow suit.

The Seed Value Asymmetry

Apart from the smoothing factor, the two exponential smoothers, EMA and SMMA, differ in how they seed the recurrence.

In ExponentialMAOnBuffer() (and our CEma), calculation begins immediately at the first available bar using the source value at that single bar ( EMA drawBegin = Source drawBegin).

In contrast, SmoothedMAOnBuffer() follows Wilder's classic convention: the recurrence is seeded with a simple moving average over the initial period bars. Because of this requirement, CSmma cannot begin plotting at the first available bar. Just like CSma, it needs an additional period - 1 input bars to accumulate this initial seed:

Method Seed Formula Bars Required Smoothing Type
SMA 1 period ∑ i = drawBegin − period + 1 drawBegin Source i sourceBarsRequired + period - 1 moving window
EMA Source drawBegin sourceBarsRequired exponential
SMMA 1 period ∑ i = drawBegin − period + 1 drawBegin Source i sourceBarsRequired + period - 1 exponential

A 14-period SMMA and a 27-period EMA of the same source have identical response curves. Because their seeds differ, they give different values at the start of the history. The EMA begins plotting earlier, so the first bar that both plot is the one at which the SMMA computes its seed. At every later bar, both apply the same recurrence with the same α = 1 14, so the difference between their values shrinks to 1 − α = 13 14 of its previous size. After 100 bars, less than 0.1% of the initial difference remains.

Implementing CSmma

To compute its seed, CSmma needs the same summation loop as CSma::computeValueAtDrawBegin(). My first thought was to move that loop into a public static method of CSma so that CSmma could call it. However, the loop computes a plain average, a formula that will never change, so two copies of it have no reason to diverge. Sharing the loop would add a method to the public interface of CSma just to avoid repeating four lines. In the end, I gave CSmma its own copy of the loop:

//+------------------------------------------------------------------+
//| Sub-indicator calculating Smoothed Moving Average (SMMA)         |
//+------------------------------------------------------------------+
class CSmma : public CSmoothingBase
  {
private:
   //--- Computes initial SMMA seed value at drawBegin by summation
   void computeValueAtDrawBegin(const double& source[])
     {
      double result = 0.0;
      for(int i = drawBegin - (period - 1); i <= drawBegin; i++)
         result += source[i];
      buffer[drawBegin] = result / period;
     }

public:
   //--- Calculates SMMA values using seed + recurrence formula
   void onCalculate(const int rates_total, const int prev_calculated, const double& source[]) override
     {
      bool isFullCalculation;
      int calcStartIdx = prepareCalculation(rates_total, prev_calculated, isFullCalculation);
      if(isFullCalculation)
        {
         computeValueAtDrawBegin(source);
         calcStartIdx = drawBegin + 1;
        }
      for(int i = calcStartIdx; i < rates_total; i++)
         buffer[i] = (buffer[i - 1] * (period - 1) + source[i]) / period;
     }

private:
   const int period;   // SMMA averaging period
public:
   CSmma(int a_period, int sourceBarsRequired)
      : CSmoothingBase(sourceBarsRequired + correctPeriod(a_period) - 1),
        period(correctPeriod(a_period, true))
     {}
  };

Code #10 | Smma.mqh | feat: implement CSmma smoothing sub-indicator

CSmma differs from CSma only in the recurrence line, which implements the fractional form derived above.

Wiring CSmma into CIndicator simply requires including Smma.mqh and adding the MODE_SMMA case to the constructor's switch (see Indicator.mqh).

Thanks to the dynamic plot label configuration we established in the previous section, no UI adjustments are needed. When the user sets the method to MODE_SMMA with a period of 14, the constructor automatically configures the label as "SMMA(14)", and both the Data Window and the chart tooltip display it.



Linear Weighted Moving Average

The fourth and final smoothing method defined in the ENUM_MA_METHOD enumeration is the Linear Weighted Moving Average (MODE_LWMA).

Like the SMA, it averages a fixed window of period bars and ignores everything older. Unlike in the SMA, the bars inside that window are not treated as equals: their weights grow linearly toward the present. The oldest bar in the window carries a weight of 1, the next one 2, and so on up to the most recent bar, whose weight equals period. Dividing by the sum of all weights normalizes the result back onto the price scale:

LWMA i = ∑ k = 1 period Source i − period + k ⋅ k ∑ k = 1 period k , ∑ k = 1 period k = period ⋅ ( period + 1 ) 2

That denominator depends only on the period, so it is a constant for the lifetime of the indicator.

The chart below compares LWMA with the three methods we have already built. It shows how much each of the most recent bars contributes to the current value of all four averages with a period of 10, with the weights normalized to sum to 1:

Weight profiles of SMA, LWMA, EMA, and SMMA with a period of 10

The table generalizes the picture to any period:

Method Weight of the Newest Bar Decay Across the Window Beyond the Window
SMA 1 period none—every bar counts equally hard cutoff
LWMA 2 period + 1 linear hard cutoff
EMA 2 period + 1 exponential infinite tail
SMMA 1 period exponential infinite tail

LWMA is the only one of the four that combines both traits: a hard window cutoff and graded weights. SMA has the cutoff but no grading; EMA and SMMA grade their weights but never fully forget anything.

In the second column, LWMA and EMA have the same entry. The newest bar enters an LWMA with a raw weight of period, and normalizing that by the total weight gives

period period ⋅ ( period + 1 ) 2 = 2 period + 1

which is exactly the EMA smoothing factor α from Section 4. An LWMA and an EMA of the same period assign identical influence to the current bar (in the chart above, both newest bars stand at 0.182). Everything that separates the two happens in the older bars.

The Straightforward Implementation

So far, every smoothing module in this series has been built around a recurrence: compute a seed value at drawBegin, then roll forward one bar at a time, each value leaning on the one before it. In its direct form, LWMA has no recurrence at all. Each bar is computed independently from its own window of source values, and nothing outside that window takes part.

CLwma implements this direct form:

//+------------------------------------------------------------------+
//| Sub-indicator calculating Linear Weighted Moving Average (LWMA)  |
//+------------------------------------------------------------------+
class CLwma : public CSmoothingBase
  {
private:
   //--- Computes LWMA value at a given bar by weighted summation
   double computeValueAt(int barIdx, const double& source[])
     {
      double result = 0.0;
      for(int i = barIdx - (period - 1), weight = 1; i <= barIdx; i++, weight++)
         result += source[i] * weight;
      return result / totalWeight;
     }

public:
   //--- Calculates LWMA values independently for each bar
   void onCalculate(const int rates_total, const int prev_calculated, const double& source[]) override
     {
      for(int i = prepareCalculation(rates_total, prev_calculated); i < rates_total; i++)
         buffer[i] = computeValueAt(i, source);
     }

private:
   const int period;      // LWMA averaging period
   const int totalWeight; // sum of all weights (period * (period + 1) / 2)
public:
   CLwma(int a_period, int sourceBarsRequired)
      : CSmoothingBase(sourceBarsRequired + correctPeriod(a_period) - 1),
        period(correctPeriod(a_period, true)),
        totalWeight(period * (period + 1) / 2)
     {}
  };

Code #11 | Lwma.mqh | feat: implement CLwma smoothing sub-indicator

Without a recurrence, CLwma is the first smoothing module that does not need the isFullCalculation overload of prepareCalculation(). There is no seed to prepare and no state to carry across the boundary between OnCalculate() calls, so the plain two-argument overload is enough—exactly as in CAppliedPrice::onCalculate(). As a result, CLwma::onCalculate() shrinks to a two-line loop that hands each bar over to computeValueAt().

Because a value requires a complete window, CLwma needs the same period - 1 additional input bars as CSma and CSmma, giving barsRequired = sourceBarsRequired + period - 1. The only exception is CEma: it starts its recurrence from a single source value and needs no additional bars.

As noted above, the sum of the weights never changes once the period is fixed, so there is no reason to recompute it for every bar. I store it in a constant totalWeight member declared immediately after period. Members are initialized in declaration order, so totalWeight can safely derive its value from the already-initialized period. The same idiom lets CSubIndiBase derive drawBegin from barsRequired.

Plugging CLwma into CIndicator is the same change as before: include Lwma.mqh and add the MODE_LWMA case to the constructor's switch (see Indicator.mqh).

The default branch stays unchanged. Every ENUM_MA_METHOD value now has a case of its own. A default is still good practice: whatever value arrives, the smoothing pointer always ends up pointing to a valid object. And once later parts replace ENUM_MA_METHOD with a custom enumeration of smoothing methods, the default branch will take up its original role from Section 3 again, covering each new method until it gets a dedicated case.

With that, the standard set is complete: SMA, EMA, SMMA, and LWMA are all implemented as autonomous modules behind a single polymorphic interface, and the indicator's values match those of the Moving Average built into MetaTrader 5 for every one of them.


Optimizing LWMA

Notice that for each bar, CLwma runs a nested loop over the entire window. The cost of that loop is negligible when only the last one or two bars are computed. It is highest during a full calculation, so that is the scenario we will focus on.

CSma, CEma, and CSmma are built around a recurrence: each value is derived from the previous one, and every step costs the same few operations whatever the period. The direct form of CLwma has no recurrence, and its nested loop costs period multiply-adds per bar.

Let's express the cost in big-O notation, which shows how the amount of work grows with the size of the input while ignoring constant factors. Here, the work depends on two numbers: the number of bars and the period.

The bar at drawBegin may differ in cost from the rest. But it is just one bar, so let's set it aside. The table below shows what a full calculation costs, counting every bar except that one:

Module Per Bar Total
CSma, CEma, CSmma O ( 1 ) O ( rates_total )
CLwma (direct form) O ( period ) O ( rates_total ⋅ period )

With 100,000 bars and a period of 200, the direct form of CLwma runs about 20 million loop iterations per full calculation, against roughly 100,000 for each of the other three modules.

Two Running Sums

The MovingAverages library that ships with MetaTrader 5 already brings a full calculation of LWMA down to O ( rates_total ). Just as we did with SMA, EMA, and SMMA, we will borrow its approach and adapt it to our object model. Open Include/MovingAverages.mqh and find LinearWeightedMAOnBuffer(). The function has two overloads, and we need the one marked "classic" in its header comment. The other one, marked "fast", runs a nested loop over the window for every bar, the same way our direct form does, so it would not make a full calculation cheaper. From here on, LinearWeightedMAOnBuffer() refers to the classic overload.

Instead of recomputing the weighted sum from scratch for every bar, LinearWeightedMAOnBuffer() carries two running sums from one bar to the next: the weighted sum in the numerator of the LWMA formula (kept in a variable named sum) and the plain, unweighted sum of the same window (kept in lsum). That gives LWMA a recurrence as well, and each new bar then costs one update per sum and a single division, whatever the period. Here is the function's main loop in formula form, with W i and S i standing for the two sums over the window that ends at bar i:

W i = W i − 1 − S i − 1 + Source i ⋅ period , S i = S i − 1 − Source i − period + Source i , LWMA i = W i totalWeight

The update of S is nothing new: it is the recurrence CSma uses, just without dividing by the period. The update of W is less obvious. When the window moves, the weight of every bar inside it changes. Yet the formula handles all of these changes by subtracting the plain sum S i − 1 just once, and it has no term at all for the bar that leaves the window.

Writing out the update of W term by term for a period of 3 shows what happens to each bar's weight. Let a, b, and c be the source values in the window ending at bar i − 1, from oldest to newest, and let d be the value of the new bar i:

Window ending at  i − 1 − S i − 1 + 3 ⋅ d W i − 1 = 1 ⋅ a + 2 ⋅ b + 3 ⋅ c = 1 ⋅ b + 2 ⋅ c + 3 ⋅ d = W i W i − 1 − + 3 ⋅ d S i − 1 = a + b + c = 1 ⋅ b + 2 ⋅ c + 3 ⋅ d = W i Subtract the plain sum Window ending at  i − 1 + 3 ⋅ d W i − 1 − S i − 1 = 0 ⋅ a + 1 ⋅ b + 2 ⋅ c = 1 ⋅ b + 2 ⋅ c + 3 ⋅ d = W i Add the new bar Window ending at  i − 1 W i − 1 − S i − 1 + 3 ⋅ d = 1 ⋅ b + 2 ⋅ c + 3 ⋅ d = W i

The key is that all of these weight changes are identical. When the window shifts one bar to the right, every bar that remains inside ends up one position closer to the oldest end of the window, so its weight decreases by exactly one. The bar weighted period is now weighted period − 1, the one weighted period − 1 drops to period − 2, and so on down the line. In W, each bar's source value is multiplied by its weight, so lowering the weight by one reduces W by exactly that value. Doing this for every bar of the old window reduces W by the sum of the window's values, which is precisely S i − 1.

The bar that falls out of the window takes care of itself. It sat at weight 1 in the previous window, so the same decrement brings it to weight 0: it leaves W for free, with no explicit subtraction of its own. All that is left is to admit the new bar at the top weight—the Source i ⋅ period term.

The figure below walks through the same update as in the example above, this time with a period of 10. Each column is as tall as the weight its bar carries in W:

One step of the LWMA recurrence with a period of 10

Where the State Lives

In the three modules built so far, the recurrence state is the output buffer. CSma, CEma, and CSmma each need exactly one number to continue: the previous indicator value. That number is already in buffer[i - 1], written during an earlier OnCalculate() call and preserved by the terminal between calls. State and result are the same thing.

LWMA breaks that coincidence. To continue, it needs both running sums, W i − 1 and S i − 1, and the previous indicator value is not enough to recover them. The sums are genuine internal state, and the buffer cannot hold them.

LinearWeightedMAOnBuffer() does not store this state anywhere. Instead, it rebuilds both sums at the start of every call, using a priming loop that runs ahead of the main loop. That costs O ( period ) once per call, while the rest of the pass costs O ( 1 ) per bar, so a full calculation drops from O ( rates_total ⋅ period ) to O ( rates_total ).

CLwma rebuilds the sums the same way: it primes them over the window that ends just before the bar where the main loop starts. That bar depends on whether the calculation is a full one, so onCalculate() needs the isFullCalculation overload after all.

The constructor and the data members are untouched, so the entire change is the algorithm itself:

//+------------------------------------------------------------------+
//| Sub-indicator calculating Linear Weighted Moving Average (LWMA)  |
//+------------------------------------------------------------------+
class CLwma : public CSmoothingBase
  {
private:
   //--- Computes both running sums for the window ending at a given bar
   void computeSumsAt(int barIdx, const double& source[], double& weightedSum, double& plainSum)
     {
      weightedSum = 0.0;
      plainSum = 0.0;
      for(int i = barIdx - (period - 1), weight = 1; i <= barIdx; i++, weight++)
        {
         weightedSum += source[i] * weight;
         plainSum += source[i];
        }
     }

public:
   //--- Calculates LWMA values using primed sums + sliding window recurrence
   void onCalculate(const int rates_total, const int prev_calculated, const double& source[]) override
     {
      bool isFullCalculation;
      int calcStartIdx = prepareCalculation(rates_total, prev_calculated, isFullCalculation);
      double weightedSum, plainSum;
      if(isFullCalculation)
        {
         computeSumsAt(drawBegin, source, weightedSum, plainSum);
         buffer[drawBegin] = weightedSum / totalWeight;
         calcStartIdx = drawBegin + 1;
        }
      else
         computeSumsAt(calcStartIdx - 1, source, weightedSum, plainSum);
      //--- Slide the window. Order matters: weightedSum needs the old plainSum
      for(int i = calcStartIdx; i < rates_total; i++)
        {
         weightedSum += source[i] * period - plainSum;
         plainSum += source[i] - source[i - period];
         buffer[i] = weightedSum / totalWeight;
        }
     }
  };

Code #12 | Lwma.mqh | perf: calculate LWMA using sliding window sums

Here is what each branch of the if statement does:

  • On a full calculation, the main loop starts at drawBegin + 1, as in the other three modules, so the sums are primed over the window ending at drawBegin. Dividing that window's weighted sum by totalWeight also gives the value at drawBegin, which is written to the buffer.
  • Otherwise, the main loop starts at calcStartIdx, to the right of drawBegin, so the sums are primed over the window ending at calcStartIdx - 1. The value at that bar is already correct, so nothing is written to the buffer.

The figure below shows where the sums are primed on three successive OnCalculate() calls: a full calculation, a current bar update, and a new bar. It is drawn for an LWMA with a period of 3 over a source that requires 2 bars:

CLwma's priming windows on three successive OnCalculate() calls

The priming window of a full calculation starts exactly at the source's first valid bar—that is what the period - 1 additional bars in barsRequired are for. No other priming window starts further left, and the main loop then shifts the window only to the right, so every value read from source[] is valid.


Conclusion

The set of standard moving averages is complete. The framework now has a module for each of the four smoothing methods of the ENUM_MA_METHOD enumeration: CSma, CEma, CSmma, and CLwma. All four adapt the algorithms of the MovingAverages library that ships with MetaTrader 5 to our object model.

The table below sets these modules side by side:

Module Weight Profile Seed Value Bars Required Per-Bar Recurrence State
CSma flat, hard cutoff SMA over the window sourceBarsRequired + period - 1 previous buffer value
CEma exponential, infinite tail single source value sourceBarsRequired previous buffer value
CSmma exponential, infinite tail SMA over the window sourceBarsRequired + period - 1 previous buffer value
CLwma linear, hard cutoff LWMA over the window sourceBarsRequired + period - 1 two local running sums

Three of the four modules got their recurrence state for free, because the terminal was already preserving it on their behalf. CLwma is the first to need something the buffer does not keep.

CSmoothingBase is the new common base class for the smoothing methods that take one series and produce one, including those that later parts will add: it holds the output buffer and declares the onCalculate() method that each of them implements. CSubIndiBase got a new overload of prepareCalculation(), which any sub-indicator, smoothing or not, can call to learn whether a calculation is a full one. The overload holds the test that fixed the bug in CSma, and all four modules call it: on a full calculation, each computes the value at drawBegin before its recurrence starts at the next bar.

For the first time in the framework, a sub-indicator is selected at runtime: the one for the chosen smoothing method is created dynamically and held through a pointer to its base class, CSmoothingBase. EMA, SMMA, and LWMA each took one new file and two additions to Indicator.mqh: an #include directive and a case in the switch statement of the CIndicator constructor. And when we replaced the algorithm of CLwma with a faster one in the last section, Lwma.mqh was the only file that changed.

The complete source code and its commit history are in the evolution repository:

https://forge.mql5.io/modular-indicator-architecture/evolution


Files Attached to the Article

The attached archive contains the source code as it stands at the end of this article:

File Name Description
Evolution.mq5 The main indicator file acting as the entry point and containing the MQL5 event handlers.
Indicator.mqh The root object that wires all sub-indicators together, eliminating the need for global state.
IndicatorBase.mqh Abstracts away infrastructure boilerplate (such as rates_total checks) from the main indicator logic.
InputsAndRelated.mqh Defines the global input variables and CIndiParams, the derived class mapping them to the parameter object.
IndiParamsBase.mqh Defines the base class for indicator parameters, decoupling the core logic from global input variables.
SubIndiRegistry.mqh A static registry that centrally manages the barsRequired requirement across all modules.
SubIndiBase.mqh The base class for all sub-indicators that extracts common traits and handles routine boilerplate.
AppliedPrice.mqh A sub-indicator that calculates the applied price.
SmoothingBase.mqh The base class for all smoothing sub-indicators that defines their common interface.
Sma.mqh A sub-indicator that calculates the Simple Moving Average.
Ema.mqh A sub-indicator that calculates the Exponential Moving Average.
Smma.mqh A sub-indicator that calculates the Smoothed Moving Average.
Lwma.mqh A sub-indicator that calculates the Linear Weighted Moving Average.
Attached files |
MQL5.zip (11.1 KB)
Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 9):  Clipping, Bounds and Hit Testing Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 9): Clipping, Bounds and Hit Testing
This article extends a Cairo-style vector engine in MQL5 with anti-aliased clipping. We build rectangular and path-based clipping regions, combine their coverage in the rasterizer, and discuss the limitations of mask multiplication. We also implement path bounds and point containment for sizing masks and testing interface interactions.
Association Rules and Probability Theory in Forex: A Signal Filter Without Neural Networks or Magic Association Rules and Probability Theory in Forex: A Signal Filter Without Neural Networks or Magic
We explore an alternative to neural network signal filters: association rules and basic probability theory in MQL5, without Python or external libraries. This guide demonstrates how to discretize market conditions (RSI, EMA, ATR, momentum, session), compile statistics on support, confidence, lift, and edge using Laplace smoothing, and apply the result as a transparent entry filter before placing a trade.
Features of Experts Advisors Features of Experts Advisors
Creation of expert advisors in the MetaTrader trading system has a number of features.
Pesaran–Timmermann Test in MQL5: Separating Real Directional Skill from a Lucky Hit Rate Pesaran–Timmermann Test in MQL5: Separating Real Directional Skill from a Lucky Hit Rate
This article implements the Pesaran–Timmermann directional accuracy test in pure MQL5 and applies its rolling right-tail p-value as a gate to enable or disable an Expert Advisor. Forecasts are scored without look-ahead, and the framework includes an EA, a rolling statistical display, and a self-test. The method is evaluated on XAUUSD, EURUSD and GBPUSD, with a coin-flip control to quantify false alarms.