EA Integration Guide
Quick Integration
Section titled “Quick Integration”Integrating NFS into your EA takes less than 5 minutes. You just need to include one file and call one function.
Step 1: Include the MQH File
Section titled “Step 1: Include the MQH File”At the top of your EA code, add:
For MT4:
// Add this at the very top of your EA (after #property declarations)#resource "\\Files\\nfs_data.dat"#include <NFS_EaIntegration.mqh>For MT5:
#resource "\\Files\\nfs_data.dat"#include <NFS_EaIntegration.mqh>Step 2: Initialize NFS
Section titled “Step 2: Initialize NFS”In your OnInit() function:
int OnInit() { // Initialize NFS (reads the data file) if (!NFS_Initialize()) { Print("❌ NFS initialization failed!"); return INIT_FAILED; }
Print("✅ NFS loaded: ", NFS_GetEventCount(), " events");
// Your other init code... return INIT_SUCCEEDED;}Step 3: Check for News Before Trading
Section titled “Step 3: Check for News Before Trading”In your trading logic (typically in OnTick() or OnTimer()):
void OnTick() { // Check if there's a news event happening NOW if (NFS_IsNewsNow(Symbol(), 15, 15)) { // 15 minutes before and 15 minutes after Print("⚠️ News detected - skipping trade"); return; // Don't trade during news }
// Safe to trade - your normal EA logic here if (BuySignal()) { OpenBuyOrder(); }}That’s it! Your EA now avoids trading during high-impact news events. 🎉
MQH Library Reference
Section titled “MQH Library Reference”Core Functions
Section titled “Core Functions”NFS_Initialize()
Section titled “NFS_Initialize()”Description: Loads the news data file and prepares the system.
Returns:
true- Successfalse- Failed (check Experts log for details)
Usage:
if (!NFS_Initialize()) { Alert("NFS data file not found!");}NFS_IsNewsNow()
Section titled “NFS_IsNewsNow()”Description: Checks if there’s a news event happening right now.
Syntax:
bool NFS_IsNewsNow( string symbol, // Currency pair (e.g., "EURUSD") int minutesBefore, // Buffer before event (e.g., 15) int minutesAfter // Buffer after event (e.g., 15))Returns:
true- News event is active (avoid trading)false- Safe to trade
Example:
// Check for high-impact news in the next 15 min and past 15 minif (NFS_IsNewsNow("EURUSD", 15, 15)) { Comment("NEWS ACTIVE - No trading allowed"); return;}NFS_GetNextEvent()
Section titled “NFS_GetNextEvent()”Description: Gets details about the next upcoming news event.
Syntax:
NewsEvent NFS_GetNextEvent(string symbol)Returns: A NewsEvent struct with:
datetime time- Event time (UTC or adjusted)string title- Event name (e.g., “Non-Farm Payrolls”)string currency- Currency code (e.g., “USD”)int impact- Impact level (1=Low, 2=Medium, 3=High)
Example:
NewsEvent nextEvent = NFS_GetNextEvent("EURUSD");
if (nextEvent.impact == 3) { Print("Next HIGH impact: ", nextEvent.title, " at ", TimeToString(nextEvent.time));}NFS_GetEventCount()
Section titled “NFS_GetEventCount()”Description: Returns the total number of news events loaded.
Returns: int - Total event count
Usage:
int count = NFS_GetEventCount();Print("Loaded ", count, " news events");NFS_IsHighImpact()
Section titled “NFS_IsHighImpact()”Description: Checks if there’s specifically a high-impact news event.
Syntax:
bool NFS_IsHighImpact(string symbol, int minutesBefore, int minutesAfter)Returns:
true- High-impact event detectedfalse- No high-impact event
Example:
// Only avoid HIGH impact news (allow trading during medium/low)if (NFS_IsHighImpact("GBPUSD", 30, 30)) { // Don't trade 30 min before/after high-impact GBP/USD news return;}Code Examples
Section titled “Code Examples”Example 1: Simple News Filter
Section titled “Example 1: Simple News Filter”#resource "\\Files\\nfs_data.dat"#include <NFS_EaIntegration.mqh>
int OnInit() { if (!NFS_Initialize()) return INIT_FAILED; return INIT_SUCCEEDED;}
void OnTick() { // Skip trading during any news event (15 min buffer) if (NFS_IsNewsNow(Symbol(), 15, 15)) { Comment("🚫 News Filter Active"); return; }
Comment("✅ Safe to Trade");
// Your normal trading logic if (BuyCondition()) { OrderSend(Symbol(), OP_BUY, 0.1, Ask, 3, 0, 0); }}Example 2: High-Impact Only Filter
Section titled “Example 2: High-Impact Only Filter”#resource "\\Files\\nfs_data.dat"#include <NFS_EaIntegration.mqh>
input int NewsBufferMinutes = 30; // User-configurable buffer
void OnTick() { // Only avoid HIGH-impact news (allow medium/low) if (NFS_IsHighImpact(Symbol(), NewsBufferMinutes, NewsBufferMinutes)) { Comment("⚠️ HIGH IMPACT NEWS - No trading"); return; }
// Trade normally during medium/low impact news if (SellCondition()) { OrderSend(Symbol(), OP_SELL, 0.1, Bid, 3, 0, 0); }}Example 3: Close Positions Before News
Section titled “Example 3: Close Positions Before News”void OnTick() { NewsEvent next = NFS_GetNextEvent(Symbol());
// Close all trades 5 minutes before high-impact news if (next.impact == 3) { int timeToNews = (int)((next.time - TimeCurrent()) / 60); // Minutes
if (timeToNews <= 5 && timeToNews > 0) { Print("⚠️ HIGH IMPACT NEWS in ", timeToNews, " minutes - closing positions!"); CloseAllOrders(); return; } }
// Normal trading logic}
void CloseAllOrders() { for (int i = OrdersTotal() - 1; i >= 0; i--) { if (OrderSelect(i, SELECT_BY_POS)) { if (OrderSymbol() == Symbol()) { OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 3); } } }}Example 4: Display Next News on Chart
Section titled “Example 4: Display Next News on Chart”void OnTick() { // Show upcoming news info on chart NewsEvent next = NFS_GetNextEvent(Symbol());
string impactStr = (next.impact == 3) ? "🔴 HIGH" : (next.impact == 2) ? "🟡 MEDIUM" : "🟢 LOW";
int minutesToNews = (int)((next.time - TimeCurrent()) / 60);
Comment( "📰 Next News Event\n", "━━━━━━━━━━━━━━━━━━\n", "Event: ", next.title, "\n", "Currency: ", next.currency, "\n", "Impact: ", impactStr, "\n", "Time: ", TimeToString(next.time, TIME_DATE|TIME_MINUTES), "\n", "In: ", minutesToNews, " minutes" );}Advanced Integration Patterns
Section titled “Advanced Integration Patterns”Pattern 1: Dynamic Lot Sizing
Section titled “Pattern 1: Dynamic Lot Sizing”Reduce lot size before news:
double CalculateLotSize() { double baseLot = 0.1;
NewsEvent next = NFS_GetNextEvent(Symbol()); int minutesToNews = (int)((next.time - TimeCurrent()) / 60);
// Reduce lot size 1 hour before high-impact news if (next.impact == 3 && minutesToNews <= 60 && minutesToNews > 0) { return baseLot * 0.5; // 50% reduction }
return baseLot;}Pattern 2: Adjust Stop Loss Before News
Section titled “Pattern 2: Adjust Stop Loss Before News”double CalculateStopLoss(int direction) { double normalSL = 50 * Point; // 50 pips
NewsEvent next = NFS_GetNextEvent(Symbol()); int minutesToNews = (int)((next.time - TimeCurrent()) / 60);
// Widen stop loss before high-impact news (prevent spikes hitting SL) if (next.impact == 3 && minutesToNews <= 30) { return normalSL * 1.5; // 50% wider SL }
return normalSL;}Pattern 3: News-Based Trading Hours
Section titled “Pattern 3: News-Based Trading Hours”bool IsSafeToTrade() { // Don't trade during news if (NFS_IsNewsNow(Symbol(), 15, 15)) { return false; }
// Don't trade if major news is within next hour NewsEvent next = NFS_GetNextEvent(Symbol()); int minutesToNews = (int)((next.time - TimeCurrent()) / 60);
if (next.impact == 3 && minutesToNews <= 60) { return false; // Avoid trading even before the news }
return true;}Error Handling
Section titled “Error Handling”Always handle potential errors:
int OnInit() { // Check if NFS is available if (!NFS_Initialize()) { Alert("NFS data file is missing or corrupted!"); Comment("❌ NFS Offline - EA will run without news filtering"); return INIT_SUCCEEDED; // Continue without NFS (optional safety) }
// Verify data is recent datetime lastUpdate = NFS_GetLastUpdate(); if (TimeCurrent() - lastUpdate > 86400) { // 24 hours Print("⚠️ WARNING: News data is ", (TimeCurrent() - lastUpdate) / 3600, " hours old"); }
return INIT_SUCCEEDED;}Best Practices
Section titled “Best Practices”- Always initialize NFS in
OnInit() - Check for news before opening trades
- Use reasonable time buffers (15-30 minutes)
- Test in Strategy Tester with news filtering ON and OFF
- Log news events in your EA for debugging
❌ DON’T:
Section titled “❌ DON’T:”- Don’t call
NFS_IsNewsNow()every tick (store result in a variable) - Don’t use zero buffer times (news can spike instantly)
- Don’t rely on news filtering alone (use proper risk management)
- Don’t backtest without setting TimeZone Shift
Performance Tips
Section titled “Performance Tips”Optimize Tick Processing
Section titled “Optimize Tick Processing”// Store news status to avoid repeated checksbool newsActive = false;datetime lastCheck = 0;
void OnTick() { // Only check for news every 60 seconds (not every tick) if (TimeCurrent() - lastCheck >= 60) { newsActive = NFS_IsNewsNow(Symbol(), 15, 15); lastCheck = TimeCurrent(); }
if (newsActive) return; // Fast return if news is active
// Your trading logic}Multi-Symbol Support
Section titled “Multi-Symbol Support”Trading multiple pairs? Check all of them:
string symbols[] = {"EURUSD", "GBPUSD", "USDJPY"};
bool IsAnyCurrencyHasNews() { for (int i = 0; i < ArraySize(symbols); i++) { if (NFS_IsNewsNow(symbols[i], 15, 15)) { Print("News detected on ", symbols[i]); return true; } } return false;}Debugging Integration
Section titled “Debugging Integration”Enable Detailed Logging
Section titled “Enable Detailed Logging”#define NFS_DEBUG_MODE // Add this before #include
#resource "\\Files\\nfs_data.dat"#include <NFS_EaIntegration.mqh>
// Now NFS will print detailed logs:// - Every news event check// - Exact times and buffers// - Why trades were blockedManual Testing
Section titled “Manual Testing”void OnStart() { // Test script to verify NFS is working NFS_Initialize();
Print("Events loaded: ", NFS_GetEventCount()); Print("Next event: ", NFS_GetNextEvent(Symbol()).title); Print("News now?: ", NFS_IsNewsNow(Symbol(), 15, 15));}Version Compatibility
Section titled “Version Compatibility”| NFS Version | MT4 Build | MT5 Build | Status |
|---|---|---|---|
| 5.0 (Current) | 1355+ | 3800+ | ✅ Fully Supported |
| 4.5 (Legacy) | 1200+ | 3500+ | ⚠️ Update Recommended |
| 4.0 (Old) | 1000+ | 3000+ | ❌ Deprecated |
Common Integration Errors
Section titled “Common Integration Errors””Cannot open include file”
Section titled “”Cannot open include file””Error:
'NFS_EaIntegration.mqh' - cannot open the fileSolution:
- Ensure
NFS_EaIntegration.mqhis in the Include folder:- MT4:
MQL4/Include/ - MT5:
MQL5/Include/
- MT4:
- Restart MetaEditor and recompile
”Resource file not found”
Section titled “”Resource file not found””Error:
resource file 'Files\\nfs_data.dat' not foundSolution:
- Copy
nfs_data.datto the Files folder:- MT4:
MQL4/Files/ - MT5:
MQL5/Files/
- MT4:
- Recompile your EA
”NFS_Initialize() returns false”
Section titled “”NFS_Initialize() returns false””Possible causes:
- Data file is corrupted (re-download from support)
- Data file is in wrong location (see above)
- File permissions issue (run MT4/MT5 as Administrator)
Debug:
if (!NFS_Initialize()) { Print("Init failed - Error code: ", GetLastError()); // Check Experts log for detailed error message}Example: Complete EA with NFS
Section titled “Example: Complete EA with NFS”Here’s a fully functional EA with NFS integration:
//+------------------------------------------------------------------+//| SafeScalpEA_NFS.mq4 |//| TradingIsChess + NFS v5.0 |//+------------------------------------------------------------------+#property copyright "Your Name"#property version "1.0"#property strict
#resource "\\Files\\nfs_data.dat"#include <NFS_EaIntegration.mqh>
// EA Parametersinput double LotSize = 0.1;input int NewsBuffer_Minutes = 15;input bool OnlyAvoidHighImpact = true;
//+------------------------------------------------------------------+int OnInit() { // Initialize NFS if (!NFS_Initialize()) { Alert("❌ NFS initialization failed! EA will run without news filtering."); return INIT_SUCCEEDED; // Continue without NFS (optional) }
Print("✅ NFS initialized: ", NFS_GetEventCount(), " events loaded"); return INIT_SUCCEEDED;}
//+------------------------------------------------------------------+void OnTick() { // Check for news before trading bool newsActive = false;
if (OnlyAvoidHighImpact) { newsActive = NFS_IsHighImpact(Symbol(), NewsBuffer_Minutes, NewsBuffer_Minutes); } else { newsActive = NFS_IsNewsNow(Symbol(), NewsBuffer_Minutes, NewsBuffer_Minutes); }
if (newsActive) { Comment("⚠️ News Filter Active - No trading"); return; }
Comment("✅ Safe to Trade");
// Your trading logic here if (BuySignal()) { int ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 3, 0, 0, "NFS Safe Buy"); if (ticket > 0) { Print("✅ Buy order opened: #", ticket); } }}
//+------------------------------------------------------------------+bool BuySignal() { // Your buy signal logic // Example: Simple moving average crossover double ma_fast = iMA(Symbol(), 0, 10, 0, MODE_SMA, PRICE_CLOSE, 0); double ma_slow = iMA(Symbol(), 0, 50, 0, MODE_SMA, PRICE_CLOSE, 0);
return (ma_fast > ma_slow && ma_fast < Close[0]);}//+------------------------------------------------------------------+Advanced: Custom Event Filtering
Section titled “Advanced: Custom Event Filtering”If you want to filter specific event types:
bool IsSpecificNews(string eventName) { // Check if current news matches specific keywords NewsEvent next = NFS_GetNextEvent(Symbol()); int timeToNews = (int)((next.time - TimeCurrent()) / 60);
if (timeToNews <= 15 && timeToNews >= -15) { if (StringFind(next.title, eventName) >= 0) { return true; } }
return false;}
// Usage:if (IsSpecificNews("NFP") || IsSpecificNews("FOMC")) { // Don't trade during NFP or FOMC specifically return;}Testing Your Integration
Section titled “Testing Your Integration”In Strategy Tester
Section titled “In Strategy Tester”- Compile your EA with NFS integration
- Open Strategy Tester
- Important: Set correct TimeZone Shift in NFS Panel settings
- Run backtest
- Check Experts log - you should see:
NFS: News detected at 2020-01-10 13:30 - Trade blockedNFS: Safe period detected - Trade allowed
Compare Results
Section titled “Compare Results”Run two backtests:
- With NFS - News filtering enabled
- Without NFS - Comment out the news check
Compare:
- Drawdown (should be lower with NFS)
- Win rate (should be higher with NFS)
- Profit factor (should be better with NFS)
Support & Updates
Section titled “Support & Updates”- 📖 Visual Panel Guide - Learn all panel features
- 💬 Get Support - Contact our team
- 🔄 Auto-Updates - NFS data updates automatically every 30 minutes
- 📥 Download MT4 | Download MT5
Ready to integrate? Copy the examples above and start coding! 🚀