//+------------------------------------------------------------------+
//|                              InternalStrengthDivergenceFade.mq5   |
//|                                                          Algobot  |
//|                                    https://www.algobot.live       |
//+------------------------------------------------------------------+
//  InternalStrengthDivergenceFade
//  ---------------------------------------------------------------------------
//  Concept:  Counter-trend reversal built on the divergence between where PRICE
//            is going and where each candle CLOSES INSIDE ITS OWN RANGE.
//
//            For every closed bar we measure "internal strength" = the close
//            location value  clv = (Close - Low) / (High - Low), in [0,1].
//            clv~1 => closed on the high (buyers own the close); clv~0 => closed
//            on the low (sellers own it). We smooth clv into a strength line S.
//
//            Healthy up-move => price rises AND S rises with it. Exhaustion tell
//            => price grinds to higher closes but S is FALLING (highs being sold
//            into): bearish divergence at a top -> FADE short. Mirror (price to
//            lower closes while S lifts) => bullish divergence -> FADE long.
//
//            Divergence measured non-repainting via least-squares SLOPES over a
//            lookback: price slope (normalized into ATR-per-bar units) runs one
//            way while the strength-line slope runs the other. Armed only at a
//            genuine extreme (close near top/bottom of the window) and confirmed
//            by the latest bar closing on the weak side of its own range.
//
//  Style :   Mean-reversion / exhaustion reversal, distinct long AND short rules.
//  Risk  :   Structural ATR-buffered stop just past the faded extreme, TP at a
//            reward:risk multiple, optional ATR trailing lock, one position at a
//            time, cooldown between entries.
//
//  Non-repainting: all logic uses CLOSED bars (shift >= 1); the forming bar
//  (shift 0) is used only to detect that a fresh bar has opened.
//+------------------------------------------------------------------+
#property copyright "Algobot"
#property link      "https://www.algobot.live"
#property version   "1.00"
#property strict

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

//--- inputs (mirror DescribeParameters) ---
input int    Lookback         = 20;        // least-squares slope / extreme window
input int    StrengthSmooth   = 5;         // EMA period for the close-location strength line
input int    AtrPeriod        = 14;        // ATR period
input double MinPriceSlope    = 0.05;      // min |price slope| (ATR units per bar)
input double MinStrengthSlope = 0.010;     // min |strength slope| (clv units per bar)
input double ExtremeFrac      = 0.70;      // how close to the window extreme to arm (0..1)
input double SlBufferAtr      = 0.5;       // ATR buffer past the faded extreme for the SL
input double RewardRisk       = 1.8;       // take-profit as a multiple of stop distance
input double TrailAtrMult     = 0.0;       // optional ATR trailing lock (0 = off)
input int    CooldownBars     = 3;         // min closed bars between entries
input double Lots             = 0.10;      // fixed volume
input long   Magic            = 20260725;  // magic number

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

//--- state ---
datetime g_lastBarTime  = 0;
double   g_lastAtr      = 0.0;
long     g_barCount     = 0;
long     g_lastEntryBar = -1000000;   // sentinel: "never entered" (avoids overflow)
int      g_maxHistory   = 0;

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

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

    g_lastBarTime  = 0;
    g_lastAtr      = 0.0;
    g_barCount     = 0;
    g_lastEntryBar = -1000000;
    g_maxHistory   = MathMax(Lookback, AtrPeriod) + 60;

    return INIT_SUCCEEDED;
}

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

