//+------------------------------------------------------------------+
//|                                             MarketMakerModel.mq5 |
//|  ICT Market Maker Buy Model / Sell Model - pure price action.    |
//|  Converted from the Algobot C# strategy MarketMakerModel.cs.     |
//+------------------------------------------------------------------+
#property copyright "Algobot"
#property link      "https://www.algobot.live"
#property version   "1.00"
#property strict

// MarketMakerModel - the ICT Market Maker Buy Model and Sell Model, traded with
// pure price action (no indicators: no averages, oscillators, bands, ATR or volume).
// Designed for EURUSD M15, but it reads only the chart timeframe, so it runs on any
// symbol / timeframe.
//
// BUY MODEL (the four stages are detected in order, on closed bars only):
//  1. Original consolidation : a box of at least RangeBars candles that is genuinely
//                              sideways - the net drift from the first open to the last
//                              close is small versus the box height, and many candles
//                              straddle the box midpoint (overlapping, balanced price).
//  2. Sell program           : price leaves the box downward in at least MinLegs legs -
//                              every swing high stays below the box high and is lower
//                              than the one before (no higher high allowed), and at
//                              least MinLegs successive lower lows print below the box.
//  3. Smart money reversal   : a candle wicks below the most recent swing low and closes
//                              back above it (sell-side liquidity swept; no candle closes
//                              through it). Then a strong bullish displacement candle -
//                              big body-to-range ratio and the largest body of the last
//                              few candles - is the first to close above the last lower
//                              high (market structure shift) and leaves a bullish fair
//                              value gap (candle 1 high < candle 3 low).
//  4. Entry                  : the first return into that FVG (bid trades down to the
//                              gap's upper edge) buys at market. Stop below the sweep
//                              low; target is the original consolidation's high. The trade
//                              is taken only if that target is at least MinRR R away.
//
// SELL MODEL: the exact mirror - produced by negating prices so both models share one
// detector and are guaranteed symmetrical.
//
// A setup is dropped if price reaches the target or the sweep extreme before returning,
// if it is not filled within SetupExpiryBars, or once its first return has been used.
// One position at a time.

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

// --- inputs declared here ---
input int    RangeBars            = 10;    // RangeBars (min 10; opt 10..30 step 2)
input double MaxRangeDrift        = 0.5;   // MaxRangeDrift (opt 0.2..0.8 step 0.1)
input int    SwingStrength        = 2;     // SwingStrength (min 1; opt 1..4 step 1)
input int    MinLegs              = 2;     // MinLegs (min 2; opt 2..4 step 1)
input int    MaxProgramBars       = 60;    // MaxProgramBars (opt 20..150 step 10)
input double DisplacementBody     = 0.6;   // DisplacementBody (opt 0.4..0.9 step 0.05)
input int    DisplacementLookback = 4;     // DisplacementLookback (min 1; opt 2..12 step 1)
input double MinRR                = 2.0;   // MinRR (min 2.0; opt 2.0..5.0 step 0.5)
input int    SetupExpiryBars      = 12;    // SetupExpiryBars (opt 3..40 step 1)
input int    StopBufferPoints     = 10;    // StopBufferPoints (opt 0..100 step 5)
input double Lots                 = 0.10;  // Lots (opt 0.01..1.0 step 0.05)
input long   Magic                = 5150;  // Magic

// --- indicator handles ---
// none: the strategy is pure price action

// fixed pattern geometry
#define SweepWindow     8     // bars before the displacement searched for the sweep candle
#define MinStraddleFrac 0.3   // share of box candles that must straddle the box midpoint

// effective (clamped) inputs
int    g_rangeBars, g_swing, g_minLegs, g_maxProgram, g_dispLook, g_expiry, g_bufferPts;
double g_maxDrift, g_dispBody, g_minRR, g_lots;
long   g_magic;

// rolling closed-bar history (newest-last) + flat OHLC work buffers
struct OHLCBar
{
   double open;
   double high;
   double low;
   double close;
};
OHLCBar  g_bars[];
double   g_o[], g_h[], g_l[], g_c[];
double   g_mo[], g_mh[], g_ml[], g_mc[];
bool     g_isHigh[], g_isLow[];
int      g_keep;
datetime g_lastBarTime = 0;

