2026-09-20 12:49:07 -07:00 | | | //+------------------------------------------------------------------+
|
| | | //| 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:
|
2026-09-24 11:13:32 -07:00 | | | //--- Computes both running sums for the window ending at a given bar
|
| | | void computeSumsAt(int barIdx, const double& source[], double& weightedSum, double& plainSum)
|
2026-09-20 12:49:07 -07:00 | | | {
|
2026-09-24 11:13:32 -07:00 | | | weightedSum = 0.0;
|
| | | plainSum = 0.0;
|
2026-09-20 12:49:07 -07:00 | | | for(int i = barIdx - (period - 1), weight = 1; i <= barIdx; i++, weight++)
|
2026-09-24 11:13:32 -07:00 | | | {
|
| | | weightedSum += source[i] * weight;
|
| | | plainSum += source[i];
|
| | | }
|
2026-09-20 12:49:07 -07:00 | | | }
|
| | |
|
| | | public:
|
2026-09-24 11:13:32 -07:00 | | | //--- Calculates LWMA values using primed sums + sliding window recurrence
|
2026-09-20 12:49:07 -07:00 | | | void onCalculate(const int rates_total, const int prev_calculated, const double& source[]) override
|
| | | {
|
2026-09-24 11:13:32 -07:00 | | | 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;
|
| | | }
|
2026-09-20 12:49:07 -07:00 | | | }
|
| | |
|
| | | 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)
|
| | | {}
|
| | | };
|