# Prop Firm Guard Prop Firm Guard is a MetaTrader 5 Expert Advisor developed as a seven part MQL5 article series. The project builds a persistent prop firm compliance monitor that combines account rules, daily session recovery, drawdown monitoring, profit target tracking, Economic Calendar restrictions, alerts, automated protection actions, SQLite persistence, and a complete chart dashboard. ## Overview The completed EA monitors the trading account against a defined set of prop firm rules and keeps the monitoring state consistent across EA removal, terminal restarts, and trading day changes. The implementation includes: - account specific rule configuration - SQLite backed persistent settings - server date based daily sessions - confirmed daily starting balances - daily drawdown monitoring - overall drawdown monitoring - profit target tracking - Economic Calendar filtering - exposure aware news checks - news position matching - news holding restrictions - alert state management - automated protection actions - runtime session persistence - restart safe state recovery - complete two column chart dashboard - controlled runtime database updates - chart presentation and cleanup ## Project Purpose The project demonstrates how to build a restart safe compliance monitor in MQL5 without relying only on volatile runtime variables. Prop Firm Guard separates the system into several cooperating layers: 1. rule and account configuration 2. persistent storage 3. daily session management 4. financial compliance calculations 5. Economic Calendar and position analysis 6. alerts and protection actions 7. runtime synchronization and dashboard reporting The completed EA uses these layers as one runtime system. ## Article Series ### Part 1 **Building a Prop Firm Compliance Monitor in MQL5 Part 1: Account Rules and Persistent Settings** Establishes the EA foundation, rule inputs, validation, live account state collection, SQLite database lifecycle, and account specific persistent settings. ### Part 2 **Building a Prop Firm Compliance Monitor in MQL5 Part 2: Daily Sessions and Restart Safe Starting Balances** Adds trading day session management based on the trading server date, account login, and server. The daily starting balance is explicitly confirmed and restored after EA removal or terminal restart. ### Part 3 **Building a Prop Firm Compliance Monitor in MQL5 Part 3: Daily Drawdown, Overall Drawdown, and Profit Targets** Implements the financial compliance engine for daily drawdown, overall drawdown, profit target progress, remaining allowance, status classification, and combined guard priority. ### Part 4 **Building a Prop Firm Compliance Monitor in MQL5 Part 4: Economic Calendar and Account Exposure Monitoring** Adds Economic Calendar monitoring and account exposure detection so relevant currencies and upcoming economic events can be evaluated against the account's current positions. ### Part 5 **Building a Prop Firm Compliance Monitor in MQL5 Part 5: News Position Matching and Holding Restrictions** Matches open positions to relevant economic events, classifies affected positions, evaluates holding restrictions, and determines when news protection is required. ### Part 6 **Building a Prop Firm Compliance Monitor in MQL5 Part 6: Alerts and Automated Protection Actions** Adds state aware alerts and configurable protection actions for daily drawdown, overall drawdown, and news restrictions. Protection can warn only, close affected positions, or close all positions according to the configured rule. ### Part 7 **Building a Prop Firm Compliance Monitor in MQL5 Part 7: Runtime Persistence and the Complete Monitoring Dashboard** Completes the runtime system by synchronizing live session values with SQLite, throttling database writes, restoring runtime state after restart, and presenting session, account, drawdown, profit target, news, and overall guard information through a two column chart dashboard. ## Main Source File The completed Expert Advisor is: ```text PropFirmGuard.mq5 ``` ## SQLite Database The EA uses the following SQLite database file: ```text prop_firm_compliance.sqlite ``` The database stores account specific settings and daily session state so the EA can restore the correct configuration and current trading day record after restart. The daily session record includes runtime fields such as: - account login - account server - trading date - starting balance - starting equity - balance confirmation state - latest balance - latest equity - daily loss - maximum daily loss reached - profit target progress - session status - creation time - update time ## Core Data Models The project uses several structures and enums to keep monitoring responsibilities separate. Important runtime models include: - `SAccountState` - `SAccountSettings` - `SDailySession` - `SDailyDrawdownState` - `SOverallDrawdownState` - `SProfitTargetState` - `SNewsState` - `SNewsPositionMatch` - `SAlertState` Important status enums include: - `ENUM_COMPLIANCE_STATUS` - `ENUM_TARGET_STATUS` - `ENUM_GUARD_STATUS` - `ENUM_NEWS_STATUS` - `ENUM_NEWS_POSITION_STATUS` - `ENUM_NEWS_HOLDING_STATUS` - `ENUM_PROTECTION_ACTION` ## Runtime Architecture The completed timer cycle follows this sequence: ```text account refresh session rollover financial calculations news state position classification alerts protection account refresh financial recalculation runtime persistence dashboard refresh ``` The second account refresh is important because a protection action may close positions and immediately change balance, equity, drawdown values, and profit target progress. The dashboard and SQLite snapshot are therefore updated from the resulting post protection state. ## Daily Session Persistence Daily sessions are associated with: - trading server date - account login - account server A confirmed starting balance becomes the daily reference used by the drawdown calculations. When the EA is removed and attached again during the same trading day, the existing session can be loaded from SQLite instead of creating a new baseline. Runtime values are synchronized into the current session and written at a controlled interval. ## Runtime Database Throttling The monitoring timer can run every second while SQLite runtime snapshots are written less frequently. The completed implementation limits runtime session persistence to no more than one update every ten seconds. This keeps the live dashboard responsive while avoiding unnecessary database writes on every timer cycle. ## Maximum Daily Loss Tracking The current daily loss and the maximum daily loss reached are stored separately. If the account reaches a daily loss of: ```text 450.00 ``` and later recovers to: ```text 180.00 ``` the current daily loss can become `180.00` while the stored maximum remains `450.00`. This preserves the greatest actual loss observed during the trading day. ## Financial Compliance Monitoring ### Daily Drawdown Tracks the current loss against the confirmed daily starting balance and reports: - maximum daily loss - current daily loss - drawdown percentage - limit usage - remaining allowance - compliance status ### Overall Drawdown Tracks account equity against the configured overall loss limit and reports: - initial challenge balance - equity floor - current equity - overall loss - limit usage - remaining allowance - compliance status ### Profit Target Tracks progress toward the configured profit target and reports: - target balance - current profit - progress percentage - remaining profit - target status ## Economic Calendar Monitoring The EA uses MetaTrader 5 Economic Calendar data to evaluate upcoming events against current account exposure. The news workflow includes: - supported currency extraction - event lookup - event importance filtering - restriction window calculation - affected position classification - news holding status - protection requirement detection The dashboard reports the selected event, event currency, importance, countdown, trading window, holding rule, affected positions, and current news status. ## Alerts Alert state is tracked so notifications are generated from meaningful state transitions instead of repeating continuously on every timer cycle. Alert monitoring covers: - daily drawdown - overall drawdown - profit target completion - approaching news events - active news restriction windows The latest alert message can also be retained for dashboard presentation. ## Protection Actions Protection behavior is configurable through `ENUM_PROTECTION_ACTION`. Supported modes include: ```text PROTECTION_WARN_ONLY PROTECTION_CLOSE_AFFECTED PROTECTION_CLOSE_ALL ``` These actions can be assigned independently to: - daily drawdown - overall drawdown - news restrictions Trade closure uses synchronous `CTrade` execution and validates the returned trade result before treating the close as successful. Automatic close tests should be performed in a safe demo environment. ## Dashboard The completed dashboard uses a two column layout. ### Left Column - SESSION - ACCOUNT - DAILY DRAWDOWN - STATUS ### Right Column - OVERALL DRAWDOWN - PROFIT TARGET - NEWS The dashboard also shows a main overall status at the top. Values are updated by modifying existing chart objects instead of recreating the interface on every timer cycle. Dashboard objects use the prefix: ```text PFG_ ``` This allows the EA to identify and remove only its own chart objects during cleanup. ## Daily Balance Confirmation Controls The dashboard integrates the existing daily starting balance edit field and confirmation button. Before confirmation, the session remains in setup mode. After a valid starting balance is confirmed: - the session is saved immediately - the confirmation controls are removed - daily drawdown monitoring becomes active - the dashboard refreshes with the confirmed session state ## Chart Presentation Prop Firm Guard configures the chart to provide a consistent workspace for the monitoring interface. The configuration includes: - light chart background - dark foreground text - hidden chart grid - candlestick mode - green bullish candles - red bearish candles - Bid and Ask colors - visible trade levels - draggable trade levels - visible One Click Trading panel - dedicated Stop Loss and Take Profit color ## Cleanup When the EA is removed, dashboard cleanup deletes only chart objects whose names begin with: ```text PFG_ ``` Unrelated chart objects remain untouched. The timer is stopped and the SQLite connection is closed cleanly during deinitialization. ## Verification The completed project can be verified by checking that: - dashboard values follow live account changes - runtime values are written to the current daily session - SQLite updates are throttled to the configured runtime interval - maximum daily loss never decreases after recovery - the same daily session is restored after EA removal and reattachment - a confirmed starting balance remains confirmed after restart - alerts still respond to monitored state changes - configured protection actions still execute correctly - dashboard and persisted financial values reflect the account state after protection actions ## Series Releases The series uses release tags following this pattern: ```text v1.0-part-1 v1.0-part-2 v1.0-part-3 v1.0-part-4 v1.0-part-5 v1.0-part-6 v1.0-part-7 ``` The final release is: ```text Tag: v1.0-part-7 Title: Part 7 - Runtime Persistence and the Complete Monitoring Dashboard ``` ## Repository Purpose This repository preserves the complete Prop Firm Guard implementation developed across the seven part MQL5 series. It can be used as a reference for: - persistent MQL5 Expert Advisor architecture - account specific SQLite storage - restart safe daily sessions - drawdown and profit target monitoring - MetaTrader Economic Calendar integration - position aware news restrictions - state aware alert systems - automated protection logic - dashboard driven compliance monitoring - coordinating runtime state, persistence, and presentation ## Original Articles Author: ```text Chacha Ian Maroa ``` Platform: ```text MQL5.com ``` Series: ```text Building a Prop Firm Compliance Monitor in MQL5 ``` Article IDs, publication dates, and final article URLs can be added to this README as each published article page becomes available. ## Tags ```text MQL5 MetaTrader5 Expert-Advisor Prop-Firm Compliance SQLite Persistence Drawdown Daily-Drawdown Overall-Drawdown Profit-Target Economic-Calendar News-Filter Risk-Management Trade-Protection Dashboard Restart-Recovery Algorithmic-Trading ``` ## Difficulty Intermediate ## Notes Prop Firm Guard is designed as a compliance monitoring and protection example for MetaTrader 5. Prop firm rules differ between providers, account types, and challenge programs, so the configured limits and restrictions should match the rules that apply to the account being monitored. Automatic trade protection can close positions when configured conditions are reached. Testing and validation should therefore be performed in a demo or other safe environment before using protection actions with a live trading account.