//+------------------------------------------------------------------+
//|                                                 StopOutGuard.mqh |
//|                                       Copyright 2026, Ali Rajput |
//+------------------------------------------------------------------+
#property copyright "Copyright 2026, Ali Rajput"
#include "StopOutMath.mqh"
//+------------------------------------------------------------------+
//| Positions of one symbol, revalued at a hypothetical bid          |
//+------------------------------------------------------------------+
class CSymbolModel : public IAccountModel
  {
private:
   string            m_symbol;     // symbol that is moved
   ENUM_SOG_MARGIN_BASIS m_basis;  // price at which the margin is charged
   double            m_spread;     // ask minus bid, held constant
   double            m_equity;     // account equity at the current prices
   double            m_margin;     // account margin at the current prices
   double            m_profit_now; // profit of the symbol's positions now
   double            m_margin_now; // margin of the symbol's positions now
   ENUM_ORDER_TYPE   m_type[];     // position types
   double            m_volume[];   // position volumes
   double            m_open[];     // open prices
   bool              Sum(const double bid,double &profit,double &margin);
public:
                     CSymbolModel(void);
   bool              Init(const string symbol,const double bid,const double ask,const double equity,
                          const double margin,const ENUM_SOG_MARGIN_BASIS basis);
   void              Add(const ENUM_ORDER_TYPE type,const double volume,const double open);
   bool              Freeze(const double bid);
   int               Count(void) const;
   double            MarginCheck(void) const;
   virtual bool      Evaluate(const double bid,double &equity,double &margin);
  };
//+------------------------------------------------------------------+
//| Constructor                                                      |
//+------------------------------------------------------------------+
CSymbolModel::CSymbolModel(void) : m_basis(SOG_MARGIN_AT_OPEN),
                                   m_spread(0.0),
                                   m_equity(0.0),
                                   m_margin(0.0),
                                   m_profit_now(0.0),
                                   m_margin_now(0.0)
  {
  }
//+------------------------------------------------------------------+
//| Start a model for one symbol from the current account state      |
//+------------------------------------------------------------------+
bool CSymbolModel::Init(const string symbol,const double bid,const double ask,const double equity,
                        const double margin,const ENUM_SOG_MARGIN_BASIS basis)
  {
   m_symbol=symbol;
   m_basis=basis;
   m_spread=ask-bid;
   m_equity=equity;
   m_margin=margin;
   ArrayResize(m_type,0);
   ArrayResize(m_volume,0);
   ArrayResize(m_open,0);
   return(bid>0.0 && ask>0.0);
  }
//+------------------------------------------------------------------+
//| Add one position (or a planned one) to the model                 |
//+------------------------------------------------------------------+
void CSymbolModel::Add(const ENUM_ORDER_TYPE type,const double volume,const double open)
  {
   int n=ArraySize(m_type);
   ArrayResize(m_type,n+1);
   ArrayResize(m_volume,n+1);
   ArrayResize(m_open,n+1);
   m_type[n]=type;
   m_volume[n]=volume;
   m_open[n]=open;
  }
//+------------------------------------------------------------------+
//| Number of modelled positions                                     |
//+------------------------------------------------------------------+
int CSymbolModel::Count(void) const
  {
   return(ArraySize(m_type));
  }
//+------------------------------------------------------------------+
//| Account margin minus the model's margin now, percent             |
//+------------------------------------------------------------------+
double CSymbolModel::MarginCheck(void) const
  {
//--- meaningful only when every position on the account is in the model
   return(m_margin>0.0 ? 100.0*(m_margin-m_margin_now)/m_margin : EMPTY_VALUE);
  }
