#property copyright "Algobot"
#property link      "https://www.algobot.live"
#property version   "1.00"
#property strict

// RoofingFilterCycleReversion
// ---------------------------
// Native MQL5 port of the Algobot C# strategy of the same name.
// A cycle mean-reversion system built on John Ehlers' two-stage "Roofing
// Filter": a 2-pole HIGH-PASS (removes trend / DC drift) feeding a 2-pole
// SUPER-SMOOTHER (Butterworth low-pass; removes tick noise). The result is a
// clean, near-zero-mean cycle wave. That wave is z-scored over a rolling window
// and we fade the RE-ENTRY from an extreme (a confirmed turn, not a naked
// touch), with symmetric long/short rules and an ATR bracket for risk.
//
// The whole filter chain is computed recursively BY HAND, one value per closed
// bar, exactly as in the C# source. Only ATR uses a library indicator handle.

#include <Trade\Trade.mqh>
CTrade trade;

//--- inputs (1:1 with DescribeParameters) --------------------------------------
input int    HighPassPeriod  = 48;    // High-pass cutoff (bars): slower swings = trend, removed
input int    SmoothPeriod    = 10;    // Super-smoother period (bars): faster movement = noise, removed
input int    NormWindow      = 50;    // Rolling window used to z-score the roofing output
input double Threshold       = 1.0;   // Sigma band the cycle must exit for a signal
input int    AtrPeriod       = 14;    // ATR lookback
input double AtrStopMult     = 1.5;   // Stop distance (x ATR) beyond entry
input double RewardRisk      = 1.2;   // Take-profit as reward:risk multiple of the ATR stop
input int    MaxSpreadPoints = 60;    // Skip entries when spread (points) exceeds this
input double Lots            = 0.10;  // Trade volume
input long   Magic           = 5150;  // Magic number

//--- working (clamped) parameters ----------------------------------------------
int    g_hpPeriod, g_ssPeriod, g_normWindow, g_atrPeriod;

//--- pre-computed filter coefficients (set once in OnInit) ---------------------
double g_hpC, g_hpB, g_hpD;      // high-pass:  (1-a/2)^2, 2(1-a), (1-a)^2
double g_ssC1, g_ssC2, g_ssC3;   // super-smoother: c1, b1, -a1^2

//--- recursive filter state (newest-last, carried across bars) -----------------
long     g_count  = 0;           // number of closed bars processed
double   g_c0=0, g_c1=0, g_c2=0; // last three closes  (g_c0 = newest)
double   g_hp0=0, g_hp1=0;       // last two high-pass  (g_hp0 = newest)
double   g_filt0=0, g_filt1=0;   // last two roofing    (g_filt0 = newest)
double   g_fh[];                 // rolling roofing history (last <=NormWindow), newest at end

//--- misc ----------------------------------------------------------------------
datetime g_lastBarTime = 0;
int      g_atrHandle   = INVALID_HANDLE;

//+------------------------------------------------------------------+
int OnInit()
{
   g_hpPeriod   = HighPassPeriod;  if(g_hpPeriod   < 8) g_hpPeriod   = 8;
   g_ssPeriod   = SmoothPeriod;    if(g_ssPeriod   < 3) g_ssPeriod   = 3;
   g_normWindow = NormWindow;      if(g_normWindow < 5) g_normWindow = 5;
   g_atrPeriod  = AtrPeriod;       if(g_atrPeriod  < 1) g_atrPeriod  = 1;

   // ---- High-pass coefficients (2-pole) ----
   double w = 0.707 * 2.0 * M_PI / g_hpPeriod;
   double a = (MathCos(w) + MathSin(w) - 1.0) / MathCos(w);
   g_hpC = (1.0 - a / 2.0) * (1.0 - a / 2.0);
   g_hpB = 2.0 * (1.0 - a);
   g_hpD = (1.0 - a) * (1.0 - a);

   // ---- Super-smoother coefficients (2-pole Butterworth) ----
   double a1 = MathExp(-1.414 * M_PI / g_ssPeriod);
   double b1 = 2.0 * a1 * MathCos(1.414 * M_PI / g_ssPeriod);
   g_ssC3 = -a1 * a1;
   g_ssC2 = b1;
   g_ssC1 = 1.0 - g_ssC2 - g_ssC3;

   trade.SetExpertMagicNumber(Magic);

   g_atrHandle = iATR(_Symbol, _Period, g_atrPeriod);
   if(g_atrHandle == INVALID_HANDLE)
   {
      Print("RFCR: failed to create ATR handle");
      return INIT_FAILED;
   }

   // Reset filter state; build history incrementally as bars close (as in C#).
   ArrayResize(g_fh, 0);
   g_count = 0;
   g_c0 = g_c1 = g_c2 = 0.0;
   g_hp0 = g_hp1 = 0.0;
   g_filt0 = g_filt1 = 0.0;
   g_lastBarTime = iTime(_Symbol, _Period, 0);   // current (forming) bar's time

   return INIT_SUCCEEDED;
}

//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   if(g_atrHandle != INVALID_HANDLE) IndicatorRelease(g_atrHandle);
}

