# Center of Gravity (CG) Oscillator Pro Suite (Standard & MTF)

## 1. Summary (Introduction)

The **Center of Gravity (CG) Oscillator Pro Suite** is an institutional-grade, zero-lag cycle-isolation suite comprising two advanced indicators:

* `CG_Oscillator_Pro` (Standard)
* `CG_Oscillator_MTF_Pro` (Multi-Timeframe)

Developed by the legendary quantitative developer John F. Ehlers, the Center of Gravity (CG) Oscillator applies the physical laws of classical mechanics—specifically the calculation of the center of mass (or center of gravity) of a physical system—to financial price series.

Traditional momentum oscillators (such as MACD, RSI, or standard Stochastics) require heavy smoothing filters to eliminate high-frequency noise. However, heavy smoothing introduces severe phase lag, causing trading signals to be generated long after the cyclical turning point has passed. The CG Oscillator resolves this fundamental trade-off. By calculating the weighted concentration of price "mass" over a rolling observation window $N$ (`InpPeriod`), the oscillator identifies cyclical turning points with **theoretically zero lag** relative to the underlying price wave.

The suite features dynamic Heikin Ashi price integration, flexible rendering modes, dynamic centerline horizontal grids, and advanced multi-timeframe step-blocking algorithms to prevent real-time drawing warping.

---

## 2. Mathematical Foundations

The physics analogy of the Center of Gravity calculates the weighted position of particles where the sum of the product of distance and mass is divided by the sum of the masses. In financial charts, price is treated as the "mass," and the distance from the current bar represents the "distance coordinate":

### A. Core CG Formula

At each bar $t$, the rolling observation window of size $N$ (`InpPeriod`) is evaluated. The numerator acts as the sum of weighted prices (weighted by distance index $j+1$), and the denominator is the simple sum of prices over the window:

$$\text{Numerator}_t = \sum_{j=0}^{N-1} (j + 1) \times P_{t-j}$$

$$\text{Denominator}_t = \sum_{j=0}^{N-1} P_{t-j}$$

$$\text{Raw CG}_t = -\frac{\text{Numerator}_t}{\text{Denominator}_t}$$

### B. Operating Modes and Value Centering

The suite implements two distinct mathematical representations of the Center of Gravity:

* **Original Ehlers Mode (`InpOriginalMode = true`):**
  This mode outputs the raw negative index position as described in Ehlers' original research. The resulting values are purely negative and oscillate around a dynamic centerline which is mathematically dependent on the period length $N$:
  $$\text{Centerline}_{\text{Original}} = -\frac{N + 1}{2}$$
  *(For $N = 10$, the centerline is exactly $-5.50$. For $N = 14$, the centerline is exactly $-7.50$.)*

* **Pro Mode (`InpOriginalMode = false`):**
  This mode adds a mathematical offset equal to half the period length plus $0.5$ to shift and center the entire oscillator perfectly around **`0.0`**, making it highly intuitive for comparative analysis:
  $$\text{Centerline}_{\text{Pro}} = 0.0$$
  $$\text{CG}_{\text{Pro}, t} = \text{Raw CG}_t + \frac{N + 1}{2}$$

### C. Signal Line Generation

To confirm turning points, a highly responsive Signal Line is generated by introducing a standard 1-bar delay directly over the computed CG buffer:

$$\text{Signal}_t = \text{CG}_{t-1}$$

---

## 3. Dynamic Centerline & Levels Configuration

In standard MT5 separate window indicators, horizontal grid levels must be hardcoded using `#property` directives. Because the CG centerline shifts dramatically depending on the selected period $N$ and the original/pro mode toggle, hardcoded levels lead to severe visual misalignment.

The CG Oscillator Pro Suite resolves this visual bug by implementing a **Dynamic Centerline Grid Engine**:

