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

//+------------------------------------------------------------------+
//| TowerPlateauReversal                                             |
//| Pure price-action "Tower Top" / "Tower Bottom" reversal system.  |
//|   left pillar (wide body into a fresh extreme)                   |
//|   -> flat plateau (n small, tightly-contained bars)              |
//|   -> right pillar (wide body firing the opposite way, breaking   |
//|      clear of the plateau).                                      |
//| Tower Bottom => BUY, Tower Top => SELL. Volatility scale is a    |
//| self-computed ATR over the window PRECEDING the tower. No        |
//| indicators/handles are used -- everything is raw OHLC geometry.  |
//+------------------------------------------------------------------+

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

//--- inputs ---
input int    PlateauBars      = 3;      // number of flat plateau bars
input int    AtrPeriod        = 14;     // ATR window (bars before the tower)
input double PillarBodyMult   = 1.0;    // pillar body >= this * ATR
input double PlateauBodyMult   = 0.5;   // each plateau body <= this * ATR
input double PlateauRangeMult  = 1.3;   // plateau high-low span <= this * ATR
input int    LookbackExtreme  = 20;     // preceding window for fresh-extreme test
input double StopBufferMult   = 0.5;    // SL buffer beyond tower extreme (* ATR)
input double RewardRisk       = 2.0;    // reward:risk multiple for TP
input double Lots             = 0.10;   // trade volume
input long   Magic            = 8421;   // magic number

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

//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
    // No indicator handles to release (ATR is self-computed).
}

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

