//+------------------------------------------------------------------+
//|                                                   PropRules.mqh  |
//|        Daily-loss and maximum-drawdown guard for Expert Advisors |
//+------------------------------------------------------------------+
#property strict

#include <Trade\Trade.mqh>

//--- how the daily loss is measured
enum ENUM_PROP_DAY_BASE
  {
   PROP_DAY_BALANCE = 0,   // balance at the daily reset
   PROP_DAY_HIGHER  = 1    // higher of balance and equity at the reset
  };

//--- how the maximum drawdown is measured
enum ENUM_PROP_DD_TYPE
  {
   PROP_DD_STATIC   = 0,   // fixed floor below the initial balance
   PROP_DD_TRAILING = 1    // floor follows the highest balance/equity reached
  };

//--- why trading is blocked
enum ENUM_PROP_LOCK
  {
   PROP_LOCK_NONE  = 0,
   PROP_LOCK_DAILY = 1,    // until the next daily reset
   PROP_LOCK_TOTAL = 2     // until the user clears it
  };

//+------------------------------------------------------------------+
//| CPropRules                                                       |
//+------------------------------------------------------------------+
class CPropRules
  {
private:
   //--- settings
   double            m_daily_pct;      // daily loss limit, % of the day base
   double            m_dd_pct;         // maximum drawdown, % of initial balance or peak
   double            m_buffer_pct;     // safety buffer, % of each limit kept unused
   double            m_initial;        // initial account size
   int               m_reset_hour;     // server hour of the daily reset (0-23)
   ENUM_PROP_DAY_BASE m_day_base_mode;
   ENUM_PROP_DD_TYPE m_dd_type;
   ulong             m_magic;          // 0 = manage every position on the account
   string            m_prefix;         // prefix for terminal global variables
   //--- state
   datetime          m_day_start;
   double            m_day_base;
   double            m_peak;
   ENUM_PROP_LOCK    m_lock;
   CTrade            m_trade;

   string            GVName(const string key) const;
   double            GVGet(const string key,const double def) const;
   void              GVSet(const string key,const double value) const;
   datetime          CurrentDayStart(void) const;
   void              RollDay(void);
   bool              Owns(const ulong ticket) const;

public:
                     CPropRules(void);
   bool              Init(const double daily_pct,const double dd_pct,const double initial_balance,
                          const int reset_hour,const ENUM_PROP_DAY_BASE day_base,
                          const ENUM_PROP_DD_TYPE dd_type,const double buffer_pct=10.0,
                          const ulong magic=0);
   void              OnTick(void);
   bool              CanOpen(const ENUM_ORDER_TYPE type,const string symbol,const double volume,
                             const double price,const double sl);
   void              CloseAll(void);
   void              ClearLock(void);
   //--- read-only information
   double            DailyLimit(void) const { return m_day_base*m_daily_pct/100.0; }
   double            DailyFloor(void) const { return m_day_base-DailyLimit(); }
   double            DrawdownBase(void) const { return m_dd_type==PROP_DD_TRAILING ? m_peak : m_initial; }
   double            DrawdownLimit(void) const { return DrawdownBase()*m_dd_pct/100.0; }
   double            DrawdownFloor(void) const { return DrawdownBase()-DrawdownLimit(); }
   double            DailyRoom(void) const { return AccountInfoDouble(ACCOUNT_EQUITY)-DailyFloor(); }
   double            DrawdownRoom(void) const { return AccountInfoDouble(ACCOUNT_EQUITY)-DrawdownFloor(); }
   double            Room(void) const { return MathMin(DailyRoom(),DrawdownRoom()); }
   ENUM_PROP_LOCK    Lock(void) const { return m_lock; }
   bool              IsLocked(void) const { return m_lock!=PROP_LOCK_NONE; }
  };

//+------------------------------------------------------------------+
CPropRules::CPropRules(void) : m_daily_pct(5.0),m_dd_pct(10.0),m_buffer_pct(10.0),m_initial(0.0),
                               m_reset_hour(0),m_day_base_mode(PROP_DAY_BALANCE),
                               m_dd_type(PROP_DD_STATIC),m_magic(0),m_prefix(""),
                               m_day_start(0),m_day_base(0.0),m_peak(0.0),m_lock(PROP_LOCK_NONE)
  {
  }