* During `OnInit()`, the engine evaluates the user-defined parameters (`InpPeriod` and `InpOriginalMode`).
* It programmatically calculates the precise mathematical center level of the selected setup:
  $$\text{Center Level} = \begin{cases}
    -(N+1)/2.0 & \text{if } \text{InpOriginalMode} = \text{true} \\
    0.0 & \text{if } \text{InpOriginalMode} = \text{false}
  \end{cases}$$
* It then registers this centerline dynamically using the MetaTrader 5 level properties, ensuring that the dynamic centerline grid is rendered at the exact mathematical center of the waves:

  ```mql5
  double center_level = InpOriginalMode ? -(InpPeriod + 1) / 2.0 : 0.0;
  IndicatorSetInteger(INDICATOR_LEVELS, 1);
  IndicatorSetDouble(INDICATOR_LEVELVALUE, 0, center_level);
  ```

---

## 4. High-Performance & Precision Enhancements

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

* **Dynamic Precision Formatting:**
  In Original Mode, the CG lines fluctuate between large negative coordinates (e.g. $-4.50$ to $-6.50$), requiring standard $2$-digit precision. In Pro Mode, the centered oscillations around `0.0` can be extremely small, requiring higher resolution. The engine automatically adapts its precision during initialization:

  ```mql5
  IndicatorSetInteger(INDICATOR_DIGITS, InpOriginalMode ? 2 : 4);
  ```

* **Szigorú 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()`.

---

## 5. Advanced MQL5 MTF Implementation Details

`CG_Oscillator_MTF_Pro` resolves 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 CG calculations rely on a sequential, rolling history of price data, calling calculations continuously on the live forming bar on every tick could corrupt the feedback states. 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.

---

## 6. Parameters

### A. CG Settings

* **Observation Period (`InpPeriod`):** The lookback window size ($N$) for the center of mass calculations (Default: `10`, Range: $\ge 2$).
* **Candle Source (`InpSource`):** Selects the price series source (`SOURCE_STANDARD` or `SOURCE_HEIKIN_ASHI`). Default: `SOURCE_STANDARD`.
* **Original Mode (`InpOriginalMode`):** Selects Ehlers' original raw negative index rendering (`true`) or centered-at-zero Pro rendering (`false`). Default: `true`.

### B. MTF Specific Settings (MTF Version Only)

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

---

## 7. Advanced Trading Strategies

### A. The Zero-Lag Crossover Trigger (CG vs. Signal)

The 1-bar delayed Signal Line acts as a highly responsive trigger. Because the CG line reacts instantly to price turns, crossovers generate immediate entries at the exact peak/valley of the cycle.

1. **Setup:** Apply `CG_Oscillator_Pro` set to Pro Mode (`InpOriginalMode = false`) on an M15 chart.
2. **BUY Signal (Long Entry):**
   * Wait for the CG Line (red) to cross above the Signal Line (blue) from below the dynamic centerline.
   * **Execution:** Enter Long. Place a protective stop-loss below the recent swing low.
3. **SELL Signal (Short Entry):**
   * Wait for the CG Line to cross below the Signal Line from above the dynamic centerline.
   * **Execution:** Enter Short. Place a protective stop-loss above the recent swing high.

### B. Dynamic Centerline Gravity Pivot (Zero-Cross Filter)

The dynamic centerline acts as the statistical equilibrium of the market. Price crossing this line signifies a major shift in the center of gravity of the asset.

1. **Setup:** Apply `CG_Oscillator_Pro` set to Pro Mode (`InpOriginalMode = false`). This centers the centerline at exactly **`0.0`**.
2. **Bullish Shift (BUY):**
   * Wait for the CG Line to cross **above the 0.0 centerline**, confirming that the center of gravity of the last $N$ bars has shifted into bullish momentum.
   * Enter Long. Trail the stop-loss using the dynamic centerline.
3. **Bearish Shift (SELL):**
   * Wait for the CG Line to cross **below the 0.0 centerline**, confirming that the center of gravity has shifted into bearish momentum.
   * Enter Short.
