Skip to content

Free utility EA · open source

Prop Guard: free MT5 daily loss and drawdown lock

An open-source Expert Advisor for MetaTrader 5 that watches the account's equity, closes everything when it reaches your daily loss limit, your maximum drawdown or your profit target, and keeps new trades out around the news times you enter. It never opens a trade. MIT licence, source included.

Download Prop Guard 1.0.0

Released 30 November 2026 · MetaTrader 5 · compiled with MetaEditor build 6361

Version
1.0.0
Licence
MIT
Self-test
101/101 pass
Compile
0 errors · 0 warnings
  • PropGuard.ex5 · 60 KBSHA-256 72e3e2bfa6746560559c7c76780ee1d1f010611f252cae08ef455ce8692960f3
  • PropGuard.mq5 · 31 KBSHA-256 ac279d19df39a72b0f00d99bbce06a462e3a9b7f1dd5d90cfb3b3d94ead3efea

The .ex5 is built from this exact source. To check it yourself, open the .mq5 in MetaEditor and compile it. Try Prop Guard on a demo account before you rely on it on a challenge. Changelog (text)

The four locks

Each lock reads the account's equity, so floating losses count, as most prop firms count them. While a lock is on, Prop Guard closes every position in its scope as soon as it appears and deletes pending orders. A more severe lock replaces a milder one; drawdown and target locks stay until you reset them.

LockFires whenWhat Prop Guard doesUntil
Daily lossEquity falls the daily limit below the day's start (by default the higher of balance and equity when the trading day began).Closes every position in scope, deletes pending orders, then closes any new position as soon as it opens.The next trading day starts (the hour you set, server time).
Maximum drawdownEquity reaches the drawdown floor: the starting balance minus the limit, or, in trailing mode, the highest equity minus the limit.Closes everything and keeps the account flat.You reset it.
Profit targetEquity reaches the starting balance plus the target.Closes everything, so a passed challenge is not given back.You reset it.
News timeThe server time is inside the window around a news time you entered (minutes before and after).Closes positions opened inside the window and deletes pending orders placed in it; optionally closes the open positions when the window starts.The window ends.

Install in MetaTrader 5

  1. Copy the file. In MetaTrader 5: File → Open Data Folder → MQL5 → Experts. Put PropGuard.ex5 there (or PropGuard.mq5 and compile it in MetaEditor).
  2. Refresh. In the Navigator, right-click Expert Advisors and choose Refresh. Prop Guard appears in the list.
  3. Attach to one chart. Drag it onto one chart of the account (any symbol, any timeframe). Set the limits a little inside your firm's limits.
  4. Allow Algo Trading. Turn on Algo Trading in the toolbar. The panel shows ACTIVE. Keep the terminal running, on a VPS for a challenge.

Settings

The inputs as they appear in the EA's dialog, with their defaults. Times are the trade server's time (the Market Watch clock).

Daily loss lock

InputDefaultWhat it does
Daily loss limit, %5.0Percent of the day's start. 0 turns it off.
Daily loss limit, money0In the account currency. With both set, the smaller amount is used.
The day's start isHigher of balance and equityOr balance, or equity, read when the trading day begins.
New trading day starts at0Server hour (0–23). Set it to your firm's daily reset.

Maximum drawdown lock

InputDefaultWhat it does
Maximum drawdown, %10.0Percent of the starting balance. 0 turns it off.
Maximum drawdown, money0In the account currency. With both set, the smaller amount is used.
Drawdown is measuredStaticStatic from the starting balance, or trailing from the highest equity.
Trailing floor stops at the starting balancetrueThe trailing floor never rises above the starting balance.
Starting balance00 takes the balance when Prop Guard first runs on the account.

Profit target

InputDefaultWhat it does
Profit target, %0Percent of the starting balance. 0 turns it off.
Profit target, money0In the account currency. With both set, the smaller amount is used.

News-time lock

InputDefaultWhat it does
News timesemptyServer time, yyyy.mm.dd hh:mi, separated by “;” (for example 2026.12.04 15:30; 2026.12.10 15:30).
Minutes before / after5 / 5The window around each time.
Close open positions at the window startfalseOff: only positions opened inside the window are closed.

Scope and actions

InputDefaultWhat it does
Magic number-1-1 guards every position on the account; a number guards only that EA's positions.
Delete pending orderstrueWhile a lock is on.
Maximum slippage30 pointsFor the closing orders.
AlertstrueAn alert and a push notification (when set up in MetaTrader) when a lock starts.
ResetfalseSet to true once to clear the stored starting balance, peak and locks, then back to false.
Panel position12, 24 pxFrom the chart's top-left corner.

The status panel

Prop Guard draws a panel in the chart's top-left corner: its state (ACTIVE, or LOCKED with the reason and until when), how much of the daily limit is used, the room to the drawdown floor, the progress to the target, the next news lock, equity and balance. A red line appears when Algo Trading is off, because then it cannot close anything. Lines turn amber at 80% of the daily limit, and when the room to the floor is under 20% of the drawdown limit.

EURUSD,H1 · Prop Guard · example values
PROP GUARD 1.0.0  |  ACTIVE
Watching 2 position(s), 0 pending order(s).
Daily loss  1,240.00 of 5,000.00 (24.8%)
Drawdown    8,760.00 to the floor 90,000.00
Target      -1,240.00 of 8,000.00 (0.0%)
News        next lock 2026.12.04 15:25
Equity      98,760.00  balance 100,000.00 USD
Server time 2026.12.04 11:42:07

How it is tested

  • A test script runs inside MetaTrader 5 (build 6361) on the same source and puts every lock through scripted balance, equity and time sequences: 101 cases, 101 pass. They cover each limit at the limit and one cent before it, the day change at the hour you set, static and trailing floors, the priority between locks, news windows to the second, and the state kept across a restart.
  • MetaEditor compiles it with 0 errors and 0 warnings, and EA Doctor finds nothing in it.
  • When a close is refused (a closed market, a requote), it tries again after 1 s, then 2 s, 4 s, up to every 30 s, until the position is gone.

What it cannot do

  • It cannot stop another EA or a manual click from sending an order. It closes the position right after it opens, so set your limits a little inside your firm's (for example 4.5% for a 5% daily limit).
  • A gap or a fast market can move past a limit before the closing orders fill. The lock fires at the limit; the fill is the market's.
  • It works only while the terminal runs and is connected. Use a VPS, and keep it on one chart only.
  • Firms define the daily loss and drawdown differently. Check your firm's rules and set the day's start, the reset hour and the mode to match. Prop Guard is not affiliated with any prop firm.
  • When an order fails, the journal's return code says why: look it up in the MQL5 error library.

Changelog

  • 1.0.0

    • First release: daily loss lock, maximum drawdown lock (static or trailing), close all at the profit target and a news-time lock.
    • On-chart status panel; the starting balance, the peak and the locks are kept across terminal restarts.
    • Closes with retries (1 s up to 30 s apart) while the market refuses, skips pending orders inside the freeze level until they can be deleted.

Source code

PROPGUARD.MQ5834 lines · MITShow the codeHide the code
//+------------------------------------------------------------------+
//| 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
//+------------------------------------------------------------------+

Want the rules inside your own EA?

A guard on the side cannot stop an EA from sending the order. We build your firm's daily loss, drawdown, news and lot rules into the EA itself, each tested against the rule it enforces.