//+------------------------------------------------------------------+
void OnTick()
{
    // Evaluate once per freshly closed bar (shift 0 is the still-forming bar).
    if(!IsNewBar()) return;

    int n = PlateauBars;

    // Bars needed: right pillar(1) + plateau(n) + left pillar(1) + ATR/lookback window + prevClose.
    int need = n + 3 + MathMax(AtrPeriod, LookbackExtreme) + 2;
    if(iBars(_Symbol, _Period) < need) return;

    // One position at a time for this magic -- SL/TP manage the exit.
    if(HasPosition(Magic)) return;

    // --- Structural shifts ---
    int rightShift = 1;          // just-closed bar = right pillar
    int leftShift  = n + 2;      // left pillar
    int preShift   = n + 3;      // first bar preceding the tower (ATR / extreme window start)

    // --- Right & left pillar OHLC ---
    double rightOpen  = iOpen(_Symbol,  _Period, rightShift);
    double rightClose = iClose(_Symbol, _Period, rightShift);
    double rightHigh  = iHigh(_Symbol,  _Period, rightShift);
    double rightLow   = iLow(_Symbol,   _Period, rightShift);

    double leftOpen   = iOpen(_Symbol,  _Period, leftShift);
    double leftClose  = iClose(_Symbol, _Period, leftShift);
    double leftHigh   = iHigh(_Symbol,  _Period, leftShift);
    double leftLow    = iLow(_Symbol,   _Period, leftShift);

    // --- ATR over the window that PRECEDES the tower (normal volatility context) ---
    double trSum = 0.0;
    for(int i = 0; i < AtrPeriod; i++)
    {
        int    s  = preShift + i;
        double bh = iHigh(_Symbol,  _Period, s);
        double bl = iLow(_Symbol,   _Period, s);
        double pc = iClose(_Symbol, _Period, s + 1);
        double tr = MathMax(bh - bl, MathMax(MathAbs(bh - pc), MathAbs(bl - pc)));
        trSum += tr;
    }
    double atr = trSum / AtrPeriod;
    if(atr <= 0.0) return;

    double pillarReq  = PillarBodyMult  * atr;   // pillar body must be this tall
    double plateauReq = PlateauBodyMult * atr;   // each plateau body must be this small

    // --- Scan the plateau: all bodies small + tightly contained range ---
    double plateauHigh = -DBL_MAX;
    double plateauLow  =  DBL_MAX;
    bool   plateauOk   = true;
    for(int s = 2; s <= n + 1; s++)
    {
        double bo = iOpen(_Symbol,  _Period, s);
        double bc = iClose(_Symbol, _Period, s);
        double bh = iHigh(_Symbol,  _Period, s);
        double bl = iLow(_Symbol,   _Period, s);
        if(MathAbs(bc - bo) > plateauReq){ plateauOk = false; break; }
        if(bh > plateauHigh) plateauHigh = bh;
        if(bl < plateauLow)  plateauLow  = bl;
    }
    if(!plateauOk) return;
    if((plateauHigh - plateauLow) > PlateauRangeMult * atr) return;  // base must be flat

    double leftBody  = MathAbs(leftClose  - leftOpen);
    double rightBody = MathAbs(rightClose - rightOpen);
    if(leftBody < pillarReq || rightBody < pillarReq) return;        // both pillars tall

    // Preceding-window extreme (does the tower carve a genuinely fresh local extreme?).
    double priorLowMin  =  DBL_MAX;
    double priorHighMax = -DBL_MAX;
    for(int i = 0; i < LookbackExtreme; i++)
    {
        double bh = iHigh(_Symbol, _Period, preShift + i);
        double bl = iLow(_Symbol,  _Period, preShift + i);
        if(bl < priorLowMin)  priorLowMin  = bl;
        if(bh > priorHighMax) priorHighMax = bh;
    }

    int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);

    // ================= TOWER BOTTOM -> BUY =================
    // down pillar into a new low -> flat base -> up pillar breaks the base upward.
    double towerLow = MathMin(MathMin(leftLow, rightLow), plateauLow);
    bool towerBottom =
        leftClose  < leftOpen  &&                 // left pillar is a down thrust
        rightClose > rightOpen &&                 // right pillar fires back up
        rightClose > plateauHigh &&               // and closes above the plateau ceiling
        towerLow   < priorLowMin;                 // tower marks a fresh local low

    if(towerBottom)
    {
        double entry = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
        double sl    = towerLow - StopBufferMult * atr;
        double risk  = entry - sl;
        if(risk > 0.0)
        {
            double tp = entry + RewardRisk * risk;
            sl = NormalizeDouble(sl, digits);
            tp = NormalizeDouble(tp, digits);
            if(trade.Buy(Lots, _Symbol, 0.0, sl, tp, "TowerBottom"))
                PrintFormat("Tower-bottom long @ %.*f SL %.*f TP %.*f (base %d bars, atr %.*f)",
                            digits, entry, digits, sl, digits, tp, n, digits, atr);
        }
        return;
    }

    // ================= TOWER TOP -> SELL =================
    // up pillar into a new high -> flat base -> down pillar breaks the base downward.
    double towerHigh = MathMax(MathMax(leftHigh, rightHigh), plateauHigh);
    bool towerTop =
        leftClose  > leftOpen  &&                 // left pillar is an up thrust
        rightClose < rightOpen &&                 // right pillar fires back down
        rightClose < plateauLow &&                // and closes below the plateau floor
        towerHigh  > priorHighMax;                // tower marks a fresh local high

    if(towerTop)
    {
        double entry = SymbolInfoDouble(_Symbol, SYMBOL_BID);
        double sl    = towerHigh + StopBufferMult * atr;
        double risk  = sl - entry;
        if(risk > 0.0)
        {
            double tp = entry - RewardRisk * risk;
            sl = NormalizeDouble(sl, digits);
            tp = NormalizeDouble(tp, digits);
            if(trade.Sell(Lots, _Symbol, 0.0, sl, tp, "TowerTop"))
                PrintFormat("Tower-top short @ %.*f SL %.*f TP %.*f (base %d bars, atr %.*f)",
                            digits, entry, digits, sl, digits, tp, n, digits, atr);
        }
    }
}
//+------------------------------------------------------------------+
