// +------------------------------------------------------------------+
// | 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