在MQL4编写的FOREX EA中实现新闻过滤器的技术咨询
Hey there! Let's tackle this news filter problem for your MQL4 EA. Ditching the ffcal indicator and going for a more direct approach makes total sense if you want full control over how each news event is handled. Here are a few proven strategies I’ve used with success:
1. Pull News Data via a Financial API (Most Flexible)
This is the most robust method—you get structured, real-time news data that your EA can parse and act on individually. Here’s how to implement it:
Step-by-Step Breakdown
- Pick a financial news API: Look for one that returns data in JSON or XML format (easier to parse). Many offer free tiers for non-commercial use, with fields like event time, currency pair, importance level, and event description.
- Use MQL4’s
WebRequest(): This function lets your EA send HTTP requests to the API. You’ll need to enable web access in your MT4 terminal settings (Tools > Options > Expert Advisors > Allow WebRequest for listed URLs). - Parse the API response: MQL4 doesn’t have built-in JSON parsing, so you can either write a simple custom parser for your target API’s format, or use a community-developed parsing library (like
JSONParser.mqh—just search the MQL4 community for open-source options). - Store and process events: Save parsed news events into a structured array, then check against the current time and active currency pairs to trigger custom logic.
Code Snippets to Get Started
First, define a struct to hold news event details:
struct NewsEvent { datetime eventTime; // UTC timestamp of the news string currencyPair; // Associated pair (e.g., "EUR", "USD" for EURUSD-relevant news) int importance; // 1=Low, 2=Medium, 3=High string eventDesc; // Human-readable event name }; NewsEvent newsEvents[]; // Array to store fetched news
Example function to fetch and parse news:
bool FetchLatestNews() { // Replace with your API endpoint and parameters (e.g., filter by currency, importance) const string API_URL = "YOUR_API_ENDPOINT?params=..."; char response[]; int httpStatusCode; // Send GET request to the API if(!WebRequest("GET", API_URL, NULL, NULL, 5000, NULL, 0, response, httpStatusCode)) { Print("Failed to fetch news. Error: ", GetLastError(), " | HTTP Code: ", httpStatusCode); return false; } // Convert response to string and parse into newsEvents array string responseStr = CharArrayToString(response); ParseNewsResponse(responseStr, newsEvents); // Implement this parser based on your API's format return true; }
Core filter logic to handle each event individually:
void ExecuteNewsFilter() { datetime now = TimeCurrent(); const int PRE_NEWS_WINDOW = 15 * 60; // 15 minutes before news const int POST_NEWS_WINDOW = 30 * 60; // 30 minutes after news for(int i = 0; i < ArraySize(newsEvents); i++) { datetime eventStart = newsEvents[i].eventTime - PRE_NEWS_WINDOW; datetime eventEnd = newsEvents[i].eventTime + POST_NEWS_WINDOW; // Check if current time is in the news window and the event affects the active symbol if(now >= eventStart && now <= eventEnd && StringFind(Symbol(), newsEvents[i].currencyPair) != -1) { switch(newsEvents[i].importance) { case 3: // High-impact news CloseAllActiveOrders(); // Custom function to close all positions global_allowTrading = false; // Global flag to block new orders break; case 2: // Medium-impact AdjustPositionSLTP(); // Widen stop-loss/take-profit to avoid volatility spikes break; case 1: // Low-impact // Optional: Reduce position size or do nothing break; } } } }
2. Preload Local News Data (Offline-Friendly)
If you don’t want to rely on external APIs, you can preload news events into a local file (like CSV) and read it during EA initialization:
- Create a CSV file with columns:
EventTime(UTC),Currency,Importance,Description - Read the file in MQL4 using
FileOpen(),FileReadString(), and parse each line into yourNewsEventarray - Update the file regularly to keep news data current
This works well for testing or if your EA needs to run without internet access, but you lose real-time updates.
Key Considerations
- Timezone consistency: Always use UTC timestamps (MT4’s
TimeCurrent()is UTC) to avoid mismatches with API data - Rate limiting: Don’t spam API requests—add a cooldown period (e.g., fetch news every 15 minutes)
- Broker restrictions: Some brokers block
WebRequest()—check your broker’s terms or test in a demo account first
内容的提问来源于stack exchange,提问作者Skillz




