| //+------------------------------------------------------------------+
|
| //| Copyright (C) 2026, boyvlad |
|
| //| https://www.mql5.com/en/users/boyvlad |
|
| //+------------------------------------------------------------------+
|
| #include "SmoothingBase.mqh"
|
|
|
| //+------------------------------------------------------------------+
|
| //| 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;
|
| }
|
| }
|
|
|
| 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)
|
| {}
|
| };
|