//+------------------------------------------------------------------+
void OnTick()
{
    // 1) Manage any open position every tick (responsive trailing lock).
    ManageOpenPosition();

    // 2) Detect a newly-closed bar (forming-bar open time changes).
    if(!IsNewBar()) return;

    g_barCount++;

    // 3) Enough history for every lookback?
    int need = MathMax(Lookback, AtrPeriod) + 1;
    int avail = Bars(_Symbol, _Period);
    if(avail < need + 2) return;

    // Warm-up / working window (newest-last), mirroring the C# rolling lists.
    int W = MathMin(g_maxHistory, avail - 1);   // need bar at shift W to exist
    if(W < need) return;

    double closes[], highs[], lows[], strength[];
    ArrayResize(closes,   W);
    ArrayResize(highs,    W);
    ArrayResize(lows,     W);
    ArrayResize(strength, W);

    // Build closed-bar series newest-last: j=0 -> oldest (shift W), j=W-1 -> newest (shift 1).
    // Smoothed internal-strength line = EMA of the close-location value clv.
    double alpha = 2.0 / (StrengthSmooth + 1.0);
    double ema   = 0.0;
    bool   has   = false;
    for(int j = 0; j < W; j++)
    {
        int    shift = W - j;
        double h = iHigh(_Symbol,  _Period, shift);
        double l = iLow(_Symbol,   _Period, shift);
        double c = iClose(_Symbol, _Period, shift);
        closes[j] = c;
        highs[j]  = h;
        lows[j]   = l;

        double rng = h - l;
        double clv = rng > 0.0 ? (c - l) / rng : 0.5;   // [0,1], 0.5 if flat
        ema = has ? alpha * clv + (1.0 - alpha) * ema : clv;
        has = true;
        strength[j] = ema;
    }

    // ATR at the last closed bar (index 1 with series ordering).
    double atrBuf[];
    ArraySetAsSeries(atrBuf, true);
    if(CopyBuffer(g_atrHandle, 0, 0, 3, atrBuf) < 3) return;
    double atr = atrBuf[1];
    g_lastAtr = atr;
    if(atr <= 0.0) return;

    // 4) Divergence via least-squares slopes over the lookback window.
    double priceSlope    = Slope(closes,   W, Lookback) / atr;   // ATR units per bar
    double strengthSlope = Slope(strength, W, Lookback);         // clv units per bar

    // 5) Where does price sit within the lookback range (at an extreme)?
    double hi = -DBL_MAX, lo = DBL_MAX;
    int startW = W - Lookback;
    for(int k = startW; k < W; k++)
    {
        if(highs[k] > hi) hi = highs[k];
        if(lows[k]  < lo) lo = lows[k];
    }
    double band = hi - lo;
    if(band <= 0.0) return;
    double lastClose = closes[W - 1];
    double rangePos  = (lastClose - lo) / band;   // 0 at window low, 1 at window high
    double lastClv   = strength[W - 1];

    // Bearish divergence: price marching UP but internal strength sliding DOWN,
    // at the top of the range, confirmed by a bar closing weak in its own range.
    bool bearDiv =
        priceSlope    >=  MinPriceSlope    &&
        strengthSlope <= -MinStrengthSlope &&
        rangePos      >=  ExtremeFrac      &&
        lastClv       <   0.5;

    // Bullish divergence: price grinding DOWN but internal strength lifting UP,
    // at the bottom of the range, confirmed by a bar closing strong in its range.
    bool bullDiv =
        priceSlope    <= -MinPriceSlope    &&
        strengthSlope >=  MinStrengthSlope &&
        rangePos      <= (1.0 - ExtremeFrac) &&
        lastClv       >   0.5;

    // 6) One position at a time + cooldown between entries.
    if(HasPosition(Magic)) return;
    if(g_barCount - g_lastEntryBar < CooldownBars) return;

    if(bearDiv)
        OpenTrade(false, hi, atr);   // fade short just past the swing high
    else if(bullDiv)
        OpenTrade(true,  lo, atr);   // fade long just past the swing low
}

//+------------------------------------------------------------------+
//| Least-squares slope of the last n values of a newest-last series |
//| (x runs 0..n-1 oldest->newest, so a rising series => positive).  |
//+------------------------------------------------------------------+
double Slope(const double &data[], int count, int n)
{
    if(n < 2 || count < n) return 0.0;
    int    start = count - n;
    double meanX = (n - 1) / 2.0;
    double sumY  = 0.0;
    for(int k = 0; k < n; k++) sumY += data[start + k];
    double meanY = sumY / n;
    double num = 0.0, den = 0.0;
    for(int k = 0; k < n; k++)
    {
        double dx = k - meanX;
        num += dx * (data[start + k] - meanY);
        den += dx * dx;
    }
    return den > 0.0 ? num / den : 0.0;
}

