I took the freedom to rewrite and optimize this indicator my own way.
Here is a detailed breakdown of the critical fixes and new features implemented:
1. Eliminated the Index Shifting Bug (`i` vs `i-1`)
The loop math has been entirely rewritten. The relationship between linear historical loop indexing and the MT5 `CopyBuffer` shift (where shift `0` is the current forming bar) is now perfectly aligned and mathematically correct.
2. Persistent State Buffers (Fixing the Live vs. History Repainting)
All vital states, including session rolling highs/lows (`dayHighBuf`/`dayLowBuf`) and triggers, have been moved into dedicated MT5 calculation buffers (`INDICATOR_CALCULATIONS`). Because these are stored per-bar, history and live charts are 100% consistent, and the indicator is fully backtest-safe.
3. Compile Fixes & Memory Initialization
Codes are strictly cleaned up. Persistent buffers are explicitly initialized on the first run (`prev_calculated == 0`) to prevent MT5 from reading dirty memory (garbage values).
4. Guarded External Indicator Calls (`CopyBuffer` Protection)
Implemented a bulletproof helper function (`GetIndiSafe`). If data copying fails or the indicator is warming up, it gracefully skips the bar and retains the previous valid mathematical state, preventing spikes or zero-value bands.
5. True Breakout Edge Arming
The trigger now arms strictly on the true breakout edge (the exact bar where the price first exits the channel). It won't continuously re-arm while the price simply drifts in a trend.
New Trading Features & EA Compatibility
1) Trigger Timeout (Bars): You can now define a timeout (e.g., 50 bars) after which an armed trigger will expire, preventing stale signals.
2) Anti-Whipsaw Filter: An optional toggle requiring the price to still reside outside the wide Keltner Channel (`KC1`) at the exact moment the fast EMA triggers the signal.
3) Mean-Reversion Target (TargetLine): Added a dashed line representing the Keltner basis (`kc1_ma`). This serves as the natural statistical target for the Mean Reversion setup.
4) EA-Ready Event Buffers: `activeDirBuf`: Tracks open virtual trades (1 for long, -1 for short, 0 for idle).
5)`targetHitBuf`: Fires a 1.0 event buffer signal when the price reaches the target.
6)`tradeOverriddenBuf`: Fires a 1.0 event if an active trade is forced closed/invalidated by a new opposite signal before hitting its target.
7) You can now easily read all these states in your automated EA using a simple `iCustom` / `CopyBuffer` setup!