// armed setup (original price space)
bool   g_armed  = false;
int    g_dir    = 0;     // +1 buy model, -1 sell model
int    g_age    = 0;     // bars elapsed since the FVG completed
double g_touch  = 0;     // FVG near edge: first return trades here
double g_sweep  = 0;     // swept extreme (stop anchor)
double g_target = 0;     // original consolidation's opposite edge

struct Model
{
   double Touch;
   double Sweep;
   double Target;
   double Shift;
};

//+------------------------------------------------------------------+
int OnInit()
{
   g_rangeBars  = MathMax(10, RangeBars);
   g_maxDrift   = MaxRangeDrift;
   g_swing      = MathMax(1, SwingStrength);
   g_minLegs    = MathMax(2, MinLegs);
   g_maxProgram = MaxProgramBars;
   g_dispBody   = DisplacementBody;
   g_dispLook   = MathMax(1, DisplacementLookback);
   g_minRR      = MathMax(2.0, MinRR);
   g_expiry     = SetupExpiryBars;
   g_bufferPts  = StopBufferPoints;
   g_lots       = Lots;
   g_magic      = Magic;

   g_keep = g_rangeBars + g_maxProgram + SweepWindow + 4 * g_swing + g_dispLook + 20;
   ArrayResize(g_o,  g_keep); ArrayResize(g_h,  g_keep); ArrayResize(g_l,  g_keep); ArrayResize(g_c,  g_keep);
   ArrayResize(g_mo, g_keep); ArrayResize(g_mh, g_keep); ArrayResize(g_ml, g_keep); ArrayResize(g_mc, g_keep);
   ArrayResize(g_isHigh, g_keep); ArrayResize(g_isLow, g_keep);

   ArrayResize(g_bars, 0, g_keep + 1);
   g_lastBarTime = 0;
   g_armed = false;
   g_dir = 0;
   g_age = 0;

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

//+------------------------------------------------------------------+
void OnTick()
{
   int available = Bars(_Symbol, _Period);
   if(available < 3) return;

   bool inTrade = HasPosition(g_magic);

   // bar bookkeeping + detection once per new bar; entry is worked on every tick
   bool firstBar = (g_lastBarTime == 0);
   if(IsNewBar())
   {
      if(firstBar && ArraySize(g_bars) == 0)
      {
         // seed with whatever closed history the terminal already holds
         for(int shift = MathMin(available - 1, g_keep); shift >= 2; shift--)
            AddBar(shift);
      }
      AddBar(1);
      TrimBars();

      if(g_armed && ++g_age > g_expiry) g_armed = false;

      if(inTrade) g_armed = false;   // one position at a time
      else Scan();
   }

   if(g_armed && !inTrade) WorkSetup();
}

//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   // no indicator handles to release
}

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

//+------------------------------------------------------------------+
void AddBar(int shift)
{
   int n = ArraySize(g_bars);
   ArrayResize(g_bars, n + 1, g_keep + 1);
   g_bars[n].open  = iOpen(_Symbol,  _Period, shift);
   g_bars[n].high  = iHigh(_Symbol,  _Period, shift);
   g_bars[n].low   = iLow(_Symbol,   _Period, shift);
   g_bars[n].close = iClose(_Symbol, _Period, shift);
}

void TrimBars()
{
   int n = ArraySize(g_bars);
   if(n <= g_keep) return;
   int excess = n - g_keep;
   for(int i = 0; i < g_keep; i++) g_bars[i] = g_bars[i + excess];
   ArrayResize(g_bars, g_keep, g_keep + 1);
}

// ---------------------------------------------------------------- detection

