//+------------------------------------------------------------------+
//|                                    OpeningBalanceReversion.mq5    |
//|  Intraday, time-anchored opening-balance mean-reversion system.  |
//|  Native MQL5 port of the Algobot C# strategy of the same name.   |
//+------------------------------------------------------------------+
#property copyright "Algobot"
#property link      "https://www.algobot.live"
#property version   "1.00"
#property strict

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

//--- inputs ---------------------------------------------------------
input int    SessionStartHour = 7;      // UTC hour a fresh session (and its opening balance) begins
input int    OpeningRangeBars = 4;      // bars from the start hour that form the opening-balance box
input int    SessionEndHour   = 18;     // UTC hour to stop taking trades and flatten
input int    AtrPeriod        = 14;     // ATR period
input double MinRangeAtrMult  = 1.00;   // balance width must be >= this many ATRs to fade
input double MaxPokeAtrMult   = 0.75;   // largest poke beyond edge (ATRs) still treated as rejection
input double TargetFraction   = 0.60;   // TP as fraction of balance width, back in from the poked edge
input double StopAtrMult       = 0.80;  // stop distance beyond the rejected extreme, in ATRs
input double BreakevenAtr      = 0.80;  // move stop to BE after this many ATRs in favour (0 = off)
input double Lots              = 0.10;  // order volume
input long   Magic             = 8163;  // magic number

//--- indicator handles ----------------------------------------------
int    g_atrHandle = INVALID_HANDLE;
double g_lastAtr   = 0.0;

//--- per-session opening-balance state -------------------------------
datetime g_sessionDate = 0;
int      g_orCount     = 0;
double   g_orHigh      = 0.0;
double   g_orLow       = 0.0;
double   g_orMid       = 0.0;
bool     g_orReady     = false;
bool     g_longDone    = false;
bool     g_shortDone   = false;

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

    g_atrHandle = iATR(_Symbol, _Period, AtrPeriod);
    if(g_atrHandle == INVALID_HANDLE) return INIT_FAILED;

    g_lastAtr = 0.0;
    ResetSession(0);
    return INIT_SUCCEEDED;
}

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

//+------------------------------------------------------------------+
//| Reset all per-session opening-balance state.                     |
//+------------------------------------------------------------------+
void ResetSession(datetime date)
{
    g_sessionDate = date;
    g_orCount     = 0;
    g_orHigh      = -DBL_MAX;
    g_orLow       =  DBL_MAX;
    g_orMid       = 0.0;
    g_orReady     = false;
    g_longDone    = false;
    g_shortDone   = false;
}

