diff --git a/Indicators/MyIndicators/Authors/Kaufman/KAMA_Pro.md b/Indicators/MyIndicators/Authors/Kaufman/KAMA_Pro.md index ba4ba95..759d763 100644 --- a/Indicators/MyIndicators/Authors/Kaufman/KAMA_Pro.md +++ b/Indicators/MyIndicators/Authors/Kaufman/KAMA_Pro.md @@ -1,76 +1,134 @@ -# Kaufman's Adaptive Moving Average (KAMA) Pro +# Kaufman's Adaptive Moving Average (KAMA) Pro (v3.30) + +Professional Quantitative Adaptive Filter with Native Multi-Timeframe (MTF) Support + +--- ## 1. Summary (Introduction) -Kaufman's Adaptive Moving Average (KAMA), developed by Perry J. Kaufman, is a sophisticated "intelligent" moving average designed to be both sensitive to trends and resilient to market noise. It addresses the fundamental trade-off of traditional moving averages: a short period is responsive but prone to whipsaws, while a long period is smooth but suffers from significant lag. +**Kaufman's Adaptive Moving Average (KAMA)**, designed by quantitative trading pioneer Perry J. Kaufman, is an intelligent, low-lag moving average engineered to solve the classic responsiveness-versus-smoothness dilemma. Standard moving averages force a compromise: short periods produce rapid signals but generate false breakout whipsaws in ranging markets, while long periods eliminate noise but lag significantly during fast trends. -KAMA solves this by dynamically adjusting its smoothing speed based on the market's directional efficiency. It automatically slows down during choppy, sideways markets and speeds up during clear, trending periods. +KAMA overcomes this by dynamically adjusting its smoothing coefficient based on the market's **Efficiency Ratio (ER)**: -Our `KAMA_Pro` implementation is a definition-true version of this powerful tool, fully supporting calculations on both **standard** and **Heikin Ashi** price data. +* **Trending Phase (High Efficiency):** KAMA accelerates dynamically toward the speed of a fast EMA (e.g., 2-period), capturing momentum with minimal lag. +* **Consolidation / Choppy Phase (Low Efficiency):** KAMA decelerates toward the speed of a slow EMA (e.g., 30-period) and flattens out, completely neutralizing market noise. -## 2. Mathematical Foundations and Calculation Logic +Our **KAMA Pro (v3.30)** implementation provides a definition-true mathematical engine with unified **Native & Multi-Timeframe (MTF)** processing, full **Heikin Ashi** synthetic price filtering, and incremental $O(1)$ performance. -The core of KAMA is the **Efficiency Ratio (ER)**, which quantifies the "trendiness" of the market by measuring its signal-to-noise ratio. +--- -### Required Components +## 2. Mathematical Foundations & Calculation Logic -* **ER Period (N):** The lookback period for calculating the Efficiency Ratio. -* **Fast EMA Period (F):** The period for the fastest possible EMA (used when the trend is perfect). -* **Slow EMA Period (S):** The period for the slowest possible EMA (used when the market is pure noise). -* **Source Price (P):** The price series for the calculation. +The foundation of KAMA is the **Efficiency Ratio (ER)**, which acts as a signal-to-noise detector. -### Calculation Steps (Algorithm) +```text -1. **Calculate the Efficiency Ratio (ER):** The ER is the ratio of the net directional movement ("Signal") to the total price movement ("Noise") over the period `N`. - * **Direction (Signal):** The absolute net change in price over `N` periods. - $\text{Direction}_t = \text{Abs}(P_t - P_{t-N})$ - * **Volatility (Noise):** The sum of the absolute price changes for each bar within the `N` period. - $\text{Volatility}_t = \sum_{i=0}^{N-1} \text{Abs}(P_{t-i} - P_{t-i-1})$ - * **Efficiency Ratio:** - $\text{ER}_t = \frac{\text{Direction}_t}{\text{Volatility}_t}$ - *(The value of ER ranges from 0 to 1)* + | Price(t) - Price(t - N) | (Net Direction / Signal) +ER(t) = ───────────────────────────────────────────────────────────── + ∑ [ | Price(t - i) - Price(t - i - 1)| ] (Total Path / Noise) -2. **Calculate the dynamic Smoothing Constant (SC):** The ER is used to create a dynamic smoothing constant that scales between the fastest and slowest possible speeds. - * First, define the fastest and slowest smoothing constants based on the EMA formula: - $\text{sc}_{fast} = \frac{2}{F + 1}$ - $\text{sc}_{slow} = \frac{2}{S + 1}$ - * Then, calculate the scaled smoothing constant and square it to give more weight to the slower end of the range: - $\text{SC}_t = (\text{ER}_t \times (\text{sc}_{fast} - \text{sc}_{slow}) + \text{sc}_{slow})^2$ +``` -3. **Calculate the KAMA:** The KAMA is calculated recursively, similar to an EMA, but using the dynamic `SC` calculated in the previous step. - $\text{KAMA}_t = \text{KAMA}_{t-1} + \text{SC}_t \times (P_t - \text{KAMA}_{t-1})$ +### 2.1. Mathematical Formulation -## 3. MQL5 Implementation Details +#### 1. Direction (Signal) -Our MQL5 implementation follows a modern, object-oriented design pattern to ensure stability, reusability, and maintainability. The logic is separated into a main indicator file and a dedicated calculator engine. +The absolute net price change over the lookback period $N$: +$$\text{Direction}_t = | P_t - P_{t-N} |$$ -* **Modular Calculator Engine (`KAMA_Calculator.mqh`):** - All core calculation logic is encapsulated within a reusable include file. This separates the mathematical complexity from the indicator's user interface and buffer management. +#### 2. Volatility (Noise) -* **Optimized Incremental Calculation:** - Unlike basic implementations that recalculate the entire history on every tick, this indicator employs an intelligent incremental algorithm. - * It utilizes the `prev_calculated` state to determine the exact starting point for updates. - * **Persistent State:** The internal price buffer (`m_price`) persists its state between ticks. This allows the calculation to efficiently access historical price data for the Efficiency Ratio without re-copying the entire series. - * This results in **O(1) complexity** per tick, ensuring instant updates and zero lag, even on charts with extensive history. +The total sum of all individual price path segments across the lookback period $N$: +$$\text{Volatility}_t = \sum_{i=0}^{N-1} | P_{t-i} - P_{t-i-1} |$$ -* **Object-Oriented Design (Inheritance):** - * A base class, `CKamaCalculator`, handles the core AMA algorithm, including the ER, SSC, and the final recursive calculation. - * A derived class, `CKamaCalculator_HA`, inherits from the base class and **overrides** only one specific function: the price series preparation. Its sole responsibility is to calculate Heikin Ashi candles and provide the selected HA price to the base class's AMA algorithm. This is a clean and efficient use of polymorphism. +#### 3. Efficiency Ratio (ER) -## 4. Parameters (`KAMA_Pro.mq5`) +$$\text{ER}_t = \begin{cases} \frac{\text{Direction}_t}{\text{Volatility}_t}, & \text{if } \text{Volatility}_t > 0 \\ 0, & \text{if } \text{Volatility}_t = 0 \end{cases}$$ +*(The ER value strictly oscillates between $0.0$ [pure noise / chop] and $1.0$ [perfect directional trend]).* -* **ER Period (`InpErPeriod`):** The lookback period for the Efficiency Ratio calculation. Kaufman's standard value is `10`. -* **Fast EMA Period (`InpFastEmaPeriod`):** The period for the fastest EMA speed. Kaufman's standard value is `2`. -* **Slow EMA Period (`InpSlowEmaPeriod`):** The period for the slowest EMA speed. Kaufman's standard value is `30`. -* **Applied Price (`InpSourcePrice`):** The source price for the calculation (Standard or Heikin Ashi). +#### 4. Scaled Smoothing Constant (SSC) -## 5. Usage and Interpretation +First, the fastest and slowest smoothing factors are determined based on standard exponential constants: +$$\alpha_{\text{fast}} = \frac{2}{F + 1}, \quad\quad \alpha_{\text{slow}} = \frac{2}{S + 1}$$ +*where $F = \text{Fast EMA Period}$ (default: 2), and $S = \text{Slow EMA Period}$ (default: 30).* -KAMA is a superior, low-lag trend line that can be used in multiple ways. +The dynamic smoothing multiplier is scaled and squared to aggressively penalize noisy market regimes: +$$\text{SC}_t = \left[ \text{ER}_t \cdot (\alpha_{\text{fast}} - \alpha_{\text{slow}}) + \alpha_{\text{slow}} \right]^2$$ -* **Primary Trend Filter:** The main function of KAMA is to identify the direction and state of the trend. - * When the price is consistently above a rising KAMA, the market is in a strong uptrend. - * When the price is consistently below a falling KAMA, the market is in a strong downtrend. - * When the KAMA line **flattens out**, it is a clear and early signal that the market has entered a consolidation or ranging phase, and trend-following strategies should be paused. This is KAMA's key advantage over traditional MAs. -* **Dynamic Support and Resistance:** In a trending market, the KAMA line acts as a highly responsive dynamic level of support (in an uptrend) or resistance (in a downtrend), providing potential entry points on pullbacks. -* **Crossover Signals:** Price crossing over the KAMA line can be used as a trade signal, which is often more reliable than traditional MA crossovers due to KAMA's adaptive nature. +#### 5. Recursive KAMA Calculation + +Similar to an exponential smoothing filter, KAMA updates recursively using the dynamic $\text{SC}_t$: +$$\text{KAMA}_t = \text{KAMA}_{t-1} + \text{SC}_t \cdot (P_t - \text{KAMA}_{t-1})$$ + +--- + +## 3. MQL5 Architecture & Engineering Standards + +```text + +┌────────────────────────────────────────────────────────┐ +│ KAMA_Calculator.mqh │ +│ (Core Math Engine - Encapsulated Heikin Ashi Engine) │ +└──────────────────────────┬─────────────────────────────┘ + │ Calculates KAMA Values (O(1)) + ▼ +┌────────────────────────────────────────────────────────┐ +│ KAMA_Pro.mq5 │ +│ (Unified Wrapper: Native Timeframe & MTF Engine) │ +├──────────────────────────┬─────────────────────────────┤ +│ Direct Mode (O(1)) │ Synchronized MTF Pipeline │ +│ • Current Timeframe │ • Forming Block Anchor │ +│ • Zero-Overhead Bypass │ • Non-Repainting Step Map │ +└──────────────────────────┴─────────────────────────────┘ + +``` + +### 3.1. Composition over Inheritance + +Rather than maintaining separate derived classes for Heikin Ashi calculations, `CKamaCalculator` embeds `CHeikinAshi_Calculator` directly via composition. All standard and Heikin Ashi price modes (`PRICE_HA_CLOSE`, `PRICE_HA_TYPICAL`, etc.) are processed through a single, type-safe internal pipeline. + +### 3.2. High-Performance MTF Framework (2026 Standard) + +* **Forming LTF Block Flat-Force (The Staircase Solution):** Prevents real-time step distortion by anchoring the mapping start index (`first_bar_of_forming_htf`) to the very first sub-bar of the active HTF candle. All forming bars update simultaneously on every live tick. +* **Strict Chronological Mapping:** Avoids legacy array-direction flipping (`ArraySetAsSeries(true/false)`) by mapping HTF bar shifts directly using zero-overhead chronological indexing: + $$\text{htf\_idx} = \text{htf\_rates\_total} - 1 - \text{iBarShift}(\dots)$$ +* **Asynchronous Data Guard (`OnTimer`):** A 1-second background timer checks whether higher-timeframe history is synchronized, automatically refreshing the indicator once historical data becomes available. + +--- + +## 4. Parameters Reference + +### Timeframe Settings + +* `InpTimeframe` (*default: `PERIOD_CURRENT`*): Timeframe for calculation. When set to `PERIOD_CURRENT`, it operates in direct high-speed mode. When set to a higher timeframe (e.g., `PERIOD_H1`, `PERIOD_D1`), it activates the synchronized MTF engine. + +### KAMA Core Settings + +* `InpErPeriod` (*default: `10`*): The lookback window ($N$) used to calculate price direction and volatility. +* `InpFastEmaPeriod` (*default: `2`*): The fastest smoothing period ($F$) used during strong trends. +* `InpSlowEmaPeriod` (*default: `30`*): The slowest smoothing period ($S$) used during consolidating markets. +* `InpSourcePrice` (*default: `PRICE_CLOSE_STD`*): Price input series. Supports all 7 Standard and 7 Heikin Ashi price representations. + +### Visual Settings + +* `InpColorKAMA` (*default: `clrCrimson`*): Color of the KAMA plot line. +* `InpStyleKAMA` (*default: `STYLE_SOLID`*): Line style (Solid, Dash, Dot). +* `InpWidthKAMA` (*default: `2`*): Line thickness. + +--- + +## 5. Usage & Trading Interpretation + +### 5.1. Trend vs. Consolidation Regime (The "Flat Filter") + +* **Rising KAMA:** Strong bullish momentum with high directional efficiency. +* **Falling KAMA:** Strong bearish momentum with high directional efficiency. +* **Horizontal / Flat KAMA:** Market is in a low-efficiency sideways consolidation. Trend-following breakout entries should be avoided during flat regimes. + +### 5.2. Dynamic Support & Resistance + +In established trending markets, KAMA acts as an adaptive institutional support or resistance line. Pullbacks into a sloping KAMA line offer high-probability entry points with tightly definable invalidation levels. + +### 5.3. Multi-Timeframe Alignment + +By attaching a higher-timeframe KAMA (e.g., `PERIOD_H4` or `PERIOD_D1`) onto an intraday chart (e.g., `PERIOD_M15`), traders can trade strictly in the direction of the macro trend while avoiding intermediate intraday counter-trend traps.