void Scan()
{
   int n = ArraySize(g_bars);
   if(n < g_rangeBars + 4 * g_swing + 6) return;

   for(int i = 0; i < n; i++)
   {
      g_o[i] = g_bars[i].open; g_h[i] = g_bars[i].high; g_l[i] = g_bars[i].low; g_c[i] = g_bars[i].close;
      // mirrored space: a bearish sell model becomes a bullish buy model
      g_mo[i] = -g_bars[i].open; g_mh[i] = -g_bars[i].low; g_ml[i] = -g_bars[i].high; g_mc[i] = -g_bars[i].close;
   }

   Model buy, sell;
   if(Detect(g_o, g_h, g_l, g_c, n, buy))
   {
      Arm(+1, buy.Touch, buy.Sweep, buy.Target);
      PrintFormat("MMBM armed: buy FVG at %.5f  sweep %.5f  MSS %.5f  target %.5f",
                  g_touch, g_sweep, buy.Shift, g_target);
   }
   else if(Detect(g_mo, g_mh, g_ml, g_mc, n, sell))
   {
      Arm(-1, -sell.Touch, -sell.Sweep, -sell.Target);
      PrintFormat("MMSM armed: sell FVG at %.5f  sweep %.5f  MSS %.5f  target %.5f",
                  g_touch, g_sweep, -sell.Shift, g_target);
   }
}

void Arm(int dir, double touch, double sweep, double target)
{
   g_dir = dir; g_touch = touch; g_sweep = sweep; g_target = target;
   g_armed = true; g_age = 0;
}

// Buy-model detector; called on mirrored prices for the sell model.
bool Detect(const double &O[], const double &H[], const double &L[], const double &C[], int n, Model &m)
{
   m.Touch = 0; m.Sweep = 0; m.Target = 0; m.Shift = 0;
   int i3 = n - 1, d = n - 2, i1 = n - 3;

   // --- displacement candle leaving a bullish fair value gap
   if(C[d] <= O[d]) return false;
   if(L[i3] <= H[i1]) return false;
   double body = C[d] - O[d], span = H[d] - L[d];
   if(span <= 0 || body < g_dispBody * span) return false;
   if(d - g_dispLook < 0) return false;
   for(int j = d - g_dispLook; j < d; j++)
      if(MathAbs(C[j] - O[j]) >= body) return false;

   MarkSwings(H, L, n);

   // --- sweep candle: the low of the move into the displacement
   int s = d;
   for(int j = d - 1; j >= MathMax(0, d - SweepWindow); j--)
      if(L[j] < L[s]) s = j;

   int hIdx = -1, lIdx = -1;
   for(int p = s - 1; p >= g_swing && hIdx < 0; p--) if(g_isHigh[p]) hIdx = p;
   for(int p = s - 1; p >= g_swing && lIdx < 0; p--) if(g_isLow[p])  lIdx = p;
   if(hIdx < 0 || lIdx < 0) return false;

   double shift = H[hIdx], swingLow = L[lIdx];

   // wick beyond the most recent swing low, close back above; nothing closes through it
   if(!(L[s] < swingLow && C[s] > swingLow)) return false;
   for(int j = lIdx + 1; j <= d; j++)
      if(L[j] < swingLow && C[j] <= swingLow) return false;

   // market structure shift: displacement is the first close above the last lower high
   if(C[d] <= shift) return false;
   for(int j = hIdx + 1; j < d; j++)
      if(C[j] > shift) return false;

   // --- original consolidation + sell program, most recent valid box first
   int first = MathMin(hIdx, lIdx) - 1;
   int last  = MathMax(g_rangeBars - 1, s - g_maxProgram);
   for(int e = first; e >= last; e--)
   {
      int a = e - g_rangeBars + 1;
      double hi = -DBL_MAX, lo = DBL_MAX;
      for(int j = a; j <= e; j++)
      {
         if(H[j] > hi) hi = H[j];
         if(L[j] < lo) lo = L[j];
      }
      double height = hi - lo;
      if(height <= 0) continue;

      // sideways: small net drift and overlapping candles around the midpoint
      if(MathAbs(C[e] - O[a]) > g_maxDrift * height) continue;
      double mid = 0.5 * (hi + lo);
      int straddle = 0;
      for(int j = a; j <= e; j++)
         if(L[j] <= mid && H[j] >= mid) straddle++;
      if(straddle < MinStraddleFrac * g_rangeBars) continue;

      // box high untouched since the box (it is the target), sweep is the program extreme
      bool valid = true;
      for(int j = e + 1; j < n && valid; j++)
         if(H[j] >= hi) valid = false;
      for(int j = e + 1; j <= d && valid; j++)
         if(L[j] < L[s]) valid = false;
      if(!valid) continue;

      // sell program: descending swing highs below the box, successive lower lows beneath it
      double hiRef = hi, loRef = lo;
      int lowerHighs = 0, lowerLows = 0;
      for(int j = e + 1; j < s && valid; j++)
      {
         if(g_isHigh[j])
         {
            if(H[j] >= hiRef) valid = false;
            else { hiRef = H[j]; lowerHighs++; }
         }
         if(g_isLow[j] && L[j] < loRef) { loRef = L[j]; lowerLows++; }
      }
      if(!valid || lowerHighs < g_minLegs || lowerLows < g_minLegs) continue;
      if(loRef != swingLow) continue;   // the swept low must be the program's latest lower low

      // only worth arming if the first touch of the gap leaves at least MinRR to the box high
      double entry = L[i3];
      double risk = entry - L[s], reward = hi - entry;
      if(risk <= 0 || reward < g_minRR * risk) return false;

      m.Touch = entry; m.Sweep = L[s]; m.Target = hi; m.Shift = shift;
      return true;
   }
   return false;
}