//+------------------------------------------------------------------+
//| Global variable helpers: one set of values per trading account   |
//+------------------------------------------------------------------+
string CPropRules::GVName(const string key) const
  {
   return(m_prefix+key);
  }

double CPropRules::GVGet(const string key,const double def) const
  {
   string name=GVName(key);
   return(GlobalVariableCheck(name) ? GlobalVariableGet(name) : def);
  }

void CPropRules::GVSet(const string key,const double value) const
  {
   GlobalVariableSet(GVName(key),value);
  }

//+------------------------------------------------------------------+
//| Start of the current trading day according to the reset hour     |
//+------------------------------------------------------------------+
datetime CPropRules::CurrentDayStart(void) const
  {
   datetime now=TimeTradeServer();
   if(now==0)
      now=TimeCurrent();
   MqlDateTime t;
   TimeToStruct(now,t);
   t.hour=m_reset_hour;
   t.min=0;
   t.sec=0;
   datetime start=StructToTime(t);
   if(start>now)
      start-=86400;
   return(start);
  }

//+------------------------------------------------------------------+
//| Record a new day base when the reset time has passed             |
//+------------------------------------------------------------------+
void CPropRules::RollDay(void)
  {
   datetime start=CurrentDayStart();
   if(start==m_day_start && m_day_base>0.0)
      return;
   double balance=AccountInfoDouble(ACCOUNT_BALANCE);
   double equity =AccountInfoDouble(ACCOUNT_EQUITY);
   m_day_start=start;
   m_day_base =(m_day_base_mode==PROP_DAY_HIGHER) ? MathMax(balance,equity) : balance;
   GVSet("day",(double)m_day_start);
   GVSet("daybase",m_day_base);
//--- a daily lock ends at the reset, a total lock does not
   if(m_lock==PROP_LOCK_DAILY)
     {
      m_lock=PROP_LOCK_NONE;
      GVSet("lock",(double)m_lock);
      PrintFormat("PropRules: new day, daily lock cleared. Day base %.2f",m_day_base);
     }
  }

//+------------------------------------------------------------------+
//| Is this position managed by the guard?                           |
//+------------------------------------------------------------------+
bool CPropRules::Owns(const ulong ticket) const
  {
   if(!PositionSelectByTicket(ticket))
      return(false);
   return(m_magic==0 || (ulong)PositionGetInteger(POSITION_MAGIC)==m_magic);
  }

//+------------------------------------------------------------------+
//| Initialisation: restore state saved by a previous session        |
//+------------------------------------------------------------------+
bool CPropRules::Init(const double daily_pct,const double dd_pct,const double initial_balance,
                      const int reset_hour,const ENUM_PROP_DAY_BASE day_base,
                      const ENUM_PROP_DD_TYPE dd_type,const double buffer_pct,
                      const ulong magic)
  {
   if(daily_pct<=0.0 || dd_pct<=0.0 || reset_hour<0 || reset_hour>23 ||
      buffer_pct<0.0 || buffer_pct>=100.0)
     {
      Print("PropRules: invalid settings");
      return(false);
     }
   m_daily_pct    =daily_pct;
   m_dd_pct       =dd_pct;
   m_buffer_pct   =buffer_pct;
   m_reset_hour   =reset_hour;
   m_day_base_mode=day_base;
   m_dd_type      =dd_type;
   m_magic        =magic;
   m_prefix       ="PR_"+IntegerToString(AccountInfoInteger(ACCOUNT_LOGIN))+"_";
   m_trade.SetExpertMagicNumber(magic);
//--- initial size: input value, then the saved value, then the current balance
   m_initial=initial_balance;
   if(m_initial<=0.0)
      m_initial=GVGet("init",0.0);
   if(m_initial<=0.0)
      m_initial=AccountInfoDouble(ACCOUNT_BALANCE);
   GVSet("init",m_initial);
//--- restore the rest of the state
   m_peak     =MathMax(m_initial,GVGet("peak",m_initial));
   m_day_start=(datetime)GVGet("day",0.0);
   m_day_base =GVGet("daybase",0.0);
   m_lock     =(ENUM_PROP_LOCK)(int)GVGet("lock",(double)PROP_LOCK_NONE);
   RollDay();
   PrintFormat("PropRules: initial %.2f, day base %.2f, peak %.2f, lock %d",
               m_initial,m_day_base,m_peak,(int)m_lock);
   return(true);
  }

