//+------------------------------------------------------------------+
//|                                           HangingManReversal.mq5 |
//|              Converted from Algobot C# strategy HangingManReversal |
//+------------------------------------------------------------------+
#property copyright "Algobot"
#property link      "https://www.algobot.live"
#property version   "1.00"
#property strict

// ============================================================================
//  HangingManReversal
//  ---------------------------------------------------------------------------
//  Concept : A pure price-action, SHORT-ONLY candlestick reversal built on the
//            HANGING MAN. The shape is a hammer, but it prints at the TOP of an
//            advance: buyers pushed price to a fresh high, sellers then drove it
//            well down inside the bar, and buyers only just dragged it back up
//            to close near the top. The long lower wick shows that supply has
//            appeared above the market for the first time in the run, even though
//            the bar's close still looks fine.
//
//            The hanging man alone is only a warning, so we wait for the next
//            candle to CLOSE BELOW THE HANGING MAN'S LOW. Everyone who bought
//            that bar, including its lower-wick buyers, is now under water, and
//            that pressure is what drives the reversal.
//
//  Market  : Built with EUR/USD, GBP/USD or XAU/USD on H1 / H4 in mind, but every
//            bar is read via _Symbol / _Period so it runs on any liquid symbol
//            and any timeframe chosen at backtest time.
//  Style   : Counter-trend swing reversal, price action only - NO indicators
//            (no MA, RSI, MACD, stochastics, bands, VWAP, ATR or volume).
//
//  Pattern (hanging-man candle H, at shift 2 once the confirm bar has closed):
//     - uptrend:   at least MinHigherCloses consecutive higher closes leading
//                  into H  (C[3] > C[4] > ... for the bars just before H)
//     - new high:  High[H] above every high of the previous HighLookback-1 bars
//                  (H is the highest candle of the last HighLookback)
//     - body:      the whole body sits in the top BodyZoneFrac of H's range
//                  (small body by construction)
//     - lower wick >= MinWickBodyRatio x body
//     - upper wick <= MaxUpperWickFrac x range (little or no upper shadow)
//
//  Short entry (confirm candle C = the bar right after H, shift 1):
//     - C closes below Low[H]  -> sell at market
//     - SL just above High[H] (+ StopBufferPoints), TP = RiskReward x risk (2R)
//
//  Long entry: none - the criteria for this system are short only.
//  One position at a time per Magic.
//  Single timeframe only: every bar read uses _Period.
// ============================================================================

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

// --- inputs ---
input int    MinHigherCloses  = 3;      // Consecutive higher closes required into the hanging man (2..6)
input int    HighLookback     = 10;     // Hanging man must be the highest of this many candles, itself included (5..30)
input double BodyZoneFrac     = 0.333;  // Whole body must sit inside this top fraction of the range (0.20..0.50)
input double MinWickBodyRatio = 2.0;    // Lower wick must be at least this multiple of the body (1.5..4.0)
input double MaxUpperWickFrac = 0.10;   // Upper wick may be at most this fraction of the range (0.0..0.25)
input int    StopBufferPoints = 10;     // Extra points above the hanging man's high for the stop (0..100)
input double RiskReward       = 2.0;    // Take profit as a multiple of the stop distance (1.0..4.0)
input double Lots             = 0.10;   // Order volume (0.01..1.0)
input long   Magic            = 726415; // Magic number

// --- indicator handles ---
// None: this strategy is pure price action and uses no indicators.

// --- working state (inputs are read-only in MQL5, so clamped copies live here) ---
int      g_minHigherCloses = 3;
int      g_highLookback    = 10;
int      g_digits          = 5;
datetime g_lastBarTime     = 0;

int OnInit()
{
    g_minHigherCloses = MinHigherCloses;
    g_highLookback    = HighLookback;

    if(g_minHigherCloses < 1) g_minHigherCloses = 1;
    if(g_highLookback < 2)    g_highLookback    = 2;

    g_digits      = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
    g_lastBarTime = 0;

    trade.SetExpertMagicNumber((ulong)Magic);
    trade.SetTypeFillingBySymbol(_Symbol);
    return INIT_SUCCEEDED;
}

