/* * FXMacroData Indicator Overlay - cTrader Custom Indicator * * Fetches a macroeconomic indicator time series from the FXMacroData REST API * and plots it on a separate panel below the main price chart inside cTrader. * * Supported indicators include: inflation, gdp, policy_rate, unemployment, * non_farm_payrolls, retail_sales, consumer_confidence, and many more. * See https://fxmacrodata.com/documentation/ for the full indicator catalogue. * * API docs : https://fxmacrodata.com/documentation/ * Website : https://fxmacrodata.com * API key : https://fxmacrodata.com/subscribe * * Usage * ────── * 1. Open cTrader Automate, create a new indicator, and paste this file. * 2. Build the indicator (F6). * 3. Add it to a chart and configure the parameters in the parameter panel. * The indicator will fetch data on load and plot it below the price chart. */ using System; using System.Collections.Generic; using System.Globalization; using System.Text.Json; using cAlgo.API; namespace cAlgo.Indicators { [Indicator( IsOverlay = false, TimeZone = TimeZones.UTC, AccessRights = AccessRights.None, AutoRescale = true)] public class FXMacroDataIndicatorOverlay : Indicator { // ─── Parameters ──────────────────────────────────────────────────────── [Parameter("Currency", DefaultValue = "USD", Group = "FXMacroData", Description = "3-letter currency code (e.g. USD, EUR, GBP, JPY). " + "USD announcements are public; non-USD announcements require an API key.")] public string Currency { get; set; } [Parameter("Indicator", DefaultValue = "inflation", Group = "FXMacroData", Description = "Indicator slug (e.g. inflation, gdp, policy_rate, unemployment, " + "non_farm_payrolls, retail_sales). " + "Full list at https://fxmacrodata.com/documentation/")] public string IndicatorSlug { get; set; } [Parameter("API Key", DefaultValue = "", Group = "FXMacroData", IsValueVisibleInTitle = false, Description = "Your FXMacroData API key. Required for non-USD currencies and full history. " + "Enter it once: it is remembered for this indicator on this computer and the " + "field can then be cleared. Enter - to forget it. " + "Get one at https://fxmacrodata.com/subscribe")] public string ApiKey { get; set; } [Parameter("Start Date (YYYY-MM-DD)", DefaultValue = "", Group = "FXMacroData", Description = "Earliest data date to fetch. Leave blank for the API default (12 months).")] public string StartDate { get; set; } [Parameter("End Date (YYYY-MM-DD)", DefaultValue = "", Group = "FXMacroData", Description = "Latest data date to fetch. Leave blank for today.")] public string EndDate { get; set; } // ─── Outputs ─────────────────────────────────────────────────────────── [Output("Value", LineColor = "DodgerBlue", Thickness = 2, PlotType = PlotType.Line)] public IndicatorDataSeries Result { get; set; } // ─── Internal state ──────────────────────────────────────────────────── private const string ApiBase = "https://api.fxmacrodata.com/v1"; private List _points = new List(); private string _loadedUnit = ""; private int _loadedCount; private const string KeyStorageName = "fxmacrodata_api_key"; private string _apiKey = ""; private string _historyWindowNote = ""; // ─── Lifecycle ───────────────────────────────────────────────────────── protected override void Initialize() { _apiKey = ResolveApiKey(); LoadData(); } // cTrader shows string parameters in plain text, so the key is kept in this // indicator'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) ?? ""; } public override void Calculate(int index) { // Period-date alignment is descriptive; it is not a publication-time backtest. // Hold the last observation at or before this bar's date, including new bars. int low = 0, high = _points.Count - 1, found = -1; while (low <= high) { int middle = low + (high - low) / 2; if (_points[middle].Date <= Bars.OpenTimes[index].Date) { found = middle; low = middle + 1; } else high = middle - 1; } Result[index] = found >= 0 ? _points[found].Value : double.NaN; } // ─── Data loading ────────────────────────────────────────────────────── private void LoadData() { try { var (points, unit) = FetchIndicatorData(); _loadedUnit = unit; points.Sort((left, right) => left.Date.CompareTo(right.Date)); _points = points; _loadedCount = points.Count; string label = $"{Currency.ToUpper()} {IndicatorSlug}" + (string.IsNullOrEmpty(_loadedUnit) ? "" : $" ({_loadedUnit})"); Print( $"FXMacroData: Loaded {_loadedCount} data point(s) - {label}"); if (!string.IsNullOrEmpty(_historyWindowNote)) Print($"FXMacroData: {_historyWindowNote}"); } catch (Exception ex) { Print( $"FXMacroData: Failed to load " + $"{Currency.ToUpper()}/{IndicatorSlug}: {ex.Message}"); } } private (List Points, string Unit) FetchIndicatorData() { string currency = Currency.Trim().ToLowerInvariant(); string indicator = IndicatorSlug.Trim().ToLowerInvariant(); string url = $"{ApiBase}/announcements/{currency}/{indicator}"; var queryParts = new List { "limit=100" }; if (!string.IsNullOrWhiteSpace(StartDate)) queryParts.Add($"start_date={Uri.EscapeDataString(StartDate)}"); if (!string.IsNullOrWhiteSpace(EndDate)) queryParts.Add($"end_date={Uri.EscapeDataString(EndDate)}"); url += "?" + string.Join("&", queryParts); var points = new List(); string unit = ""; int offset = 0; while (true) { var request = new HttpRequest(new Uri(url + "&offset=" + offset)) { 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 cannot make web requests; " + "use the indicator in cTrader on Windows or Mac."); if (!response.IsSuccessful) throw new InvalidOperationException($"HTTP {response.StatusCode}"); using (JsonDocument doc = JsonDocument.Parse(response.Body)) { JsonElement root = doc.RootElement; // Extract unit from catalogue metadata when present. if (root.TryGetProperty("unit", out JsonElement unitProp) && unitProp.ValueKind == JsonValueKind.String) unit = unitProp.GetString() ?? ""; // Keyless requests return a recent window only; say so in the log. if (root.TryGetProperty("freemium_window", out JsonElement window) && window.ValueKind == JsonValueKind.Object && window.TryGetProperty("applied", out JsonElement applied) && applied.ValueKind == JsonValueKind.True && window.TryGetProperty("message", out JsonElement note) && note.ValueKind == JsonValueKind.String) _historyWindowNote = note.GetString() ?? ""; if (!root.TryGetProperty("data", out JsonElement data) || data.ValueKind != JsonValueKind.Array) throw new InvalidOperationException("Indicator response has no data array."); foreach (JsonElement item in data.EnumerateArray()) { if (!item.TryGetProperty("date", out JsonElement dateProp)) continue; if (!item.TryGetProperty("val", out JsonElement valProp)) continue; if (valProp.ValueKind != JsonValueKind.Number || dateProp.ValueKind != JsonValueKind.String) continue; string dateStr = dateProp.GetString(); if (dateStr == null || !DateTime.TryParseExact(dateStr, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime date)) continue; if (!valProp.TryGetDouble(out double val)) continue; points.Add(new MacroDataPoint { Date = date, Value = val }); } if (!root.TryGetProperty("pagination", out var pagination) || !pagination.TryGetProperty("has_more", out var hasMore) || hasMore.ValueKind != JsonValueKind.True) break; if (!pagination.TryGetProperty("next_offset", out var next) || !next.TryGetInt32(out int nextOffset) || nextOffset <= offset) throw new InvalidOperationException("Indicator pagination did not advance."); offset = nextOffset; } } return (points, unit); } // ─── Helpers ─────────────────────────────────────────────────────────── private struct MacroDataPoint { public DateTime Date; public double Value; } } }