//+------------------------------------------------------------------+
//|                                                GridGuardDemo.mq5 |
//|                                       Copyright 2026, Ali Rajput |
//+------------------------------------------------------------------+
#property copyright "Copyright 2026, Ali Rajput"
#property version   "1.10"
#property description "A plain averaging grid. With the guard on, an add is skipped when it would leave the"
#property description "stop-out too close, and the grid is closed before the broker's stop-out is reached."
//+------------------------------------------------------------------+
//| Includes                                                         |
//+------------------------------------------------------------------+
#include <Trade\Trade.mqh>
#include <StopOutGuard\StopOutRecorder.mqh>
//+------------------------------------------------------------------+
//| Inputs                                                           |
//+------------------------------------------------------------------+
input bool   InpSell          = true;  // Grid side: true sells, false buys
input double InpLot           = 0.05;  // Volume of every grid position
input double InpStepPercent   = 1.0;   // Add a position after this adverse move, % of price
input double InpTakeMoney     = 100.0; // Close the whole grid at this profit, account currency
input bool   InpUseGuard      = false; // Use the guard for adds and for the own exit
input double InpMinPercent    = 3.0;   // Smallest stop-out distance an add may leave, % of price
input double InpExitPercent   = 1.0;   // Close the grid when the stop-out is closer than this, % of price
input int    InpCheckSecs     = 10;    // Seconds between stop-out checks while a grid is open
input double InpCheckLevel    = 200.0; // Search only below this margin level, percent
input bool   InpStopAfterExit = true;  // Stop trading after an own exit
input string InpRunTag        = "";    // CSV name tag (empty: no CSV)
//+------------------------------------------------------------------+
//| Global objects and state                                         |
//+------------------------------------------------------------------+
CTrade           g_trade;             // order sending
CStopOutGuard    g_guard;             // stop-out search
CStopOutRecorder g_rec;               // stop-out deals and daily lines
double           g_last_open=0.0;     // open price of the newest grid position
int              g_adds=0;            // grid positions opened
int              g_refused=0;         // adds the guard refused
int              g_baskets=0;         // grids closed in profit
int              g_exits=0;           // grids closed by the own exit
double           g_exit_loss=0.0;     // money lost in the own exits
int              g_max_positions=0;   // most positions open at once
datetime         g_last_day=0;        // day of the last daily line
datetime         g_last_check=0;      // time of the last stop-out check
datetime         g_pause_until=0;     // no trading before this time
bool             g_stopped=false;     // trading stopped after an own exit
//+------------------------------------------------------------------+
//| Profit of all open positions on the symbol                       |
//+------------------------------------------------------------------+
double BasketProfit(int &count)
  {
   double sum=0.0;
   count=0;
   for(int i=PositionsTotal()-1; i>=0; i--)
     {
      if(PositionGetSymbol(i)!=_Symbol)
         continue;
      sum+=PositionGetDouble(POSITION_PROFIT)+PositionGetDouble(POSITION_SWAP);
      count++;
     }
   return(sum);
  }
//+------------------------------------------------------------------+
//| Close every position on the symbol, true if all are gone         |
//+------------------------------------------------------------------+
bool CloseAll(void)
  {
   for(int i=PositionsTotal()-1; i>=0; i--)
     {
      ulong ticket=PositionGetTicket(i);
      if(PositionGetString(POSITION_SYMBOL)!=_Symbol)
         continue;
      if(!g_trade.PositionClose(ticket) && g_trade.ResultRetcode()==TRADE_RETCODE_MARKET_CLOSED)
        {
         //--- ticks can arrive in a session break, so wait instead of retrying on every tick
         g_pause_until=TimeCurrent()+60;
         return(false);
        }
     }
   int count=0;
   BasketProfit(count);
   return(count==0);
  }
//+------------------------------------------------------------------+
//| True if the server's own order check accepts the grid order      |
//+------------------------------------------------------------------+
bool OrderFits(const ENUM_ORDER_TYPE type)
  {
   MqlTradeRequest     req={};
   MqlTradeCheckResult chk={};
   req.action=TRADE_ACTION_DEAL;
   req.symbol=_Symbol;
   req.volume=InpLot;
   req.type=type;
   req.price=SymbolInfoDouble(_Symbol,type==ORDER_TYPE_BUY ? SYMBOL_ASK : SYMBOL_BID);
   req.deviation=10;
   req.type_filling=ORDER_FILLING_FOK;
//--- retcode 0 means the check passed, OrderCheck() returning true alone does not
   return(OrderCheck(req,chk) && chk.retcode==0);
  }
//+------------------------------------------------------------------+
//| Open one grid position, asking the guard first when it is on     |
//+------------------------------------------------------------------+
void OpenOne(void)
  {
   ENUM_ORDER_TYPE type=InpSell ? ORDER_TYPE_SELL : ORDER_TYPE_BUY;
//--- CanAdd() checks the stop-out distance only, free margin and the rest are OrderCheck()'s job
   if(!OrderFits(type))
      return;
   if(InpUseGuard)
     {
      SStopOutPoint after;
      if(!g_guard.CanAdd(_Symbol,type,InpLot,InpMinPercent,after))
        {
         g_refused++;
         //--- move the reference so the next try waits for one more step
         g_last_open=SymbolInfoDouble(_Symbol,InpSell ? SYMBOL_BID : SYMBOL_ASK);
         //--- a refused first position would be asked again on every tick, so wait an hour
         int count=0;
         BasketProfit(count);
         if(count==0)
            g_pause_until=TimeCurrent()+3600;
         return;
        }
     }
   bool sent=InpSell ? g_trade.Sell(InpLot,_Symbol) : g_trade.Buy(InpLot,_Symbol);
   if(sent && g_trade.ResultRetcode()==TRADE_RETCODE_DONE)
     {
      g_adds++;
      g_last_open=g_trade.ResultPrice();
     }
   else
      if(g_trade.ResultRetcode()==TRADE_RETCODE_MARKET_CLOSED)
         g_pause_until=TimeCurrent()+60;
  }
