Building a Prop-Firm Rule Guard in MQL5 (Part 2): Eight Rules, One Directive, and the Action Layer
Contents
- Introduction
- Eight rules and what a violation costs
- The rule table and the two-phase pass
- The one thing MQL5 will not let you do
- Closing positions, proving it, and surviving a restart
- One facade over the whole package
- The demo and the proof
- Limitations
- Conclusion
Introduction
The observation half of a prop-firm rule guard freezes the account into one immutable record per pass. It separates a finding from an action and defines the contract that every rule implements. Part 1 built this observation layer. A session clock, a profit ledger, an excursion tracker, and a calendar feed fill that record.
Part 2 covers the deciding half and the acting half. The eight rules come first, then the table that holds them, then the pass that turns eight independent opinions into at most one directive. After that come the actuators, the state file, the facade, the demo, and the verification script.
Part 1 also numbered nine failure modes of the hand-written guard, from C1 to C9. They are referenced below by number, because almost every decision here exists to make one of them unreachable. One note on scope carries over: this is a guard and not a strategy, and it never decides when to enter.
Eight rules and what a violation costs
With the snapshot and the shared contract in place, each rule becomes small. They are grouped below by the reasoning they share rather than given eight identical treatments, because the interesting differences sit between the groups. What a violation actually costs is the axis that matters here.
The eight rules, the table that owns them, and the action layer