//+------------------------------------------------------------------+
void OnTick()
{
    // Manage any open trade on every tick (break-even trail).
    ManageBreakeven();

    // Act only once per freshly-completed bar (no repaint).
    if(!IsNewBar()) return;

    if(Bars(_Symbol, _Period) < AtrPeriod + 3) return;

    // The bar that just closed (shift 1) drives all logic.
    double   barOpen  = iOpen(_Symbol,  _Period, 1);
    double   barHigh  = iHigh(_Symbol,  _Period, 1);
    double   barLow   = iLow(_Symbol,   _Period, 1);
    double   barClose = iClose(_Symbol, _Period, 1);
    datetime barTime  = iTime(_Symbol,  _Period, 1);

    double atr = AtrValue();
    g_lastAtr  = atr;
    if(atr <= 0.0) return;

    MqlDateTime dt;
    TimeToStruct(barTime, dt);
    int      hour = dt.hour;
    datetime date = barTime - (barTime % 86400);   // midnight of the bar's day

    // --- Session anchoring: outside the tracked session we never hold risk ---
    if(date != g_sessionDate)
    {
        CloseAll(Magic);                    // no overnight / between-session carry
        if(hour >= SessionStartHour)
            ResetSession(date);             // a new session (and its balance) begins now
        else
            return;                         // pre-session hours: stay idle
    }

    // --- Phase 1: accumulate the opening balance from the first bars of the session ---
    if(!g_orReady)
    {
        if(barHigh > g_orHigh) g_orHigh = barHigh;
        if(barLow  < g_orLow)  g_orLow  = barLow;
        g_orCount++;
        if(g_orCount >= OpeningRangeBars && g_orHigh > g_orLow)
        {
            g_orReady = true;
            g_orMid   = 0.5 * (g_orHigh + g_orLow);
            PrintFormat("OB set %s H=%.5f L=%.5f mid=%.5f",
                        TimeToString(date, TIME_DATE), g_orHigh, g_orLow, g_orMid);
        }
        return;
    }

    // --- Session close-out: stop trading and flatten at the end hour ---
    if(hour >= SessionEndHour)
    {
        CloseAll(Magic);
        return;
    }

    // One position from this Magic at a time.
    if(HasPosition(Magic)) return;

    double width = g_orHigh - g_orLow;
    if(width < MinRangeAtrMult * atr) return;   // balance too shallow to fade
    double maxPoke   = MaxPokeAtrMult * atr;
    double minTarget = 0.20 * atr;              // reject degenerate targets

    // --- SHORT: poke the top, rejected back inside -> fade toward the midpoint ---
    if(!g_shortDone &&
       barHigh >= g_orHigh &&                   // reached the upper edge
       barHigh <= g_orHigh + maxPoke &&         // but not a runaway trend break
       barClose < g_orHigh &&                   // closed back inside the balance
       barClose < barOpen)                      // bearish rejection bar
    {
        double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
        double tp  = g_orHigh - TargetFraction * width;
        double sl  = g_orHigh + StopAtrMult * atr;
        if(bid - tp >= minTarget && sl > bid)
        {
            g_shortDone = true;
            trade.Sell(Lots, _Symbol, 0.0, sl, tp, "OBR short");
            PrintFormat("SHORT fade top @ %.5f sl=%.5f tp=%.5f atr=%.5f", bid, sl, tp, atr);
            return;
        }
    }

    // --- LONG: poke the bottom, reclaimed back inside -> fade toward the midpoint ---
    if(!g_longDone &&
       barLow <= g_orLow &&                     // reached the lower edge
       barLow >= g_orLow - maxPoke &&           // but not a runaway trend break
       barClose > g_orLow &&                    // closed back inside the balance
       barClose > barOpen)                      // bullish rejection bar
    {
        double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
        double tp  = g_orLow + TargetFraction * width;
        double sl  = g_orLow - StopAtrMult * atr;
        if(tp - ask >= minTarget && sl < ask)
        {
            g_longDone = true;
            trade.Buy(Lots, _Symbol, 0.0, sl, tp, "OBR long");
            PrintFormat("LONG fade bottom @ %.5f sl=%.5f tp=%.5f atr=%.5f", ask, sl, tp, atr);
        }
    }
}

//+------------------------------------------------------------------+
//| ATR of the just-closed bar (shift 1), matching the C# window.    |
//+------------------------------------------------------------------+
double AtrValue()
{
    double buf[];
    ArraySetAsSeries(buf, true);
    if(CopyBuffer(g_atrHandle, 0, 0, 3, buf) < 2) return 0.0;
    return buf[1];
}

//+------------------------------------------------------------------+
//| Pull the stop to entry once price travels BreakevenAtr*ATR       |
//| in our favour.                                                   |
//+------------------------------------------------------------------+
void ManageBreakeven()
{
    if(BreakevenAtr <= 0.0 || g_lastAtr <= 0.0) return;
    double trigger = BreakevenAtr * g_lastAtr;

    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;

        long   type         = PositionGetInteger(POSITION_TYPE);
        double priceOpen    = PositionGetDouble(POSITION_PRICE_OPEN);
        double priceCurrent = PositionGetDouble(POSITION_PRICE_CURRENT);
        double sl           = PositionGetDouble(POSITION_SL);
        double tp           = PositionGetDouble(POSITION_TP);

        if(type == POSITION_TYPE_BUY)
        {
            if(priceCurrent >= priceOpen + trigger && (sl < priceOpen || sl == 0.0))
                trade.PositionModify(t, priceOpen, tp);
        }
        else if(type == POSITION_TYPE_SELL)
        {
            if(priceCurrent <= priceOpen - trigger && (sl > priceOpen || sl == 0.0))
                trade.PositionModify(t, priceOpen, tp);
        }
    }
}

//+------------------------------------------------------------------+
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 CloseAll(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) trade.PositionClose(t);
    }
}
//+------------------------------------------------------------------+
