//+------------------------------------------------------------------+
//| PropGuard.mq5                                                     |
//| Prop Guard 1.0.0 - an open-source account guard for MetaTrader 5  |
//| Copyright (c) 2026 AtaQuant. MIT licence, see LICENSE.txt.        |
//| https://ataquant.com/tools/prop-guard/                            |
//+------------------------------------------------------------------+
//| Prop Guard watches the account's equity and locks trading when a  |
//| limit is reached:                                                 |
//|  - daily loss lock: equity falls the set amount below the day's   |
//|    start. Closes everything and stays locked until the next       |
//|    trading day.                                                   |
//|  - maximum drawdown lock: equity reaches the drawdown floor       |
//|    (static, or trailing the highest equity). Closes everything    |
//|    and stays locked until you reset it.                           |
//|  - profit target: equity reaches the target. Closes everything    |
//|    and stays locked until you reset it.                           |
//|  - news-time lock: a window around each time you enter. Positions |
//|    opened inside the window are closed (optionally the open ones  |
//|    too when the window starts).                                   |
//| While a lock is on, every position in Prop Guard's scope is       |
//| closed as soon as it appears and pending orders are deleted.      |
//| Prop Guard never opens a trade.                                   |
//|                                                                   |
//| Attach it to ONE chart of the account (any symbol, any timeframe) |
//| and allow Algo Trading. The terminal must stay running (a VPS).   |
//| All times are the trade server's time.                            |
//+------------------------------------------------------------------+
#property copyright   "Copyright (c) 2026 AtaQuant (MIT licence)"
#property link        "https://ataquant.com/tools/prop-guard/"
#property version     "1.00"
#property description "Prop Guard 1.0.0: daily loss lock, maximum drawdown lock, close all at the profit target and a news-time lock, with an on-chart status panel."
#property description "Open source (MIT). It never opens a trade."

#include <Trade\Trade.mqh>

#define PG_VERSION "1.0.0"

//--- lock states, from the mildest to the most severe
enum ENUM_PG_LOCK
  {
   PG_LOCK_NONE = 0,
   PG_LOCK_NEWS = 1,
   PG_LOCK_DAILY = 2,
   PG_LOCK_TARGET = 3,
   PG_LOCK_DRAWDOWN = 4
  };

enum ENUM_PG_DAY_BASE
  {
   PG_DAY_HIGHER = 0,   // Higher of balance and equity
   PG_DAY_BALANCE = 1,  // Balance
   PG_DAY_EQUITY = 2    // Equity
  };

enum ENUM_PG_DD_MODE
  {
   PG_DD_STATIC = 0,    // Static: from the starting balance
   PG_DD_TRAILING = 1   // Trailing: from the highest equity
  };

input group "Daily loss lock"
input double           InpDailyLossPct     = 5.0;            // Daily loss limit, % of the day's start (0 = off)
input double           InpDailyLossMoney   = 0.0;            // Daily loss limit in account currency (0 = off)
input ENUM_PG_DAY_BASE InpDayBase          = PG_DAY_HIGHER;  // The day's start is
input int              InpDayStartHour     = 0;              // New trading day starts at (server hour, 0-23)

input group "Maximum drawdown lock"
input double           InpMaxDrawdownPct   = 10.0;           // Maximum drawdown, % of the starting balance (0 = off)
input double           InpMaxDrawdownMoney = 0.0;            // Maximum drawdown in account currency (0 = off)
input ENUM_PG_DD_MODE  InpDrawdownMode     = PG_DD_STATIC;   // Drawdown is measured
input bool             InpTrailStopsAtStart = true;          // Trailing: the floor stops rising at the starting balance
input double           InpStartBalance     = 0.0;            // Starting balance (0 = balance when Prop Guard first runs)

input group "Profit target"
input double           InpTargetPct        = 0.0;            // Close all at a profit of % of the starting balance (0 = off)
input double           InpTargetMoney      = 0.0;            // Close all at a profit in account currency (0 = off)

input group "News-time lock"
input string           InpNewsTimes        = "";             // News times, server time (2026.12.04 15:30; 2026.12.10 15:30)
input int              InpNewsBefore       = 5;              // Lock starts this many minutes before
input int              InpNewsAfter        = 5;              // Lock ends this many minutes after
input bool             InpNewsCloseOpen    = false;          // Also close the positions already open when the lock starts

