From 232a24bc174dbabb7ff1ce8c53375cca0665a713 Mon Sep 17 00:00:00 2001 From: Robert Tidball Date: Thu, 9 Jul 2026 10:13:40 +1000 Subject: [PATCH 1/5] Add FXMacroData client --- src/utilities/FxMacroDataClient.cs | 243 ++++++++++++++++++ .../UtilitesTests/FxMacroDataClientTests.cs | 95 +++++++ 2 files changed, 338 insertions(+) create mode 100644 src/utilities/FxMacroDataClient.cs create mode 100644 tests/backtesting/UtilitesTests/FxMacroDataClientTests.cs diff --git a/src/utilities/FxMacroDataClient.cs b/src/utilities/FxMacroDataClient.cs new file mode 100644 index 0000000..8fc8042 --- /dev/null +++ b/src/utilities/FxMacroDataClient.cs @@ -0,0 +1,243 @@ +using System.Net; +using System.Text; +using System.Text.Json; + +namespace Utilities; + +public sealed class FxMacroDataClient +{ + private static readonly Uri DefaultBaseUri = new("https://fxmacrodata.com/api/v1/"); + + private readonly HttpClient _httpClient; + private readonly string _apiKey; + private readonly Uri _baseUri; + + public FxMacroDataClient(string apiKey, HttpClient? httpClient = null, Uri? baseUri = null) + { + if (string.IsNullOrWhiteSpace(apiKey)) + { + throw new ArgumentException("FXMacroData API key is required.", nameof(apiKey)); + } + + _apiKey = apiKey; + _httpClient = httpClient ?? new HttpClient(); + _baseUri = NormalizeBaseUri(baseUri ?? DefaultBaseUri); + } + + public static FxMacroDataClient FromEnvironment(HttpClient? httpClient = null, Uri? baseUri = null) + { + var apiKey = Environment.GetEnvironmentVariable("FXMACRODATA_API_KEY") + ?? Environment.GetEnvironmentVariable("FXMD_API_KEY"); + + if (string.IsNullOrWhiteSpace(apiKey)) + { + throw new InvalidOperationException("Set FXMACRODATA_API_KEY or FXMD_API_KEY."); + } + + return new FxMacroDataClient(apiKey, httpClient, baseUri); + } + + public Task GetAsync( + string path, + IReadOnlyDictionary? query = null, + CancellationToken cancellationToken = default) => + SendGetAsync(path, query, cancellationToken); + + public Task DataCatalogueAsync( + string currency, + IReadOnlyDictionary? query = null, + CancellationToken cancellationToken = default) => + SendGetAsync($"data_catalogue/{currency}", query, cancellationToken); + + public Task AnnouncementsAsync( + string currency, + string indicator, + IReadOnlyDictionary? query = null, + CancellationToken cancellationToken = default) => + SendGetAsync($"announcements/{currency}/{indicator}", query, cancellationToken); + + public Task LatestAnnouncementsAsync( + string currency, + IReadOnlyDictionary? query = null, + CancellationToken cancellationToken = default) => + SendGetAsync($"announcements/{currency}/latest", query, cancellationToken); + + public Task AnnouncementChangesAsync( + IReadOnlyDictionary? query = null, + CancellationToken cancellationToken = default) => + SendGetAsync("announcements/changes", query, cancellationToken); + + public Task CalendarAsync( + string currency, + IReadOnlyDictionary? query = null, + CancellationToken cancellationToken = default) => + SendGetAsync($"calendar/{currency}", query, cancellationToken); + + public Task PredictionsAsync( + string currency, + string indicator, + IReadOnlyDictionary? query = null, + CancellationToken cancellationToken = default) => + SendGetAsync($"predictions/{currency}/{indicator}", query, cancellationToken); + + public Task ForexAsync( + string baseCurrency, + string quoteCurrency, + IReadOnlyDictionary? query = null, + CancellationToken cancellationToken = default) => + SendGetAsync($"forex/{baseCurrency}/{quoteCurrency}", query, cancellationToken); + + public Task CotAsync( + string currency, + IReadOnlyDictionary? query = null, + CancellationToken cancellationToken = default) => + SendGetAsync($"cot/{currency}", query, cancellationToken); + + public Task CommodityAsync( + string indicator, + IReadOnlyDictionary? query = null, + CancellationToken cancellationToken = default) => + SendGetAsync($"commodities/{indicator}", query, cancellationToken); + + public Task CommoditiesLatestAsync( + IReadOnlyDictionary? query = null, + CancellationToken cancellationToken = default) => + SendGetAsync("commodities/latest", query, cancellationToken); + + public Task CurvesAsync( + string currency, + IReadOnlyDictionary? query = null, + CancellationToken cancellationToken = default) => + SendGetAsync($"curves/{currency}", query, cancellationToken); + + public Task CurveProxiesAsync( + string currency, + IReadOnlyDictionary? query = null, + CancellationToken cancellationToken = default) => + SendGetAsync($"curve_proxies/{currency}", query, cancellationToken); + + public Task ForwardCurvesAsync( + string currency, + IReadOnlyDictionary? query = null, + CancellationToken cancellationToken = default) => + SendGetAsync($"forward_curves/{currency}", query, cancellationToken); + + public Task RateDifferentialsAsync( + string baseCurrency, + string quoteCurrency, + IReadOnlyDictionary? query = null, + CancellationToken cancellationToken = default) => + SendGetAsync($"rate_differentials/{baseCurrency}/{quoteCurrency}", query, cancellationToken); + + public Task ForwardDifferentialsAsync( + string baseCurrency, + string quoteCurrency, + IReadOnlyDictionary? query = null, + CancellationToken cancellationToken = default) => + SendGetAsync($"forward_differentials/{baseCurrency}/{quoteCurrency}", query, cancellationToken); + + public Task MarketSessionsAsync( + IReadOnlyDictionary? query = null, + CancellationToken cancellationToken = default) => + SendGetAsync("market_sessions", query, cancellationToken); + + public Task RiskSentimentAsync( + IReadOnlyDictionary? query = null, + CancellationToken cancellationToken = default) => + SendGetAsync("risk_sentiment", query, cancellationToken); + + public Task NewsAsync( + string currency, + IReadOnlyDictionary? query = null, + CancellationToken cancellationToken = default) => + SendGetAsync($"news/{currency}", query, cancellationToken); + + public Task PressReleasesAsync( + string currency, + IReadOnlyDictionary? query = null, + CancellationToken cancellationToken = default) => + SendGetAsync($"press-releases/{currency}", query, cancellationToken); + + public async Task GraphQlAsync( + string query, + JsonElement? variables = null, + CancellationToken cancellationToken = default) + { + var body = JsonSerializer.Serialize(new + { + query, + variables + }); + + using var content = new StringContent(body, Encoding.UTF8, "application/json"); + using var response = await _httpClient + .PostAsync(BuildUri("graphql"), content, cancellationToken) + .ConfigureAwait(false); + + return await ParseJsonAsync(response, cancellationToken).ConfigureAwait(false); + } + + public Uri BuildUri(string path, IReadOnlyDictionary? query = null) + { + var relativePath = path.TrimStart('/'); + var uri = new Uri(_baseUri, relativePath); + + var parameters = new List> + { + new("api_key", _apiKey) + }; + + if (query is not null) + { + parameters.InsertRange(0, query); + } + + var queryString = string.Join( + "&", + parameters + .Where(pair => pair.Value is not null) + .Select(pair => $"{WebUtility.UrlEncode(pair.Key)}={WebUtility.UrlEncode(pair.Value)}")); + + return new UriBuilder(uri) + { + Query = queryString + }.Uri; + } + + private async Task SendGetAsync( + string path, + IReadOnlyDictionary? query, + CancellationToken cancellationToken) + { + using var response = await _httpClient + .GetAsync(BuildUri(path, query), cancellationToken) + .ConfigureAwait(false); + + return await ParseJsonAsync(response, cancellationToken).ConfigureAwait(false); + } + + private static async Task ParseJsonAsync( + HttpResponseMessage response, + CancellationToken cancellationToken) + { + var body = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + if (!response.IsSuccessStatusCode) + { + throw new HttpRequestException( + $"FXMacroData HTTP {(int)response.StatusCode}: {body}", + null, + response.StatusCode); + } + + using var document = JsonDocument.Parse(body); + return document.RootElement.Clone(); + } + + private static Uri NormalizeBaseUri(Uri baseUri) + { + var value = baseUri.ToString(); + return value.EndsWith("/", StringComparison.Ordinal) + ? baseUri + : new Uri(value + "/"); + } +} diff --git a/tests/backtesting/UtilitesTests/FxMacroDataClientTests.cs b/tests/backtesting/UtilitesTests/FxMacroDataClientTests.cs new file mode 100644 index 0000000..9212ee5 --- /dev/null +++ b/tests/backtesting/UtilitesTests/FxMacroDataClientTests.cs @@ -0,0 +1,95 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using Utilities; +using Xunit; + +namespace tests.backtesting.UtilitesTests; + +public class FxMacroDataClientTests +{ + [Fact] + public async Task ForexAsyncAddsApiKeyAndQueryParameters() + { + var handler = new CaptureHandler(); + var client = new FxMacroDataClient( + "test-key", + new HttpClient(handler), + new Uri("https://example.com/api/v1/")); + + var result = await client.ForexAsync( + "eur", + "usd", + new Dictionary + { + ["limit"] = "1" + }); + + Assert.True(result.GetProperty("ok").GetBoolean()); + Assert.Equal(HttpMethod.Get, handler.LastRequest?.Method); + Assert.Equal( + "https://example.com/api/v1/forex/eur/usd?limit=1&api_key=test-key", + handler.LastRequest?.RequestUri?.ToString()); + } + + [Fact] + public void BuildUriPreservesFullEndpointSurface() + { + var client = new FxMacroDataClient( + "test-key", + new HttpClient(new CaptureHandler()), + new Uri("https://example.com/api/v1/")); + + var paths = new[] + { + "data_catalogue/usd", + "announcements/usd/non_farm_payrolls", + "announcements/usd/latest", + "announcements/changes", + "calendar/usd", + "predictions/usd/non_farm_payrolls", + "forex/eur/usd", + "cot/usd", + "commodities/brent", + "commodities/latest", + "curves/usd", + "curve_proxies/usd", + "forward_curves/usd", + "rate_differentials/eur/usd", + "forward_differentials/eur/usd", + "market_sessions", + "risk_sentiment", + "news/usd", + "press-releases/usd", + "graphql" + }; + + foreach (var path in paths) + { + var uri = client.BuildUri(path); + + Assert.StartsWith("https://example.com/api/v1/", uri.ToString()); + Assert.Contains("api_key=test-key", uri.Query); + } + } + + private sealed class CaptureHandler : HttpMessageHandler + { + public HttpRequestMessage? LastRequest { get; private set; } + + protected override Task SendAsync( + HttpRequestMessage request, + CancellationToken cancellationToken) + { + LastRequest = request; + + return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent("{\"ok\":true}") + }); + } + } +} From e4c5cd6ae3ade35dcd278cb8ed05617aa2303682 Mon Sep 17 00:00:00 2001 From: Robert Tidball Date: Wed, 26 Aug 2026 12:12:39 +1000 Subject: [PATCH 2/5] Use the documented FXMacroData API host Switches the base URL from the undocumented fxmacrodata.com/api/v1 alias to the published api.fxmacrodata.com/v1 host, so the client matches the public API reference. --- src/utilities/FxMacroDataClient.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utilities/FxMacroDataClient.cs b/src/utilities/FxMacroDataClient.cs index 8fc8042..5fb6ef1 100644 --- a/src/utilities/FxMacroDataClient.cs +++ b/src/utilities/FxMacroDataClient.cs @@ -6,7 +6,7 @@ namespace Utilities; public sealed class FxMacroDataClient { - private static readonly Uri DefaultBaseUri = new("https://fxmacrodata.com/api/v1/"); + private static readonly Uri DefaultBaseUri = new("https://api.fxmacrodata.com/v1/"); private readonly HttpClient _httpClient; private readonly string _apiKey; From 40c4da4c5c0d541d9cbc3ee8f1e4d957cb62f031 Mon Sep 17 00:00:00 2001 From: Robert Tidball Date: Mon, 28 Sep 2026 12:50:13 +1000 Subject: [PATCH 3/5] Send the FXMacroData API key in the X-API-Key header --- src/utilities/FxMacroDataClient.cs | 25 ++++++++++--------- .../UtilitesTests/FxMacroDataClientTests.cs | 7 +++--- 2 files changed, 17 insertions(+), 15 deletions(-) diff --git a/src/utilities/FxMacroDataClient.cs b/src/utilities/FxMacroDataClient.cs index 5fb6ef1..dd41dc9 100644 --- a/src/utilities/FxMacroDataClient.cs +++ b/src/utilities/FxMacroDataClient.cs @@ -169,9 +169,10 @@ public async Task GraphQlAsync( variables }); - using var content = new StringContent(body, Encoding.UTF8, "application/json"); + using var request = CreateRequest(HttpMethod.Post, BuildUri("graphql")); + request.Content = new StringContent(body, Encoding.UTF8, "application/json"); using var response = await _httpClient - .PostAsync(BuildUri("graphql"), content, cancellationToken) + .SendAsync(request, cancellationToken) .ConfigureAwait(false); return await ParseJsonAsync(response, cancellationToken).ConfigureAwait(false); @@ -182,15 +183,7 @@ public Uri BuildUri(string path, IReadOnlyDictionary? query = n var relativePath = path.TrimStart('/'); var uri = new Uri(_baseUri, relativePath); - var parameters = new List> - { - new("api_key", _apiKey) - }; - - if (query is not null) - { - parameters.InsertRange(0, query); - } + var parameters = query ?? new Dictionary(); var queryString = string.Join( "&", @@ -209,13 +202,21 @@ private async Task SendGetAsync( IReadOnlyDictionary? query, CancellationToken cancellationToken) { + using var request = CreateRequest(HttpMethod.Get, BuildUri(path, query)); using var response = await _httpClient - .GetAsync(BuildUri(path, query), cancellationToken) + .SendAsync(request, cancellationToken) .ConfigureAwait(false); return await ParseJsonAsync(response, cancellationToken).ConfigureAwait(false); } + private HttpRequestMessage CreateRequest(HttpMethod method, Uri uri) + { + var request = new HttpRequestMessage(method, uri); + request.Headers.Add("X-API-Key", _apiKey); + return request; + } + private static async Task ParseJsonAsync( HttpResponseMessage response, CancellationToken cancellationToken) diff --git a/tests/backtesting/UtilitesTests/FxMacroDataClientTests.cs b/tests/backtesting/UtilitesTests/FxMacroDataClientTests.cs index 9212ee5..d4aa562 100644 --- a/tests/backtesting/UtilitesTests/FxMacroDataClientTests.cs +++ b/tests/backtesting/UtilitesTests/FxMacroDataClientTests.cs @@ -12,7 +12,7 @@ namespace tests.backtesting.UtilitesTests; public class FxMacroDataClientTests { [Fact] - public async Task ForexAsyncAddsApiKeyAndQueryParameters() + public async Task ForexAsyncSendsApiKeyHeaderAndQueryParameters() { var handler = new CaptureHandler(); var client = new FxMacroDataClient( @@ -31,8 +31,9 @@ public async Task ForexAsyncAddsApiKeyAndQueryParameters() Assert.True(result.GetProperty("ok").GetBoolean()); Assert.Equal(HttpMethod.Get, handler.LastRequest?.Method); Assert.Equal( - "https://example.com/api/v1/forex/eur/usd?limit=1&api_key=test-key", + "https://example.com/api/v1/forex/eur/usd?limit=1", handler.LastRequest?.RequestUri?.ToString()); + Assert.Equal(new[] { "test-key" }, handler.LastRequest?.Headers.GetValues("X-API-Key")); } [Fact] @@ -72,7 +73,7 @@ public void BuildUriPreservesFullEndpointSurface() var uri = client.BuildUri(path); Assert.StartsWith("https://example.com/api/v1/", uri.ToString()); - Assert.Contains("api_key=test-key", uri.Query); + Assert.DoesNotContain("api_key", uri.Query); } } From eff772b555dec5b6fa91616fa3225e1ccde7194c Mon Sep 17 00:00:00 2001 From: Robert Tidball Date: Mon, 28 Sep 2026 13:30:08 +1000 Subject: [PATCH 4/5] Document limit/offset paging in the FXMacroData client --- src/utilities/FxMacroDataClient.cs | 5 +++++ tests/backtesting/UtilitesTests/FxMacroDataClientTests.cs | 5 +++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/utilities/FxMacroDataClient.cs b/src/utilities/FxMacroDataClient.cs index dd41dc9..f0a068a 100644 --- a/src/utilities/FxMacroDataClient.cs +++ b/src/utilities/FxMacroDataClient.cs @@ -4,6 +4,11 @@ namespace Utilities; +/// +/// List endpoints (announcements, predictions, forex, COT, commodities) return 20 rows by +/// default and at most 100 per request, newest first. Pass "limit" and "offset" in the query +/// and follow pagination.next_offset while pagination.has_more is true. +/// public sealed class FxMacroDataClient { private static readonly Uri DefaultBaseUri = new("https://api.fxmacrodata.com/v1/"); diff --git a/tests/backtesting/UtilitesTests/FxMacroDataClientTests.cs b/tests/backtesting/UtilitesTests/FxMacroDataClientTests.cs index d4aa562..dbc57d9 100644 --- a/tests/backtesting/UtilitesTests/FxMacroDataClientTests.cs +++ b/tests/backtesting/UtilitesTests/FxMacroDataClientTests.cs @@ -25,13 +25,14 @@ public async Task ForexAsyncSendsApiKeyHeaderAndQueryParameters() "usd", new Dictionary { - ["limit"] = "1" + ["limit"] = "100", + ["offset"] = "200" }); Assert.True(result.GetProperty("ok").GetBoolean()); Assert.Equal(HttpMethod.Get, handler.LastRequest?.Method); Assert.Equal( - "https://example.com/api/v1/forex/eur/usd?limit=1", + "https://example.com/api/v1/forex/eur/usd?limit=100&offset=200", handler.LastRequest?.RequestUri?.ToString()); Assert.Equal(new[] { "test-key" }, handler.LastRequest?.Headers.GetValues("X-API-Key")); } From bbeea73eba9bb27f4e16cae2bc5d02122ffd654e Mon Sep 17 00:00:00 2001 From: Robert Tidball Date: Mon, 5 Oct 2026 21:05:39 +1100 Subject: [PATCH 5/5] Do not follow redirects in the default FXMacroData HttpClient --- src/utilities/FxMacroDataClient.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/utilities/FxMacroDataClient.cs b/src/utilities/FxMacroDataClient.cs index f0a068a..878f0ed 100644 --- a/src/utilities/FxMacroDataClient.cs +++ b/src/utilities/FxMacroDataClient.cs @@ -25,7 +25,8 @@ public FxMacroDataClient(string apiKey, HttpClient? httpClient = null, Uri? base } _apiKey = apiKey; - _httpClient = httpClient ?? new HttpClient(); + // Redirects are not followed, so the X-API-Key header is never forwarded to another host. + _httpClient = httpClient ?? new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }); _baseUri = NormalizeBaseUri(baseUri ?? DefaultBaseUri); }