//+------------------------------------------------------------------+
//| Profit and margin of the modelled positions at one bid           |
//+------------------------------------------------------------------+
bool CSymbolModel::Sum(const double bid,double &profit,double &margin)
  {
   profit=0.0;
   margin=0.0;
   double ask=bid+m_spread;
   double buys=0.0,sells=0.0,buy_open=0.0,sell_open=0.0;
   for(int i=0; i<ArraySize(m_type); i++)
     {
      //--- a buy closes at the bid, a sell at the ask
      bool   buy=(m_type[i]==ORDER_TYPE_BUY);
      double p=0.0;
      if(!OrderCalcProfit(m_type[i],m_symbol,m_volume[i],m_open[i],buy ? bid : ask,p))
         return(false);
      profit+=p;
      if(buy)
        {
         buys+=m_volume[i];
         buy_open+=m_volume[i]*m_open[i];
        }
      else
        {
         sells+=m_volume[i];
         sell_open+=m_volume[i]*m_open[i];
        }
     }
//--- the margin is taken on the total volume of each side, since the volume tiers measured on
//--- MetaQuotes-Demo apply to the whole side, and the larger side is charged as it was there;
//--- other hedge rules (SYMBOL_MARGIN_HEDGED), exchange or portfolio margin are not modelled;
//--- the tester kept the margin of an open position at its value from the fill, so by default
//--- each side is charged at its volume-weighted open price
   double pb=(m_basis==SOG_MARGIN_AT_OPEN && buys>0.0) ? buy_open/buys : ask;
   double ps=(m_basis==SOG_MARGIN_AT_OPEN && sells>0.0) ? sell_open/sells : bid;
   double mb=0.0,ms=0.0;
   if(buys>0.0 && !OrderCalcMargin(ORDER_TYPE_BUY,m_symbol,buys,pb,mb))
      return(false);
   if(sells>0.0 && !OrderCalcMargin(ORDER_TYPE_SELL,m_symbol,sells,ps,ms))
      return(false);
   margin=MathMax(mb,ms);
   return(true);
  }
//+------------------------------------------------------------------+
//| Store the profit and margin at the current bid as the baseline   |
//+------------------------------------------------------------------+
bool CSymbolModel::Freeze(const double bid)
  {
   return(Sum(bid,m_profit_now,m_margin_now));
  }
//+------------------------------------------------------------------+
//| Account equity and margin if only this symbol moved to bid       |
//+------------------------------------------------------------------+
bool CSymbolModel::Evaluate(const double bid,double &equity,double &margin)
  {
   double p=0.0,m=0.0;
   if(bid<=0.0 || !Sum(bid,p,m))
      return(false);
//--- only the change is applied, so swaps, commissions and other symbols stay as they are
   equity=m_equity+(p-m_profit_now);
   margin=m_margin+(m-m_margin_now);
   return(true);
  }
//+------------------------------------------------------------------+
//| Stop-out and margin call distances for an account                |
//+------------------------------------------------------------------+
class CStopOutGuard
  {
private:
   SStopOutRules     m_rules;     // stop-out settings of the account
   double            m_range;     // search range, percent of the bid
   ENUM_SOG_MARGIN_BASIS m_basis; // price at which the margin is charged
   bool              Build(CSymbolModel &model,const string symbol,double &bid,double &tick,int &others);
   void              Search(CSymbolModel &model,const string symbol,const double level,const double bid,
                            const double tick,SStopOutPoint &down,SStopOutPoint &up);
   void              Fill(SStopOutPoint &pt,const string symbol,const ENUM_SOG_STATUS status,
                          const double bid_now,const double bid_at,const double equity,const double margin);
public:
                     CStopOutGuard(void);
   bool              LoadRules(void);
   void              SetRules(const bool percent,const double call,const double stop_out);
   void              SetRange(const double percent);
   void              SetMarginBasis(const ENUM_SOG_MARGIN_BASIS basis);
   SStopOutRules     Rules(void) const;
   bool              Find(const string symbol,const double level,SStopOutPoint &down,SStopOutPoint &up);
   bool              Nearest(const string symbol,const double level,SStopOutPoint &pt);
   bool              StopOut(const string symbol,SStopOutPoint &pt);
   bool              MarginCall(const string symbol,SStopOutPoint &pt);
   bool              CanAdd(const string symbol,const ENUM_ORDER_TYPE type,const double volume,
                            const double min_percent,SStopOutPoint &after);
  };
//+------------------------------------------------------------------+
//| Constructor                                                      |
//+------------------------------------------------------------------+
CStopOutGuard::CStopOutGuard(void) : m_range(50.0),
                                     m_basis(SOG_MARGIN_AT_OPEN)
  {
   m_rules.percent=true;
   m_rules.call=100.0;
   m_rules.stop_out=50.0;
  }
//+------------------------------------------------------------------+
//| Read the margin call and stop-out levels of the account          |
//+------------------------------------------------------------------+
bool CStopOutGuard::LoadRules(void)
  {
   m_rules.percent=((ENUM_ACCOUNT_STOPOUT_MODE)AccountInfoInteger(ACCOUNT_MARGIN_SO_MODE)==ACCOUNT_STOPOUT_MODE_PERCENT);
   m_rules.call=AccountInfoDouble(ACCOUNT_MARGIN_SO_CALL);
   m_rules.stop_out=AccountInfoDouble(ACCOUNT_MARGIN_SO_SO);
   return(m_rules.stop_out>0.0);
  }