input group "Scope and actions"
input long             InpMagic            = -1;             // Guard only this magic number (-1 = every position)
input bool             InpDeletePending    = true;           // Delete pending orders while a lock is on
input int              InpDeviationPoints  = 30;             // Maximum slippage when closing, points
input bool             InpAlerts           = true;           // Alert and push notification when a lock starts
input bool             InpResetState       = false;          // Reset the starting balance, peak and locks (once)
input bool             InpShowPanel        = true;           // Show the status panel
input int              InpPanelX           = 12;             // Panel distance from the left edge, px
input int              InpPanelY           = 24;             // Panel distance from the top edge, px

//+------------------------------------------------------------------+
//| The rules: pure functions over numbers and times, no terminal    |
//| calls, so the same code runs in the EA and in the self-test.     |
//+------------------------------------------------------------------+
struct PGConfig
  {
   double            dailyPct;
   double            dailyMoney;
   int               dayBase;
   int               dayStartHour;
   double            ddPct;
   double            ddMoney;
   int               ddMode;
   bool              trailStopsAtStart;
   double            targetPct;
   double            targetMoney;
   int               newsBefore;
   int               newsAfter;
  };

struct PGState
  {
   datetime          day;        // start of the current trading day
   double            dayStart;   // the day's reference amount
   double            start;      // starting balance
   double            peak;       // highest equity seen
   int               lock;       // lasting lock: none, daily, target or drawdown
   datetime          lockedAt;
   datetime          lockUntil;  // daily lock: the next day's start; 0 = until reset
  };

//--- start of the trading day that contains t (the day starts at startHour, server time)
datetime PG_TradingDay(const datetime t, const int startHour)
  {
   long h = (startHour < 0 || startHour > 23) ? 0 : startHour;
   long s = (long)t - h * 3600;
   s -= s % 86400;
   return (datetime)(s + h * 3600);
  }

//--- the day's reference amount
double PG_DayBase(const int base, const double balance, const double equity)
  {
   if(base == PG_DAY_BALANCE)
      return balance;
   if(base == PG_DAY_EQUITY)
      return equity;
   return MathMax(balance, equity);
  }

//--- a limit given as % of an amount and/or as money; both set = the smaller; 0 = off
double PG_Limit(const double pct, const double money, const double amount)
  {
   double a = (pct > 0.0 && amount > 0.0) ? amount * pct / 100.0 : 0.0;
   double b = money > 0.0 ? money : 0.0;
   if(a > 0.0 && b > 0.0)
      return MathMin(a, b);
   return a > 0.0 ? a : b;
  }

double PG_DailyLimit(const PGConfig &c, const PGState &s)
  {
   return PG_Limit(c.dailyPct, c.dailyMoney, s.dayStart);
  }

double PG_DrawdownLimit(const PGConfig &c, const PGState &s)
  {
   return PG_Limit(c.ddPct, c.ddMoney, s.start);
  }

//--- equity at or below the floor locks; -1 = drawdown lock off
double PG_DrawdownFloor(const PGConfig &c, const PGState &s)
  {
   double lim = PG_DrawdownLimit(c, s);
   if(lim <= 0.0)
      return -1.0;
   if(c.ddMode != PG_DD_TRAILING)
      return s.start - lim;
   double f = MathMax(s.peak, s.start) - lim;
   if(c.trailStopsAtStart)
      f = MathMin(f, s.start);
   return f;
  }

//--- equity at or above the level closes all; 0 = target off
double PG_TargetLevel(const PGConfig &c, const PGState &s)
  {
   double lim = PG_Limit(c.targetPct, c.targetMoney, s.start);
   return lim > 0.0 ? s.start + lim : 0.0;
  }

//--- one news time "yyyy.mm.dd hh:mi" (also "-" or "/" between the date parts); 0 = not a valid time
datetime PG_ParseTime(string p)
  {
   StringReplace(p, "-", ".");
   StringReplace(p, "/", ".");
   if(StringLen(p) != 16)
      return 0;
   for(int i = 0; i < 16; i++)
     {
      ushort ch = StringGetCharacter(p, i);
      if(i == 4 || i == 7)
        {
         if(ch != '.')
            return 0;
        }
      else
         if(i == 10)
           {
            if(ch != ' ')
               return 0;
           }
         else
            if(i == 13)
              {
               if(ch != ':')
                  return 0;
              }
            else
               if(ch < '0' || ch > '9')
                  return 0;
     }
   MqlDateTime dt;
   ZeroMemory(dt);
   dt.year = (int)StringToInteger(StringSubstr(p, 0, 4));
   dt.mon = (int)StringToInteger(StringSubstr(p, 5, 2));
   dt.day = (int)StringToInteger(StringSubstr(p, 8, 2));
   dt.hour = (int)StringToInteger(StringSubstr(p, 11, 2));
   dt.min = (int)StringToInteger(StringSubstr(p, 14, 2));
   if(dt.year < 2000 || dt.year > 2100 || dt.mon < 1 || dt.mon > 12 || dt.day < 1 || dt.day > 31 || dt.hour > 23 || dt.min > 59)
      return 0;
   datetime t = StructToTime(dt);
   MqlDateTime back;
   TimeToStruct(t, back);
   if(back.year != dt.year || back.mon != dt.mon || back.day != dt.day)
      return 0; // e.g. 30 February
   return t;
  }