- Static drawdown: a fixed floor below the starting balance that never moves.
- Trailing drawdown: a floor that ratchets up with the peak and then locks for good.
- Daily loss: a session limit that ends the day and not the challenge.
- Profit target: the objective, reported as good news and never as a breach.
- Consistency: a ceiling on the best single day's share of total profit.
- Minimum trading days: a payout precondition counted in qualifying days.
- News window: a blackout around a high-impact release, with an exemption.
- Weekend flat: a cutoff after which no position may be carried.
The static floor holds one anchor and exposes no operation that lowers it. Its whole breach test is three lines, and the latch makes the finding terminal. The empty intraday reset below is deliberate rather than an omission, because a fixed floor has no opinion about where a day starts.
//--- once breached, the account is dead for this challenge. The rule //--- keeps saying so on every later pass instead of forgetting, and //--- keeps the SAME anchor, so a recovery does not buy a second life. if(m_latched || snap.equity <= floor_level) { bool first = !m_latched; m_latched = true; Report(out, snap, PROP_SEV_BREACH, PROP_DIRECTIVE_LOCKDOWN, snap.equity, floor_level, headroom, "ccy", StringFormat("%s: equity %.2f at or below the static floor %.2f " "(anchor %.2f - %.2f)%s", Name(), snap.equity, floor_level, m_anchor, m_dd_amount, (first ? "" : " [latched]")), true); return; } //--- ...and the intraday reset of the same class virtual void ResetIntraday(const PropAccountSnapshot &snap) { //--- nothing: the static floor does not know what a day is }
The trailing floor is the harder of the two, and it enforces two invariants structurally. The first is monotonicity, and it comes from giving the floor member exactly one writer. The second is the one-way lock: the lock test runs before the ratchet, because reaching the lock level ends trailing for good.
//--- the ONLY writer of m_floor. Never lowers it. void RaiseFloor(const double candidate) { if(candidate > m_floor) m_floor = candidate; } //--- inside Evaluate(): //--- 1. lock check first: reaching the lock level ends trailing for good if(m_lock_enabled && !m_locked && snap.balance >= m_lock_level) { m_locked = true; RaiseFloor(m_lock_level - m_trail_amount); PrintFormat("%s: floor locked at %.2f (balance %.2f reached the lock level %.2f) " "-- it behaves as a static floor from here on.", Name(), m_floor, snap.balance, m_lock_level); } //--- 2. ratchet, but only while unlocked if(!m_locked) { if(m_mode == PROP_TRAIL_END_OF_DAY) { //--- the closed-balance variant only advances at the rollover, //--- which ResetIntraday() drives; nothing to do intra-day } else { //--- intraday variant: floating profit counts toward the peak double candidate = MathMax(snap.balance, snap.equity); if(candidate > m_peak) m_peak = candidate; RaiseFloor(m_peak - m_trail_amount); } }
The daily loss rule measures the day's loss against its limit, and the directive is where it parts company with the account-level floors. While exposure is open the correct action is to close it; once flat, it is to stay out for the rest of the prop day. C5 crippled this rule, so the rearm below is the fix made concrete.
//--- while exposure is open the correct action is to close it; once //--- flat, the correct action is simply to stay out for the rest of //--- the prop day. Escalating to LOCKDOWN would be wrong: a daily //--- breach does not end the challenge; it ends the day. ENUM_PROP_DIRECTIVE directive = snap.HasExposure() ? PROP_DIRECTIVE_FLATTEN : PROP_DIRECTIVE_BLOCK_NEW_ENTRIES; //--- ...and the rearm, which turns "the daily protection still works" //--- into something a test can assert virtual void ResetIntraday(const PropAccountSnapshot &snap) { if(m_latched) { m_rearm_count++; PrintFormat("%s: rearmed at the %s prop-day boundary (breach was on day index %d)", Name(), TimeToString(snap.prop_day_start, TIME_DATE | TIME_MINUTES), m_latched_day); } m_latched = false; m_latched_day = 0; }
The profit target rule exists partly to make C6 unreachable. It contains no peak, reads no peak, and cannot be handed one, because its only comparison is against a level. Note the severity too: reaching a target reports information and never a breach. Good news on the channel that carries account-killing events makes a journal unreadable.
double level = TargetLevel(); double progress = snap.equity - m_anchor; // NOT a drop from any peak double headroom = level - snap.equity; // still to go, in account currency if(m_reached || snap.equity >= level) { bool first = !m_reached; m_reached = true; //--- reaching a target is good news; the only debatable part is //--- whether to bank it, which is what m_flatten controls and what //--- the coordinator may still veto on consistency grounds (P5). ENUM_PROP_DIRECTIVE directive = PROP_DIRECTIVE_ADVISORY; if(m_flatten && snap.HasExposure()) directive = PROP_DIRECTIVE_FLATTEN;
The two payout rules share one property: violating them blocks a withdrawal and not the account. Both are capped at advisory strength by construction rather than by configuration. The abstain branch of the consistency rule is the more interesting half, because with no positive profit there is no share to judge at all.
//--- with no positive total profit there is no share to judge. This is //--- an abstention, not a pass: reporting "0% is fine" would be a lie //--- the moment the first profitable day lands. if(snap.total_realized_profit <= 0.0) { Abstain(out, snap, StringFormat("%s: no positive realized profit yet (total %.2f), " "consistency share is undefined", Name(), snap.total_realized_profit)); out.threshold = m_max_share; out.unit = "share"; out.projected = snap.projected_best_day_share; m_last = out; return; } //--- P5 hand-off: what the share becomes if today's floating profit is //--- banked now. The coordinator vetoes a profit-target flatten on it. out.projected = snap.projected_best_day_share; m_last = out;
When there is a share to judge, exceeding the ceiling produces an advisory severity and an advisory directive, and that is the strongest thing this rule may ask for. The minimum trading days rule goes further and emits no directive at all while the requirement is unmet.
//--- ADVISORY, and PROP_DIRECTIVE_NONE on purpose: this is a payout //--- precondition, not a risk condition. Nothing must be closed and //--- nothing must be blocked because of it. Report(out, snap, PROP_SEV_ADVISORY, PROP_DIRECTIVE_NONE, (double)done, (double)m_required_days, headroom, "days", StringFormat("%s: %d of %d qualifying days done, %d still needed " "(a day counts only with a trade of %.2f lots or more)", Name(), done, m_required_days, m_required_days - done, m_min_volume));
Blocking entries because an account has not traded enough days is not a conservative error, since such an account needs to trade more. Both conduct rules are pure functions of the snapshot, and the news rule never touches the calendar API, which is what makes it testable with synthetic events.
//--- no calendar, no opinion if(!snap.news_available) { Abstain(out, snap, StringFormat("%s: economic calendar unavailable on this terminal -- " "abstaining instead of blocking", Name())); out.unit = "minutes"; m_last = out; return; } //--- inside the blackout window, the "opened well in advance" exemption bool IsPositionExempt(const datetime opened, const datetime event_time) const { if(m_exempt_hours <= 0) return false; if(opened == 0 || event_time == 0) return false; return ((long)event_time - (long)opened) >= (long)m_exempt_hours * 3600; }
An unknown open time is never exempt. Exposure inside the window without an exemption is the violation itself, so the rule asks for a flatten, while exempt exposure only blocks new entries. The weekend rule compares one precomputed boolean, and flat past the cutoff reports the account as compliant rather than as a warning.
if(snap.HasExposure()) { m_flatten_asked = true; Report(out, snap, PROP_SEV_BREACH, PROP_DIRECTIVE_FLATTEN, minutes_left, 0.0, 0.0, "minutes", StringFormat("%s: past the %s cutoff with %d position(s) and %.2f lots open " "-- weekend gap risk", Name(), CutoffText(), snap.positions_total, snap.open_volume), true); return; } //--- already flat: stay out until the cutoff window ends Report(out, snap, PROP_SEV_OK, PROP_DIRECTIVE_BLOCK_NEW_ENTRIES, minutes_left, 0.0, 0.0, "minutes", StringFormat("%s: past the %s cutoff and flat, new entries blocked", Name(), CutoffText()));
The rule table and the two-phase pass
Eight rule classes and a profile still leave one question open, and that is which of them exist at runtime. Include/PropRulebook/CRuleRegistry.mqh answers it with three possible outcomes per rule and no fourth. A rule object only survives if it accepted its parameters, and a rejected rule is deleted on the spot.
//--- Configure-or-destroy. The rule object only survives if it accepted //--- its parameters; a rejected rule is deleted here and now, so no //--- half-configured evaluator can ever reach the table. bool Register(IPropRule *rule, const PropFirmProfile &profile) { if(rule == NULL) { m_build_error = "out of memory while creating a rule"; return false; } string err = ""; if(!rule.Configure(profile, err)) { m_build_error = rule.Name() + ": " + err; delete rule; return false; } int n = ArraySize(m_rules); if(ArrayResize(m_rules, n + 1) != n + 1) { m_build_error = "could not grow the rule table"; delete rule; return false; } m_rules[n] = rule; return true; }
A flag that is off means the rule is never constructed. A flag that is on with an unset value means the build fails and names the field. A flag that is on with a real value means the rule is registered. No unconfigured evaluator can sit in the table waiting to compare true against zero, and that is what makes C1 unreachable.
//--- a rejected rule empties the whole table: a partially armed guard is //--- more dangerous than none, because it looks like it is protecting bool Fail(string &err) { err = m_build_error; Clear(); return false; } //--- Build() itself reads as a list of the rule families, in order if(profile.use_static_dd && !Register(new CStaticDrawdownRule(), profile)) return Fail(err); if(profile.use_trailing_dd && !Register(new CTrailingDrawdownRule(), profile)) return Fail(err); //--- session-level risk rules if(profile.use_daily_loss && !Register(new CDailyLossRule(), profile)) return Fail(err); // ... //--- an empty table is legal: a profile with every flag off guards //--- nothing, which is exactly what it asked for return true;
The registry owns every rule it creates and deletes them from its destructor, which settles the ownership question in one place. The coordinator then turns eight independent verdicts into one action, and it runs a strictly two-phase pass over the table.
//--- PHASE 1: evaluate everything, act on nothing for(int i = 0; i < n; i++) { IPropRule *rule = registry.At(i); verdicts[i].Clear(); if(rule == NULL) continue; rule.Evaluate(snap, verdicts[i]); if(verdicts[i].IsBreach()) m_breach_count++; } //--- PHASE 2: read the stored verdicts, touch no rule object again for(int i = 0; i < n; i++) { if(!verdicts[i].evaluated || verdicts[i].abstained) continue; ENUM_PROP_DIRECTIVE effective = verdicts[i].directive; // ... if(PropDirectiveRank(effective) > PropDirectiveRank(m_directive)) { m_directive = effective; m_source = verdicts[i].rule; m_reason = verdicts[i].message; } }
That is the whole cascade fix. A close-all in the middle of a trigger loop has nowhere to happen, because there is no trigger loop: there is an evaluation loop that cannot act, and a resolution loop that cannot evaluate. It also gives C3 for free, since one directive can never mean a disable and an enable at once.
One Evaluate() pass — evaluate everything, then resolve once

