// +------------------------------------------------------------------+ // | FXMacroDataService.cs | // | FXMacroData API helper for NinjaTrader 8 | // | https://fxmacrodata.com | // +------------------------------------------------------------------+ // // INSTALLATION // 1. Copy this file to your NinjaTrader 8 Custom folder: // Documents\NinjaTrader 8\bin\Custom\AddOns\ // 2. In NinjaTrader open New > NinjaScript Editor and press F5. // 3. In your indicator or strategy: add a using for NinjaTrader.Custom // and call FXMacroDataService.GetIndicator(...) directly. // // QUICK REFERENCE // FXMacroDataService.GetIndicator("usd","inflation") // no-key eval, 100/day // FXMacroDataService.GetIndicator("eur","policy_rate","MY_KEY") // paid currencies // FXMacroDataService.GetCalendar("aud","MY_KEY") // FXMacroDataService.GetForex("usd","jpy") // FXMacroDataService.GetCOT("EUR","MY_KEY") // FXMacroDataService.LastValue(json) // most recent val // FXMacroDataService.JsonDouble(json,"val") // field extractor // FXMacroDataService.JsonString(json,"date") // field extractor // // DOCUMENTATION https://fxmacrodata.com/documentation/ninjatrader // API KEY https://fxmacrodata.com/subscribe // +------------------------------------------------------------------+ using System; using System.Collections.Generic; using System.Globalization; using System.Net; using System.Text; namespace NinjaTrader.Custom { /// /// Static helper class for accessing the FXMacroData REST API from NinjaTrader 8. /// public static class FXMacroDataService { private const string ApiBase = "https://api.fxmacrodata.com/v1"; private const int TimeoutMs = 15000; // ── Internal helpers ─────────────────────────────────────────────────── // The API key, when set, is sent as an X-API-Key request header, never in the URL. private static string WebGet(string url, string apiKey = "") { try { using (var client = new WebClient()) { client.Encoding = Encoding.UTF8; client.Headers[HttpRequestHeader.Accept] = "application/json"; if (!string.IsNullOrEmpty(apiKey)) client.Headers.Add("X-API-Key", apiKey); // Respect the timeout by wrapping in a synchronous task var task = client.DownloadStringTaskAsync(url); if (task.Wait(TimeoutMs)) return task.Result; client.CancelAsync(); return string.Empty; } } catch { return string.Empty; } } private static string BuildUrl(string path) { return ApiBase + "/" + path; } // ── Public API methods ───────────────────────────────────────────────── /// /// Fetches a macroeconomic indicator time series. /// /// Lowercase currency code, e.g. "usd", "eur", "gbp". /// Snake_case indicator name, e.g. "inflation", "policy_rate". /// Your FXMacroData API key. Leave empty for free USD endpoints. /// JSON string: {"data":[{"date":"...","val":X,"announcement_datetime":"..."}]} public static string GetIndicator(string currency, string indicator, string apiKey = "") { return WebGet(BuildUrl("announcements/" + currency + "/" + indicator + "?limit=1"), apiKey); } /// /// Fetches upcoming release dates for a currency. /// /// Lowercase currency code, e.g. "usd", "eur". /// Your FXMacroData API key. /// JSON string: {"releases":[{"indicator":"...","date":"...","announcement_datetime":"..."}]} public static string GetCalendar(string currency, string apiKey = "") { return WebGet(BuildUrl("calendar/" + currency), apiKey); } /// /// Fetches FX spot rate history for a currency pair. Free — no API key required. /// /// Lowercase base currency code, e.g. "usd". /// Lowercase quote currency code, e.g. "jpy". /// JSON string: {"data":[{"date":"...","val":X}]} public static string GetForex(string baseCcy, string quoteCcy) { return WebGet(BuildUrl("forex/" + baseCcy + "/" + quoteCcy)); } /// /// Fetches CFTC Commitment of Traders (COT) positioning data. /// /// Uppercase currency code, e.g. "EUR", "GBP", "JPY". /// Your FXMacroData API key. /// JSON string with net non-commercial positioning series. public static string GetCOT(string currency, string apiKey = "") { return WebGet(BuildUrl("cot/" + currency), apiKey); } // ── JSON helpers ─────────────────────────────────────────────────────── /// /// Returns the first non-null row value from a newest-first announcement /// response. Nested revision values are never selected. /// Returns double.NaN for unavailable or invalid data. /// public static double LastValue(string json) { var root = ParseObject(json); var rows = Json.GetArray(root, "data"); if (rows == null) return double.NaN; foreach (object item in rows) { double value = Number(Json.Get(Json.AsObject(item), "val")); if (!double.IsNaN(value)) return value; } return double.NaN; } /// Reads a top-level numeric field, or double.NaN if unavailable. public static double JsonDouble(string json, string key) { return Number(Json.Get(ParseObject(json), key)); } /// Reads a top-level JSON string, including escaped characters. public static string JsonString(string json, string key) { return Json.Get(ParseObject(json), key) as string ?? string.Empty; } private static double Number(object value) { if (!(value is double) && !(value is long)) return double.NaN; double number = Convert.ToDouble(value, CultureInfo.InvariantCulture); return double.IsNaN(number) || double.IsInfinity(number) ? double.NaN : number; } private static Dictionary ParseObject(string json) { if (string.IsNullOrEmpty(json)) return null; try { return Json.AsObject(Json.Parse(json)); } catch (FormatException) { return null; } catch (OverflowException) { return null; } catch (ArgumentException) { return null; } } private static class Json { public static object Parse(string text) { if (text == null) throw new ArgumentNullException("text"); int pos = 0; object value = ReadValue(text, ref pos); SkipWhitespace(text, ref pos); if (pos != text.Length) throw new FormatException("Unexpected data after JSON value at " + pos); return value; } public static Dictionary AsObject(object value) { return value as Dictionary; } public static List AsArray(object value) { return value as List; } public static object Get(Dictionary obj, string key) { object value; if (obj == null || !obj.TryGetValue(key, out value)) return null; return value; } public static string GetString(Dictionary obj, string key) { object value = Get(obj, key); return value == null ? null : Convert.ToString(value, CultureInfo.InvariantCulture); } public static double? GetDouble(Dictionary obj, string key) { object value = Get(obj, key); if (value is double) return (double)value; if (value is long) return (long)value; return null; } public static long? GetLong(Dictionary obj, string key) { object value = Get(obj, key); if (value is long) return (long)value; if (value is double) return (long)Math.Round((double)value); return null; } public static bool GetBool(Dictionary obj, string key, bool fallback) { object value = Get(obj, key); if (value is bool) return (bool)value; return fallback; } public static Dictionary GetObject(Dictionary obj, string key) { return Get(obj, key) as Dictionary; } public static List GetArray(Dictionary obj, string key) { return Get(obj, key) as List; } private static void SkipWhitespace(string s, ref int pos) { while (pos < s.Length && char.IsWhiteSpace(s[pos])) pos++; } private static object ReadValue(string s, ref int pos) { SkipWhitespace(s, ref pos); if (pos >= s.Length) throw new FormatException("Unexpected end of JSON"); char c = s[pos]; if (c == '{') return ReadObject(s, ref pos); if (c == '[') return ReadArray(s, ref pos); if (c == '"') return ReadString(s, ref pos); if (c == 't') { Expect(s, ref pos, "true"); return true; } if (c == 'f') { Expect(s, ref pos, "false"); return false; } if (c == 'n') { Expect(s, ref pos, "null"); return null; } return ReadNumber(s, ref pos); } private static void Expect(string s, ref int pos, string word) { if (string.CompareOrdinal(s, pos, word, 0, word.Length) != 0) throw new FormatException("Invalid JSON literal at " + pos); pos += word.Length; } private static Dictionary ReadObject(string s, ref int pos) { var result = new Dictionary(StringComparer.Ordinal); pos++; // { SkipWhitespace(s, ref pos); if (pos < s.Length && s[pos] == '}') { pos++; return result; } while (true) { SkipWhitespace(s, ref pos); if (pos >= s.Length || s[pos] != '"') throw new FormatException("Expected a key at " + pos); string key = ReadString(s, ref pos); SkipWhitespace(s, ref pos); if (pos >= s.Length || s[pos] != ':') throw new FormatException("Expected ':' at " + pos); pos++; result[key] = ReadValue(s, ref pos); SkipWhitespace(s, ref pos); if (pos >= s.Length) throw new FormatException("Unexpected end of object"); if (s[pos] == ',') { pos++; continue; } if (s[pos] == '}') { pos++; return result; } throw new FormatException("Expected ',' or '}' at " + pos); } } private static List ReadArray(string s, ref int pos) { var result = new List(); pos++; // [ SkipWhitespace(s, ref pos); if (pos < s.Length && s[pos] == ']') { pos++; return result; } while (true) { result.Add(ReadValue(s, ref pos)); SkipWhitespace(s, ref pos); if (pos >= s.Length) throw new FormatException("Unexpected end of array"); if (s[pos] == ',') { pos++; continue; } if (s[pos] == ']') { pos++; return result; } throw new FormatException("Expected ',' or ']' at " + pos); } } private static string ReadString(string s, ref int pos) { var sb = new StringBuilder(); pos++; // opening quote while (pos < s.Length) { char c = s[pos++]; if (c == '"') return sb.ToString(); if (c != '\\') { sb.Append(c); continue; } if (pos >= s.Length) break; char e = s[pos++]; switch (e) { case '"': sb.Append('"'); break; case '\\': sb.Append('\\'); break; case '/': sb.Append('/'); break; case 'b': sb.Append('\b'); break; case 'f': sb.Append('\f'); break; case 'n': sb.Append('\n'); break; case 'r': sb.Append('\r'); break; case 't': sb.Append('\t'); break; case 'u': if (pos + 4 > s.Length) throw new FormatException("Bad \\u escape"); sb.Append((char)int.Parse(s.Substring(pos, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture)); pos += 4; break; default: throw new FormatException("Bad escape at " + pos); } } throw new FormatException("Unterminated string"); } private static object ReadNumber(string s, ref int pos) { int start = pos; while (pos < s.Length && "+-0123456789.eE".IndexOf(s[pos]) >= 0) pos++; string token = s.Substring(start, pos - start); if (token.Length == 0) throw new FormatException("Unexpected character at " + start); long whole; if (token.IndexOfAny(new[] { '.', 'e', 'E' }) < 0 && long.TryParse(token, NumberStyles.Integer, CultureInfo.InvariantCulture, out whole)) return whole; return double.Parse(token, NumberStyles.Float, CultureInfo.InvariantCulture); } } } }