//--- the news list: times separated by ";", "," or new lines; sorted. `bad` lists what was not understood.
int PG_ParseNews(const string text, datetime &times[], string &bad)
  {
   ArrayResize(times, 0);
   bad = "";
   string s = text;
   StringReplace(s, "\r", ";");
   StringReplace(s, "\n", ";");
   StringReplace(s, ",", ";");
   string parts[];
   int n = StringSplit(s, ';', parts);
   for(int i = 0; i < n; i++)
     {
      string p = parts[i];
      StringTrimLeft(p);
      StringTrimRight(p);
      if(StringLen(p) == 0)
         continue;
      datetime t = PG_ParseTime(p);
      if(t == 0)
        {
         bad += (bad == "" ? "" : ", ") + p;
         continue;
        }
      int k = ArraySize(times);
      ArrayResize(times, k + 1);
      times[k] = t;
     }
   if(ArraySize(times) > 1)
      ArraySort(times);
   return ArraySize(times);
  }

//--- is `now` inside a news window? from/to: the window (overlapping windows that contain now are joined)
bool PG_NewsWindow(const datetime now, const datetime &times[], const int before, const int after, datetime &from, datetime &to)
  {
   from = 0;
   to = 0;
   long b = before > 0 ? before : 0;
   long a = after > 0 ? after : 0;
   for(int i = 0; i < ArraySize(times); i++)
     {
      datetime f = (datetime)((long)times[i] - b * 60);
      datetime e = (datetime)((long)times[i] + a * 60);
      if(now >= f && now < e)
        {
         if(from == 0 || f < from)
            from = f;
         if(e > to)
            to = e;
        }
     }
   return to > 0;
  }

//--- start of the next news window after now; 0 = none
datetime PG_NextNews(const datetime now, const datetime &times[], const int before)
  {
   long b = before > 0 ? before : 0;
   for(int i = 0; i < ArraySize(times); i++)
     {
      datetime f = (datetime)((long)times[i] - b * 60);
      if(f > now)
         return f;
     }
   return 0;
  }

//+------------------------------------------------------------------+
//| One check: rolls the trading day, follows the peak, starts a     |
//| lasting lock when a limit is reached (only a more severe lock    |
//| replaces one that is on), ends a daily lock at the next day.     |
//| Returns the lock in force; `started` is true when a lasting lock |
//| started in this check.                                           |
//+------------------------------------------------------------------+
int PG_Evaluate(const PGConfig &c, PGState &s, const double balance, const double equity, const datetime now,
                const datetime &news[], datetime &newsFrom, datetime &newsTo, bool &started)
  {
   started = false;
   newsFrom = 0;
   newsTo = 0;
   if(s.start <= 0.0)
      s.start = balance;
   if(s.peak < s.start)
      s.peak = s.start;
   datetime day = PG_TradingDay(now, c.dayStartHour);
   if(day != s.day)
     {
      s.day = day;
      s.dayStart = PG_DayBase(c.dayBase, balance, equity);
     }
   if(s.lock == PG_LOCK_DAILY && s.lockUntil > 0 && now >= s.lockUntil)
     {
      s.lock = PG_LOCK_NONE;
      s.lockedAt = 0;
      s.lockUntil = 0;
     }
   if(equity > s.peak)
      s.peak = equity;
   int hit = PG_LOCK_NONE;
   double floor = PG_DrawdownFloor(c, s);
   double target = PG_TargetLevel(c, s);
   double daily = PG_DailyLimit(c, s);
   if(floor >= 0.0 && equity <= floor)
      hit = PG_LOCK_DRAWDOWN;
   else
      if(target > 0.0 && equity >= target)
         hit = PG_LOCK_TARGET;
      else
         if(daily > 0.0 && s.dayStart - equity >= daily)
            hit = PG_LOCK_DAILY;
   if(hit > s.lock)
     {
      s.lock = hit;
      s.lockedAt = now;
      s.lockUntil = hit == PG_LOCK_DAILY ? (datetime)((long)day + 86400) : 0;
      started = true;
     }
   if(s.lock != PG_LOCK_NONE)
      return s.lock;
   if(PG_NewsWindow(now, news, c.newsBefore, c.newsAfter, newsFrom, newsTo))
      return PG_LOCK_NEWS;
   return PG_LOCK_NONE;
  }