The verdict array is still filled in registry order and handed back to the caller, so every finding stays visible even though one directive wins. Between the two phases sits the only piece of cross-rule reasoning in the package, and the coordinator handles it without knowing any concrete type.
That cross-rule case is worth naming, because the source comments refer to it as P5 throughout. Closing positions at the profit target is an obvious protective move. However, if the account is near its consistency ceiling, realizing the day's floating profit may push that day's share above the limit.
//--- P5 veto. Looks for the consistency verdict of THIS pass and //--- asks whether realizing today's open profit would push the //--- best-day share past the ceiling. Returns true when the flatten //--- must be downgraded. bool ConsistencyVetoesFlatten(const PropRuleVerdict &verdicts[], string &why) { int n = ArraySize(verdicts); for(int i = 0; i < n; i++) { if(verdicts[i].rule != PROP_RULE_CONSISTENCY) continue; if(!verdicts[i].evaluated) return false; if(verdicts[i].threshold <= 0.0) return false; if(verdicts[i].projected > verdicts[i].threshold) { why = StringFormat("banking the open profit now would make the best day " "%.1f%% of total profit, above the %.1f%% consistency " "ceiling (currently %.1f%%)", verdicts[i].projected * 100.0, verdicts[i].threshold * 100.0, verdicts[i].measured * 100.0); return true; } return false; } return false; }
When the veto fires, the downgrade is written back into the verdict rather than applied only inside the coordinator. Without that write-back, the pre-trade gate and status panel would still see a flatten directive that the guard never executed. The two consumers would therefore report a decision inconsistent with the action taken.
if(veto && verdicts[i].rule == PROP_RULE_PROFIT_TARGET && effective == PROP_DIRECTIVE_FLATTEN) { effective = PROP_DIRECTIVE_ADVISORY; m_downgraded = true; m_downgrade_reason = veto_why; //--- the downgrade is written back so every consumer of the //--- verdict list (CanOpen(), StatusReport(), a panel) sees the //--- same decision the coordinator acted on verdicts[i].directive = effective; verdicts[i].message += " | flatten downgraded to advisory (consistency)"; }
The two reset drivers live in the coordinator as well, and both run outside the evaluation phase. Each rule decides for itself what a new prop day means: the daily rule rearms, the end-of-day trailing floor advances its peak, and the account-level floors do nothing at all.
//--- C5. Prop-day boundary, driven across the whole table BEFORE //--- the evaluation phase of the pass that detected the rollover. //--- Each rule decides for itself what a new day means to it: the //--- daily loss rule rearms, the end-of-day trailing rule advances //--- its peak, the account-level rules do nothing at all. void DriveIntradayReset(CRuleRegistry *registry, const PropAccountSnapshot &snap) { if(registry == NULL) return; for(int i = 0; i < registry.Count(); i++) { IPropRule *rule = registry.At(i); if(rule != NULL) rule.ResetIntraday(snap); } }
The one thing MQL5 will not let you do
Every class so far has been ordinary MQL5, and this one is not. When an account-level limit is breached, closing positions is only half the job: the next signal reopens if Algo Trading is still on. MQL5 offers no way to switch it off, because the two properties that report the permission are read-only.
#import "user32.dll" int PostMessageW(long hWnd, uint Msg, long wParam, long lParam); long GetAncestor(long hWnd, uint gaFlags); #import //+------------------------------------------------------------------+ //| WinAPI constants for the Algo Trading toggle | //+------------------------------------------------------------------+ #define PROP_WM_COMMAND 0x0111 // standard Windows menu/command message #define PROP_ALGO_COMMAND_ID 32851 // MetaTrader 5 "Algo Trading" menu command #define PROP_GA_ROOT 2 // GetAncestor: walk up to the root window
The only available route is the terminal's own menu command, posted to its main window. The handle is a long, because the 64-bit terminal passes 8-byte handles, and the code walks up from the chart to the root. Command 32851 is a toggle rather than a setter, which is the first of three properties that shape the design.
The current state is therefore read first, and the message goes out only when reality disagrees. The PostMessageW function reference published by Microsoft states the second property outright: the call queues the message and returns at once.
//--- Posts the toggle ONCE, and only when the button is currently //--- in the wrong position. Returns false when the message could //--- not even be posted. bool PostToggle() { bool actual = (bool)TerminalInfoInteger(TERMINAL_TRADE_ALLOWED); if(actual == m_desired_state) return true; // nothing to toggle: already correct if(m_main_window == 0) m_main_window = ResolveMainWindow(); if(m_main_window == 0) { Print("CTerminalAlgoSwitch: could not resolve the terminal main window handle"); return false; } ResetLastError(); int posted = PostMessageW(m_main_window, (uint)PROP_WM_COMMAND, (long)PROP_ALGO_COMMAND_ID, (long)0); m_attempts++; m_last_post_time = TimeCurrent(); // ... }
Reading the permission property on the next line therefore reports the value from before the toggle. That is C7 exactly, and it is why the request never verifies itself. Verification happens on a later pass, against a deadline, and with a bounded number of re-posts.
//--- deliberately NOT verifying here. The terminal processes the //--- message on its own thread; reading TERMINAL_TRADE_ALLOWED on the //--- next line would report the pre-toggle value and be meaningless. return true; //--- verification, one later pass at a time void Update(const datetime now) { if(!m_ready || m_latch != ALGO_LATCH_PENDING) return; bool actual = (bool)TerminalInfoInteger(TERMINAL_TRADE_ALLOWED); if(actual == m_desired_state) { m_latch = ALGO_LATCH_SETTLED; PrintFormat("CTerminalAlgoSwitch: verified, Algo Trading is now %s after %d " "attempt(s) and %d second(s).", (m_desired_state ? "ON" : "OFF"), m_attempts, (int)((long)now - (long)m_request_time)); return; } if(m_last_post_time != 0 && ((long)now - (long)m_last_post_time) < m_verify_seconds) return; // still inside this attempt's grace period if(m_attempts >= m_max_attempts) { Escalate(); return; } PostToggle(); }
Neither a call to Sleep nor a busy wait appears anywhere in this class. The passage of time between passes is the wait, which keeps the whole thing safe to call from the tick handler. The latch has four states, and only two of them mean the caller may relax. An escalated latch never counts as settled.
//--- C7. The ONLY thing a caller may trust. Pending means "we asked //--- and the terminal has not confirmed yet" -- not "done". bool IsSettled() const { return (m_latch == ALGO_LATCH_IDLE || m_latch == ALGO_LATCH_SETTLED); } //--- the C3 half is a refusal rather than a queue bool RequestEnable() { if(!m_ready || !m_required) return false; if(m_disable_held) { Print("CTerminalAlgoSwitch: enable request REFUSED -- a protective disable is " "held. Only ClearLatch() lifts it."); return false; } // ... }
A queued enable would eventually fire and re-arm a breached account, so refusing outright is what keeps trading from coming back on behind the trader's back. The third property is the uncomfortable one, because the obvious mental model is wrong: the import binds at program initialization, before the init handler runs.
if(!(bool)TerminalInfoInteger(TERMINAL_DLLS_ALLOWED)) { Print("CTerminalAlgoSwitch::Init failed: 'Allow DLL imports' is OFF in the " "terminal options. There is no native MQL5 way to switch global Algo " "Trading, so either enable DLL imports or set the profile's " "disable_algo_on_breach to false and handle the lockdown manually."); return false; }
Measured on build 6120 with DLL imports switched off, the terminal logs that DLL loading is not allowed, reports that initializing failed with code 0, and runs no MQL5 at all. The permission test above is therefore a redundant safety check and not a degradation path.
Closing positions, proving it, and surviving a restart
C8 is the most dangerous failure mode in the list, because a false all-clear is indistinguishable from a real one until the next statement arrives. The executor fixes it with three requirements that only work together. The first is that retcodes are inspected, and the retryable set is explicit.
//--- Retcodes worth trying again. Everything else is either final //--- success or a permanent condition that retrying cannot fix. bool IsRetryable(const uint retcode) const { switch(retcode) { case TRADE_RETCODE_REQUOTE: case TRADE_RETCODE_PRICE_CHANGED: case TRADE_RETCODE_PRICE_OFF: case TRADE_RETCODE_REJECT: case TRADE_RETCODE_ERROR: case TRADE_RETCODE_TIMEOUT: case TRADE_RETCODE_CONNECTION: case TRADE_RETCODE_TOO_MANY_REQUESTS: case TRADE_RETCODE_ORDER_CHANGED: case TRADE_RETCODE_DONE_PARTIAL: return true; default: return false; } }
Everything else is either a final success or a permanent condition. A closed market is not retried three times; it is reported. The second requirement is to re-read the price before every attempt, especially after a requote. The loop must also interpret a true return from the send call correctly.
bool sent = OrderSend(req, res); m_last_retcode = res.retcode; //--- OrderSend() == true only means the request was accepted for //--- processing. The retcode is the part that says what happened. if(sent && IsSuccess(res.retcode)) { if(res.retcode == TRADE_RETCODE_DONE_PARTIAL) { PrintFormat("CProtectiveActionExecutor: partial close on #%I64u " "(%.2f of %.2f), continuing", ticket, res.volume, volume); continue; // loop again for the remainder } return true; } //--- the filling mode comes from the symbol, never hardcoded: a wrong //--- type_filling turns a valid close into a rejection ENUM_ORDER_TYPE_FILLING PickFilling(const string symbol) const { long modes = 0; if(!SymbolInfoInteger(symbol, SYMBOL_FILLING_MODE, modes)) return ORDER_FILLING_IOC; if((modes & SYMBOL_FILLING_FOK) != 0) return ORDER_FILLING_FOK; if((modes & SYMBOL_FILLING_IOC) != 0) return ORDER_FILLING_IOC; return ORDER_FILLING_RETURN; }
The third requirement makes the other two trustworthy. Success is a recount and not an inference: the positions are counted again after the loop, and the report says what is still open. One detail bites everyone once, so the ticket list is snapshotted before the closing loop starts.
m_last_remaining = CountRelevantPositions(); m_last_success = (m_last_remaining == 0); if(m_last_success) { m_last_report = StringFormat("flat verified: %d closed, 0 remaining (%s)", m_last_closed, reason); Print("CProtectiveActionExecutor: " + m_last_report); } else { m_last_report = StringFormat("NOT PROTECTED: %d closed, %d failed, %d still open " "(last retcode %u) -- %s", m_last_closed, m_last_failed, m_last_remaining, m_last_retcode, reason); Print("CProtectiveActionExecutor: " + m_last_report); } //--- snapshot the ticket list first: closing inside the enumeration //--- shifts the indices under our feet ulong tickets[]; int total = PositionsTotal(); ArrayResize(tickets, 0);
C9 is not exotic at all. A virtual server reboots, a terminal updates, and a chart reloads. If the guard comes back believing the account has lost nothing, it re-anchors at the depleted balance and allows the whole drawdown allowance to be lost a second time.
The state store is a checksummed key and value file, and its design is about what happens when the file goes wrong. A file is preferable to a terminal global variable. Global variables share a flat namespace and expire after four weeks, creating a risk of account collisions and loss of the anchor.
m_file_name = (StringLen(file_name) > 0) ? file_name : StringFormat("PropRulebook_%I64d.dat", login); //--- Replace the live file only once the temporary one is complete and //--- closed. FILE_REWRITE overwrites in one step, so the previous good //--- state is never deleted before its replacement exists. if(!FileMove(tmp_name, m_common_flag, m_file_name, FILE_REWRITE))
The header line carries a magic string, a version, the record count, and a checksum. The hash is the 32-bit variant described on the reference page for the FNV hash family: cheap, dependency-free, and enough for the truncation cases this guards against.
//--- FNV-1a over the payload. Cheap, dependency-free, and enough to //--- catch the truncation and partial-write cases this guards against. uint Checksum(const string payload) const { uint hash = 0x811C9DC5; // FNV-1a 32-bit offset basis int len = StringLen(payload); for(int i = 0; i < len; i++) { hash ^= (uint)StringGetCharacter(payload, i); hash *= 0x01000193; // FNV-1a 32-bit prime } return hash; }
The most important behavior is what the load path does with a file it does not fully trust, and the answer is that it rejects the whole thing. Half-loaded state is worse than no state, because it looks valid. An incorrect magic string, a version mismatch, a record with no separator, and a bad checksum all take the same path.
if(read != expected_count) { ClearAll(); m_last_error = StringFormat("corrupt state file: %d records, header says %d " "(truncated?)", read, expected_count); Print("CGuardStateStore: " + m_last_error); return false; } if(Checksum(payload) != expected_checksum) { ClearAll(); m_last_error = "corrupt state file: checksum mismatch"; Print("CGuardStateStore: " + m_last_error); return false; }
One facade over the whole package
The facade owns all ten components by value, plus the two things no single component may own: the challenge anchor, and the decision to act. Its init routine runs seven steps in an order that is not arbitrary. Step three restores persisted state before the rules are configured, because the restored anchor is what they must use.
//--- 3. persisted state, BEFORE the rules are configured, because the //--- restored anchor is what they must be anchored to (C4/C9) m_store.Init(m_profile.state_file_name, m_profile.state_in_common_folder); bool restored = m_store.Load(); if(restored) { double stored = m_store.GetDouble(PFD_KEY_ANCHOR, 0.0); if(stored > 0.0) { if(MathAbs(stored - anchor) > 0.01) PrintFormat("CPropRulebook: restoring the persisted anchor %.2f " "(the profile suggested %.2f) -- the consumed drawdown " "budget is NOT refilled by a restart.", stored, anchor); anchor = stored; } // ... } //--- 7. per-component restore; any failure falls back to a clean start if(restored && !RestoreComponents()) { Print("CPropRulebook: persisted state is inconsistent -- discarding it and " "starting from a fresh anchor rather than loading partial data."); m_store.Delete(); // ... }
If any component fails to restore, the whole restore is rolled back rather than partially applied, including the rules that already succeeded. There is no partial success anywhere in the init path, because a guard that half-started is a guard that lies. The evaluation pass itself is short, since every hard decision was made inside a component.
//--- One complete non-cascading pass. ENUM_PROP_DIRECTIVE Evaluate() { if(!m_initialized) return PROP_DIRECTIVE_NONE; datetime now = TimeCurrent(); //--- C7: verify the outstanding Algo Trading request against reality //--- BEFORE anything else, because a pass that started with a pending //--- latch must not pretend the account is already protected m_algo.Update(now); //--- C2: exactly one observation for the whole pass if(!m_builder.Build(now, m_anchor, m_snap)) return PROP_DIRECTIVE_NONE; //--- C5: the prop-day rollover, driven across the table OUTSIDE the //--- evaluation phase, rearming intraday latches only if(m_snap.is_new_prop_day) { m_coordinator.DriveIntradayReset(GetPointer(m_registry), m_snap); m_state_dirty = true; } //--- two-phase resolution into at most one directive string reason = ""; m_last_directive = m_coordinator.RunPass(GetPointer(m_registry), m_snap, m_verdicts, reason); m_last_reason = reason; m_last_pass_time = now; ApplyDirective(m_last_directive, reason); MaybeSave(now); return m_last_directive; }
The action phase runs after the whole table was evaluated, and its first two lines encode a rule that is easy to get wrong in the opposite direction. Latching everything is the safe instinct, and it leaves the account blocked forever after one news release. Latching nothing lets a breached challenge resume.
//--- Non-latched blocking is recomputed from scratch every pass: a news //--- window that has passed, or a weekend cutoff on a new week, must //--- stop blocking by itself. Only an account-level lockdown latch //--- survives a pass, and only ResetChallenge() lifts that. The same //--- applies to "a protective action is outstanding": if no rule is //--- asking for one this pass, there is nothing left to settle. m_block_new_entries = m_lockdown_latched; m_protection_requested = m_lockdown_latched; case PROP_DIRECTIVE_LOCKDOWN: { bool first = !m_lockdown_latched; m_lockdown_latched = true; m_block_new_entries = true; m_protection_requested = true; m_state_dirty = true; // ... if(!m_executor.IsFlat()) { m_last_flatten_ok = m_executor.FlattenAll(reason); m_executor.DeletePendingOrders(reason); } else m_last_flatten_ok = true; //--- the switch request is idempotent: it will not post a second //--- message while its own latch is still pending (C3/C7) if(m_profile.disable_algo_on_breach) m_algo.RequestDisable(); if(first) PersistState(); // a breach is worth an immediate flush return; }
The pre-trade gate refuses for five separate reasons before it looks at the verdicts, and the staleness check is the one people trip over. The middle loop matters too: the winning directive is not the only one that blocks. A news rule asking to block new entries still blocks, even when a weekend flatten outranked it.
if(m_last_pass_time == 0 || ((long)TimeCurrent() - (long)m_last_pass_time) > m_profile.max_pass_age_secs) { PrintFormat("CPropRulebook::CanOpen(%s, %.2f) refused: no fresh evaluation " "pass -- call Evaluate() from OnTick() before gating entries.", symbol, volume); return false; } //--- any rule of the last pass still asking for a block wins, even if //--- another rule's directive outranked it in the resolution phase for(int i = 0; i < ArraySize(m_verdicts); i++) { if(!m_verdicts[i].evaluated || m_verdicts[i].abstained) continue; if(PropDirectiveRank(m_verdicts[i].directive) >= PropDirectiveRank(PROP_DIRECTIVE_BLOCK_NEW_ENTRIES)) return false; } //--- an outstanding, unverified protective request also blocks (C7) if(!IsProtectionSettled()) return false;
The demo and the proof
The demo expert advisor wires the guard into the five handlers it needs and takes no position of its own. Its init handler loads a preset, overrides only the account-specific wiring, and starts the guard. Every threshold stays as the preset left it, so the journal numbers match the published rulebook figures.
//--- 1. start from the researched trailing-preset numbers instead of the //--- zeros a hand-filled profile would carry. The preset scales the //--- trailing amount, the daily cap and the target to the account //--- size, and switches the lock mechanic on. PropFirmProfile profile; if(!CPropRulebook::LoadPreset(profile, PROP_PRESET_TRAILING_LOCKED, InpDemo_AccountSize)) { Print("PropRulebookDemo: LoadPreset() refused the account size, error ", GetLastError()); return INIT_FAILED; } //--- 2. only the account-specific wiring is set on top of the preset. //--- Every threshold above stays exactly as the preset left it, so //--- the journal numbers match the published rulebook figures. profile.magic = InpDemo_Magic; profile.restrict_to_magic = InpDemo_RestrictToMagic; profile.timezone_offset_hours = InpDemo_TimezoneOffsetHours; profile.disable_algo_on_breach = InpDemo_DisableAlgoOnBreach; //--- 3. Init() validates the profile, refuses to start half-armed, //--- checks the DLL permission the Algo Trading switch needs and //--- restores any persisted anchor, ledger and latch. if(!g_guard.Init(profile)) { Print("PropRulebookDemo: guard did not start -- ", g_guard.InitError()); return INIT_FAILED; }
The preset behind those numbers, PROP_PRESET_TRAILING_LOCKED, scales its amounts to the account size in three tiers.
| Rule | Up to 50,000 | 50,001 to 100,000 | Above 100,000 |
|---|---|---|---|
| Trailing drawdown (intraday; the floor locks at the starting balance) | 2,000 | 3,000 | 4,500 |
| Daily loss limit | 1,000 | 2,000 | 3,000 |
| Profit target (no automatic flatten) | 3,000 | 6,000 | 9,000 |
| Consistency: best day as a share of total profit | 0.30 | 0.30 | 0.30 |
| Minimum trading days (0.01 lot to qualify) | 5 | 5 | 5 |
| Weekend flat, cutoff | Friday 20:00 | Friday 20:00 | Friday 20:00 |
| Daily reset, firm-local | 17:00 | 17:00 | 17:00 |
| Static drawdown | off | off | off |
| News window | off | off | off |
These amounts are the levels commonly published for trailing-drawdown evaluation accounts of these sizes. They are a starting point only, and the preset code asks the user to check every number against the real contract before trading it.
The cadence of the guard is the tick handler, and the demo wraps the pass in change-only reporting so the journal reads as a narrative. The simulated entry signal is handled by the timer. The comment explains the required call order, which is easy to get wrong.
//+------------------------------------------------------------------+ //| The simulated strategy signal. | //+------------------------------------------------------------------+ void OnTimer() { //--- CRITICAL ORDERING, and the single easiest way to misuse this //--- package: Evaluate() must have run in THIS pass before CanOpen() //--- is asked anything. CanOpen() refuses outright when the last pass //--- is older than profile.max_pass_age_secs (120 s by default), //--- because a guard that has not looked at the account for two //--- minutes cannot honestly clear a trade. Gate an entry without a //--- fresh pass and every entry is refused for staleness -- which //--- looks exactly like a rule breach in the log, and is not one. RunGuardPass(); if(!g_guard.CanOpen(g_symbol, InpDemo_Volume)) { PrintFormat("PropRulebookDemo: entry on %s (%.2f lots) BLOCKED by the guard", g_symbol, InpDemo_Volume); Print("PropRulebookDemo: ", g_guard.StatusReport()); return; } // ... }
When the demo is attached to a chart on a demo account, the journal shows the story on its own: the trailing floor ratchets as equity makes new highs, and a single lockdown directive is emitted if equity ever touches the floor. The demo still proves nothing, because a demo account that behaves normally exercises none of the paths that matter.
Verification is a separate script, and it never opens a position, never copies rates, and never needs a broker connection. Every figure in it is constructed by hand, which is what makes the awkward states reachable at all.
Rules are exercised through their real public interface against hand-built snapshot records, which is the seam the package was designed around. Each test overwrites only the fields its own scenario is about, and assertions go through one recorder. There are 25 scenario functions, one per entry in the design list.
//+------------------------------------------------------------------+ //| Synthetic snapshot factory. Produces a healthy, internally | //| consistent observation; each test then overwrites only the fields| //| its scenario is about. | //+------------------------------------------------------------------+ void MakeSnap(PropAccountSnapshot &s, const datetime when, const double balance, const double equity, const double anchor) { s.Clear(); s.pass_id = 1; s.server_time = when; s.balance = balance; s.equity = equity; s.credit = 0.0; s.floating_pl = equity - balance; // ... }
The scenarios that carry the most weight are the ones aimed straight at a numbered failure mode:
- An all-off profile with zero thresholds registers zero rules and emits no directive, and each enabled-but-unset threshold is then rejected by name (C1).
- Equity 89,000 against a 100,000 anchor with an 11,000 day loss and two positions open past the weekend cutoff produces three breaches and exactly one lockdown (C2).
- The static anchor does not move under a 10,000 profit, after a breach, or after a refund to 120,000 (C4).
- A 50,000 anchor with a 2,000 trail: the floor rises to 49,000, stays there while balance falls back, and locks at 50,000 (C4).
- Seven components serialize, are destroyed, and come back identical, and five kinds of damaged file are each rejected whole (C9).
- A projected best-day share of 0.45 against a 0.30 ceiling downgrades a profit-target flatten to an advisory (P5).
RecordResult(coord.BreachCount() == 3, "S03 all three rules independently report a breach", "3", I2(coord.BreachCount())); RecordResult(dir == PROP_DIRECTIVE_LOCKDOWN, "S03 exactly one terminal directive survives, the highest-ranked one", "LOCKDOWN", PropDirectiveName(dir)); RecordResult(coord.SourceRule() == PROP_RULE_STATIC_DD, "S03 the surviving directive is attributed to the static DD rule", "StaticDD", PropRuleName(coord.SourceRule()));
The last scenario registers all eight rules on a healthy account and asserts zero directives, zero breaches, eight verdicts, and one shared observation instant. The builder's pass counter is asserted to still read 1 after all eight rules have run, which is the direct proof that the account was read exactly once.
=== 332 assert(s) run, 0 failed === ALL TESTS PASSED
On the run of 2026-11-04, executed in an isolated terminal instance, 332 assertions ran and none failed. Both the demo and the verification script compile under MetaEditor with zero errors and zero warnings. The script also writes a machine-readable result file, so a build pipeline can read the outcome directly.
Those 332 assertions check rule logic against hand-built records. They do not test a broker, a real fill or the Algo Trading switch. Live integration is exercised separately by the demo on a demo account.
How to reproduce. The run above used this setup:
- MetaTrader 5 and MetaEditor build 6296 (x64) on Windows Server 2019 (build 17763), with a MetaQuotes-Demo account logged in. The script itself needs no connection.
- Unpack MQL5.zip into the terminal data folder (File > Open Data Folder). The headers land in MQL5\Include\PropRulebook, the demo in MQL5\Experts\PropRulebook and the script in MQL5\Scripts\PropRulebook.
- Compile TestPropRulebook.mq5 in MetaEditor. The expected result is 0 errors and 0 warnings.
- Both programs import user32.dll for the Algo Trading switch, so Allow DLL imports must be on (Tools > Options > Expert Advisors). The demo also needs Algo Trading enabled.
- Drag TestPropRulebook from the Navigator onto any chart. The run above used EURUSD M1.
- In the Experts tab, every assertion prints one line starting with PASS: and none starts with FAIL:. The last two lines read "=== 332 assert(s) run, 0 failed ===" and "ALL TESTS PASSED".
- The result file is mql5_test_result.json in the common data folder (%APPDATA%\MetaQuotes\Terminal\Common\Files). It reports "passed": true, "total": 332 and "failed": 0, with one entry per assertion under "details".
Limitations
Everything below is a real constraint of the code as written. The Algo Trading actuator makes the program Windows-only and dependent on the DLL permission, because the import binds before the init handler runs. Command 32851 is undocumented too: a future build may change it, after which the latch escalates and stays unrecoverable.
The guard evaluates only when the consuming expert advisor calls it. Over a weekend, during a broker outage, or on a symbol that stops ticking, nothing is evaluated and nothing is enforced. The weekend rule exists because of this, and a gap that opens beyond the floor is already beyond it when the first tick arrives.
Rules measure the whole account while the executor may close only part of it. With the magic-number restriction on, account equity still reflects every position, so a breach caused by another program is detected and cannot be resolved by flattening. The safe setting for a prop account is the default, which also means the guard closes everything.
The ledger only knows what it was told. There is no history backfill at startup, so deals executed while the terminal was closed stay invisible, and the ring holds 120 prop days by default. The day baseline is captured at the first pass of the day rather than at the boundary, and daily loss is measured on equity.
Three smaller constraints close the list. The economic calendar returns nothing in the Strategy Tester, so a backtest validates seven rules and not eight. State is stored per file name, so two terminals on one account share a file with no locking. Closing at market can deepen the breach, because a breach usually arrives in a fast market.
Three extensions fit the existing seams without touching the resolution logic:
- A chart panel, built on the verdict accessors and the unit field, so a generic renderer formats any rule without a switch over rule identifiers.
- A ninth rule, added by implementing the contract, adding one flag-and-threshold pair to the profile, and adding one registration line.
- A third actuator, plugged into the same directive switch, using the pending-latch pattern for anything else that is asynchronous.
Conclusion
The problem this started from is narrow and common. An expert advisor trading a prop-firm account has no idea the account has rules, and MetaTrader 5 provides nothing to teach it. Thresholds and conditions inside the tick handler turn out to carry nine failure modes, all of them silent while the account is healthy.
Each decision along the way removed a class of failure by changing shape rather than by adding a check. Rules report verdicts instead of taking actions. The floor has one writer that only raises it. An asynchronous request is verified on a later pass. Positions are recounted before anything reports the account protected.
The most transferable part is not the prop-firm domain. It is the frame: one observation per pass, verdicts before actions, exactly one terminal decision, actuators that verify instead of assume, and state that survives a restart. Swap the eight rules for your own constraints and the frame still holds.
The files below are attached individually and also together in MQL5.zip, which already carries the folder structure the terminal expects.
| # | Name | Type | Description |
|---|---|---|---|
| 1 | MQL5/Experts/PropRulebook/PropRulebookDemo.mq5 | Expert Advisor | Minimal integration demo: loads a preset, runs one evaluation pass per tick, gates a simulated entry behind CanOpen() and feeds executed deals into the daily ledger. |
| 2 | MQL5/Include/PropRulebook/CConsistencyRule.mqh | Include | Weighs the best single day's profit as a share of total profit against the payout consistency threshold. |
| 3 | MQL5/Include/PropRulebook/CDailyLossRule.mqh | Include | Weighs the loss accumulated since the configured daily reset boundary against the daily loss limit. |
| 4 | MQL5/Include/PropRulebook/CDailyProfitLedger.mqh | Include | Records realized profit and qualifying-trade facts per prop day, and answers the aggregate questions the rules ask. |
| 5 | MQL5/Include/PropRulebook/CEconomicCalendarFeed.mqh | Include | Reads high-impact events from the native economic calendar into a plain array, and reports when it cannot see them. |
| 6 | MQL5/Include/PropRulebook/CExcursionTracker.mqh | Include | Measures maximum favorable and adverse excursion of balance and equity against the challenge anchor, and tracks the running peak. |
| 7 | MQL5/Include/PropRulebook/CGuardStateStore.mqh | Include | Persists and restores the guard's state across restarts through a checksummed, atomically replaced terminal file. |
| 8 | MQL5/Include/PropRulebook/CMinTradingDaysRule.mqh | Include | Counts the days carrying a trade of at least the qualifying size against the minimum-trading-days requirement. |
| 9 | MQL5/Include/PropRulebook/CNewsWindowRule.mqh | Include | Decides whether the current moment falls inside the blackout window around a high-impact economic event. |
| 10 | MQL5/Include/PropRulebook/CProfitTargetRule.mqh | Include | Tracks progress toward the profit target and can ask for a flatten once that level is reached. |
| 11 | MQL5/Include/PropRulebook/CPropRulebook.mqh | Include | Public facade of the package: wires the session clock, ledger, calendar feed, excursion tracker, snapshot builder, rule table, coordinator and executor. |
| 12 | MQL5/Include/PropRulebook/CPropSessionClock.mqh | Include | Translates broker-server time into calendar boundaries: which day a moment falls in, when it started, and when it resets. |
| 13 | MQL5/Include/PropRulebook/CPropSnapshotBuilder.mqh | Include | Assembles the one frozen snapshot that every rule of a single evaluation pass reads. |
| 14 | MQL5/Include/PropRulebook/CProtectiveActionExecutor.mqh | Include | Closes positions and removes pending orders with per-request retcode inspection, bounded retries and an explicit verification pass. |
| 15 | MQL5/Include/PropRulebook/CRuleCoordinator.mqh | Include | Resolves the verdicts of one pass into at most one terminal directive, with no rule able to mutate another's outcome. |
| 16 | MQL5/Include/PropRulebook/CRuleRegistry.mqh | Include | Builds and owns the active rule table, refusing to register any rule whose parameters are absent or otherwise unconfigured. |
| 17 | MQL5/Include/PropRulebook/CStaticDrawdownRule.mqh | Include | Weighs equity against a floor anchored permanently to the initial balance captured at challenge start. |
| 18 | MQL5/Include/PropRulebook/CTerminalAlgoSwitch.mqh | Include | Drives the terminal's global Algo Trading button through a pending latch that verifies the requested state on later passes. |
| 19 | MQL5/Include/PropRulebook/CTrailingDrawdownRule.mqh | Include | Weighs equity against a floor that ratchets up with the account peak and then freezes. |
| 20 | MQL5/Include/PropRulebook/CWeekendFlatRule.mqh | Include | Asks for a flatten only when the pre-weekend cutoff has been reached while exposure is still open. |
| 21 | MQL5/Include/PropRulebook/IPropRule.mqh | Include | Abstract base class holding the one contract every rule implements: configure or refuse, evaluate a frozen snapshot, report a verdict. |
| 22 | MQL5/Include/PropRulebook/PropAccountSnapshot.mqh | Include | Immutable per-pass record holding every account, session, excursion and calendar figure a rule is allowed to read. |
| 23 | MQL5/Include/PropRulebook/PropFirmProfile.mqh | Include | Configuration record in which every threshold is paired with its own explicit enable flag. |
| 24 | MQL5/Include/PropRulebook/PropRuleVerdict.mqh | Include | Verdict record plus the rule-id, severity and directive enumerations one rule reports for one pass. |
| 25 | MQL5/Scripts/PropRulebook/TestPropRulebook.mq5 | Script | Synthetic-data verification script: every figure is built in the file, the rules are exercised through their real public API, and the outcome is written to the Journal and to a JSON file. |
| 26 | MQL5.zip | Archive | Archive containing all files in the required folder structure. |
Warning: All rights to these materials are reserved by MetaQuotes Ltd. Copying or reprinting of these materials in whole or in part is prohibited.
This article was written by a user of the site and reflects their personal views. MetaQuotes Ltd is not responsible for the accuracy of the information presented, nor for any consequences resulting from the use of the solutions, strategies or recommendations described.