//+------------------------------------------------------------------+
//|                                     MesaAdaptiveTrendShift.mq5    |
//|  Trend-following EA built on John Ehlers' MESA Adaptive Moving    |
//|  Average (MAMA) and its follower (FAMA).                          |
//|                                                                   |
//|  Ordinary adaptive averages (KAMA, VIDYA, FRAMA...) adapt from    |
//|  amplitude cues. MAMA instead measures the market's dominant      |
//|  cycle with a Hilbert-transform quadrature pair and a homodyne    |
//|  discriminator, then adapts its smoothing factor to the RATE OF   |
//|  CHANGE OF PHASE. FAMA uses half that alpha, lagging MAMA like a   |
//|  slower shadow.                                                    |
//|                                                                   |
//|  SIGNAL: MAMA/FAMA behave as a self-tuning fast/slow pair.        |
//|    * MAMA above FAMA by more than a volatility band -> uptrend.   |
//|    * MAMA below FAMA by more than a volatility band -> downtrend. |
//|  The ATR-scaled separation band adds hysteresis so we act only on |
//|  a genuine regime FLIP. Each flip closes the opposite position    |
//|  and opens a new one; an ATR stop / target frames the risk.       |
//+------------------------------------------------------------------+
#property copyright "Algobot"
#property link      "https://www.algobot.live"
#property version   "1.00"
#property strict

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

//--- inputs (mirror DescribeParameters / OnInit GetInput calls) ----
input double FastLimit  = 0.50;   // fast alpha limit
input double SlowLimit  = 0.05;   // slow alpha limit (floor)
input double SepAtrMult = 0.15;   // ATR-scaled MAMA/FAMA hysteresis band
input int    AtrPeriod  = 14;     // ATR period
input double SlMult     = 2.0;    // stop-loss ATR multiple
input double TpMult     = 3.0;    // take-profit ATR multiple
input double Lots       = 0.10;   // fixed lot size
input long   Magic      = 8841;   // magic number

//--- indicator handles ---------------------------------------------
int g_atrHandle = INVALID_HANDLE;

//--- MESA / Hilbert-transform state series (newest-last arrays) ----
double g_price[], g_smooth[], g_detrender[];
double g_i1[], g_q1[], g_i2[], g_q2[], g_re[], g_im[];

//--- recursive scalars carried bar-to-bar --------------------------
double g_period, g_smoothPeriod, g_mama, g_fama, g_phasePrev;
bool   g_seeded;
int    g_signalState;    // 0 = neutral band, +1 = long regime, -1 = short regime
int    g_barsProcessed;  // count of closed bars fed into the MESA engine

//+------------------------------------------------------------------+
//| Value at `shift` bars back from newest; 0.0 if history too short  |
//+------------------------------------------------------------------+
double AtS(const double &s[], const int shift)
{
    int i = ArraySize(s) - 1 - shift;
    return (i >= 0) ? s[i] : 0.0;
}

//+------------------------------------------------------------------+
//| Append a value to a newest-last series                            |
//+------------------------------------------------------------------+
void PushS(double &s[], const double v)
{
    int n = ArraySize(s);
    ArrayResize(s, n + 1);
    s[n] = v;
}

//+------------------------------------------------------------------+
//| Keep a series bounded without disturbing end-relative shifts      |
//+------------------------------------------------------------------+
void TrimS(double &s[], const int cap)
{
    int n = ArraySize(s);
    if(n > cap)
    {
        int rem = n - cap;
        for(int i = 0; i < cap; i++) s[i] = s[i + rem];
        ArrayResize(s, cap);
    }
}

//+------------------------------------------------------------------+
//| Ehlers Hilbert-transform quadrature FIR over a newest-last series |
//+------------------------------------------------------------------+
double Hilbert(const double &s[])
{
    return 0.0962 * AtS(s, 0) + 0.5769 * AtS(s, 2)
         - 0.5769 * AtS(s, 4) - 0.0962 * AtS(s, 6);
}

//+------------------------------------------------------------------+
//| Trim every aligned MESA state buffer                              |
//+------------------------------------------------------------------+
void TrimState()
{
    const int cap = 64;
    TrimS(g_price, cap);   TrimS(g_smooth, cap); TrimS(g_detrender, cap);
    TrimS(g_i1, cap);      TrimS(g_q1, cap);     TrimS(g_i2, cap);
    TrimS(g_q2, cap);      TrimS(g_re, cap);     TrimS(g_im, cap);
}