string PG_LockName(const int lock)
  {
   switch(lock)
     {
      case PG_LOCK_NEWS:
         return "news";
      case PG_LOCK_DAILY:
         return "daily loss";
      case PG_LOCK_TARGET:
         return "profit target";
      case PG_LOCK_DRAWDOWN:
         return "maximum drawdown";
     }
   return "none";
  }

//--- 1234567.891 -> "1,234,567.89"
string PG_Money(const double v)
  {
   string s = DoubleToString(MathAbs(v), 2);
   int dot = StringFind(s, ".");
   string whole = dot >= 0 ? StringSubstr(s, 0, dot) : s;
   string frac = dot >= 0 ? StringSubstr(s, dot) : "";
   string out = "";
   int n = StringLen(whole);
   for(int i = 0; i < n; i++)
     {
      if(i > 0 && (n - i) % 3 == 0)
         out += ",";
      out += StringSubstr(whole, i, 1);
     }
   return (v < 0.0 && out + frac != "0.00" ? "-" : "") + out + frac;
  }

//--- the stored state (terminal global variables, kept across restarts)
void PG_SaveTo(const string prefix, const PGState &s)
  {
   GlobalVariableSet(prefix + "day", (double)s.day);
   GlobalVariableSet(prefix + "daystart", s.dayStart);
   GlobalVariableSet(prefix + "start", s.start);
   GlobalVariableSet(prefix + "peak", s.peak);
   GlobalVariableSet(prefix + "lock", (double)s.lock);
   GlobalVariableSet(prefix + "lockedat", (double)s.lockedAt);
   GlobalVariableSet(prefix + "until", (double)s.lockUntil);
  }

bool PG_LoadFrom(const string prefix, PGState &s)
  {
   ZeroMemory(s);
   if(!GlobalVariableCheck(prefix + "start"))
      return false;
   s.day = (datetime)GlobalVariableGet(prefix + "day");
   s.dayStart = GlobalVariableGet(prefix + "daystart");
   s.start = GlobalVariableGet(prefix + "start");
   s.peak = GlobalVariableGet(prefix + "peak");
   s.lock = (int)GlobalVariableGet(prefix + "lock");
   s.lockedAt = (datetime)GlobalVariableGet(prefix + "lockedat");
   s.lockUntil = (datetime)GlobalVariableGet(prefix + "until");
   if(s.lock < PG_LOCK_NONE || s.lock > PG_LOCK_DRAWDOWN || s.lock == PG_LOCK_NEWS)
      s.lock = PG_LOCK_NONE;
   return true;
  }

void PG_ClearStored(const string prefix)
  {
   GlobalVariablesDeleteAll(prefix);
  }

#ifndef PROPGUARD_TEST
//+------------------------------------------------------------------+
//| The EA: reads the account, applies the rules, closes positions   |
//| while a lock is on, draws the status panel.                      |
//+------------------------------------------------------------------+
CTrade   g_trade;
PGConfig g_cfg;
PGState  g_st;
datetime g_news[];
string   g_newsBad = "";
string   g_prefix = "";
bool     g_ready = false;
int      g_lock = PG_LOCK_NONE;
datetime g_newsFrom = 0;
datetime g_newsTo = 0;
ulong    g_nextTry = 0;          // GetTickCount64() before which no new close attempt is made after a failure
uint     g_backoff = 0;          // ms
datetime g_lastFailLog = 0;
datetime g_lastSave = 0;
string   g_lastAction = "";
string   g_panelText[];

#define PG_PANEL "PropGuard.panel."
#define PG_LINES 9