//+------------------------------------------------------------------+
//| Open the faded reversal trade with a structural ATR-buffered stop|
//+------------------------------------------------------------------+
void OpenTrade(bool isLong, double structuralExtreme, double atr)
{
    double vol = MathRound(Lots * 100.0) / 100.0;   // round to 2 dp
    vol = MathMax(0.01, MathMin(vol, 100.0));
    if(vol <= 0.0) return;

    double buffer = SlBufferAtr * atr;
    double entry, sl, tp;

    if(isLong)
    {
        entry = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
        sl    = structuralExtreme - buffer;   // just below the faded swing low
        double risk = entry - sl;
        if(risk <= 0.0) return;
        tp = entry + RewardRisk * risk;

        sl = NormalizeDouble(sl, _Digits);
        tp = NormalizeDouble(tp, _Digits);
        if(!trade.Buy(vol, _Symbol, 0.0, sl, tp, "IntStrengthDiv-Long"))
        {
            Print("InternalStrengthDivergenceFade: Buy failed, ret=", trade.ResultRetcode());
            return;
        }
    }
    else
    {
        entry = SymbolInfoDouble(_Symbol, SYMBOL_BID);
        sl    = structuralExtreme + buffer;   // just above the faded swing high
        double risk = sl - entry;
        if(risk <= 0.0) return;
        tp = entry - RewardRisk * risk;

        sl = NormalizeDouble(sl, _Digits);
        tp = NormalizeDouble(tp, _Digits);
        if(!trade.Sell(vol, _Symbol, 0.0, sl, tp, "IntStrengthDiv-Short"))
        {
            Print("InternalStrengthDivergenceFade: Sell failed, ret=", trade.ResultRetcode());
            return;
        }
    }

    g_lastEntryBar = g_barCount;
    PrintFormat("InternalStrengthDivergenceFade %s %s entry=%.5f sl=%.5f tp=%.5f atr=%.5f",
                isLong ? "LONG" : "SHORT", _Symbol, entry, sl, tp, atr);
}

//+------------------------------------------------------------------+
//| Optional ATR trailing stop: only ratchets in the trade's favour. |
//+------------------------------------------------------------------+
void ManageOpenPosition()
{
    if(TrailAtrMult <= 0.0) return;
    double atr = g_lastAtr;
    if(atr <= 0.0) return;

    for(int i = PositionsTotal() - 1; i >= 0; i--)
    {
        ulong ticket = PositionGetTicket(i);
        if(!PositionSelectByTicket(ticket)) continue;
        if(PositionGetString(POSITION_SYMBOL) != _Symbol) continue;
        if(PositionGetInteger(POSITION_MAGIC) != Magic)   continue;

        long   dir   = PositionGetInteger(POSITION_TYPE);
        double posSl = PositionGetDouble(POSITION_SL);
        double posTp = PositionGetDouble(POSITION_TP);

        if(dir == POSITION_TYPE_BUY)
        {
            double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
            double newSl = price - atr * TrailAtrMult;
            if(newSl < price && newSl > posSl + atr * 0.05)
                trade.PositionModify(ticket, NormalizeDouble(newSl, _Digits), posTp);
        }
        else // POSITION_TYPE_SELL
        {
            double price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
            double newSl = price + atr * TrailAtrMult;
            if(newSl > price && (posSl <= 0.0 || newSl < posSl - atr * 0.05))
                trade.PositionModify(ticket, NormalizeDouble(newSl, _Digits), posTp);
        }
    }
}

//+------------------------------------------------------------------+
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;
}
//+------------------------------------------------------------------+