//+------------------------------------------------------------------+
//| Ehlers MESA Adaptive Moving Average (MAMA / FAMA) one-bar update  |
//+------------------------------------------------------------------+
void UpdateMesa(const double high, const double low)
{
    double price = (high + low) / 2.0;
    PushS(g_price, price);

    if(!g_seeded)
    {
        g_mama = price;   // seed the recursions on the very first bar
        g_fama = price;
        g_seeded = true;
    }

    double prevPeriod = g_period;
    double perAdj = 0.075 * prevPeriod + 0.54;

    // Smoother (weighted 4-bar FIR).
    double smooth = (4.0 * AtS(g_price, 0) + 3.0 * AtS(g_price, 1)
                   + 2.0 * AtS(g_price, 2) + 1.0 * AtS(g_price, 3)) / 10.0;
    PushS(g_smooth, smooth);

    // Detrender (Hilbert quadrature FIR), scaled by the running cycle estimate.
    double detrender = Hilbert(g_smooth) * perAdj;
    PushS(g_detrender, detrender);

    // In-phase and quadrature components.
    double q1 = Hilbert(g_detrender) * perAdj;
    double i1 = AtS(g_detrender, 3);
    PushS(g_q1, q1);
    PushS(g_i1, i1);

    // Advance the phase of I1 and Q1 by 90 degrees.
    double jI = Hilbert(g_i1) * perAdj;
    double jQ = Hilbert(g_q1) * perAdj;

    // Phasor addition for 3-bar averaging, then a light smoothing.
    double i2 = i1 - jQ;
    double q2 = q1 + jI;
    i2 = 0.2 * i2 + 0.8 * AtS(g_i2, 0);
    q2 = 0.2 * q2 + 0.8 * AtS(g_q2, 0);
    PushS(g_i2, i2);
    PushS(g_q2, q2);

    // Homodyne discriminator -> dominant cycle period.
    double re = i2 * AtS(g_i2, 1) + q2 * AtS(g_q2, 1);
    double im = i2 * AtS(g_q2, 1) - q2 * AtS(g_i2, 1);
    re = 0.2 * re + 0.8 * AtS(g_re, 0);
    im = 0.2 * im + 0.8 * AtS(g_im, 0);
    PushS(g_re, re);
    PushS(g_im, im);

    double period = prevPeriod;
    if(im != 0.0 && re != 0.0)
        period = 2.0 * M_PI / MathArctan(im / re);   // 360/atan(deg) reduces to 2*pi/atan(rad)

    if(period > 1.5 * prevPeriod)  period = 1.5 * prevPeriod;
    if(period < 0.67 * prevPeriod) period = 0.67 * prevPeriod;
    if(period < 6.0)  period = 6.0;
    if(period > 50.0) period = 50.0;
    period = 0.2 * period + 0.8 * prevPeriod;
    g_period = period;
    g_smoothPeriod = 0.33 * period + 0.67 * g_smoothPeriod;

    // Phase and its rate of change drive the adaptive alpha.
    double phase = g_phasePrev;
    if(i1 != 0.0) phase = MathArctan(q1 / i1) * 180.0 / M_PI;   // degrees
    double deltaPhase = g_phasePrev - phase;
    g_phasePrev = phase;
    if(deltaPhase < 1.0) deltaPhase = 1.0;

    double alpha = FastLimit / deltaPhase;
    if(alpha < SlowLimit) alpha = SlowLimit;

    g_mama = alpha * price + (1.0 - alpha) * g_mama;
    g_fama = 0.5 * alpha * g_mama + (1.0 - 0.5 * alpha) * g_fama;

    TrimState();
}

//+------------------------------------------------------------------+
//| ATR of the just-closed bar (shift 1)                              |
//+------------------------------------------------------------------+
double GetAtr()
{
    double buf[];
    ArraySetAsSeries(buf, true);
    if(CopyBuffer(g_atrHandle, 0, 1, 1, buf) < 1) return 0.0;
    return buf[0];
}

//+------------------------------------------------------------------+
//| New-bar detector                                                  |
//+------------------------------------------------------------------+
bool IsNewBar()
{
    static datetime last = 0;
    datetime cur = iTime(_Symbol, _Period, 0);
    if(cur != last){ last = cur; return true; }
    return false;
}