int OnInit()
  {
   g_cfg.dailyPct = MathMax(InpDailyLossPct, 0.0);
   g_cfg.dailyMoney = MathMax(InpDailyLossMoney, 0.0);
   g_cfg.dayBase = InpDayBase;
   g_cfg.dayStartHour = InpDayStartHour;
   g_cfg.ddPct = MathMax(InpMaxDrawdownPct, 0.0);
   g_cfg.ddMoney = MathMax(InpMaxDrawdownMoney, 0.0);
   g_cfg.ddMode = InpDrawdownMode;
   g_cfg.trailStopsAtStart = InpTrailStopsAtStart;
   g_cfg.targetPct = MathMax(InpTargetPct, 0.0);
   g_cfg.targetMoney = MathMax(InpTargetMoney, 0.0);
   g_cfg.newsBefore = MathMax(InpNewsBefore, 0);
   g_cfg.newsAfter = MathMax(InpNewsAfter, 0);
   if(InpDayStartHour < 0 || InpDayStartHour > 23)
     {
      Print("Prop Guard: the day start hour must be 0-23.");
      return INIT_PARAMETERS_INCORRECT;
     }
   PG_ParseNews(InpNewsTimes, g_news, g_newsBad);
   if(g_newsBad != "")
      Print("Prop Guard: news times not understood (use yyyy.mm.dd hh:mi): ", g_newsBad);
   g_trade.SetDeviationInPoints(InpDeviationPoints > 0 ? InpDeviationPoints : 30);
   g_trade.LogLevel(LOG_LEVEL_ERRORS);
   ArrayResize(g_panelText, PG_LINES);
   g_ready = false;
   EventSetMillisecondTimer(500);
   PG_Check();
   return INIT_SUCCEEDED;
  }

void OnDeinit(const int reason)
  {
   EventKillTimer();
   if(g_ready)
      PG_SaveTo(g_prefix, g_st);
   ObjectsDeleteAll(0, PG_PANEL);
   ChartRedraw();
  }

void OnTick()
  {
   PG_Check();
#ifdef PROPGUARD_DRIVER
   PG_DriverTick(); // only in AtaQuant's Strategy Tester proof build, never in this EA
#endif
  }

void OnTimer()
  {
   PG_Check();
  }

void OnTradeTransaction(const MqlTradeTransaction &trans, const MqlTradeRequest &request, const MqlTradeResult &result)
  {
   if(trans.type == TRADE_TRANSACTION_DEAL_ADD || trans.type == TRADE_TRANSACTION_ORDER_ADD)
      PG_Check();
  }

//--- loads the stored state once the account is known (the login is 0 before the terminal connects)
bool PG_Prepare()
  {
   long login = AccountInfoInteger(ACCOUNT_LOGIN);
   if(login <= 0 || AccountInfoDouble(ACCOUNT_BALANCE) <= 0.0)
      return false;
   g_prefix = "PropGuard." + IntegerToString(login) + "." + (InpMagic >= 0 ? IntegerToString(InpMagic) : "all") + ".";
   string resetDone = g_prefix + "reset";
   if(InpResetState && !GlobalVariableCheck(resetDone))
     {
      PG_ClearStored(g_prefix);
      GlobalVariableSet(resetDone, 1.0);
      Print("Prop Guard: stored state cleared (reset). Set \"Reset\" back to false.");
     }
   if(!InpResetState && GlobalVariableCheck(resetDone))
      GlobalVariableDel(resetDone);
   if(!PG_LoadFrom(g_prefix, g_st))
      ZeroMemory(g_st);
   if(InpStartBalance > 0.0)
      g_st.start = InpStartBalance;
   g_lock = g_st.lock;
   g_ready = true;
   PrintFormat("Prop Guard %s on account %I64d: starting balance %s, %s.", PG_VERSION, login,
               g_st.start > 0.0 ? PG_Money(g_st.start) : PG_Money(AccountInfoDouble(ACCOUNT_BALANCE)),
               g_st.lock == PG_LOCK_NONE ? "no lock" : "lock on: " + PG_LockName(g_st.lock));
   return true;
  }

bool PG_TradeAllowed()
  {
   return TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) && MQLInfoInteger(MQL_TRADE_ALLOWED) && AccountInfoInteger(ACCOUNT_TRADE_EXPERT);
  }

void PG_Check()
  {
   if(!g_ready && !PG_Prepare())
     {
      PG_Panel(0.0, 0.0, TimeTradeServer());
      return;
     }
   double balance = AccountInfoDouble(ACCOUNT_BALANCE);
   double equity = AccountInfoDouble(ACCOUNT_EQUITY);
   datetime now = TimeTradeServer();
   PGState before = g_st;
   bool started = false;
   int lock = PG_Evaluate(g_cfg, g_st, balance, equity, now, g_news, g_newsFrom, g_newsTo, started);
   if(started)
      PG_Announce(lock, equity, balance);
   if(lock != g_lock)
     {
      if(lock == PG_LOCK_NEWS)
         PrintFormat("Prop Guard: news lock from %s to %s.", TimeToString(g_newsFrom, TIME_DATE | TIME_MINUTES), TimeToString(g_newsTo, TIME_DATE | TIME_MINUTES));
      else
         if(lock == PG_LOCK_NONE)
            Print("Prop Guard: lock ended, trading is open.");
      g_lock = lock;
     }
   if(lock == PG_LOCK_NEWS)
      PG_Enforce(InpNewsCloseOpen ? 0 : g_newsFrom);
   else
      if(lock != PG_LOCK_NONE)
         PG_Enforce(0);
   //--- save on any change of the day, the lock or the start, the peak at most every 10 s
   if(before.day != g_st.day || before.lock != g_st.lock || before.start != g_st.start || before.dayStart != g_st.dayStart
      || (before.peak != g_st.peak && now - g_lastSave >= 10))
     {
      PG_SaveTo(g_prefix, g_st);
      g_lastSave = now;
      if(before.lock != g_st.lock)
         GlobalVariablesFlush();
     }
   PG_Panel(balance, equity, now);
  }

