/* * FXMacroData News Filter - cTrader cBot * * Pauses new order entry (and optionally closes existing positions) during * a configurable window around scheduled economic data releases fetched live * from the FXMacroData release calendar API. * * API docs : https://fxmacrodata.com/documentation/ * Website : https://fxmacrodata.com * API key : https://fxmacrodata.com/subscribe * * Usage * ────── * 1. Open cTrader Automate, create a new cBot, and paste this file. * 2. Build the cBot (F6). * 3. Add it to a chart and configure the parameters in the parameter panel. * 4. To gate another cBot, copy the calendar fields and methods into it and * call IsBlockingPeriod() before placing an order. */ using System; using System.Collections.Generic; using System.Text.Json; using cAlgo.API; namespace cAlgo.Robots { [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)] public class FXMacroDataNewsFilter : Robot { // ─── Parameters ──────────────────────────────────────────────────────── [Parameter("API Key", DefaultValue = "", Group = "FXMacroData", IsValueVisibleInTitle = false, Description = "USD works without a key; other currencies require your FXMacroData API key. " + "Enter it once: it is remembered for this cBot on this computer and the field " + "can then be cleared. Enter - to forget it.")] public string ApiKey { get; set; } [Parameter("Currencies (comma-separated)", DefaultValue = "USD", Group = "FXMacroData", Description = "Economic calendars to monitor. Separate multiple codes with commas, e.g. USD,EUR,GBP")] public string Currencies { get; set; } [Parameter("Minutes to Block Before Release", DefaultValue = 15, MinValue = 1, MaxValue = 240, Group = "News Filter", Description = "How many minutes before a scheduled release to start blocking new orders")] public int BlockMinutesBefore { get; set; } [Parameter("Minutes to Block After Release", DefaultValue = 15, MinValue = 1, MaxValue = 240, Group = "News Filter", Description = "How many minutes after a scheduled release to continue blocking new orders")] public int BlockMinutesAfter { get; set; } [Parameter("Close Positions During Block", DefaultValue = false, Group = "News Filter", Description = "When true, automatically closes all open positions at the start of each blocking window")] public bool ClosePositionsDuringBlock { get; set; } [Parameter("Calendar Refresh Interval (minutes)", DefaultValue = 60, MinValue = 10, MaxValue = 1440, Group = "FXMacroData", Description = "How often to refresh the release calendar from FXMacroData")] public int RefreshIntervalMinutes { get; set; } // ─── Internal state ──────────────────────────────────────────────────── private const string ApiBase = "https://api.fxmacrodata.com/v1"; private const string KeyStorageName = "fxmacrodata_api_key"; private const string ChartObjectPrefix = "fxmd_release_"; private static readonly Color ReleaseColor = Color.FromArgb(255, 255, 214, 10); private static readonly Color WindowColor = Color.FromArgb(40, 255, 214, 10); private readonly List _releaseTimes = new List(); private readonly Dictionary _releaseNames = new Dictionary(); private readonly List _drawnObjects = new List(); private string _apiKey = ""; private const string PanelName = "fxmd_panel"; private DateTime _lastPanel = DateTime.MinValue; private readonly Dictionary> _calendars = new Dictionary>(StringComparer.OrdinalIgnoreCase); private DateTime _lastRefresh = DateTime.MinValue; private bool _wasBlocking; private bool _calendarHealthy; private DateTime _lastSuccessfulRefresh = DateTime.MinValue; private string _calendarIssue = "Calendar has not loaded."; public bool IsCalendarAvailable() => _calendarHealthy && (DateTime.UtcNow - _lastSuccessfulRefresh).TotalMinutes <= RefreshIntervalMinutes * 2; // A calling strategy must refuse new entries while the schedule is unavailable. public bool CanEnterOrders() => IsCalendarAvailable() && !IsBlockingPeriod(); // ─── Lifecycle ───────────────────────────────────────────────────────── protected override void OnStart() { _apiKey = ResolveApiKey(); RefreshCalendar(); Timer.Start(1); EvaluateWindow(); } protected override void OnTick() { EvaluateWindow(); } protected override void OnTimer() { EvaluateWindow(); } private void EvaluateWindow() { if ((DateTime.UtcNow - _lastRefresh).TotalMinutes >= RefreshIntervalMinutes) RefreshCalendar(); bool blocking = IsBlockingPeriod(); if (blocking && !_wasBlocking) { Print("FXMacroData News Filter: Blocking window started."); if (ClosePositionsDuringBlock) CloseAllPositions(); } else if (!blocking && _wasBlocking) { Print("FXMacroData News Filter: Blocking window ended - trading resumed."); } if (blocking != _wasBlocking || (DateTime.UtcNow - _lastPanel).TotalSeconds >= 15) DrawPanel(blocking); _wasBlocking = blocking; } protected override void OnStop() { Timer.Stop(); if (Chart != null) { foreach (string name in _drawnObjects) Chart.RemoveObject(name); Chart.RemoveObject(PanelName); } Print("FXMacroData News Filter: Stopped."); } // ─── Public API ──────────────────────────────────────────────────────── /// /// Returns true when the current UTC time falls inside a blocking window /// around a scheduled economic release. Call this from your own cBot to /// gate order entry. /// public bool IsBlockingPeriod() { var now = DateTimeOffset.UtcNow; foreach (var release in _releaseTimes) { double diff = (release - now).TotalMinutes; if (diff >= -BlockMinutesAfter && diff <= BlockMinutesBefore) return true; } return false; } /// /// Returns the UTC timestamp of the next scheduled release, or null when /// no further releases are loaded in the calendar. /// public DateTimeOffset? NextRelease() { var now = DateTimeOffset.UtcNow; DateTimeOffset? next = null; foreach (var r in _releaseTimes) { if (r > now && (next == null || r < next.Value)) next = r; } return next; } // ─── Calendar refresh ────────────────────────────────────────────────── private void RefreshCalendar() { _lastRefresh = DateTime.UtcNow; var now = DateTimeOffset.UtcNow; string[] currencies = (Currencies ?? "").Split( new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); var requested = new HashSet(StringComparer.OrdinalIgnoreCase); bool healthy = currencies.Length > 0; _calendarIssue = currencies.Length == 0 ? "Enter at least one currency." : ""; _releaseNames.Clear(); foreach (string currency in currencies) { string code = currency.Trim().ToLowerInvariant(); if (code.Length != 3 || !System.Text.RegularExpressions.Regex.IsMatch(code, "^[a-z]{3}$")) { healthy = false; _calendarIssue = "Use three-letter currency codes."; continue; } if (!requested.Add(code)) continue; try { List releases = FetchCalendar(code, _releaseNames); var retained = new HashSet(releases); // The endpoint may stop returning an event once its time passes. // Preserve its already active after-release window until it ends. if (_calendars.TryGetValue(code, out var previous)) { foreach (var r in previous) if (r <= now && r.AddMinutes(BlockMinutesAfter) >= now) retained.Add(r); } _calendars[code] = new List(retained); Print( $"FXMacroData: Loaded {releases.Count} release(s) for " + $"{code.ToUpper()}."); } catch (Exception ex) { healthy = false; _calendarIssue = "Calendar unavailable for " + code.ToUpperInvariant() + "."; Print( $"FXMacroData: Failed to load calendar for " + $"{code.ToUpper()}: {ex.Message}"); } } _calendarHealthy = healthy; if (healthy) _lastSuccessfulRefresh = DateTime.UtcNow; _releaseTimes.Clear(); foreach (string code in requested) if (_calendars.TryGetValue(code, out var releases)) foreach (var r in releases) if (r.AddMinutes(BlockMinutesAfter) >= now) _releaseTimes.Add(r); Print( $"FXMacroData: Calendar refreshed - " + $"{_releaseTimes.Count} upcoming release(s) tracked."); DrawReleases(); DrawPanel(IsBlockingPeriod()); } // ─── Chart markers ───────────────────────────────────────────────────── // Marks each release in the next 7 days with a line, its blocking window and its name. private void DrawReleases() { if (Chart == null) return; foreach (string name in _drawnObjects) Chart.RemoveObject(name); _drawnObjects.Clear(); var horizon = DateTimeOffset.UtcNow.AddDays(7); double span = Math.Max(Chart.TopY - Chart.BottomY, Symbol.PipSize); foreach (var release in _releaseTimes) { if (release > horizon) continue; string id = ChartObjectPrefix + release.ToUnixTimeSeconds(); DateTime time = release.UtcDateTime; var line = Chart.DrawVerticalLine(id + "_line", time, ReleaseColor, 1, LineStyle.Solid); line.IsInteractive = false; var window = Chart.DrawRectangle(id + "_window", time.AddMinutes(-BlockMinutesBefore), Chart.BottomY - span * 10, time.AddMinutes(BlockMinutesAfter), Chart.TopY + span * 10, WindowColor); window.IsFilled = true; window.IsInteractive = false; _releaseNames.TryGetValue(release, out string label); var text = Chart.DrawText(id + "_label", $"{label} {time:HH:mm} UTC", time, Chart.TopY, ReleaseColor); text.IsInteractive = false; text.VerticalAlignment = VerticalAlignment.Top; text.HorizontalAlignment = HorizontalAlignment.Right; _drawnObjects.Add(id + "_line"); _drawnObjects.Add(id + "_window"); _drawnObjects.Add(id + "_label"); } } // A fixed panel that stays readable on every timeframe and zoom level. private void DrawPanel(bool blocking) { _lastPanel = DateTime.UtcNow; if (Chart == null) return; var now = DateTimeOffset.UtcNow; var lines = new List { "FXMacroData News Filter | " + (!IsCalendarAvailable() ? "CALENDAR UNAVAILABLE" : blocking ? "Release window active" : "Outside release windows"), "Status applies to strategies using CanEnterOrders().", "Next releases (UTC):" }; if (!IsCalendarAvailable()) lines.Add(_calendarIssue.Length > 0 ? _calendarIssue : "Calendar is stale; refresh required."); var upcoming = new List(); foreach (var r in _releaseTimes) if (r > now) upcoming.Add(r); upcoming.Sort(); for (int i = 0; i < Math.Min(5, upcoming.Count); i++) { var r = upcoming[i]; TimeSpan left = r - now; string inText = left.TotalHours >= 24 ? $"in {(int)left.TotalDays}d {left.Hours}h" : $"in {(int)left.TotalHours}h {left.Minutes:00}m"; _releaseNames.TryGetValue(r, out string label); lines.Add($"{r.UtcDateTime:ddd dd MMM HH:mm} {label} ({inText})"); } if (upcoming.Count == 0) lines.Add("No upcoming releases loaded."); var panel = Chart.DrawStaticText(PanelName, string.Join(Environment.NewLine, lines), VerticalAlignment.Top, HorizontalAlignment.Left, ReleaseColor); panel.FontSize = 12; } // ─── API key ─────────────────────────────────────────────────────────── // cTrader shows string parameters in plain text, so the key is kept in this cBot's // local storage after the first run and the field can be left blank. private string ResolveApiKey() { string entered = (ApiKey ?? "").Trim(); if (entered == "-") { LocalStorage.Remove(KeyStorageName, LocalStorageScope.Type); LocalStorage.Flush(LocalStorageScope.Type); Print("FXMacroData: Saved API key removed from this computer."); return ""; } if (entered.Length > 0) { LocalStorage.SetString(KeyStorageName, entered, LocalStorageScope.Type); LocalStorage.Flush(LocalStorageScope.Type); Print("FXMacroData: API key saved on this computer; you can clear the API Key field."); return entered; } return LocalStorage.GetString(KeyStorageName, LocalStorageScope.Type) ?? ""; } private List FetchCalendar(string currency, Dictionary names) { string url = $"{ApiBase}/calendar/{currency}"; var request = new HttpRequest(new Uri(url)) { Timeout = TimeSpan.FromSeconds(15) }; request.Headers.Add("Accept", "application/json"); if (!string.IsNullOrWhiteSpace(_apiKey)) request.Headers.Add("X-API-Key", _apiKey); var response = Http.Send(request); // cTrader Cloud does not send web requests and answers 503 with no body. if ((response.StatusCode == 503 || response.StatusCode == 403) && string.IsNullOrEmpty(response.Body)) throw new InvalidOperationException( "HTTP 503 with no response. cTrader Cloud instances cannot make web " + "requests; run this cBot as a local instance on your computer."); if (!response.IsSuccessful) throw new InvalidOperationException($"HTTP {response.StatusCode}"); string json = response.Body; var result = new List(); using (JsonDocument doc = JsonDocument.Parse(json)) { if (!doc.RootElement.TryGetProperty("data", out JsonElement data) || data.ValueKind != JsonValueKind.Array) throw new InvalidOperationException("Calendar response has no data array."); foreach (JsonElement item in data.EnumerateArray()) { if (!item.TryGetProperty("time_announced", out var timed) || timed.ValueKind != JsonValueKind.True || (item.TryGetProperty("release_time_assumed", out var assumed) && assumed.ValueKind == JsonValueKind.True) || (item.TryGetProperty("release_date_confirmed", out var confirmed) && confirmed.ValueKind == JsonValueKind.False) || (item.TryGetProperty("release_date_status", out var status) && status.ValueKind == JsonValueKind.String && status.GetString() != "confirmed")) continue; if (item.TryGetProperty("announcement_datetime", out JsonElement epochProp) && epochProp.ValueKind == JsonValueKind.Number && epochProp.TryGetInt64(out long epoch)) { var release = DateTimeOffset.FromUnixTimeSeconds(epoch); result.Add(release); string label = currency.ToUpperInvariant(); if (item.TryGetProperty("name", out JsonElement nameProp) && nameProp.ValueKind == JsonValueKind.String) label += " " + nameProp.GetString(); names[release] = names.TryGetValue(release, out string existing) && !existing.Contains(label) ? existing + " / " + label : existing ?? label; } } } return result; } // ─── Helpers ─────────────────────────────────────────────────────────── private void CloseAllPositions() { foreach (Position position in new List(Positions)) { TradeResult result = position.Close(); if (result.IsSuccessful) Print( $"FXMacroData: Closed position {position.Id} " + $"({position.SymbolName}) before news release."); else Print( $"FXMacroData: Failed to close position {position.Id}: " + $"{result.Error}"); } } } }