//+------------------------------------------------------------------+
//| One line per day: balance, equity, positions, stop-out distance  |
//+------------------------------------------------------------------+
void DailyLine(const int count)
  {
   MqlDateTime dt;
   TimeToStruct(TimeCurrent(),dt);
   datetime day=TimeCurrent()-(dt.hour*3600+dt.min*60+dt.sec);
   if(day==g_last_day)
      return;
   g_last_day=day;
   SStopOutPoint pt;
   double dist=0.0;
   if(count>0 && g_guard.StopOut(_Symbol,pt) && pt.status==SOG_OK)
      dist=MathAbs(pt.percent);
   g_rec.Line(StringFormat("Y,%s,%.2f,%.2f,%d,%.3f,%.2f,,,",TimeToString(day,TIME_DATE),AccountInfoDouble(ACCOUNT_BALANCE),
                           AccountInfoDouble(ACCOUNT_EQUITY),count,dist,AccountInfoDouble(ACCOUNT_MARGIN)));
  }
//+------------------------------------------------------------------+
//| Own exit: close the grid before the broker's stop-out            |
//+------------------------------------------------------------------+
bool OwnExit(const double profit)
  {
   if(!InpUseGuard || InpExitPercent<=0.0 || TimeCurrent()-g_last_check<InpCheckSecs)
      return(false);
   g_last_check=TimeCurrent();
//--- the margin level costs nothing to read, the search runs only when the account is near danger
   double level=CStopOutMath::MarginLevel(AccountInfoDouble(ACCOUNT_EQUITY),AccountInfoDouble(ACCOUNT_MARGIN));
   if(level>InpCheckLevel)
      return(false);
   SStopOutPoint pt;
   if(!g_guard.StopOut(_Symbol,pt))
      return(false);
   bool close=(pt.status==SOG_ALREADY_BELOW) || (pt.status==SOG_OK && MathAbs(pt.percent)<InpExitPercent);
   if(!close)
      return(false);
   double equity=AccountInfoDouble(ACCOUNT_EQUITY);
   if(!CloseAll())
      return(false);
   g_exits++;
   g_exit_loss+=profit;
   g_rec.Line(StringFormat("O,%s,%.2f,%.2f,%.3f,,,,,",TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),profit,equity,
                           MathAbs(pt.percent)));
   PrintFormat("GridGuardDemo: own exit, stop-out was %.2f%% away, grid closed at %.2f, equity before %.2f",
               MathAbs(pt.percent),profit,equity);
//--- the exit works as a circuit breaker, or the grid waits a day and starts again
   g_stopped=InpStopAfterExit;
   g_pause_until=TimeCurrent()+86400;
   return(true);
  }
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   if(!g_guard.LoadRules())
      return(INIT_FAILED);
   string csv=(InpRunTag=="") ? "" : "GridGuardDemo_"+InpRunTag+".csv";
   if(!g_rec.Init(GetPointer(g_guard),_Symbol,csv))
      return(INIT_FAILED);
   PrintFormat("GridGuardDemo: %s %s grid, %.2f lots every %.2f%%, take %.2f, guard %s (add %.2f%%, exit %.2f%%)",
               _Symbol,InpSell ? "sell" : "buy",InpLot,InpStepPercent,InpTakeMoney,InpUseGuard ? "on" : "off",
               InpMinPercent,InpExitPercent);
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   g_rec.ScanHistory(0);
   PrintFormat("GridGuardDemo: %d positions opened, %d adds refused, %d grids closed in profit, %d own exits (%.2f), %d stop-out deals, at most %d open, balance %.2f",
               g_adds,g_refused,g_baskets,g_exits,g_exit_loss,g_rec.Events(),g_max_positions,AccountInfoDouble(ACCOUNT_BALANCE));
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   int count=0;
   double profit=BasketProfit(count);
   DailyLine(count);
   if(count>g_max_positions)
      g_max_positions=count;
   if(g_stopped || TimeCurrent()<g_pause_until)
      return;
   if(count==0)
     {
      OpenOne();
      return;
     }
   if(OwnExit(profit))
      return;
   if(profit>=InpTakeMoney)
     {
      if(CloseAll())
         g_baskets++;
      return;
     }
//--- price that has moved against the newest position by one step
   double px=SymbolInfoDouble(_Symbol,InpSell ? SYMBOL_ASK : SYMBOL_BID);
   double move=100.0*(px-g_last_open)/g_last_open*(InpSell ? 1.0 : -1.0);
   if(move>=InpStepPercent)
      OpenOne();
  }
//+------------------------------------------------------------------+
//| Trade transaction handler                                        |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction &trans,const MqlTradeRequest &request,const MqlTradeResult &result)
  {
   g_rec.OnTransaction(trans);
  }
//+------------------------------------------------------------------+