//+------------------------------------------------------------------+
void OnTick()
{
   // Act once per newly-closed primary bar.
   if(!IsNewBar()) return;
   if(Bars(_Symbol, _Period) < 2) return;

   // The bar that was forming has just closed -> it is now shift 1. Record it.
   double closeC = iClose(_Symbol, _Period, 1);
   double openC  = iOpen(_Symbol,  _Period, 1);

   // ---- Advance the recursive roofing filter by one bar ----
   g_c2 = g_c1; g_c1 = g_c0; g_c0 = closeC;   // shift closes (newest-last)
   g_count++;

   double hpNew;
   if(g_count < 3)                            // warm up: closes<3 || hp<2
      hpNew = 0.0;
   else
      hpNew = g_hpC * (g_c0 - 2.0 * g_c1 + g_c2)
            + g_hpB * g_hp0 - g_hpD * g_hp1;
   g_hp1 = g_hp0; g_hp0 = hpNew;              // shift high-pass

   double filtNew;
   if(g_count < 3)                            // let the filter warm up (filt<2)
      filtNew = hpNew;
   else
      filtNew = g_ssC1 * (g_hp0 + g_hp1) / 2.0
              + g_ssC2 * g_filt0 + g_ssC3 * g_filt1;
   g_filt1 = g_filt0; g_filt0 = filtNew;      // shift roofing
   PushFilt(filtNew);                         // keep rolling z-score window in lock-step

   // Warm-up: need a settled filter, a full norm window and ATR history.
   int need = MathMax(g_normWindow + 2, MathMax(g_hpPeriod, g_atrPeriod + 1)) + 5;
   if(g_count < need) return;

   // One position per magic; the ATR bracket manages exits.
   if(HasPosition(Magic)) return;
   if((int)SymbolInfoInteger(_Symbol, SYMBOL_SPREAD) > MaxSpreadPoints) return;

   // ---- Z-score the roofing wave over the rolling window ----
   int wsz = ArraySize(g_fh);                 // == min(NormWindow, count)
   if(wsz < 2) return;
   double sum = 0.0;
   for(int i = 0; i < wsz; i++) sum += g_fh[i];
   double mean = sum / wsz;
   double varSum = 0.0;
   for(int i = 0; i < wsz; i++){ double d = g_fh[i] - mean; varSum += d * d; }
   double std = MathSqrt(varSum / wsz);
   if(std <= 0.0) return;

   double cycNow  = (g_filt0 - mean) / std;   // just-closed bar
   double cycPrev = (g_filt1 - mean) / std;   // bar before it

   // ---- ATR stop distance (library ATR at the just-closed bar, shift 1) ----
   double atrBuf[];
   ArraySetAsSeries(atrBuf, true);
   if(CopyBuffer(g_atrHandle, 0, 0, 3, atrBuf) < 3) return;
   double atr = atrBuf[1];
   if(atr <= 0.0) return;
   double stopDist = AtrStopMult * atr;
   double reward   = RewardRisk * stopDist;

   bool bullish = closeC > openC;             // the signal bar
   bool bearish = closeC < openC;

   // ---- LONG: cycle leaves the oversold band turning up, bar confirms ----
   bool crossUp = (cycPrev < -Threshold) && (cycNow >= -Threshold);
   if(crossUp && bullish)
   {
      double entry = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
      double sl    = NormalizeDouble(entry - stopDist, _Digits);
      double tp    = NormalizeDouble(entry + reward,  _Digits);
      bool ok = trade.Buy(Lots, _Symbol, 0.0, sl, tp, "RFCR long");
      PrintFormat("RFCR LONG cyc %.2f->%.2f filt=%.6f entry=%.5f sl=%.5f tp=%.5f -> %s",
                  cycPrev, cycNow, g_filt0, entry, sl, tp, (ok ? "ok" : "fail"));
      return;
   }

   // ---- SHORT: cycle leaves the overbought band turning down, bar confirms ----
   bool crossDown = (cycPrev > Threshold) && (cycNow <= Threshold);
   if(crossDown && bearish)
   {
      double entry = SymbolInfoDouble(_Symbol, SYMBOL_BID);
      double sl    = NormalizeDouble(entry + stopDist, _Digits);
      double tp    = NormalizeDouble(entry - reward,  _Digits);
      bool ok = trade.Sell(Lots, _Symbol, 0.0, sl, tp, "RFCR short");
      PrintFormat("RFCR SHORT cyc %.2f->%.2f filt=%.6f entry=%.5f sl=%.5f tp=%.5f -> %s",
                  cycPrev, cycNow, g_filt0, entry, sl, tp, (ok ? "ok" : "fail"));
      return;
   }
}

//+------------------------------------------------------------------+
//| Push a roofing value into the rolling z-score window             |
//| (keeps the last <=NormWindow values, newest at the end).         |
//+------------------------------------------------------------------+
void PushFilt(double v)
{
   int n = ArraySize(g_fh);
   if(n < g_normWindow)
   {
      ArrayResize(g_fh, n + 1);
      g_fh[n] = v;
   }
   else
   {
      for(int i = 0; i < g_normWindow - 1; i++) g_fh[i] = g_fh[i + 1];
      g_fh[g_normWindow - 1] = v;
   }
}

//+------------------------------------------------------------------+
bool IsNewBar()
{
   datetime cur = iTime(_Symbol, _Period, 0);
   if(cur != g_lastBarTime){ g_lastBarTime = cur; return true; }
   return false;
}

//+------------------------------------------------------------------+
bool HasPosition(long magic)
{
   for(int i = PositionsTotal() - 1; i >= 0; i--)
   {
      ulong t = PositionGetTicket(i);
      if(PositionSelectByTicket(t) &&
         PositionGetString(POSITION_SYMBOL) == _Symbol &&
         PositionGetInteger(POSITION_MAGIC) == magic) return true;
   }
   return false;
}
//+------------------------------------------------------------------+