//+------------------------------------------------------------------+
//| Init                                                              |
//+------------------------------------------------------------------+
int OnInit()
{
    trade.SetExpertMagicNumber(Magic);

    g_atrHandle = iATR(_Symbol, _Period, AtrPeriod);
    if(g_atrHandle == INVALID_HANDLE) return INIT_FAILED;

    // Clear all MESA state buffers.
    ArrayFree(g_price);   ArrayFree(g_smooth); ArrayFree(g_detrender);
    ArrayFree(g_i1);      ArrayFree(g_q1);     ArrayFree(g_i2);
    ArrayFree(g_q2);      ArrayFree(g_re);     ArrayFree(g_im);

    g_period       = 20.0;   // sensible cycle seed; clamps drive it to the real value fast
    g_smoothPeriod = 20.0;
    g_mama         = 0.0;
    g_fama         = 0.0;
    g_phasePrev    = 0.0;
    g_seeded       = false;
    g_signalState  = 0;
    g_barsProcessed = 0;

    return INIT_SUCCEEDED;
}

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

//+------------------------------------------------------------------+
//| Tick                                                              |
//+------------------------------------------------------------------+
void OnTick()
{
    // Act once per CLOSED bar: when bar 0's time advances, shift 1 has closed.
    if(!IsNewBar()) return;
    if(Bars(_Symbol, _Period) < 2) return;

    // Advance the MESA engine one bar with the just-closed candle.
    double h = iHigh(_Symbol, _Period, 1);
    double l = iLow(_Symbol, _Period, 1);
    UpdateMesa(h, l);
    g_barsProcessed++;

    // Warm up until MAMA/FAMA have stabilised and ATR is available.
    int need = (AtrPeriod + 2 > 60) ? AtrPeriod + 2 : 60;
    if(g_barsProcessed < need || !g_seeded) return;

    double atr = GetAtr();
    if(atr <= 0.0) return;

    // Regime decision with an ATR-scaled hysteresis band around the MAMA/FAMA gap.
    double gap = g_mama - g_fama;
    double sep = SepAtrMult * atr;

    int newState = g_signalState;
    if(gap > sep)       newState = 1;
    else if(gap < -sep) newState = -1;
    // Inside the neutral band we hold the previous regime (hysteresis).

    bool flipLong  = (newState == 1  && g_signalState != 1);
    bool flipShort = (newState == -1 && g_signalState != -1);
    g_signalState = newState;

    if(!flipLong && !flipShort) return;

    if(flipLong)
    {
        // Close any shorts, then open long if not already long.
        bool haveLong = false;
        for(int i = PositionsTotal() - 1; i >= 0; i--)
        {
            ulong t = PositionGetTicket(i);
            if(!PositionSelectByTicket(t)) continue;
            if(PositionGetString(POSITION_SYMBOL) != _Symbol) continue;
            if(PositionGetInteger(POSITION_MAGIC) != Magic) continue;
            long type = PositionGetInteger(POSITION_TYPE);
            if(type == POSITION_TYPE_SELL)      trade.PositionClose(t);
            else if(type == POSITION_TYPE_BUY)  haveLong = true;
        }
        if(!haveLong)
        {
            double entry = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
            double sl = NormalizeDouble(entry - SlMult * atr, _Digits);
            double tp = NormalizeDouble(entry + TpMult * atr, _Digits);
            trade.Buy(Lots, _Symbol, 0.0, sl, tp, "MATS long flip");
            PrintFormat("MATS LONG gap=%.5f sep=%.5f cyc=%.1f mama=%.5f fama=%.5f",
                        gap, sep, g_smoothPeriod, g_mama, g_fama);
        }
    }
    else // flipShort
    {
        bool haveShort = false;
        for(int i = PositionsTotal() - 1; i >= 0; i--)
        {
            ulong t = PositionGetTicket(i);
            if(!PositionSelectByTicket(t)) continue;
            if(PositionGetString(POSITION_SYMBOL) != _Symbol) continue;
            if(PositionGetInteger(POSITION_MAGIC) != Magic) continue;
            long type = PositionGetInteger(POSITION_TYPE);
            if(type == POSITION_TYPE_BUY)       trade.PositionClose(t);
            else if(type == POSITION_TYPE_SELL) haveShort = true;
        }
        if(!haveShort)
        {
            double entry = SymbolInfoDouble(_Symbol, SYMBOL_BID);
            double sl = NormalizeDouble(entry + SlMult * atr, _Digits);
            double tp = NormalizeDouble(entry - TpMult * atr, _Digits);
            trade.Sell(Lots, _Symbol, 0.0, sl, tp, "MATS short flip");
            PrintFormat("MATS SHORT gap=%.5f sep=%.5f cyc=%.1f mama=%.5f fama=%.5f",
                        gap, sep, g_smoothPeriod, g_mama, g_fama);
        }
    }
}
//+------------------------------------------------------------------+