//+------------------------------------------------------------------+
//| Set the levels by hand, for tests or a stricter own limit        |
//+------------------------------------------------------------------+
void CStopOutGuard::SetRules(const bool percent,const double call,const double stop_out)
  {
   m_rules.percent=percent;
   m_rules.call=call;
   m_rules.stop_out=stop_out;
  }
//+------------------------------------------------------------------+
//| Search range on each side of the bid, percent of the bid         |
//+------------------------------------------------------------------+
void CStopOutGuard::SetRange(const double percent)
  {
   m_range=MathMax(percent,0.01);
  }
//+------------------------------------------------------------------+
//| Margin at the open prices or at the moved price                  |
//+------------------------------------------------------------------+
void CStopOutGuard::SetMarginBasis(const ENUM_SOG_MARGIN_BASIS basis)
  {
//--- margin_check shows which basis matches the account: the wrong one drifts with the price
   m_basis=basis;
  }
//+------------------------------------------------------------------+
//| Levels in use                                                    |
//+------------------------------------------------------------------+
SStopOutRules CStopOutGuard::Rules(void) const
  {
   return(m_rules);
  }
//+------------------------------------------------------------------+
//| Put the open positions of one symbol into a model                |
//+------------------------------------------------------------------+
bool CStopOutGuard::Build(CSymbolModel &model,const string symbol,double &bid,double &tick,int &others)
  {
   others=0;
   MqlTick t;
   if(!SymbolInfoTick(symbol,t) || t.bid<=0.0)
      return(false);
   bid=t.bid;
   tick=SymbolInfoDouble(symbol,SYMBOL_TRADE_TICK_SIZE);
   if(tick<=0.0)
      tick=SymbolInfoDouble(symbol,SYMBOL_POINT);
   if(!model.Init(symbol,t.bid,t.ask,AccountInfoDouble(ACCOUNT_EQUITY),AccountInfoDouble(ACCOUNT_MARGIN),m_basis))
      return(false);
   for(int i=PositionsTotal()-1; i>=0; i--)
     {
      if(PositionGetSymbol(i)!=symbol)
        {
         others++;
         continue;
        }
      ENUM_ORDER_TYPE type=((ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY) ?
                           ORDER_TYPE_BUY : ORDER_TYPE_SELL;
      model.Add(type,PositionGetDouble(POSITION_VOLUME),PositionGetDouble(POSITION_PRICE_OPEN));
     }
   return(true);
  }
//+------------------------------------------------------------------+
//| Copy one search result into a result structure                   |
//+------------------------------------------------------------------+
void CStopOutGuard::Fill(SStopOutPoint &pt,const string symbol,const ENUM_SOG_STATUS status,
                         const double bid_now,const double bid_at,const double equity,const double margin)
  {
   pt.symbol=symbol;
   pt.status=status;
   pt.bid_now=bid_now;
   pt.bid_at=bid_at;
   double point=SymbolInfoDouble(symbol,SYMBOL_POINT);
   bool found=(status==SOG_OK || status==SOG_ALREADY_BELOW);
   pt.points=(found && point>0.0) ? (bid_at-bid_now)/point : 0.0;
   pt.percent=(found && bid_now>0.0) ? 100.0*(bid_at-bid_now)/bid_now : 0.0;
   pt.equity=equity;
   pt.margin=margin;
   pt.margin_check=EMPTY_VALUE;
  }
//+------------------------------------------------------------------+
//| Search below and above the bid for the given level               |
//+------------------------------------------------------------------+
void CStopOutGuard::Search(CSymbolModel &model,const string symbol,const double level,const double bid,
                           const double tick,SStopOutPoint &down,SStopOutPoint &up)
  {
   double at=0.0,e=0.0,m=0.0;
   double low=CStopOutMath::SnapToTick(bid*(1.0-m_range/100.0),tick,false);
   ENUM_SOG_STATUS s=CStopOutMath::Solve(model,m_rules.percent,level,bid,MathMax(low,tick),tick,at,e,m);
   Fill(down,symbol,s,bid,at,e,m);
   double high=CStopOutMath::SnapToTick(bid*(1.0+m_range/100.0),tick,true);
   s=CStopOutMath::Solve(model,m_rules.percent,level,bid,high,tick,at,e,m);
   Fill(up,symbol,s,bid,at,e,m);
  }
//+------------------------------------------------------------------+
//| Level price below and above the bid, other symbols held still    |
//+------------------------------------------------------------------+
bool CStopOutGuard::Find(const string symbol,const double level,SStopOutPoint &down,SStopOutPoint &up)
  {
   CSymbolModel model;
   double bid=0.0,tick=0.0;
   int    others=0;
   if(!Build(model,symbol,bid,tick,others))
     {
      Fill(down,symbol,SOG_CALC_FAILED,0.0,0.0,0.0,0.0);
      Fill(up,symbol,SOG_CALC_FAILED,0.0,0.0,0.0,0.0);
      return(false);
     }
   if(model.Count()==0)
     {
      Fill(down,symbol,SOG_NO_POSITIONS,bid,0.0,0.0,0.0);
      Fill(up,symbol,SOG_NO_POSITIONS,bid,0.0,0.0,0.0);
      return(true);
     }
   if(!model.Freeze(bid))
     {
      Fill(down,symbol,SOG_CALC_FAILED,bid,0.0,0.0,0.0);
      Fill(up,symbol,SOG_CALC_FAILED,bid,0.0,0.0,0.0);
      return(false);
     }
   Search(model,symbol,level,bid,tick,down,up);
//--- with no other symbol open, the model's margin now must equal the account margin
   if(others==0)
     {
      down.margin_check=model.MarginCheck();
      up.margin_check=down.margin_check;
     }
   return(true);
  }
//+------------------------------------------------------------------+
//| The closer of the two directions                                 |
//+------------------------------------------------------------------+
bool CStopOutGuard::Nearest(const string symbol,const double level,SStopOutPoint &pt)
  {
   SStopOutPoint down,up;
   bool ok=Find(symbol,level,down,up);
   bool d=(down.status==SOG_OK || down.status==SOG_ALREADY_BELOW);
   bool u=(up.status==SOG_OK || up.status==SOG_ALREADY_BELOW);
   if(d && (!u || MathAbs(down.points)<=MathAbs(up.points)))
      pt=down;
   else
      if(u)
         pt=up;
      else
         pt=(down.status!=SOG_OUT_OF_RANGE) ? down : up;
   return(ok);
  }
//+------------------------------------------------------------------+
//| Threshold distance after a planned market order is filled        |
//+------------------------------------------------------------------+
bool CStopOutGuard::CanAdd(const string symbol,const ENUM_ORDER_TYPE type,const double volume,
                           const double min_percent,SStopOutPoint &after)
  {
//--- this is a check of the stop-out distance only, not an order check: free margin, stop and
//--- freeze levels, slippage, partial fills and the spread at the fill are left to OrderCheck()
   CSymbolModel model;
   double bid=0.0,tick=0.0;
   int    others=0;
   if(!Build(model,symbol,bid,tick,others) || !model.Freeze(bid))
     {
      Fill(after,symbol,SOG_CALC_FAILED,bid,0.0,0.0,0.0);
      return(false);
     }
   double check=(others==0) ? model.MarginCheck() : EMPTY_VALUE;
//--- the new position joins the model after the baseline, so its spread cost and margin count
   MqlTick t;
   SymbolInfoTick(symbol,t);
   model.Add(type,volume,type==ORDER_TYPE_BUY ? t.ask : t.bid);
   SStopOutPoint down,up;
   Search(model,symbol,m_rules.stop_out,bid,tick,down,up);
   bool d=(down.status==SOG_OK || down.status==SOG_ALREADY_BELOW);
   bool u=(up.status==SOG_OK || up.status==SOG_ALREADY_BELOW);
   if(d && (!u || MathAbs(down.points)<=MathAbs(up.points)))
      after=down;
   else
      after=u ? up : down;
   after.margin_check=check;
//--- out of range on both sides only says the threshold is further away than the range
   if(!d && !u)
      return(down.status==SOG_OUT_OF_RANGE && up.status==SOG_OUT_OF_RANGE && min_percent<=m_range);
   return(after.status==SOG_OK && MathAbs(after.percent)>=min_percent);
  }
//+------------------------------------------------------------------+
//| Nearest stop-out price of a symbol                               |
//+------------------------------------------------------------------+
bool CStopOutGuard::StopOut(const string symbol,SStopOutPoint &pt)
  {
   return(Nearest(symbol,m_rules.stop_out,pt));
  }
//+------------------------------------------------------------------+
//| Nearest margin call price of a symbol                            |
//+------------------------------------------------------------------+
bool CStopOutGuard::MarginCall(const string symbol,SStopOutPoint &pt)
  {
   return(Nearest(symbol,m_rules.call,pt));
  }
//+------------------------------------------------------------------+
