# Laguerre RSI & Nested Stochastic Oscillators Pro Suite (Standard & MTF)

## 1. Summary (Introduction)

The **Laguerre RSI & Nested Stochastic Oscillators Pro Suite** is an elite, multi-stage quantitative signal processing suite comprising six advanced indicators:

* `Laguerre_RSI_Pro` (Standard LagRSI)
* `Laguerre_RSI_MTF_Pro` (Multi-Timeframe LagRSI)
* `StochasticFast_on_LaguerreRSI_Pro` (Standard Nested Fast Stochastic)
* `StochasticFast_on_LaguerreRSI_MTF_Pro` (Multi-Timeframe Nested Fast Stochastic)
* `StochasticSlow_on_LaguerreRSI_Pro` (Standard Nested Slow Stochastic)
* `StochasticSlow_on_LaguerreRSI_MTF_Pro` (Multi-Timeframe Nested Slow Stochastic)

### The Multi-Stage Signal Processing Concept

Standard momentum oscillators (such as Wilder's RSI) calculate momentum directly on volatile raw closing prices, leading to jagged oscillations, lag, and false breakouts. The Laguerre RSI solves this by calculating relative strength on the four polynomial state registers ($L_0$ to $L_3$) of the Laguerre Filter, yielding a clean, ultra-responsive momentum curve.

To unlock the maximum potential of this smooth indicator, the suite implements **Nested Stochastic Scaling**. By applying Stochastic mathematics (Fast and Slow) directly over the Laguerre RSI buffer instead of price:

1. **Stage 1 (State Filter):** Price is filtered in polynomial Laguerre space to isolate short-term cycles.
2. **Stage 2 (RSI Mapping):** Filtered states are mapped to a relative strength index, creating a smooth momentum line.
3. **Stage 3 (Stochastic Normalization):** The Laguerre RSI curve is normalized to a standardized $0-100$ range using rolling high-low Stochastic boundaries.

This multi-stage transformation completely eliminates high-frequency noise, yielding highly defined cyclical waves and pristine crossover turning points.

---

## 2. Mathematical Foundations

The calculations flow in a cascading sequence, starting from raw prices and culminating in smoothed, nested stochastic coordinates:

### A. Stage 1 & 2: Laguerre RSI Calculation

At each bar $t$, the Laguerre state registers ($L_0$ to $L_3$) are recursively calculated using the Gamma factor $\gamma$ (`InpGamma`). The cumulative upward change ($cu$) and cumulative downward change ($cd$) between these state registers are accumulated:

$$\text{If } L_{0, t} \ge L_{1, t} \implies cu = L_{0, t} - L_{1, t} \quad \text{else} \quad cd = L_{1, t} - L_{0, t}$$

$$\text{If } L_{1, t} \ge L_{2, t} \implies cu = cu + (L_{1, t} - L_{2, t}) \quad \text{else} \quad cd = cd + (L_{2, t} - L_{1, t})$$

$$\text{If } L_{2, t} \ge L_{3, t} \implies cu = cu + (L_{2, t} - L_{3, t}) \quad \text{else} \quad cd = cd + (L_{3, t} - L_{2, t})$$

The raw **Laguerre RSI** value is calculated as the ratio of upward accumulation to total accumulation:

$$\text{LagRSI}_t = \frac{cu}{cu + cd} \times 100$$

If total accumulation is $0$, the value falls back to the previous state to prevent division-by-zero errors:

$$\text{LagRSI}_t = \begin{cases}
  \text{LagRSI}_{t-1} & \text{if } (cu + cd) \le 1.0 \times 10^{-9} \text{ and } t > 0 \\
  50.0 & \text{if } (cu + cd) \le 1.0 \times 10^{-9} \text{ and } t = 0
\end{cases}$$

### B. Stage 3: Nested Fast Stochastic %K on Laguerre RSI

The nested Stochastic lookback period $K$ (`InpKPeriod`) is applied directly to the historical `LagRSI[]` buffer. The highest and lowest RSI values over the window are determined:

$$H_{\text{RSI}, t} = \max(\text{LagRSI}_t, \text{LagRSI}_{t-1}, \dots, \text{LagRSI}_{t-K+1})$$

$$L_{\text{RSI}, t} = \min(\text{LagRSI}_t, \text{LagRSI}_{t-1}, \dots, \text{LagRSI}_{t-K+1})$$

$$\text{Range}_{\text{RSI}, t} = H_{\text{RSI}, t} - L_{\text{RSI}, t}$$

$$\%K_{\text{Fast}, t} = \frac{\text{LagRSI}_t - L_{\text{RSI}, t}}{\text{Range}_{\text{RSI}, t}} \times 100$$

### C. Signal Line Smoothing (Fast vs. Slow)

* **Fast %D Signal:**
  For the `StochasticFast_on_LaguerreRSI` indicators, a single Signal line $\%D_{\text{Fast}}$ is calculated by smoothing the $\%K_{\text{Fast}}$ line over the period $D$ (`InpDPeriod`):
  $$\%D_{\text{Fast}, t} = \text{MA}(\%K_{\text{Fast}}, D)_t$$

* **Slow %K Smoothing:**
  For the `StochasticSlow_on_LaguerreRSI` indicators, the $\%K_{\text{Fast}}$ is smoothed over the slowing period $S$ (`InpSlowingPeriod`) to establish the **Slow %K** line:
  $$\%K_{\text{Slow}, t} = \text{MA}(\%K_{\text{Fast}}, S)_t$$

* **Slow Signal %D:**
  The Slow Signal $\%D_{\text{Slow}}$ is generated by applying a secondary moving average directly over the Slow %K line:
  $$\%D_{\text{Slow}, t} = \text{MA}(\%K_{\text{Slow}}, D)_t$$

Both the slowing and signal engines natively support standard moving averages and **Volume-Weighted Moving Averages (VWMA)** to incorporate volume confirmation into crossovers.

---

## 3. High-Performance & Precision Enhancements

The entire suite is engineered to conform with our strict quantitative design guidelines:

* **Three-Decimal Precision Formatting:**
  To natively support precise Fibonacci Gamma inputs (e.g., `0.236`, `0.382`, `0.618`) without visual rounding, the indicator short name formatting is expanded to three decimal places. The dynamic ShortName in `OnInit()` uses a `%.3f` formatting mask:
  ```mql5
  IndicatorSetString(INDICATOR_SHORTNAME, StringFormat("StochSlow on LagRSI(%.3f, %d, %d)", InpGamma, InpKPeriod, InpSlowingPeriod));
  ```

* **Strict Chronological Sorting Safeguards:**
  To prevent calculation corruption caused by reverse-chronological array states (often forced by custom templates or third-party indicators on the active chart), the suite enforces chronological sorting (`ArraySetAsSeries(..., false)`) on all price inputs inside `OnCalculate()`.

* **Memory Safety Validation (Pointer Guards):**
  To shield the terminal from runtime memory violations (such as access violation fatal crashes), a robust pointer-safety layer validates all dynamic objects via `CheckPointer()` before any calculation sequence is allowed to execute.

---

## 4. Advanced MQL5 MTF Implementation Details

All three MTF wrappers resolve standard MTF calculation and display limitations by implementing a synchronized multi-timeframe pipeline:

### A. Forming LTF Block Flat-Force (The Warping Solution)

To prevent real-time step warping and slope distortion on lower timeframe charts, the indicator implements a step-blocking algorithm. On every tick, the indicator isolates the beginning of the active forming HTF block and forces the calculations to rewrite that block completely, keeping the visual lines perfectly flat and historically stable:

```mql5
int first_bar_of_forming_htf = rates_total - 1;
while(first_bar_of_forming_htf > 0 &&
      iBarShift(_Symbol, g_calc_timeframe, time[first_bar_of_forming_htf], false) == 0)
  {
   first_bar_of_forming_htf--;
  }
first_bar_of_forming_htf++; // Dynamic anchor start

if(start > first_bar_of_forming_htf)
   start = first_bar_of_forming_htf;
```

### B. State Mocking for IIR State Stability

Since the Laguerre Filter is highly recursive, calling calculations continuously on the live forming bar on every tick would corrupt the feedback states ($L_0$ to $L_3$). To avoid this, we perform **State Mocking** by passing `prev_calculated = g_htf_count` during live ticks. This processes the forming index exactly once, protecting closed historical registers from accumulation errors.

---

## 5. Parameters

### A. Laguerre RSI Settings

* **Gamma Factor (`InpGamma`):** Controls the dampening speed of the polynomial states. Lower values (e.g., `0.382` or `0.500`) are faster; higher values (e.g., `0.700` or `0.850`) are smoother (Default: `0.500`, Fibonacci Recommendations: `0.236`, `0.382`, `0.618`).
* **Source Price (`InpSourcePrice`):** Selects the pricing input, supporting Standard and Heikin Ashi price series (Default: `PRICE_CLOSE_STD`).

### B. Stochastic Settings (Stoch Fast/Slow on LagRSI Only)

* **K Period (`InpKPeriod`):** The lookback window size used strictly for the stochastic highest-high and lowest-low calculations (Default: `14`).
* **Slowing Period (`InpSlowingPeriod` - Slow Version Only):** The smoothing lookback period for Fast %K to establish Slow %K (Default: `3`).
* **Slowing Method (`InpSlowingMAType` - Slow Version Only):** The MA type used for Slowing (Default: `SMA`). Supports `VWMA`.
* **D Period / Signal Period (`InpDPeriod`):** The lookback period for the Signal line (Default: `3`).
* **D MA Type / Signal Method (`InpDMAType`):** The MA type used for the Signal line (Default: `SMA`). Supports `VWMA`.

### C. MTF Specific Settings (MTF Versions Only)

* **Target Timeframe (`InpUpperTimeframe`):** The target higher timeframe to calculate momentum on (Default: `PERIOD_H1`).

---

## 6. Quantitative Trading Strategies

### A. Nested Fast Stochastic Extreme Reversals (Momentum Crossovers)

Nesting a Fast Stochastic on top of Laguerre RSI provides highly precise overbought and oversold extreme boundaries. By waiting for the stochastic lines to cross back into the neutral zone, traders avoid premature counter-trend entries.

1. **Setup:** Apply `StochasticFast_on_LaguerreRSI_Pro` on an M5 execution chart:
   * `InpGamma = 0.500` (Balanced Laguerre RSI speed)
   * `InpKPeriod = 14`
   * `InpDPeriod = 3`
2. **Execution Trigger:**
   * **BUY Entry:** Wait for the Fast %K line (blue) to fall below **`10.0`** (extreme oversold). Enter long once Fast %K crosses back **above the Signal %D line** and closes above the `10.0`/`20.0` boundaries.
   * **SELL Entry:** Wait for the Fast %K line to rise above **`90.0`** (extreme overbought). Enter short once Fast %K crosses back **below the Signal %D line** and closes below the `90.0`/`80.0` boundaries.
3. **Stop-Loss:** Place the protective stop strictly beyond the high/low of the reversal trigger bar.

### B. Top-Down Institutional Cycle Alignment (MTF Trend Following)

Using the Slow Stochastic on Laguerre RSI on a higher timeframe ensures that lower timeframe trade executions are aligned with large-scale institutional cycles.

1. **Setup:** Apply `StochasticSlow_on_LaguerreRSI_MTF_Pro` set to H1 or H4 on an M15 chart:
   * `InpGamma = 0.618` (The Golden Ratio anchor)
   * `InpKPeriod = 14`, `InpSlowingPeriod = 3`, `InpDPeriod = 3` (All MA Types set to `VWMA` to filter out low-volume noise).
2. **Trend Definition:**
   * **Bullish Regime:** The H1 Slow %K is above its Signal %D line and rising from the `20.0` or `50.0` key levels. Strictly seek buy setups on the lower timeframe.
   * **Bearish Regime:** The H1 Slow %K is below its Signal %D line and falling from the `80.0` or `50.0` key levels. Strictly seek sell setups.
3. **LTF Execution:** On the local M15 chart, apply a fast local oscillator. When the H1 MTF indicator defines a Bullish Regime, execute **BUY** orders strictly when the local oscillator crosses above its signal line, using the macro trend alignment to filter out high-frequency false breakouts.
