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

// ============================================================================
//  SpinningTopClusterBreakout
//  ---------------------------------------------------------------------------
//  Price-action compression breakout keyed on candle BODY indecision, not
//  candle RANGE. A "spinning top" is a candle whose real body is small relative
//  to its total high-low range (|Close-Open|/(High-Low) <= BodyRatioMax) -- it
//  signals balance. A CLUSTER of them marks an equilibrium pocket. Resolution
//  comes from a DECISIVE candle whose body dominates its range
//  (>= BreakoutBodyRatio) and that CLOSES beyond the pocket fence + ATR buffer.
//
//    Long  : decisive BULLISH body closes above cluster high + buffer.
//    Short : decisive BEARISH body closes below cluster low  - buffer.
//
//  Single timeframe only (_Symbol / _Period). The bar that just completed is at
//  shift 1; the balance pocket is the ClusterWindow bars before it (shifts
//  2 .. ClusterWindow+1).
// ============================================================================

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

// --- inputs ---
input int    ClusterWindow     = 6;      // bars before the escape bar forming the balance pocket
input int    MinSpinningTops    = 3;      // how many of those must be spinning tops
input double BodyRatioMax       = 0.30;   // max body/range ratio to count as a spinning top
input double BreakoutBodyRatio  = 0.55;   // min body/range ratio for the escape candle
input double BreakBufferAtr     = 0.10;   // extra clearance beyond the fence, as fraction of ATR
input int    AtrPeriod          = 14;     // ATR period for buffer + risk
input double AtrStopMult        = 1.5;    // ATR multiple for stop distance
input double AtrTargetMult      = 2.5;    // ATR multiple for target distance
input double Lots               = 0.10;   // trade volume
input long   Magic              = 5321;   // magic number

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

int OnInit()
{
    trade.SetExpertMagicNumber(Magic);

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

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

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()
{
    if(!IsNewBar()) return;

    // Need enough completed bars: cluster window + escape bar, and the ATR window.
    int need = MathMax(ClusterWindow + 1, AtrPeriod + 1);
    if(Bars(_Symbol, _Period) < need + 2) return;

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

    // ---- The escape candidate = the bar that just completed (shift 1) ----
    double escOpen  = iOpen (_Symbol, _Period, 1);
    double escHigh  = iHigh (_Symbol, _Period, 1);
    double escLow   = iLow  (_Symbol, _Period, 1);
    double escClose = iClose(_Symbol, _Period, 1);

    double escRange = escHigh - escLow;
    if(escRange <= 0) return;

    double escBodyRatio = MathAbs(escClose - escOpen) / escRange;
    bool decisive = escBodyRatio >= BreakoutBodyRatio;
    if(!decisive) return;                    // no full-commit escape candle -> nothing to do

    // ---- The balance pocket = the ClusterWindow bars BEFORE the escape bar ----
    // Escape bar is shift 1, so the pocket is shifts [2 .. ClusterWindow+1].
    int tops = 0;
    double fenceHigh = -DBL_MAX;
    double fenceLow  =  DBL_MAX;
    for(int shift = 2; shift <= ClusterWindow + 1; shift++)
    {
        double o = iOpen (_Symbol, _Period, shift);
        double h = iHigh (_Symbol, _Period, shift);
        double l = iLow  (_Symbol, _Period, shift);
        double c = iClose(_Symbol, _Period, shift);

        double r = h - l;
        if(r > 0 && MathAbs(c - o) / r <= BodyRatioMax)
            tops++;
        if(h > fenceHigh) fenceHigh = h;
        if(l < fenceLow)  fenceLow  = l;
    }
    if(tops < MinSpinningTops) return;       // not enough indecision -> not a real balance pocket

    // ---- ATR for buffer + risk (value at the just-completed bar, shift 1) ----
    double atrBuf[];
    ArraySetAsSeries(atrBuf, true);
    if(CopyBuffer(g_atrHandle, 0, 0, 3, atrBuf) < 2) return;
    double atr = atrBuf[1];
    if(atr <= 0) return;

    double buffer = BreakBufferAtr * atr;

    bool bullBody = escClose > escOpen;
    bool bearBody = escClose < escOpen;

    bool breakUp   = bullBody && escClose > fenceHigh + buffer;
    bool breakDown = bearBody && escClose < fenceLow  - buffer;

    if(breakUp)
        TryEnter(true,  atr, tops);
    else if(breakDown)
        TryEnter(false, atr, tops);
}

void TryEnter(bool isLong, double atr, int tops)
{
    double stopDist   = AtrStopMult   * atr;
    double targetDist = AtrTargetMult * atr;
    if(stopDist <= 0 || targetDist <= 0) return;

    double price, sl, tp;

    if(isLong)
    {
        price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
        sl    = price - stopDist;
        tp    = price + targetDist;
    }
    else
    {
        price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
        sl    = price + stopDist;
        tp    = price - targetDist;
    }

    int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
    sl = NormalizeDouble(sl, digits);
    tp = NormalizeDouble(tp, digits);

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

    PrintFormat("SpinningTopClusterBreakout %s @ %.5f SL %.5f TP %.5f tops %d/%d atr %.5f -> %s",
                (isLong ? "LONG" : "SHORT"), price, sl, tp, tops, ClusterWindow, atr,
                (ok ? "ok" : "fail"));
}