void MarkSwings(const double &H[], const double &L[], int n)
{
   int k = g_swing;
   for(int p = 0; p < n; p++)
   {
      bool hi = (p >= k && p + k < n), lo = hi;
      for(int j = 1; j <= k && (hi || lo); j++)
      {
         if(hi && !(H[p] > H[p - j] && H[p] >= H[p + j])) hi = false;
         if(lo && !(L[p] < L[p - j] && L[p] <= L[p + j])) lo = false;
      }
      g_isHigh[p] = hi;
      g_isLow[p]  = lo;
   }
}

// ---------------------------------------------------------------- execution

void WorkSetup()
{
   double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID), ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
   double pt = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
   int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
   double minDist = (double)SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL) * pt;

   if(g_dir > 0)
   {
      if(bid >= g_target || bid <= g_sweep) { g_armed = false; return; }
      if(bid > g_touch) return;                 // not back in the gap yet
      g_armed = false;                          // the first return is the only entry

      double sl = NormalizeDouble(g_sweep - g_bufferPts * pt, digits);
      double tp = NormalizeDouble(g_target, digits);
      double risk = ask - sl, reward = tp - ask;
      if(risk <= minDist || reward < g_minRR * risk)
      {
         PrintFormat("MMBM skipped: %.2fR available at %.5f", reward / MathMax(risk, pt), ask);
         return;
      }
      if(SendOk(trade.Buy(Volume(), _Symbol, ask, sl, tp, "MMBM FVG")))
         PrintFormat("MMBM long @ %.5f  SL %.5f  TP %.5f  (%.2fR)", ask, sl, tp, reward / risk);
   }
   else
   {
      if(bid <= g_target || bid >= g_sweep) { g_armed = false; return; }
      if(bid < g_touch) return;
      g_armed = false;

      double sl = NormalizeDouble(g_sweep + g_bufferPts * pt + (ask - bid), digits);
      double tp = NormalizeDouble(g_target, digits);
      double risk = sl - bid, reward = bid - tp;
      if(risk <= minDist || reward < g_minRR * risk)
      {
         PrintFormat("MMSM skipped: %.2fR available at %.5f", reward / MathMax(risk, pt), bid);
         return;
      }
      if(SendOk(trade.Sell(Volume(), _Symbol, bid, sl, tp, "MMSM FVG")))
         PrintFormat("MMSM short @ %.5f  SL %.5f  TP %.5f  (%.2fR)", bid, sl, tp, reward / risk);
   }
}

bool SendOk(bool sent)
{
   if(!sent) return false;
   uint rc = trade.ResultRetcode();
   return rc == TRADE_RETCODE_DONE || rc == TRADE_RETCODE_DONE_PARTIAL || rc == TRADE_RETCODE_PLACED;
}

double Volume()
{
   double step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
   double vmax = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
   double vmin = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);

   double v = g_lots;
   if(step > 0) v = MathFloor(v / step + 1e-9) * step;
   if(vmax > 0) v = MathMin(v, vmax);
   v = MathMax(v, vmin);
   if(step <= 0) return v;

   // strip floating-point residue so the server sees an exact multiple of the step
   int vd = 0;
   for(double s = step; vd < 8 && MathAbs(s - MathRound(s)) > 1e-9; s *= 10) vd++;
   return NormalizeDouble(v, vd);
}
//+------------------------------------------------------------------+