void PG_Announce(const int lock, const double equity, const double balance)
  {
   string until = lock == PG_LOCK_DAILY ? "until " + TimeToString(g_st.lockUntil, TIME_DATE | TIME_MINUTES) + " (server time)" : "until you reset it";
   string msg = StringFormat("Prop Guard: %s lock at equity %s (balance %s). Closing positions; locked %s.", PG_LockName(lock),
                             PG_Money(equity), PG_Money(balance), until);
   Print(msg);
   if(InpAlerts && !MQLInfoInteger(MQL_TESTER))
     {
      Alert(msg);
      if(TerminalInfoInteger(TERMINAL_NOTIFICATIONS_ENABLED))
         SendNotification(msg);
     }
  }

//--- closes the positions in scope (opened at or after `since` when it is set) and deletes pending orders
void PG_Enforce(const datetime since)
  {
   if(!PG_TradeAllowed())
      return;
   if(GetTickCount64() < g_nextTry)
      return;
   bool hedging = AccountInfoInteger(ACCOUNT_MARGIN_MODE) == ACCOUNT_MARGIN_MODE_RETAIL_HEDGING;
   int closed = 0, failed = 0;
   uint lastRc = 0;
   for(int i = PositionsTotal() - 1; i >= 0; i--)
     {
      ulong ticket = PositionGetTicket(i);
      if(ticket == 0)
         continue;
      if(InpMagic >= 0 && PositionGetInteger(POSITION_MAGIC) != InpMagic)
         continue;
      if(since > 0 && (datetime)PositionGetInteger(POSITION_TIME) < since)
         continue;
      string symbol = PositionGetString(POSITION_SYMBOL);
      double volume = PositionGetDouble(POSITION_VOLUME);
      double maxVolume = SymbolInfoDouble(symbol, SYMBOL_VOLUME_MAX);
      bool sent;
      if(hedging && maxVolume > 0.0 && volume > maxVolume)
         sent = g_trade.PositionClosePartial(ticket, maxVolume);
      else
         sent = g_trade.PositionClose(ticket);
      uint rc = g_trade.ResultRetcode();
      if(sent && (rc == TRADE_RETCODE_DONE || rc == TRADE_RETCODE_DONE_PARTIAL || rc == TRADE_RETCODE_PLACED))
         closed++;
      else
        {
         failed++;
         lastRc = rc;
         PG_LogFailure(StringFormat("close #%I64u %s", ticket, symbol), rc);
        }
     }
   if(InpDeletePending)
      for(int i = OrdersTotal() - 1; i >= 0; i--)
        {
         ulong ticket = OrderGetTicket(i);
         if(ticket == 0)
            continue;
         if(InpMagic >= 0 && OrderGetInteger(ORDER_MAGIC) != InpMagic)
            continue;
         if(since > 0 && (datetime)OrderGetInteger(ORDER_TIME_SETUP) < since)
            continue;
         //--- an order within the freeze level cannot be deleted: try again on a later pass
         if(PG_Frozen(OrderGetString(ORDER_SYMBOL), (ENUM_ORDER_TYPE)OrderGetInteger(ORDER_TYPE), OrderGetDouble(ORDER_PRICE_OPEN)))
           {
            failed++;
            lastRc = TRADE_RETCODE_FROZEN;
            continue;
           }
         bool sent = g_trade.OrderDelete(ticket);
         uint rc = g_trade.ResultRetcode();
         if(sent && (rc == TRADE_RETCODE_DONE || rc == TRADE_RETCODE_PLACED))
            closed++;
         else
           {
            failed++;
            lastRc = rc;
            PG_LogFailure(StringFormat("delete order #%I64u", ticket), rc);
           }
        }
   if(closed > 0)
     {
      g_lastAction = StringFormat("%s: closed or deleted %d", TimeToString(TimeTradeServer(), TIME_MINUTES | TIME_SECONDS), closed);
      PrintFormat("Prop Guard (%s lock): closed or deleted %d position(s)/order(s).", PG_LockName(g_lock), closed);
     }
   if(failed > 0)
     {
      //--- retry with a growing pause: 1 s, 2 s, 4 s ... 30 s (a closed market answers 10018 until it opens)
      g_backoff = g_backoff == 0 ? 1000 : MathMin(g_backoff * 2, 30000);
      g_nextTry = GetTickCount64() + g_backoff;
      g_lastAction = StringFormat("retrying: %d failed (retcode %u)", failed, lastRc);
     }
   else
     {
      g_backoff = 0;
      g_nextTry = 0;
     }
  }