void OnTick()
{
    // shift 0 = forming, 1 = confirm candle, 2 = hanging man, 3.. = history.
    int history = (g_highLookback - 1 > g_minHigherCloses + 1) ? g_highLookback - 1 : g_minHigherCloses + 1;
    if(Bars(_Symbol, _Period) < history + 4) return;

    // Act once per freshly-closed bar.
    if(!IsNewBar()) return;

    // One position at a time for this strategy's magic.
    if(HasPosition(Magic)) return;

    double   confirmClose = iClose(_Symbol, _Period, 1);
    double   hmOpen       = iOpen(_Symbol,  _Period, 2);
    double   hmHigh       = iHigh(_Symbol,  _Period, 2);
    double   hmLow        = iLow(_Symbol,   _Period, 2);
    double   hmClose      = iClose(_Symbol, _Period, 2);
    datetime hmTime       = iTime(_Symbol,  _Period, 2);

    // Trigger first (cheapest test): the next candle must close below the hanging man's low.
    if(confirmClose >= hmLow) return;

    if(!IsHangingMan(hmOpen, hmHigh, hmLow, hmClose)) return;
    if(!IsNewHigh(hmHigh)) return;
    if(!HasHigherCloses()) return;

    double point = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
    if(point <= 0) point = 0.0001;
    double entry     = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    double sl        = hmHigh + StopBufferPoints * point;
    long   stopLevel = SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL);
    double minDist   = (stopLevel + 1) * point;
    if(sl - entry < minDist) sl = entry + minDist;

    double risk = sl - entry;
    if(risk <= 0) return;
    double tp = entry - RiskReward * risk;

    sl = Norm(sl);
    tp = Norm(tp);

    bool ok = trade.Sell(Volume(), _Symbol, entry, sl, tp, "HangingMan-Short");
    PrintFormat("HangingManReversal SHORT @ %.5f SL %.5f TP %.5f HM %s H %.5f L %.5f -> %s (%u %s)",
                entry, sl, tp, TimeToString(hmTime, TIME_DATE | TIME_MINUTES), hmHigh, hmLow,
                ok ? "sent" : "failed", trade.ResultRetcode(), trade.ResultRetcodeDescription());
}

void OnDeinit(const int reason)
{
    // No indicator handles to release.
}

bool IsNewBar()
{
    datetime cur = iTime(_Symbol, _Period, 0);
    if(cur == 0) return false;
    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;
}

// Small body in the top zone, long lower wick, little or no upper wick.
bool IsHangingMan(double open, double high, double low, double close)
{
    double range = high - low;
    if(range <= 0) return false;

    double bodyTop    = MathMax(open, close);
    double bodyBottom = MathMin(open, close);
    double body       = bodyTop - bodyBottom;
    double lowerWick  = bodyBottom - low;
    double upperWick  = high - bodyTop;

    bool bodyInTopZone  = bodyBottom >= high - BodyZoneFrac * range;
    bool longLowerWick  = lowerWick >= MinWickBodyRatio * body && lowerWick > 0;
    bool smallUpperWick = upperWick <= MaxUpperWickFrac * range;

    return bodyInTopZone && longLowerWick && smallUpperWick;
}

// The hanging man's high tops every one of the previous HighLookback-1 candles.
bool IsNewHigh(double hmHigh)
{
    for(int shift = 3; shift <= g_highLookback + 1; shift++)
        if(iHigh(_Symbol, _Period, shift) >= hmHigh) return false;
    return true;
}

// At least MinHigherCloses consecutive higher closes on the bars right before the hanging man.
bool HasHigherCloses()
{
    for(int shift = 3; shift < 3 + g_minHigherCloses; shift++)
        if(iClose(_Symbol, _Period, shift) <= iClose(_Symbol, _Period, shift + 1)) return false;
    return true;
}

double Volume()
{
    double vstep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
    if(vstep <= 0) vstep = 0.01;
    double v = MathRound(Lots / vstep) * vstep;
    v = NormalizeDouble(v, 2);
    double vmin = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
    double vmax = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
    if(v < vmin) v = vmin;
    if(vmax > 0 && v > vmax) v = vmax;
    return v;
}

double Norm(double price)
{
    return NormalizeDouble(price, g_digits);
}
//+------------------------------------------------------------------+
