//+------------------------------------------------------------------+
//|                                  TrendStateForecastPullback.mq5   |
//|                                                          Algobot   |
//|                                    https://www.algobot.live        |
//+------------------------------------------------------------------+
#property copyright "Algobot"
#property link      "https://www.algobot.live"
#property version   "1.00"
#property strict

// ============================================================================
//  TrendStateForecastPullback  (native MQL5 port of the C# Algobot strategy)
//  ---------------------------------------------------------------------------
//  Trend-following pullback system built on HOLT'S LINEAR TREND forecast
//  (double exponential smoothing). Two state variables are advanced every bar:
//
//        Level_t = a * Close_t + (1 - a) * (Level_{t-1} + Trend_{t-1})
//        Trend_t = b * (Level_t - Level_{t-1}) + (1 - b) * Trend_{t-1}
//
//  Forecast = Level_t + h * Trend_t.  Three filters gate entries:
//    1. REGIME  : s = Trend / ATR must clear +/- SlopeGate.
//    2. RECLAIM : prior bar closed on the counter-trend side of Level, the
//                 just-closed bar closes back through it, with a with-trend body.
//    3. NO-CHASE: price must not have overshot the Holt h-step forecast.
//  Structural stop just past the pullback extreme (rejected if > MaxStopAtr*ATR),
//  R-multiple TP, break-even lock at BreakevenR then ATR trailing stop.
// ============================================================================

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

//--- inputs (mirror DescribeParameters) -------------------------------------
input double LevelAlpha      = 0.25;   // Level smoothing constant (a)
input double TrendBeta       = 0.10;   // Trend (slope) smoothing constant (b)
input double SlopeGate       = 0.08;   // Min |Trend/ATR| for a valid regime
input int    AtrPeriod       = 14;     // ATR period (vol unit for gate/stops/trail)
input int    PullbackBars    = 3;      // Lookback bars for pullback extreme / stop
input int    ForecastHorizon = 3;      // Horizon h in the no-chase filter
input double MaxStopAtr       = 2.5;    // Reject setups wider than this many ATR
input double StopBufferAtr    = 0.15;   // Extra stop buffer beyond extreme, in ATR
input double RewardRatio      = 2.0;    // Take-profit reward:risk multiple
input double BreakevenR       = 1.0;    // Move stop to BE after this multiple of risk
input double TrailAtrMult     = 2.0;    // ATR multiple for the trailing stop
input double Lots             = 0.10;   // Order volume
input long   Magic            = 8813;   // Magic number

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

//--- Holt state (persisted across bars) -------------------------------------
bool   g_hasLevel     = false;
double g_level        = 0.0;
double g_trend        = 0.0;
bool   g_hasPrevClose = false;
double g_prevClose    = 0.0;
bool   g_hasPrevLevel = false;
double g_prevLevel    = 0.0;
int    g_updates      = 0;

double g_atr          = 0.0;   // ATR from the latest completed bar
double g_entryRisk    = 0.0;   // risk of the live position (for BE/trail)

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

    g_atrHandle = iATR(_Symbol, _Period, AtrPeriod);
    if(g_atrHandle == INVALID_HANDLE)
    {
        Print("Failed to create iATR handle");
        return INIT_FAILED;
    }

    // reset state
    g_hasLevel = false; g_level = 0.0; g_trend = 0.0;
    g_hasPrevClose = false; g_prevClose = 0.0;
    g_hasPrevLevel = false; g_prevLevel = 0.0;
    g_updates = 0;
    g_atr = 0.0;
    g_entryRisk = 0.0;

    return INIT_SUCCEEDED;
}

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

//+------------------------------------------------------------------+
void OnTick()
{
    // Manage any live position every tick (break-even + ATR trail).
    ManagePositions();

    if(Bars(_Symbol, _Period) < 2) return;

    // Act once per newly-formed bar; trade off the bar that just closed.
    if(!IsNewBar()) return;

    // The bar that just closed is shift 1.
    double cbClose = iClose(_Symbol, _Period, 1);
    double cbOpen  = iOpen(_Symbol,  _Period, 1);

    //---- advance the Holt level+trend state with the new completed bar ------
    if(!g_hasLevel)
    {
        g_level = cbClose;      // seed on the first bar
        g_trend = 0.0;
        g_hasLevel = true;
    }
    else
    {
        if(g_trend == 0.0 && g_hasPrevClose)
            g_trend = cbClose - g_prevClose;    // seed the slope once
        double newLevel = LevelAlpha * cbClose + (1.0 - LevelAlpha) * (g_level + g_trend);
        g_trend = TrendBeta * (newLevel - g_level) + (1.0 - TrendBeta) * g_trend;
        g_level = newLevel;
    }
    g_updates++;

    g_atr = ComputeAtr();

    // The cross state uses the PREVIOUS bar (close vs its own level) versus the
    // CURRENT bar (close vs the freshly-updated level). Capture old markers.
    double prevClose   = g_prevClose;
    double prevLevel   = g_prevLevel;
    bool   hadPrevClose = g_hasPrevClose;
    bool   hadPrevLevel = g_hasPrevLevel;

    // Roll the "previous" markers forward BEFORE any early return.
    g_prevClose = cbClose; g_hasPrevClose = true;
    g_prevLevel = g_level; g_hasPrevLevel = true;

    //---- warmup / preconditions --------------------------------------------
    if(g_updates <= AtrPeriod + 5) return;
    if(g_atr <= 0.0) return;
    if(!hadPrevClose || !hadPrevLevel) return;     // (NaN check equivalent)
    if(g_updates < PullbackBars + 2) return;

    // One position per magic at a time.
    if(HasPosition(Magic)) return;

    //---- regime from the modelled slope state ------------------------------
    double slope      = g_trend / g_atr;           // dimensionless per-bar drift
    bool   upRegime   = slope >=  SlopeGate;
    bool   downRegime = slope <= -SlopeGate;
    if(!upRegime && !downRegime) return;

    double forecast = g_level + ForecastHorizon * g_trend;   // Holt h-step forecast

    //---- LONG: fresh reclaim of the Level in an up-regime -------------------
    if(upRegime)
    {
        bool wasBelow  = prevClose < prevLevel;    // genuine pullback last bar
        bool reclaimed = cbClose  > g_level;       // closed back above baseline
        bool body      = cbClose  > cbOpen;        // with-trend resumption candle
        bool noChase   = cbClose <= forecast;      // not already past the forecast

        if(wasBelow && reclaimed && body && noChase)
            TryEnter(true);
    }
    //---- SHORT: mirror image in a down-regime ------------------------------
    else // downRegime
    {
        bool wasAbove  = prevClose > prevLevel;
        bool reclaimed = cbClose  < g_level;
        bool body      = cbClose  < cbOpen;
        bool noChase   = cbClose >= forecast;

        if(wasAbove && reclaimed && body && noChase)
            TryEnter(false);
    }
}