//--- is a pending order's price within the symbol's freeze level (the server refuses to delete it)?
bool PG_Frozen(const string symbol, const ENUM_ORDER_TYPE type, const double price)
  {
   long freeze = SymbolInfoInteger(symbol, SYMBOL_TRADE_FREEZE_LEVEL);
   if(freeze <= 0)
      return false;
   bool buy = type == ORDER_TYPE_BUY_LIMIT || type == ORDER_TYPE_BUY_STOP || type == ORDER_TYPE_BUY_STOP_LIMIT;
   double market = buy ? SymbolInfoDouble(symbol, SYMBOL_ASK) : SymbolInfoDouble(symbol, SYMBOL_BID);
   return MathAbs(market - price) <= freeze * SymbolInfoDouble(symbol, SYMBOL_POINT);
  }

void PG_LogFailure(const string what, const uint rc)
  {
   datetime now = TimeTradeServer();
   if(now - g_lastFailLog < 30)
      return;
   g_lastFailLog = now;
   PrintFormat("Prop Guard: %s failed, retcode %u (%s), error %d. Retrying.", what, rc, g_trade.ResultRetcodeDescription(), GetLastError());
  }

//+------------------------------------------------------------------+
//| Status panel                                                     |
//+------------------------------------------------------------------+
void PG_Line(const int i, const string text, const color clr)
  {
   string name = PG_PANEL + IntegerToString(i);
   if(ObjectFind(0, name) < 0)
     {
      ObjectCreate(0, name, OBJ_LABEL, 0, 0, 0);
      ObjectSetInteger(0, name, OBJPROP_CORNER, CORNER_LEFT_UPPER);
      ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_LEFT_UPPER);
      ObjectSetInteger(0, name, OBJPROP_XDISTANCE, InpPanelX + 10);
      ObjectSetInteger(0, name, OBJPROP_YDISTANCE, InpPanelY + 8 + i * 17);
      ObjectSetString(0, name, OBJPROP_FONT, "Consolas");
      ObjectSetInteger(0, name, OBJPROP_FONTSIZE, 9);
      ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
      ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
     }
   ObjectSetString(0, name, OBJPROP_TEXT, text);
   ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
  }

string PG_Pct(const double part, const double whole)
  {
   return whole > 0.0 ? DoubleToString(100.0 * part / whole, 1) + "%" : "-";
  }

