Building a Prop Firm Compliance Monitor in MQL5 (Part 4): Economic Calendar and Account Exposure Monitoring
Introduction
Some prop-firm programs restrict how traders manage open positions around important economic releases. For Prop Firm Guard, the problem is not simply reading MetaTrader 5's Economic Calendar. The EA first needs to determine which events are relevant to the account's current holdings.
Checking only the chart's _Symbol is not enough because the account may hold positions on several instruments. Part 4 therefore scans all open positions, derives the supported exposed currencies, removes duplicates, and uses that set to filter the calendar. For example, EURUSD and GBPUSD produce EUR, USD, and GBP exposure. For the explicit XAU/USD case used in this implementation, USD is monitored when the broker reports XAU as the base currency and USD as the profit currency.
This Part is limited to holding-based news monitoring. If there are no supported open positions, the EA can report no supported holding exposure, but that does not mean a new trade would necessarily be allowed.
By the end of Part 4, Prop Firm Guard will distinguish no supported holding exposure, no qualifying event, unavailable data, a safe upcoming event, and an active news restriction. A manual verification matrix near the end of this article provides repeatable scenarios for checking these states. The tests use the account-level variable g_newsState.status, which can be inspected in the MetaEditor debugger immediately after UpdateNewsState() executes in OnTimer(). Because exposure is collected across the account, the chart symbol does not determine which positions are monitored.
Define the News Model and Validate Its Inputs
Before collecting position exposure or querying the Economic Calendar, Part 4 needs clear result states. In particular, the EA must not treat an empty search as a data failure, or an unsupported instrument as an unreadable one. These distinctions begin with the news-related enumerations. Place the following news-status enumeration immediately after ENUM_GUARD_STATUS:
//+------------------------------------------------------------------+ //| Economic news monitoring status | //+------------------------------------------------------------------+ //| Represents the current account-level holding-news condition. | //+------------------------------------------------------------------+ enum ENUM_NEWS_STATUS { NEWS_DISABLED = 0, // Economic news monitoring is disabled NEWS_NO_EXPOSURE, // No supported current holding exposure exists NEWS_NO_EVENT, // Search succeeded but no qualifying event exists NEWS_SAFE, // Relevant event exists outside its restriction window NEWS_RESTRICTED, // Current time is inside the news restriction window NEWS_UNAVAILABLE // Required exposure or calendar data could not be verified };
The key distinction is between NEWS_NO_EXPOSURE, NEWS_NO_EVENT, and NEWS_UNAVAILABLE. The first means the account has no supported current holding exposure. The second means supported exposure exists and a valid calendar search found no qualifying event. The third means the EA could not reliably verify the required exposure or calendar data. An enabled news subsystem should therefore begin in NEWS_UNAVAILABLE until its first complete evaluation. Starting in NEWS_NO_EXPOSURE would incorrectly claim that the account had already been inspected.
Next, place ENUM_NEWS_SEARCH_RESULT immediately after ENUM_NEWS_STATUS:
//+------------------------------------------------------------------+ //| Economic calendar search result | //+------------------------------------------------------------------+ //| Separates retrieval failure from a valid empty calendar search. | //+------------------------------------------------------------------+ enum ENUM_NEWS_SEARCH_RESULT { NEWS_SEARCH_ERROR = -1, // Required calendar data could not be retrieved reliably NEWS_SEARCH_NO_EVENT = 0, // Search completed but found no qualifying event NEWS_SEARCH_FOUND = 1 // Search completed and found a qualifying event };
This enumeration gives the calendar layer three explicit outcomes instead of returning one Boolean for both failure and absence. A successful empty search can now propagate NEWS_SEARCH_NO_EVENT, while a failed calendar request propagates NEWS_SEARCH_ERROR. The symbol layer needs the same distinction. Place ENUM_SYMBOL_NEWS_RESULT immediately after ENUM_NEWS_SEARCH_RESULT:
//+------------------------------------------------------------------+ //| Symbol news exposure result | //+------------------------------------------------------------------+ //| Distinguishes supported, unsupported, and unreadable symbols. | //+------------------------------------------------------------------+ enum ENUM_SYMBOL_NEWS_RESULT { SYMBOL_NEWS_ERROR = -1, // Required symbol properties could not be verified SYMBOL_NEWS_UNSUPPORTED = 0, // Symbol is outside the supported Part 4 exposure model SYMBOL_NEWS_SUPPORTED = 1 // Symbol contributes one or more monitored currencies };
An unsupported instrument is not automatically an error. It simply falls outside the exposure model implemented in this Part. SYMBOL_NEWS_ERROR is reserved for cases where the EA cannot verify the properties required to classify the symbol. Account-wide collection also needs to preserve partial results. Place ENUM_EXPOSURE_COLLECTION_RESULT immediately after ENUM_SYMBOL_NEWS_RESULT:
//+------------------------------------------------------------------+ //| Account news exposure collection result | //+------------------------------------------------------------------+ //| Distinguishes complete, empty, partial, and failed collection. | //+------------------------------------------------------------------+ enum ENUM_EXPOSURE_COLLECTION_RESULT { EXPOSURE_COLLECTION_ERROR = -1, // Collection could not produce a usable result EXPOSURE_COLLECTION_NO_EXPOSURE = 0, // Complete scan found no supported holding exposure EXPOSURE_COLLECTION_COMPLETE = 1, // Complete scan produced supported currencies EXPOSURE_COLLECTION_PARTIAL = 2 // Some position data could not be verified };
EXPOSURE_COLLECTION_PARTIAL allows the EA to retain currencies discovered from readable positions while still acknowledging that the complete account exposure could not be verified. Later, that condition will produce NEWS_UNAVAILABLE rather than a misleading safe result.
The main distinctions established so far are:
NO EXPOSURE != NO EVENT NO EVENT != UNAVAILABLE UNSUPPORTED != ERROR
Storing the Account-Level News State
The result of the complete monitoring cycle needs one runtime structure. Place SNewsState immediately after SProfitTargetState:
//+------------------------------------------------------------------+ //| Economic news monitoring state | //+------------------------------------------------------------------+ //| Holds the current runtime result of holding-based news analysis. | //+------------------------------------------------------------------+ struct SNewsState { bool hasExposure; // Supported holding exposure was identified bool exposureComplete; // Current holding exposure was fully verified int monitoredCurrencies; // Number of unique monitored currencies string currencyList; // Readable monitored currency list bool eventFound; // A relevant calendar event was selected string eventCurrency; // Currency associated with selected event ulong eventId; // Selected Economic Calendar event identifier string eventName; // Selected Economic Calendar event name ENUM_CALENDAR_EVENT_IMPORTANCE importance; // Importance of selected event datetime eventTime; // Selected event time in trade-server time long secondsToEvent; // Signed seconds relative to selected event datetime restrictionStart; // Start of configured restriction interval datetime restrictionEnd; // End of configured restriction interval bool restrictedWindow; // Whether restriction is currently active ENUM_NEWS_STATUS status; // Current account-level news condition };
The structure separates exposure completeness from event availability. For example, hasExposure may be true while exposureComplete is false if some positions were readable and another could not be verified. That distinction prevents partially known exposure from being presented as a complete account result.
Adding the Runtime News and Cache State
In the global-variable block, add the following declaration immediately after g_profitTarget:
SNewsState g_newsState; // Current economic-news runtime state Then, after the existing database and session globals, add:
datetime g_newsLastCalendarRefresh = 0; // Last successful calendar evaluation string g_newsCachedExposureKey = ""; // Exposure set used by cached calendar state bool g_newsCalendarCacheValid = false; // Whether cached calendar state is reusable
g_newsState remains the authoritative Part 4 runtime result. The three additional variables do not duplicate that state. They only record whether the current calendar result can be reused and when it was last refreshed. Immediately after the global variables, add the internal news constants:
//+------------------------------------------------------------------+ //| Economic news monitoring constants | //+------------------------------------------------------------------+ const int NEWS_DEFAULT_FORWARD_MINUTES = 24 * 60; const int NEWS_CALENDAR_REFRESH_SECONDS = 60;
NEWS_DEFAULT_FORWARD_MINUTES provides a 24-hour minimum forward search horizon. Later, the search can expand beyond that value when InpMinutesBeforeNews requires a longer interval. NEWS_CALENDAR_REFRESH_SECONDS will limit redundant calendar calls while allowing the timer itself to continue running more frequently.
Validating the News Inputs
Part 4 introduces configuration values that directly affect the search interval and restriction window. Negative restriction periods or an invalid calendar importance value should therefore be rejected during initialization rather than allowed to reach the calendar engine. Replace the existing ValidateComplianceInputs() function with the following complete version:
//+------------------------------------------------------------------+ //| Validate compliance inputs | //+------------------------------------------------------------------+ bool ValidateComplianceInputs() { //--- Validate the monitoring interval if(InpTimerSeconds < 1) { Print("Prop Firm Guard: Timer interval must be at least 1 second."); return(false); } //--- Validate the configured daily reset hour if(InpDailyResetHour < 0 || InpDailyResetHour > 23) { Print("Prop Firm Guard: Daily reset hour must be between 0 and 23."); return(false); } //--- Validate the configured daily reset minute if(InpDailyResetMinute < 0 || InpDailyResetMinute > 59) { Print("Prop Firm Guard: Daily reset minute must be between 0 and 59."); return(false); } //--- Validate the initial account balance if(InpInitialAccountBalance <= 0.0) { Print("Prop Firm Guard: Initial account balance must be greater than zero."); return(false); } //--- Validate the daily drawdown percentage if(InpDailyDrawdownPercent <= 0.0 || InpDailyDrawdownPercent > 100.0) { Print("Prop Firm Guard: Daily drawdown percentage must be between 0 and 100."); return(false); } //--- Validate the overall drawdown percentage if(InpOverallDrawdownPercent <= 0.0 || InpOverallDrawdownPercent > 100.0) { Print("Prop Firm Guard: Overall drawdown percentage must be between 0 and 100."); return(false); } //--- Validate the profit target percentage if(InpProfitTargetPercent <= 0.0 || InpProfitTargetPercent > 100.0) { Print("Prop Firm Guard: Profit target percentage must be between 0 and 100."); return(false); } //--- Validate the warning threshold if(InpWarningLevelPercent <= 0.0 || InpWarningLevelPercent >= InpCriticalLevelPercent) { Print("Prop Firm Guard: Warning level must be greater than 0 and below the critical level."); return(false); } //--- Validate the critical threshold if(InpCriticalLevelPercent <= InpWarningLevelPercent || InpCriticalLevelPercent >= 100.0) { Print("Prop Firm Guard: Critical level must be above the warning level and below 100."); return(false); } //--- Validate the news restriction windows if(InpMinutesBeforeNews < 0 || InpMinutesAfterNews < 0) { Print("Prop Firm Guard: News restriction minutes cannot be negative."); return(false); } //--- Accept only known Economic Calendar importance values switch(InpNewsImportance) { case CALENDAR_IMPORTANCE_NONE: case CALENDAR_IMPORTANCE_LOW: case CALENDAR_IMPORTANCE_MODERATE: case CALENDAR_IMPORTANCE_HIGH: break; default: Print("Prop Firm Guard: Economic news importance setting is invalid."); return(false); } return(true); }
The existing Part 3 checks remain unchanged. Part 4 adds validation for InpMinutesBeforeNews, InpMinutesAfterNews, and InpNewsImportance. This prevents invalid restriction periods from producing malformed time ranges and ensures that only recognized Economic Calendar importance values reach the search layer.
The four news-filter inputs and their default values in the attached source are listed below.
| Input | Type | Default | Purpose |
|---|---|---|---|
| InpEnableNewsFilter | bool | true | Enables or disables economic news monitoring. |
| InpMinutesBeforeNews | int | 10 | Number of minutes before a qualifying event when the restriction begins. |
| InpMinutesAfterNews | int | 10 | Number of minutes after a qualifying event when the restriction ends. |
| InpNewsImportance | ENUM_CALENDAR_EVENT_IMPORTANCE | CALENDAR_IMPORTANCE_HIGH | Minimum event importance accepted by the calendar filter. |
With these defaults, the monitor considers high-importance events and applies a 10-minute restriction before and after each qualifying event. The importance setting acts as a minimum threshold, so events below the selected level are excluded.
These values reproduce the defaults in the attached source. They are starting configuration values, not universal requirements for every prop-firm program. Adjust them to match the rules of the program being monitored.
At this point, the news model has explicit contracts for successful, empty, unsupported, partial, and unavailable conditions. The next section can use those contracts to build the actual holding-exposure set without confusing absence with failure.
Build the Supported Holding-Exposure Set
The calendar search should begin from the positions the account is actually holding. Prop Firm Guard therefore builds one unique set of currencies from all supported open positions. The revised implementation also separates unsupported instruments from positions whose required symbol data cannot be verified, allowing readable exposure to be preserved even when one position fails.
Initialize the News State
Before collecting exposure, the runtime state needs a known starting condition. Place InitializeNewsState() immediately after ResetProfitTargetState():
//+------------------------------------------------------------------+ //| Initialize economic news state | //+------------------------------------------------------------------+ void InitializeNewsState() { //--- Clear the current holding-exposure result g_newsState.hasExposure = false; g_newsState.exposureComplete = false; g_newsState.monitoredCurrencies = 0; g_newsState.currencyList = ""; //--- Clear the previously selected calendar event g_newsState.eventFound = false; g_newsState.eventCurrency = ""; g_newsState.eventId = 0; g_newsState.eventName = ""; g_newsState.importance = CALENDAR_IMPORTANCE_NONE; g_newsState.eventTime = 0; //--- Clear event timing and restriction-window values g_newsState.secondsToEvent = 0; g_newsState.restrictionStart = 0; g_newsState.restrictionEnd = 0; g_newsState.restrictedWindow = false; //--- Preserve disabled configuration; otherwise require fresh evaluation if(InpEnableNewsFilter) g_newsState.status = NEWS_UNAVAILABLE; else g_newsState.status = NEWS_DISABLED; }
The function clears both exposure and event information. Notice that an enabled subsystem begins as NEWS_UNAVAILABLE. At this point no exposure scan or calendar search has been completed, so reporting NEWS_NO_EXPOSURE would make a claim that has not yet been verified.
Some later operations need to discard only the selected calendar event while keeping the current exposure. Place ResetNewsEventState() immediately after InitializeNewsState():
//+------------------------------------------------------------------+ //| Reset selected news-event state | //+------------------------------------------------------------------+ void ResetNewsEventState() { //--- Clear only calendar-event fields while preserving exposure g_newsState.eventFound = false; g_newsState.eventCurrency = ""; g_newsState.eventId = 0; g_newsState.eventName = ""; g_newsState.importance = CALENDAR_IMPORTANCE_NONE; g_newsState.eventTime = 0; g_newsState.secondsToEvent = 0; g_newsState.restrictionStart = 0; g_newsState.restrictionEnd = 0; g_newsState.restrictedWindow = false; }
Unlike InitializeNewsState(), this helper leaves the holding-exposure fields unchanged. It will become useful when cached calendar information must be replaced without discarding a valid exposure scan
Build a Unique Currency Set
Several positions may contribute the same currency. EURUSD and GBPUSD, for example, both introduce USD exposure. The calendar layer needs USD only once.For the current cumulative source, place CurrencyExists() immediately after ResetNewsEventState():
//+------------------------------------------------------------------+ //| Check whether currency already exists in array | //+------------------------------------------------------------------+ bool CurrencyExists(const string ¤cies[], const string currency) { int count = ArraySize(currencies); //--- Search the current unique currency set for(int i = 0; i < count; i++) { if(currencies[i] == currency) return(true); } return(false); }
The helper performs a direct lookup through the working currency array. The set is normally small because it is derived only from currencies represented by open positions. Place AddUniqueCurrency() immediately after CurrencyExists():
//+------------------------------------------------------------------+ //| Add one unique currency to array | //+------------------------------------------------------------------+ bool AddUniqueCurrency(string ¤cies[], const string currency) { //--- Ignore an empty currency because it contributes no exposure if(currency == "") return(true); //--- Existing currencies already satisfy the request if(CurrencyExists(currencies, currency)) return(true); int currentSize = ArraySize(currencies); //--- Extend the array for one new currency int newSize = ArrayResize(currencies, currentSize + 1); if(newSize != currentSize + 1) { Print("Prop Firm Guard: Could not expand the monitored currency array."); return(false); } //--- Append the newly discovered currency currencies[currentSize] = currency; return(true); }
An empty or duplicated currency is not an error. The function returns false only when the array cannot be expanded for a genuinely new value. The working array will later also need a readable representation. Place BuildCurrencyList() immediately after AddUniqueCurrency():
//+------------------------------------------------------------------+ //| Build readable monitored currency list | //+------------------------------------------------------------------+ string BuildCurrencyList(const string ¤cies[]) { string result = ""; int count = ArraySize(currencies); //--- Join the working currency set for logs and presentation for(int i = 0; i < count; i++) { if(i > 0) result += ", "; result += currencies[i]; } return(result); }
The array remains the working representation used by the monitoring logic. BuildCurrencyList() only converts it into a readable value such as EUR, USD, GBP for runtime state and later presentation.
Derive News Currencies From a Symbol
The next step is to determine what one position contributes. The EA uses broker-defined symbol properties rather than splitting the visible symbol name, so suffixes or prefixes do not determine the mapping. Place GetSymbolNewsCurrencies() immediately after BuildCurrencyList():
//+------------------------------------------------------------------+ //| Get supported news currencies for one symbol | //+------------------------------------------------------------------+ ENUM_SYMBOL_NEWS_RESULT GetSymbolNewsCurrencies(const string symbol, string ¤cy1, string ¤cy2) { currency1 = ""; currency2 = ""; //--- Require a usable symbol identifier if(symbol == "") { Print("Prop Firm Guard: Cannot evaluate news exposure for an empty symbol."); return(SYMBOL_NEWS_ERROR); } string baseCurrency; string profitCurrency; //--- Read the broker-defined base currency ResetLastError(); if(!SymbolInfoString(symbol, SYMBOL_CURRENCY_BASE, baseCurrency)) { Print("Prop Firm Guard: Could not read base currency for ", symbol, ". Error: ", GetLastError()); return(SYMBOL_NEWS_ERROR); } //--- Read the broker-defined profit currency ResetLastError(); if(!SymbolInfoString(symbol, SYMBOL_CURRENCY_PROFIT, profitCurrency)) { Print("Prop Firm Guard: Could not read profit currency for ", symbol, ". Error: ", GetLastError()); return(SYMBOL_NEWS_ERROR); } //--- Apply the explicit XAU/USD monitoring assumption if(baseCurrency == "XAU" && profitCurrency == "USD") { currency1 = "USD"; return(SYMBOL_NEWS_SUPPORTED); } long calculationMode = 0; //--- Read the broker-defined symbol calculation model ResetLastError(); if(!SymbolInfoInteger(symbol, SYMBOL_TRADE_CALC_MODE, calculationMode)) { Print("Prop Firm Guard: Could not read calculation mode for ", symbol, ". Error: ", GetLastError()); return(SYMBOL_NEWS_ERROR); } //--- Limit normal currency extraction to supported Forex modes if(calculationMode != SYMBOL_CALC_MODE_FOREX && calculationMode != SYMBOL_CALC_MODE_FOREX_NO_LEVERAGE) return(SYMBOL_NEWS_UNSUPPORTED); //--- Require both broker-defined Forex currencies if(baseCurrency == "" || profitCurrency == "") { Print("Prop Firm Guard: Supported Forex symbol ", symbol, " does not provide complete currency metadata."); return(SYMBOL_NEWS_ERROR); } //--- Publish the supported Forex exposure currency1 = baseCurrency; currency2 = profitCurrency; return(SYMBOL_NEWS_SUPPORTED); }
For supported Forex calculation modes, the function contributes both broker-defined currencies. EURUSD therefore contributes EUR and USD, while GBPJPY contributes GBP and JPY.
The XAU/USD branch is narrower by design. It applies only when the broker reports XAU as the base currency and USD as the profit currency. In that exact case, the implementation contributes USD only. This is an explicit assumption used by Prop Firm Guard, not a universal model for every gold instrument.
Other calculation modes return SYMBOL_NEWS_UNSUPPORTED. A failure to obtain required symbol properties instead returns SYMBOL_NEWS_ERROR. Keeping those results separate is important because unsupported instruments may be skipped normally, while unreadable data means the complete holding exposure cannot be verified.
The resulting mappings are:
| Position definition | Exposure result |
|---|---|
| Forex EURUSD | EUR, USD |
| Forex GBPUSD | GBP, USD |
| XAU/USD assumption | USD |
| Unsupported index | Ignored |
| Unreadable symbol | Exposure marked incomplete |
Add One Position to the Exposure Set
GetSymbolNewsCurrencies() interprets one symbol, while the next helper adds the resulting currencies to the account-wide unique set. Place AddPositionCurrencies() immediately after GetSymbolNewsCurrencies():
//+------------------------------------------------------------------+ //| Add supported currencies from one position symbol | //+------------------------------------------------------------------+ ENUM_SYMBOL_NEWS_RESULT AddPositionCurrencies(const string symbol, string ¤cies[]) { string currency1; string currency2; //--- Determine how this position symbol maps into the news model ENUM_SYMBOL_NEWS_RESULT result = GetSymbolNewsCurrencies(symbol, currency1, currency2); //--- Preserve unsupported and unreadable outcomes for the caller if(result != SYMBOL_NEWS_SUPPORTED) return(result); //--- Add each supported currency without duplication if(!AddUniqueCurrency(currencies, currency1)) return(SYMBOL_NEWS_ERROR); if(!AddUniqueCurrency(currencies, currency2)) return(SYMBOL_NEWS_ERROR); return(SYMBOL_NEWS_SUPPORTED); }
The function deliberately returns the symbol result to its caller instead of reducing everything to true or false. This allows the account-level collector to skip unsupported positions while treating unreadable positions as incomplete exposure.
Collect Exposure Across the Account
The final helper scans every open account position and combines the supported currencies. Place CollectExposureCurrencies() immediately after AddPositionCurrencies():
//+------------------------------------------------------------------+ //| Collect supported currencies from all open positions | //+------------------------------------------------------------------+ ENUM_EXPOSURE_COLLECTION_RESULT CollectExposureCurrencies( string ¤cies[]) { //--- Start every account scan with an empty working set if(ArrayResize(currencies, 0) != 0) { Print("Prop Firm Guard: Could not reset the monitored currency array."); return(EXPOSURE_COLLECTION_ERROR); } int totalPositions = PositionsTotal(); //--- A complete empty account has no current holding exposure if(totalPositions == 0) return(EXPOSURE_COLLECTION_NO_EXPOSURE); bool collectionIncomplete = false; //--- Inspect every currently open account position for(int i = 0; i < totalPositions; i++) { ResetLastError(); string symbol = PositionGetSymbol(i); if(symbol == "") { Print("Prop Firm Guard: Could not retrieve position symbol at index ", i, ". Error: ", GetLastError()); collectionIncomplete = true; continue; } //--- Interpret this position without allowing one failure to erase others ENUM_SYMBOL_NEWS_RESULT result = AddPositionCurrencies(symbol, currencies); if(result == SYMBOL_NEWS_UNSUPPORTED) continue; if(result == SYMBOL_NEWS_ERROR) { collectionIncomplete = true; continue; } } int currencyCount = ArraySize(currencies); //--- Any unreadable position means the complete exposure is unverified if(collectionIncomplete) return(EXPOSURE_COLLECTION_PARTIAL); //--- A complete scan may legitimately contain no supported currencies if(currencyCount == 0) return(EXPOSURE_COLLECTION_NO_EXPOSURE); return(EXPOSURE_COLLECTION_COMPLETE); }
The important change is the use of collectionIncomplete. A failure involving one position no longer ends the loop immediately. The EA continues inspecting the remaining positions and preserves any valid currencies it can derive.
Suppose EURUSD contributes EUR and USD, but another position has unreadable symbol properties. The array still contains EUR and USD, but the function returns EXPOSURE_COLLECTION_PARTIAL. The later account-level news calculation will treat that result as NEWS_UNAVAILABLE because the complete holding exposure cannot be verified.
Unsupported instruments behave differently. They are skipped without setting collectionIncomplete. If every open position is unsupported but all were inspected successfully, the result is EXPOSURE_COLLECTION_NO_EXPOSURE.
This gives the exposure layer the fault-aware contract required by the calendar engine:
supported position -> add its currencies unsupported position -> skip it unreadable position -> preserve known currencies -> mark exposure incomplete complete scan with no supported currencies -> NO EXPOSURE
The next section can now use this verified exposure set as the input to a calendar search that likewise distinguishes a valid empty result from unavailable data.
Build a Fault-Aware Economic Calendar Search
The holding-exposure set tells Prop Firm Guard which currencies matter. Before querying the Economic Calendar, the EA must establish a valid server time and a search interval wide enough to include both active post-news restrictions and upcoming events.
Set the Forward Search Horizon
Place GetNewsForwardSearchSeconds() immediately after ValidateComplianceInputs():
//+------------------------------------------------------------------+ //| Get economic news forward search horizon | //+------------------------------------------------------------------+ long GetNewsForwardSearchSeconds() { //--- Preserve a 24-hour minimum while covering longer pre-news rules long forwardMinutes = NEWS_DEFAULT_FORWARD_MINUTES; if((long)InpMinutesBeforeNews > forwardMinutes) forwardMinutes = (long)InpMinutesBeforeNews; return(forwardMinutes * 60); }
The search normally looks at least 24 hours ahead. If 'InpMinutesBeforeNews' is greater than 24 hours, the horizon expands accordingly. This prevents a long pre-news restriction from referring to an event outside the search range.
Validate Trade-Server Time
Place GetValidTradeServerTime() immediately after GetNewsForwardSearchSeconds():
//+------------------------------------------------------------------+ //| Get validated trade-server time | //+------------------------------------------------------------------+ bool GetValidTradeServerTime(datetime &serverTime) { //--- Read the time source used by MetaTrader Economic Calendar data serverTime = TimeTradeServer(); if(serverTime <= 0) { Print("Prop Firm Guard: Trade-server time is unavailable."); serverTime = 0; return(false); } //--- Confirm that the returned timestamp can be interpreted normally MqlDateTime timeParts; if(!TimeToStruct(serverTime, timeParts)) { Print("Prop Firm Guard: Trade-server time could not be validated."); serverTime = 0; return(false); } return(true); }
The Economic Calendar uses trade-server time. The function therefore validates TimeTradeServer() before that value is allowed into the news calculation.
Build the Calendar Search Range
Place BuildNewsSearchRange() immediately after GetValidTradeServerTime():
//+------------------------------------------------------------------+ //| Build economic news calendar search range | //+------------------------------------------------------------------+ bool BuildNewsSearchRange(const datetime currentTime, datetime &searchFrom, datetime &searchTo) { searchFrom = 0; searchTo = 0; //--- Require a validated current server timestamp if(currentTime <= 0) { Print("Prop Firm Guard: Cannot build a news search range from invalid server time."); return(false); } //--- Convert the configured post-news interval safely to seconds long backwardSeconds = (long)InpMinutesAfterNews * 60; long forwardSeconds = GetNewsForwardSearchSeconds(); //--- Reject unusable derived durations if(backwardSeconds < 0 || forwardSeconds <= 0) { Print("Prop Firm Guard: Economic news search duration is invalid."); return(false); } //--- Prevent the lower boundary from preceding the datetime epoch if(backwardSeconds > (long)currentTime) { Print("Prop Firm Guard: Post-news search interval exceeds the available server-time range."); return(false); } //--- Calculate the time boundaries using the underlying integer type long searchFromValue = (long)currentTime - backwardSeconds; long searchToValue = (long)currentTime + forwardSeconds; //--- Defend against invalid or overflowing time arithmetic if(searchFromValue < 0 || searchToValue <= (long)currentTime || searchToValue <= searchFromValue) { Print("Prop Firm Guard: Economic news search range could not be constructed safely."); return(false); } //--- Publish validated values only after the arithmetic succeeds searchFrom = (datetime)searchFromValue; searchTo = (datetime)searchToValue; return(true); }
The resulting interval is:
current time - post-news interval through current time + forward horizon
Looking backward is necessary because an event that has already been released may still be inside its post-news restriction. Looking forward allows the EA to detect upcoming events early enough for the configured pre-news interval.
The calendar search added in the next section will use the three results defined earlier:
NEWS_SEARCH_ERROR NEWS_SEARCH_NO_EVENT NEWS_SEARCH_FOUND
These meanings are intentionally separate. A calendar failure is not a valid no-event result, and an empty successful search is not a failure. With the search boundaries prepared, we can now define which event should be selected when the interval contains both recent and upcoming releases.
Select the Active or Upcoming Relevant Event
Calling the selected release the next event would be misleading. The search range includes the recent past so that an event whose post-news restriction is still active can outrank a later scheduled event. The selection logic must therefore distinguish an active relevant event from the nearest upcoming relevant event.
Detect an Active Restriction
Place IsNewsRestrictionActive() immediately after CollectExposureCurrencies():
//+------------------------------------------------------------------+ //| Check whether event restriction is active | //+------------------------------------------------------------------+ bool IsNewsRestrictionActive(const datetime eventTime, const datetime currentTime) { //--- Reject unusable timestamps before constructing the window if(eventTime <= 0 || currentTime <= 0) return(false); //--- Convert configured restriction intervals to seconds long beforeSeconds = (long)InpMinutesBeforeNews * 60; long afterSeconds = (long)InpMinutesAfterNews * 60; //--- Work with the underlying integer representation of datetime long eventValue = (long)eventTime; long currentValue = (long)currentTime; long restrictionStart = eventValue - beforeSeconds; long restrictionEnd = eventValue + afterSeconds; //--- Current time belongs to an inclusive restriction interval return(currentValue >= restrictionStart && currentValue <= restrictionEnd); }
The restriction is inclusive from the configured pre-news boundary through the post-news boundary. A recently released event can therefore remain active even though its event time is already in the past.
Rank Competing Events
Place IsBetterNewsCandidate() immediately after IsNewsRestrictionActive():
//+------------------------------------------------------------------+ //| Check whether a news candidate should replace the current one | //+------------------------------------------------------------------+ bool IsBetterNewsCandidate(const string candidateCurrency, const MqlCalendarValue &candidateValue, const MqlCalendarEvent &candidateEvent, const string currentCurrency, const MqlCalendarValue ¤tValue, const MqlCalendarEvent ¤tEvent, const datetime currentTime, const bool hasCurrent) { //--- The first valid candidate becomes the initial selection if(!hasCurrent) return(true); bool candidateActive = IsNewsRestrictionActive(candidateValue.time, currentTime); bool currentActive = IsNewsRestrictionActive(currentValue.time, currentTime); //--- An active restriction always outranks an inactive event if(candidateActive && !currentActive) return(true); if(!candidateActive && currentActive) return(false); //--- When both restrictions are active, prefer the nearer event time if(candidateActive && currentActive) { long candidateDistance = (long)candidateValue.time - (long)currentTime; long currentDistance = (long)currentValue.time - (long)currentTime; if(candidateDistance < 0) candidateDistance = -candidateDistance; if(currentDistance < 0) currentDistance = -currentDistance; if(candidateDistance < currentDistance) return(true); if(candidateDistance > currentDistance) return(false); } else { //--- Without an active restriction, only future events are relevant bool candidateFuture = candidateValue.time > currentTime; bool currentFuture = currentValue.time > currentTime; if(candidateFuture && !currentFuture) return(true); if(!candidateFuture && currentFuture) return(false); //--- Prefer the nearest future event if(candidateFuture && currentFuture) { if(candidateValue.time < currentValue.time) return(true); if(candidateValue.time > currentValue.time) return(false); } } //--- Resolve equal timing deterministically by currency int currencyComparison = StringCompare(candidateCurrency, currentCurrency); if(currencyComparison < 0) return(true); if(currencyComparison > 0) return(false); //--- Use event identifier as the final stable tie-breaker return(candidateEvent.id < currentEvent.id); }
An active restriction takes priority. If both candidates are active, the event closest to the current time wins. Otherwise, the earlier future event is preferred. Remaining ties are resolved by currency and finally by event ID, making the result deterministic.
For example, at 14:05 an event released at 14:00 may still be inside a 10-minute post-news restriction, while another event is scheduled for 14:20. The 14:00 event remains relevant first. After its restriction expires, the future event can become the selected candidate.
Search One Exposed Currency
The ranking dependencies now exist. Place FindRelevantNewsForCurrency() immediately after IsBetterNewsCandidate():
//+------------------------------------------------------------------+ //| Find active or upcoming relevant event for one currency | //+------------------------------------------------------------------+ ENUM_NEWS_SEARCH_RESULT FindRelevantNewsForCurrency( const string currency, const datetime timeFrom, const datetime timeTo, const datetime currentTime, MqlCalendarValue &bestValue, MqlCalendarEvent &bestEvent) { MqlCalendarValue values[]; //--- Require valid search inputs if(currency == "" || timeFrom <= 0 || timeTo <= timeFrom || currentTime <= 0) { Print("Prop Firm Guard: Cannot search calendar with invalid currency or time values."); return(NEWS_SEARCH_ERROR); } //--- Retrieve calendar values for one monitored currency ResetLastError(); int valueCount = CalendarValueHistory(values, timeFrom, timeTo, NULL, currency); if(valueCount < 0) { Print("Prop Firm Guard: Could not retrieve calendar values for ", currency, ". Error: ", GetLastError()); return(NEWS_SEARCH_ERROR); } //--- A successful empty response is a valid no-event result if(valueCount == 0) return(NEWS_SEARCH_NO_EVENT); bool foundCandidate = false; bool metadataFailure = false; string currentCurrency = ""; //--- Inspect every returned calendar value for(int i = 0; i < valueCount; i++) { MqlCalendarEvent event; ResetLastError(); if(!CalendarEventById(values[i].event_id, event)) { Print("Prop Firm Guard: Could not retrieve calendar event ", values[i].event_id, " for ", currency, ". Error: ", GetLastError()); metadataFailure = true; continue; } //--- Reject events below the configured importance threshold if(event.importance < InpNewsImportance) continue; //--- Require a precise scheduled datetime if(event.time_mode != CALENDAR_TIMEMODE_DATETIME) continue; //--- Ignore past events whose post-news restriction has expired if(values[i].time < currentTime && !IsNewsRestrictionActive(values[i].time, currentTime)) continue; //--- Retain the best active or upcoming qualifying event if(IsBetterNewsCandidate(currency, values[i], event, currentCurrency, bestValue, bestEvent, currentTime, foundCandidate)) { bestValue = values[i]; bestEvent = event; currentCurrency = currency; foundCandidate = true; } } //--- Do not publish a verified result from incomplete event metadata if(metadataFailure) { Print("Prop Firm Guard: Calendar event metadata for ", currency, " could not be completely verified."); return(NEWS_SEARCH_ERROR); } //--- A successful complete search may legitimately find no event if(!foundCandidate) return(NEWS_SEARCH_NO_EVENT); return(NEWS_SEARCH_FOUND); }
CalendarValueHistory() failure produces NEWS_SEARCH_ERROR, while a successful empty response produces NEWS_SEARCH_NO_EVENT. The function also requires the configured minimum importance and CALENDAR_TIMEMODE_DATETIME.
A failure in CalendarEventById() marks the search incomplete. Even if another candidate was readable, the function returns NEWS_SEARCH_ERROR because the complete result could not be verified. Expired past events are ignored. Remaining candidates are passed to IsBetterNewsCandidate() rather than selected simply by the smallest timestamp.
Build the Selected Restriction Window
Finally, place BuildNewsRestrictionWindow() immediately after FindRelevantNewsForCurrency():
//+------------------------------------------------------------------+ //| Build restriction window for one selected news event | //+------------------------------------------------------------------+ bool BuildNewsRestrictionWindow(const datetime eventTime, datetime &restrictionStart, datetime &restrictionEnd) { restrictionStart = 0; restrictionEnd = 0; //--- Require a usable scheduled event time if(eventTime <= 0) { Print("Prop Firm Guard: Cannot build a news restriction window from invalid event time."); return(false); } //--- Convert the configured rule windows to seconds long beforeSeconds = (long)InpMinutesBeforeNews * 60; long afterSeconds = (long)InpMinutesAfterNews * 60; long eventValue = (long)eventTime; //--- Prevent the pre-news boundary from preceding the datetime epoch if(beforeSeconds > eventValue) { Print("Prop Firm Guard: News restriction start exceeds the available datetime range."); return(false); } //--- Calculate the restriction boundaries using integer arithmetic long startValue = eventValue - beforeSeconds; long endValue = eventValue + afterSeconds; //--- Reject invalid or overflowing restriction boundaries if(startValue < 0 || endValue < eventValue || endValue < startValue) { Print("Prop Firm Guard: News restriction window could not be constructed safely."); return(false); } //--- Publish the validated datetime boundaries restrictionStart = (datetime)startValue; restrictionEnd = (datetime)endValue; return(true); }
This final helper converts the selected event into the exact pre-news and post-news boundaries that will be stored in the account-level news state.
Build the Account-Level News State
The account-level state must preserve the distinctions established earlier. NEWS_NO_EXPOSURE means that the account was inspected successfully but no supported current holding exposure was found. NEWS_NO_EVENT means that supported exposure exists and the calendar search completed successfully, but no event met the configured requirements. NEWS_UNAVAILABLE is reserved for cases where required position, symbol, server-time, or calendar information could not be verified.
When a qualifying event is available, the remaining distinction is temporal. NEWS_SAFE means the selected event is relevant but the current server time is outside its configured restriction interval. NEWS_RESTRICTED means the current server time is inside that interval.
Keeping these states separate prevents uncertainty from being reported as safety. A calendar retrieval failure, for example, must never produce NEWS_NO_EVENT, because the EA has not proved that no relevant event exists.
Format Time Relative to the Selected Event
The selected event also needs a readable indication of how far it is from the current server time. Later, UpdateNewsState() stores this difference in secondsToEvent. The value is calculated as the selected event time minus the current server time.
A positive secondsToEvent therefore means the event is still ahead. A negative value means the scheduled release has already occurred, which is possible because a recently released event may remain relevant during its post-news restriction period.
Place FormatNewsCountdown() immediately after BuildNewsRestrictionWindow():
//+------------------------------------------------------------------+ //| Format time relative to selected news event | //+------------------------------------------------------------------+ string FormatNewsCountdown(const long secondsToEvent) { bool eventPassed = (secondsToEvent < 0); long absoluteSeconds = secondsToEvent; if(absoluteSeconds < 0) absoluteSeconds = -absoluteSeconds; long hours = absoluteSeconds / 3600; long minutes = (absoluteSeconds % 3600) / 60; long seconds = absoluteSeconds % 60; string formatted; if(hours > 0) { formatted = StringFormat("%02d:%02d:%02d", (int)hours, (int)minutes, (int)seconds); } else { formatted = StringFormat("%02d:%02d", (int)minutes, (int)seconds); } //--- Distinguish an upcoming release from one already published if(eventPassed) return(formatted + " AGO"); return(formatted); }
If secondsToEvent is 1122, the event is 18 minutes and 42 seconds ahead, so the function returns:
18:42
If secondsToEvent is -195, the event occurred 3 minutes and 15 seconds earlier, so the result becomes:
03:15 AGO
The helper does not decide whether the account is restricted. It only converts the signed event-time difference into a readable value. Restriction status remains the responsibility of the account-level news update.
Before that update is added, one performance issue still needs to be addressed. The EA may run its timer every second, but repeating a full Economic Calendar search at the same frequency would create unnecessary requests. The next section adds a small cache layer so that exposure remains responsive while calendar queries are performed only when necessary.
Reduce Calendar Load With Periodic Refresh
The timer may execute every second because account and session information needs frequent updates. The Economic Calendar does not need to be queried at the same frequency. Section 2 already defined g_newsLastCalendarRefresh, g_newsCachedExposureKey, g_newsCalendarCacheValid, and NEWS_CALENDAR_REFRESH_SECONDS. These values now allow Prop Firm Guard to separate two activities: current holding exposure can still be rebuilt on every timer cycle, while calendar searches are performed only when the cached result is no longer suitable.
Invalidate an Outdated Calendar Result
The first helper clears the cached calendar state when it can no longer be trusted. Place InvalidateNewsCalendarCache() immediately after ResetNewsEventState():
//+------------------------------------------------------------------+ //| Invalidate cached Economic Calendar state | //+------------------------------------------------------------------+ void InvalidateNewsCalendarCache() { //--- Force the next eligible evaluation to query the calendar again g_newsCalendarCacheValid = false; g_newsLastCalendarRefresh = 0; g_newsCachedExposureKey = ""; ResetNewsEventState(); }
Invalidation removes the selected event and marks the cache unusable. The next news evaluation will therefore perform a fresh calendar search rather than reuse old event information.
Decide When a Fresh Search Is Required
Place ShouldRefreshNewsCalendar() immediately after InvalidateNewsCalendarCache():
//+------------------------------------------------------------------+ //| Check whether Economic Calendar data requires refresh | //+------------------------------------------------------------------+ bool ShouldRefreshNewsCalendar(const datetime currentTime, const string exposureKey) { //--- No valid cache requires an immediate calendar evaluation if(!g_newsCalendarCacheValid) return(true); //--- A changed holding exposure requires a new relevant-event search if(exposureKey != g_newsCachedExposureKey) return(true); //--- Invalid cache timing cannot be reused safely if(g_newsLastCalendarRefresh <= 0 || currentTime < g_newsLastCalendarRefresh) return(true); //--- Refresh periodically even when the exposure remains unchanged long cacheAge = (long)currentTime - (long)g_newsLastCalendarRefresh; if(cacheAge >= NEWS_CALENDAR_REFRESH_SECONDS) return(true); //--- Refresh immediately after the selected event loses relevance if(g_newsState.eventFound && g_newsState.restrictionEnd > 0 && currentTime > g_newsState.restrictionEnd) return(true); return(false); }
The function refreshes immediately when the holding exposure changes because the previously selected event may no longer represent the account. It also refreshes after the configured 60-second interval and when the current event's restriction period has ended. A backward movement in server time also invalidates the cache because the stored refresh age can no longer be trusted. If none of these conditions applies, the existing calendar result can be reused.
Keep Cached Timing Current
Reusing a calendar result does not mean freezing its countdown or restriction status. Those values still need to follow the current server time. Place UpdateCachedNewsTiming() immediately after ShouldRefreshNewsCalendar():
//+------------------------------------------------------------------+ //| Update timing from cached selected news event | //+------------------------------------------------------------------+ void UpdateCachedNewsTiming(const datetime currentTime) { //--- A cached no-event result has no timing information to update if(!g_newsState.eventFound) return; //--- Recalculate the signed countdown without querying the calendar g_newsState.secondsToEvent = (long)g_newsState.eventTime - (long)currentTime; //--- Re-evaluate the restriction window from the cached event g_newsState.restrictedWindow = IsNewsRestrictionActive(g_newsState.eventTime, currentTime); //--- Keep the account-level status synchronized with current time if(g_newsState.restrictedWindow) g_newsState.status = NEWS_RESTRICTED; else g_newsState.status = NEWS_SAFE; }
This function recalculates secondsToEvent from the cached event time and the current server time. It also checks the restriction interval again, so the state can change from NEWS_SAFE to NEWS_RESTRICTED between calendar refreshes. The calendar itself is therefore throttled, but the countdown and restriction status can still update every second.
Assemble the Account-Level News State
All dependencies for the final integration function now exist. Place UpdateNewsState() immediately after FormatNewsCountdown():
//+------------------------------------------------------------------+ //| Update account-level economic news state | //+------------------------------------------------------------------+ void UpdateNewsState() { //--- Disabled monitoring must not retain an old calendar result if(!InpEnableNewsFilter) { InitializeNewsState(); InvalidateNewsCalendarCache(); return; } datetime currentTime = 0; //--- Calendar timing requires a valid trade-server time if(!GetValidTradeServerTime(currentTime)) { InitializeNewsState(); InvalidateNewsCalendarCache(); g_newsState.status = NEWS_UNAVAILABLE; return; } string currencies[]; //--- Rebuild current holding exposure on every monitoring cycle ENUM_EXPOSURE_COLLECTION_RESULT exposureResult = CollectExposureCurrencies(currencies); int currencyCount = ArraySize(currencies); string exposureKey = BuildCurrencyList(currencies); //--- Preserve the latest successfully derived exposure information g_newsState.monitoredCurrencies = currencyCount; g_newsState.currencyList = exposureKey; g_newsState.hasExposure = (currencyCount > 0); //--- An exposure collection failure invalidates calendar relevance if(exposureResult == EXPOSURE_COLLECTION_ERROR) { InvalidateNewsCalendarCache(); g_newsState.exposureComplete = false; g_newsState.monitoredCurrencies = currencyCount; g_newsState.currencyList = exposureKey; g_newsState.hasExposure = (currencyCount > 0); g_newsState.status = NEWS_UNAVAILABLE; return; } //--- Partial exposure cannot support a verified account news state if(exposureResult == EXPOSURE_COLLECTION_PARTIAL) { InvalidateNewsCalendarCache(); g_newsState.exposureComplete = false; g_newsState.monitoredCurrencies = currencyCount; g_newsState.currencyList = exposureKey; g_newsState.hasExposure = (currencyCount > 0); g_newsState.status = NEWS_UNAVAILABLE; return; } //--- All current holdings were inspected successfully g_newsState.exposureComplete = true; //--- Complete absence of supported holdings requires no calendar query if(exposureResult == EXPOSURE_COLLECTION_NO_EXPOSURE) { InvalidateNewsCalendarCache(); g_newsState.exposureComplete = true; g_newsState.hasExposure = false; g_newsState.monitoredCurrencies = 0; g_newsState.currencyList = ""; g_newsState.status = NEWS_NO_EXPOSURE; return; } //--- Defend against an inconsistent collection result if(exposureResult != EXPOSURE_COLLECTION_COMPLETE || currencyCount <= 0) { InvalidateNewsCalendarCache(); g_newsState.exposureComplete = false; g_newsState.monitoredCurrencies = currencyCount; g_newsState.currencyList = exposureKey; g_newsState.hasExposure = (currencyCount > 0); g_newsState.status = NEWS_UNAVAILABLE; Print("Prop Firm Guard: Exposure collection returned an inconsistent result."); return; } //--- Reuse the cached calendar result when no refresh trigger exists if(!ShouldRefreshNewsCalendar(currentTime, exposureKey)) { UpdateCachedNewsTiming(currentTime); return; } //--- Exposure changed or cached calendar information expired ResetNewsEventState(); g_newsState.exposureComplete = true; g_newsState.hasExposure = true; g_newsState.monitoredCurrencies = currencyCount; g_newsState.currencyList = exposureKey; g_newsState.status = NEWS_UNAVAILABLE; datetime searchFrom = 0; datetime searchTo = 0; //--- Build one common search interval for the complete refresh if(!BuildNewsSearchRange(currentTime, searchFrom, searchTo)) { InvalidateNewsCalendarCache(); g_newsState.exposureComplete = true; g_newsState.hasExposure = true; g_newsState.monitoredCurrencies = currencyCount; g_newsState.currencyList = exposureKey; g_newsState.status = NEWS_UNAVAILABLE; return; } bool foundEvent = false; string bestCurrency = ""; MqlCalendarValue bestValue = {}; MqlCalendarEvent bestEvent = {}; //--- Search each exposed currency only during an actual calendar refresh for(int i = 0; i < currencyCount; i++) { MqlCalendarValue currencyValue = {}; MqlCalendarEvent currencyEvent = {}; ENUM_NEWS_SEARCH_RESULT searchResult = FindRelevantNewsForCurrency(currencies[i], searchFrom, searchTo, currentTime, currencyValue, currencyEvent); //--- Any calendar failure invalidates the whole account result if(searchResult == NEWS_SEARCH_ERROR) { InvalidateNewsCalendarCache(); g_newsState.exposureComplete = true; g_newsState.hasExposure = true; g_newsState.monitoredCurrencies = currencyCount; g_newsState.currencyList = exposureKey; g_newsState.status = NEWS_UNAVAILABLE; return; } //--- A valid empty search contributes no candidate if(searchResult == NEWS_SEARCH_NO_EVENT) continue; //--- Reject any unexpected search-result value if(searchResult != NEWS_SEARCH_FOUND) { InvalidateNewsCalendarCache(); g_newsState.exposureComplete = true; g_newsState.hasExposure = true; g_newsState.monitoredCurrencies = currencyCount; g_newsState.currencyList = exposureKey; g_newsState.status = NEWS_UNAVAILABLE; Print("Prop Firm Guard: Calendar search returned an unexpected result."); return; } //--- Select one deterministic account-level candidate if(IsBetterNewsCandidate(currencies[i], currencyValue, currencyEvent, bestCurrency, bestValue, bestEvent, currentTime, foundEvent)) { bestCurrency = currencies[i]; bestValue = currencyValue; bestEvent = currencyEvent; foundEvent = true; } } //--- Successful search with no qualifying event is cacheable if(!foundEvent) { ResetNewsEventState(); g_newsState.exposureComplete = true; g_newsState.hasExposure = true; g_newsState.monitoredCurrencies = currencyCount; g_newsState.currencyList = exposureKey; g_newsState.status = NEWS_NO_EVENT; g_newsLastCalendarRefresh = currentTime; g_newsCachedExposureKey = exposureKey; g_newsCalendarCacheValid = true; return; } datetime restrictionStart = 0; datetime restrictionEnd = 0; //--- Build the selected event's restriction boundaries if(!BuildNewsRestrictionWindow(bestValue.time, restrictionStart, restrictionEnd)) { InvalidateNewsCalendarCache(); g_newsState.exposureComplete = true; g_newsState.hasExposure = true; g_newsState.monitoredCurrencies = currencyCount; g_newsState.currencyList = exposureKey; g_newsState.status = NEWS_UNAVAILABLE; return; } //--- Publish the newly refreshed selected event g_newsState.eventFound = true; g_newsState.eventCurrency = bestCurrency; g_newsState.eventId = bestEvent.id; g_newsState.eventName = bestEvent.name; g_newsState.importance = bestEvent.importance; g_newsState.eventTime = bestValue.time; g_newsState.restrictionStart = restrictionStart; g_newsState.restrictionEnd = restrictionEnd; //--- Calculate current timing from the newly cached event UpdateCachedNewsTiming(currentTime); //--- Mark this complete calendar result as reusable g_newsLastCalendarRefresh = currentTime; g_newsCachedExposureKey = exposureKey; g_newsCalendarCacheValid = true; }
UpdateNewsState() begins by validating the time source and rebuilding current holding exposure. If that exposure is incomplete, the state becomes NEWS_UNAVAILABLE. If the scan is complete but contains no supported exposure, the function reports NEWS_NO_EXPOSURE without making an unnecessary calendar request.
When supported currencies exist, the function first checks whether the existing calendar result can still be reused. If a refresh is required, every exposed currency is searched. Any calendar error makes the complete account result unavailable. By contrast, NEWS_NO_EVENT is assigned only after all required searches complete successfully and none produces a qualifying candidate.
When an event is found, the account-level comparison selects one deterministic candidate. Its restriction boundaries are stored in g_newsState, and UpdateCachedNewsTiming() calculates the current secondsToEvent and chooses between NEWS_SAFE and NEWS_RESTRICTED.
The cache therefore changes the frequency of calendar retrieval, not the meaning or freshness of the account-level state.
Integrate the News Engine Into the EA Runtime
The Part 4 monitoring functions are now complete. The final step is to connect them to the normal EA lifecycle without disturbing the account persistence, daily-session handling, or financial calculations established in the previous parts.
Part 3 already established an important initialization order. Inputs must be validated before runtime work begins. The account identity must then be available before the account-specific instance lock is acquired. The SQLite database and account settings must be ready before the daily session is restored, and the daily session must exist before the initial financial calculations are performed.
Part 4 adds the news calculation only after those dependencies are ready. Daily-session controls and the periodic timer are still created afterward.
Initialize the News Engine
Replace the existing OnInit() function with the following complete version:
//+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { //--- Validate the complete input configuration if(!ValidateComplianceInputs()) return(INIT_PARAMETERS_INCORRECT); //--- Refresh the account identity and current financial state UpdateAccountState(); //--- Enforce one Prop Firm Guard instance for the trading account if(!AcquireInstanceLock()) return(INIT_FAILED); //--- Open the SQLite persistence layer if(!OpenDatabase()) { Print("Prop Firm Guard: Database initialization failed."); if(!ReleaseInstanceLock()) Print("Prop Firm Guard: Instance lock cleanup was incomplete."); return(INIT_FAILED); } //--- Ensure all persistence tables required through Part 2 exist if(!EnsureDatabaseTables()) { Print("Prop Firm Guard: Could not initialize database tables."); CloseDatabase(); if(!ReleaseInstanceLock()) Print("Prop Firm Guard: Instance lock cleanup was incomplete."); return(INIT_FAILED); } //--- Restore and synchronize the account settings if(!InitializeAccountSettings()) { Print("Prop Firm Guard: Could not initialize account settings."); CloseDatabase(); if(!ReleaseInstanceLock()) Print("Prop Firm Guard: Instance lock cleanup was incomplete."); return(INIT_FAILED); } //--- Restore or create the current configured daily session if(!InitializeDailySession()) { Print("Prop Firm Guard: Could not initialize daily session."); CloseDatabase(); if(!ReleaseInstanceLock()) Print("Prop Firm Guard: Instance lock cleanup was incomplete."); return(INIT_FAILED); } //--- Build the initial Part 3 financial runtime state CalculateDailyDrawdown(); CalculateOverallDrawdown(); CalculateProfitTarget(); //--- Establish and evaluate the initial Part 4 news runtime state InitializeNewsState(); UpdateNewsState(); //--- Report unavailable news data without blocking EA initialization if(InpEnableNewsFilter && g_newsState.status == NEWS_UNAVAILABLE) { Print("Prop Firm Guard: Economic news state is currently unavailable. " "Monitoring will continue through timer refreshes."); } //--- Match the confirmation controls to the current session state if(!SynchronizeDailySessionControls()) { Print("Prop Firm Guard: Could not synchronize daily session controls."); if(!DeleteDailySessionControls()) Print("Prop Firm Guard: Daily session control cleanup was incomplete."); CloseDatabase(); if(!ReleaseInstanceLock()) Print("Prop Firm Guard: Instance lock cleanup was incomplete."); return(INIT_FAILED); } //--- Start periodic session, financial, and news monitoring ResetLastError(); if(!EventSetTimer(InpTimerSeconds)) { Print("Prop Firm Guard: Could not start the session timer. Error: ", GetLastError()); if(!DeleteDailySessionControls()) Print("Prop Firm Guard: Daily session control cleanup was incomplete."); CloseDatabase(); if(!ReleaseInstanceLock()) Print("Prop Firm Guard: Instance lock cleanup was incomplete."); return(INIT_FAILED); } Print("Prop Firm Guard initialized successfully."); return(INIT_SUCCEEDED); }
The existing dependency order is preserved. The new Part 4 step consists of initializing g_newsState and immediately calling UpdateNewsState() after the financial states have been calculated.
Economic-news availability is deliberately non-fatal. If the calendar, server time, or exposure data cannot be verified at initialization, UpdateNewsState() reports NEWS_UNAVAILABLE. The EA logs that condition and continues starting normally. A later timer cycle can try again and recover without requiring the EA to be reattached.
This behavior is different from failures in the persistence or daily-session foundation. If the database, account settings, session initialization, controls, or timer cannot be established, initialization still fails because those components are required by the existing EA architecture.
Extend the Periodic Runtime
Part 3 already uses OnTimer() to refresh account values, maintain the daily-session boundary, synchronize the confirmation controls, and recalculate the financial rules. Part 4 extends that sequence by adding UpdateNewsState() after the financial calculations.
Replace the existing OnTimer() with:
//+------------------------------------------------------------------+ //| Timer function | //+------------------------------------------------------------------+ void OnTimer() { //--- Refresh the account snapshot used by the monitoring engines UpdateAccountState(); //--- Maintain the configured daily session boundary before calculation if(!CheckForNewTradingDay()) { Print("Prop Firm Guard: Daily session maintenance could not be completed."); return; } //--- Keep chart controls aligned with the authoritative session state if(!SynchronizeDailySessionControls()) { Print("Prop Firm Guard: Daily session controls could not be synchronized."); } //--- Recalculate the current Part 3 financial state CalculateDailyDrawdown(); CalculateOverallDrawdown(); CalculateProfitTarget(); //--- Refresh holding exposure and the throttled Part 4 news state UpdateNewsState(); }
UpdateAccountState() remains first so that subsequent calculations use the latest account values. CheckForNewTradingDay() follows because a session rollover may change the daily reference before the financial rules are recalculated. The controls are then synchronized with that authoritative session state.
Only after the Part 3 financial calculations are refreshed does the timer call UpdateNewsState(). The news engine rebuilds the current holding exposure on that cycle and decides internally whether it can reuse the cached calendar result or whether a fresh search is required.
A temporary failure in the news layer does not stop the timer or invalidate the financial calculations. It is represented by NEWS_UNAVAILABLE, allowing the next timer cycle to attempt recovery.
Part 4 therefore extends the existing runtime rather than replacing it. The database, daily-session model, financial calculations, and chart controls retain their earlier behavior, while economic-news monitoring becomes an additional read-only account state.
Verifying the News-Monitoring States
The news monitor should be checked under different account and calendar conditions. The following procedure uses a temporary diagnostic version of OnTimer() to print the current news state whenever it changes. This makes the result visible in the MetaTrader Experts tab without generating a new message on every timer cycle.
Step 1. Replace the production timer function
Locate the current OnTimer() function from the section Extend the Periodic Runtime. Before changing it, keep a copy of the production function. Then replace the entire function with the temporary version below. Do not insert this code inside the existing function or retain both versions.
//+------------------------------------------------------------------+ //| Timer function - temporary news verification version | //+------------------------------------------------------------------+ void OnTimer() { static bool hasLoggedNewsStatus = false; static ENUM_NEWS_STATUS previousNewsStatus = NEWS_UNAVAILABLE; //--- Refresh the account snapshot used by the monitoring engines UpdateAccountState(); //--- Maintain the configured daily session boundary before calculation if(!CheckForNewTradingDay()) { Print("Prop Firm Guard: Daily session maintenance could not be completed."); return; } //--- Keep chart controls aligned with the authoritative session state if(!SynchronizeDailySessionControls()) { Print("Prop Firm Guard: Daily session controls could not be synchronized."); } //--- Recalculate the current Part 3 financial state CalculateDailyDrawdown(); CalculateOverallDrawdown(); CalculateProfitTarget(); //--- Refresh holding exposure and the Part 4 news state UpdateNewsState(); //--- Print the news state only when its status changes if(!hasLoggedNewsStatus || previousNewsStatus != g_newsState.status) { PrintFormat("News status: %s | Exposure: %s | Complete: %s | Currencies: %s | Event: %s | Event time: %s | Restricted: %s", EnumToString(g_newsState.status), g_newsState.hasExposure ? "yes" : "no", g_newsState.exposureComplete ? "yes" : "no", g_newsState.currencyList, g_newsState.eventFound ? g_newsState.eventName : "none", g_newsState.eventTime > 0 ? TimeToString(g_newsState.eventTime, TIME_DATE | TIME_MINUTES) : "n/a", g_newsState.restrictedWindow ? "yes" : "no"); previousNewsStatus = g_newsState.status; hasLoggedNewsStatus = true; } }
The temporary function preserves the existing account update, daily-session maintenance, control synchronization, and financial calculations. It adds diagnostic output immediately after UpdateNewsState().
Step 2. Compile and prepare the test account
Compile the EA and attach it to a demo-account chart. Open the MetaTrader Experts tab so that you can inspect the diagnostic messages. Use the EA inputs to configure the monitoring window and minimum event importance. For the initial tests, retain the defaults:
- News monitoring enabled.
- 10 minutes before an event.
- 10 minutes after an event.
- High event importance.
The test cases below assume these settings unless a different value is specified.
Step 3. Run the test cases
Use open positions to change the account’s supported currency exposure. Allow the timer to execute after each change, then compare the reported state with the expected result.
| Test | Account Condition | Input or calendar condition | Expected state |
|---|---|---|---|
| Monitoring disabled | Any holdings | Set InpEnableNewsFilter to false | NEWS_DISABLED |
| No supported exposure | No open positions, or no supported currency exposurefrom the inspected holdings | Monitoring enabled | NEWS_NO_EXPOSURE |
| No qualifying event | Open a position on any financial market such as EURUSD | Calendar search succeeds but returns no qualifying EUR/USD event | NEWS_NO_EVENT |
| Event outside restriction window | Open a position on any financial market such as EURUSD | A qualifying high-importance event is approximately 30 minutes away, with a 10-minute pre-event window | NEWS_SAFE |
| Event inside the pre-event window | Open a position on any financial market such as EURUSD | A qualifying event is approximately 5 minutes away | NEWS_RESTRICTED |
| Event inside the post-event window | Open a position on any financial market such as EURUSD | A qualifying event occurred approximately 5 minutes ago | NEWS_RESTRICTED |
| Required monitoring data unavailable | Open a position on any financial market such as EURUSD | Required position, symbol, or calendar data cannot be retrieved or verified | NEWS_UNAVAILABLE |
A successful search that finds no qualifying event must produce NEWS_NO_EVENT, not NEWS_UNAVAILABLE. The latter indicates that the monitor could not complete a required part of its work. Likewise, an unsupported instrument does not automatically indicate a monitoring failure. If the monitor successfully inspects all open positions and finds no supported currency exposure, the expected state is NEWS_NO_EXPOSURE.
Step 4. Account for calendar caching
The calendar retrieval layer uses a cache to avoid repeatedly calling the Economic Calendar API. Consequently, changing positions or waiting for another timer cycle does not necessarily trigger a fresh calendar request.
When testing event retrieval, make sure the cache is invalidated or a refresh is due. The monitor rebuilds holding exposure on each timer cycle, but calendar data can be reused until the refresh conditions are met.
For the event-window tests, select events that fall within the calendar search interval and satisfy the configured importance filter. The pre-event and post-event tests must also fall within the configured restriction window.
A controlled retrieval failure may be necessary to verify NEWS_UNAVAILABLE. Do not treat an empty calendar result as a retrieval failure.
Step 5. Restore the production timer function
After completing the tests, return to Extend the Periodic Runtime and replace the temporary diagnostic OnTimer() with the original production version provided there. Compile the EA again and confirm that:
- The production timer function is restored.
- The temporary diagnostic logging has been removed.
- The news monitor continues to update through the production timer sequence.
- The project compiles without errors or warnings.
The temporary version is for verification only. It should not be left in the final production source.
Conclusion
Part 4 adds account-wide economic-news monitoring to Prop Firm Guard. It derives currency exposure from the account’s open positions, removes duplicates, and uses the resulting exposure set to identify relevant events in MetaTrader’s Economic Calendar. The implementation also handles incomplete exposure data and applies its documented XAU/USD-to-USD assumption.
The news monitor distinguishes between no supported exposure, no qualifying event, unavailable data, a safe trading window, and an active restriction. It selects a relevant event, maintains the countdown and restriction window, and throttles calendar requests while continuing to rebuild account exposure on each timer cycle.
This remains a monitoring feature: it does not block new trades or close existing positions. The input defaults and verification procedure provide a practical way to configure and test the six news states. The existing persistence, daily-session, and drawdown logic from the earlier parts remains intact.
Attachments
The attachment for this article contains the PropFirmGuard.mq5 source file completed through Part 4. It includes the Part 3 financial monitoring foundation together with the holding-aware Economic Calendar monitoring introduced in this part.
This file should be treated as the working checkpoint for the series. The revised Part 4 release is available here:
Prop Firm Guard — Part 4 Revised Release (v1.0-part-4-revised)
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.