//+------------------------------------------------------------------+
//| Enter a structural pullback trade                                |
//+------------------------------------------------------------------+
void TryEnter(bool isLong)
{
    double buffer   = StopBufferAtr * g_atr;
    int    lookback = PullbackBars + 1;            // include the reclaim bar

    double price, sl;
    if(isLong)
    {
        price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
        sl    = LowestLow(lookback) - buffer;      // just past the pullback low
    }
    else
    {
        price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
        sl    = HighestHigh(lookback) + buffer;
    }

    double risk = isLong ? price - sl : sl - price;
    if(risk <= 0.0) return;                         // structure already broken
    if(risk > MaxStopAtr * g_atr) return;           // too wide - skip for low DD

    double tp = isLong ? price + RewardRatio * risk : price - RewardRatio * risk;

    sl = NormalizeDouble(sl, _Digits);
    tp = NormalizeDouble(tp, _Digits);

    bool ok;
    if(isLong) ok = trade.Buy (Lots, _Symbol, 0.0, sl, tp, "TSFP-long");
    else       ok = trade.Sell(Lots, _Symbol, 0.0, sl, tp, "TSFP-short");

    if(ok) g_entryRisk = risk;

    PrintFormat("TrendStateForecastPullback %s @ %.5f SL %.5f TP %.5f slope %.3f -> %s",
                (isLong ? "LONG" : "SHORT"), price, sl, tp, (g_trend / g_atr),
                (ok ? "OK" : "FAIL"));
}

//+------------------------------------------------------------------+
//| Break-even lock then ATR trailing stop                           |
//+------------------------------------------------------------------+
void ManagePositions()
{
    if(g_atr <= 0.0) return;

    bool any = 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;
        any = true;

        double open  = PositionGetDouble(POSITION_PRICE_OPEN);
        double curSl = PositionGetDouble(POSITION_SL);
        double curTp = PositionGetDouble(POSITION_TP);
        long   ptype = PositionGetInteger(POSITION_TYPE);

        double risk = g_entryRisk;
        if(risk <= 0.0) risk = MathAbs(open - curSl);
        if(risk <= 0.0) risk = g_atr;

        if(ptype == POSITION_TYPE_BUY)
        {
            double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
            if(price - open < BreakevenR * risk) continue;

            double be    = open;
            double trail = price - TrailAtrMult * g_atr;
            double newSl = MathMax(be, trail);
            newSl = NormalizeDouble(newSl, _Digits);
            if(newSl > curSl && newSl < price)
                trade.PositionModify(t, newSl, curTp);
        }
        else // POSITION_TYPE_SELL
        {
            double price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
            if(open - price < BreakevenR * risk) continue;

            double be    = open;
            double trail = price + TrailAtrMult * g_atr;
            double newSl = MathMin(be, trail);
            newSl = NormalizeDouble(newSl, _Digits);
            if((curSl <= 0.0 || newSl < curSl) && newSl > price)
                trade.PositionModify(t, newSl, curTp);
        }
    }

    if(!any) g_entryRisk = 0.0;
}

//+------------------------------------------------------------------+
//| ATR of the just-closed bar (shift 1)                             |
//+------------------------------------------------------------------+
double ComputeAtr()
{
    double buf[];
    ArraySetAsSeries(buf, true);
    if(CopyBuffer(g_atrHandle, 0, 0, 3, buf) < 3) return 0.0;
    double v = buf[1];               // completed bar
    if(v <= 0.0 || !MathIsValidNumber(v)) return 0.0;
    return v;
}

//+------------------------------------------------------------------+
//| Lowest low over the last `count` completed bars (shifts 1..count)|
//+------------------------------------------------------------------+
double LowestLow(int count)
{
    double lo = DBL_MAX;
    for(int s = 1; s <= count; s++)
    {
        double v = iLow(_Symbol, _Period, s);
        if(v < lo) lo = v;
    }
    return lo;
}

//+------------------------------------------------------------------+
//| Highest high over the last `count` completed bars                |
//+------------------------------------------------------------------+
double HighestHigh(int count)
{
    double hi = -DBL_MAX;
    for(int s = 1; s <= count; s++)
    {
        double v = iHigh(_Symbol, _Period, s);
        if(v > hi) hi = v;
    }
    return hi;
}

//+------------------------------------------------------------------+
bool IsNewBar()
{
    static datetime last = 0;
    datetime cur = iTime(_Symbol, _Period, 0);
    if(cur != last){ last = 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;
}
//+------------------------------------------------------------------+