void PG_Panel(const double balance, const double equity, const datetime now)
  {
   if(!InpShowPanel || (MQLInfoInteger(MQL_TESTER) && !MQLInfoInteger(MQL_VISUAL_MODE)))
      return;
   const color cText = C'222,226,232', cMuted = C'139,148,160', cOk = C'52,199,89', cWarn = C'255,176,32', cLock = C'255,84,74';
   string lines[PG_LINES];
   color colors[PG_LINES];
   for(int i = 0; i < PG_LINES; i++)
     {
      lines[i] = "";
      colors[i] = cText;
     }
   string cur = AccountInfoString(ACCOUNT_CURRENCY);
   if(!g_ready)
     {
      lines[0] = "PROP GUARD " + PG_VERSION + "  |  WAITING";
      colors[0] = cWarn;
      lines[1] = "Waiting for the account to connect.";
      colors[1] = cMuted;
     }
   else
     {
      if(g_lock == PG_LOCK_NONE)
        {
         lines[0] = "PROP GUARD " + PG_VERSION + "  |  ACTIVE";
         colors[0] = cOk;
         lines[1] = StringFormat("Watching %d position(s), %d pending order(s).", PositionsTotal(), OrdersTotal());
         colors[1] = cMuted;
        }
      else
        {
         lines[0] = "PROP GUARD " + PG_VERSION + "  |  LOCKED: " + PG_LockName(g_lock);
         colors[0] = g_lock == PG_LOCK_NEWS ? cWarn : cLock;
         if(g_lock == PG_LOCK_NEWS)
            lines[1] = "No new positions until " + TimeToString(g_newsTo, TIME_DATE | TIME_MINUTES) + ".";
         else
            if(g_lock == PG_LOCK_DAILY)
               lines[1] = "No trading until " + TimeToString(g_st.lockUntil, TIME_DATE | TIME_MINUTES) + ".";
            else
               lines[1] = g_lock == PG_LOCK_TARGET ? "Target reached. Locked until you reset it." : "Drawdown floor reached. Locked until you reset it.";
         colors[1] = colors[0];
        }
      double dlim = PG_DailyLimit(g_cfg, g_st);
      double dloss = MathMax(g_st.dayStart - equity, 0.0);
      lines[2] = dlim > 0.0 ? StringFormat("Daily loss  %s of %s (%s)", PG_Money(dloss), PG_Money(dlim), PG_Pct(dloss, dlim)) : "Daily loss  off";
      colors[2] = dlim > 0.0 && dloss >= 0.8 * dlim ? cWarn : cText;
      double floor = PG_DrawdownFloor(g_cfg, g_st);
      lines[3] = floor >= 0.0 ? StringFormat("Drawdown    %s to the floor %s", PG_Money(MathMax(equity - floor, 0.0)), PG_Money(floor)) : "Drawdown    off";
      colors[3] = floor >= 0.0 && equity - floor <= 0.2 * PG_DrawdownLimit(g_cfg, g_st) ? cWarn : cText;
      double target = PG_TargetLevel(g_cfg, g_st);
      lines[4] = target > 0.0 ? StringFormat("Target      %s of %s (%s)", PG_Money(equity - g_st.start), PG_Money(target - g_st.start),
                                               PG_Pct(MathMax(equity - g_st.start, 0.0), target - g_st.start)) : "Target      off";
      datetime next = PG_NextNews(now, g_news, g_cfg.newsBefore);
      if(g_newsBad != "")
        {
         lines[5] = "News        times not understood: " + StringSubstr(g_newsBad, 0, 28);
         colors[5] = cWarn;
        }
      else
         lines[5] = ArraySize(g_news) == 0 ? "News        no times entered"
                    : next > 0 ? "News        next lock " + TimeToString(next, TIME_DATE | TIME_MINUTES) : "News        no more times";
      lines[6] = StringFormat("Equity      %s  balance %s %s", PG_Money(equity), PG_Money(balance), cur);
      colors[6] = cMuted;
      if(!PG_TradeAllowed())
        {
         lines[7] = "Algo Trading is off: Prop Guard cannot close trades.";
         colors[7] = cLock;
        }
      else
        {
         lines[7] = g_lastAction;
         colors[7] = cMuted;
        }
      lines[8] = "Server time " + TimeToString(now, TIME_DATE | TIME_MINUTES | TIME_SECONDS);
      colors[8] = cMuted;
     }
   string bg = PG_PANEL + "bg";
   if(ObjectFind(0, bg) < 0)
     {
      ObjectCreate(0, bg, OBJ_RECTANGLE_LABEL, 0, 0, 0);
      ObjectSetInteger(0, bg, OBJPROP_CORNER, CORNER_LEFT_UPPER);
      ObjectSetInteger(0, bg, OBJPROP_XDISTANCE, InpPanelX);
      ObjectSetInteger(0, bg, OBJPROP_YDISTANCE, InpPanelY);
      ObjectSetInteger(0, bg, OBJPROP_XSIZE, 400);
      ObjectSetInteger(0, bg, OBJPROP_YSIZE, 16 + PG_LINES * 17);
      ObjectSetInteger(0, bg, OBJPROP_BGCOLOR, C'17,21,28');
      ObjectSetInteger(0, bg, OBJPROP_BORDER_TYPE, BORDER_FLAT);
      ObjectSetInteger(0, bg, OBJPROP_COLOR, C'58,66,80');
      ObjectSetInteger(0, bg, OBJPROP_SELECTABLE, false);
      ObjectSetInteger(0, bg, OBJPROP_HIDDEN, true);
     }
   bool changed = false;
   for(int i = 0; i < PG_LINES; i++)
     {
      string key = lines[i] + "|" + IntegerToString(colors[i]);
      if(g_panelText[i] == key)
         continue;
      g_panelText[i] = key;
      PG_Line(i, lines[i], colors[i]);
      changed = true;
     }
   if(changed)
      ChartRedraw();
  }
#endif // PROPGUARD_TEST
//+------------------------------------------------------------------+