//+------------------------------------------------------------------+
//| Call on every tick: update state and enforce the limits          |
//+------------------------------------------------------------------+
void CPropRules::OnTick(void)
  {
   RollDay();
//--- trailing peak
   double high=MathMax(AccountInfoDouble(ACCOUNT_BALANCE),AccountInfoDouble(ACCOUNT_EQUITY));
   if(high>m_peak)
     {
      m_peak=high;
      GVSet("peak",m_peak);
     }
//--- remaining room against each limit, minus the safety buffer
   double daily_buffer=DailyLimit()*m_buffer_pct/100.0;
   double dd_buffer   =DrawdownLimit()*m_buffer_pct/100.0;
   ENUM_PROP_LOCK hit=PROP_LOCK_NONE;
   if(DrawdownRoom()<=dd_buffer)
      hit=PROP_LOCK_TOTAL;
   else
      if(DailyRoom()<=daily_buffer)
         hit=PROP_LOCK_DAILY;
   if(hit==PROP_LOCK_NONE)
      return;
//--- a total lock always wins over a daily lock
   if(hit>m_lock)
     {
      m_lock=hit;
      GVSet("lock",(double)m_lock);
      PrintFormat("PropRules: %s limit buffer reached. Equity %.2f, daily room %.2f, drawdown room %.2f",
                  hit==PROP_LOCK_TOTAL ? "drawdown" : "daily",
                  AccountInfoDouble(ACCOUNT_EQUITY),DailyRoom(),DrawdownRoom());
     }
   CloseAll();
  }

//+------------------------------------------------------------------+
//| Pre-trade check: would this order fit in the remaining room?     |
//+------------------------------------------------------------------+
bool CPropRules::CanOpen(const ENUM_ORDER_TYPE type,const string symbol,const double volume,
                         const double price,const double sl)
  {
   if(IsLocked())
     {
      Print("PropRules: order blocked, trading is locked");
      return(false);
     }
   if(sl<=0.0)
     {
      Print("PropRules: order blocked, a stop loss is required to measure the risk");
      return(false);
     }
   double profit=0.0;
   if(!OrderCalcProfit(type,symbol,volume,price,sl,profit))
     {
      PrintFormat("PropRules: OrderCalcProfit failed, error %d",GetLastError());
      return(false);
     }
   double risk=-profit;   // loss if the stop is hit, in account currency
//--- usable room = room against the nearer limit, minus its buffer
   double usable=MathMin(DailyRoom()-DailyLimit()*m_buffer_pct/100.0,
                         DrawdownRoom()-DrawdownLimit()*m_buffer_pct/100.0);
   if(risk>usable)
     {
      PrintFormat("PropRules: order blocked, risk %.2f exceeds usable room %.2f",risk,usable);
      return(false);
     }
   return(true);
  }

//+------------------------------------------------------------------+
//| Close every managed position and delete managed pending orders   |
//+------------------------------------------------------------------+
void CPropRules::CloseAll(void)
  {
   for(int i=PositionsTotal()-1; i>=0; i--)
     {
      ulong ticket=PositionGetTicket(i);
      if(ticket==0 || !Owns(ticket))
         continue;
      if(!m_trade.PositionClose(ticket))
         PrintFormat("PropRules: failed to close #%I64u, retcode %u",ticket,m_trade.ResultRetcode());
     }
   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      ulong ticket=OrderGetTicket(i);
      if(ticket==0)
         continue;
      if(m_magic!=0 && (ulong)OrderGetInteger(ORDER_MAGIC)!=m_magic)
         continue;
      m_trade.OrderDelete(ticket);
     }
  }

//+------------------------------------------------------------------+
//| Manual reset of a total lock, e.g. after a new account is issued |
//+------------------------------------------------------------------+
void CPropRules::ClearLock(void)
  {
   m_lock=PROP_LOCK_NONE;
   GVSet("lock",(double)m_lock);
  }
//+------------------------------------------------------------------+
