Files
Alby96andClaude Opus 5.5 956306a8fa Add OKX Europe and Alpaca market data clients (refs #18 #19)
Both clients are written in house on HttpClient and ClientWebSocket, behind
IMarketDataSource, with a rate limiter on the injected clock and retries
that wait on it too.

OKX: EUR pairs only (trap 14), rules from public/instruments, daily
candles with bar=1Dutc and a refusal of any candle not opening at 00:00
UTC (trap 23), backwards paging of history-candles, errors read from the
code field because OKX answers them with HTTP 200, tickers on the public
stream and candles on the business stream with ping after silence. The
HMAC signer and the demo header are ready for Phase 3.

Alpaca: consolidated daily bars, real and adjusted, dated in New York and
never newer than 15 minutes (trap 8), an explicit feed on every request,
IEX for recent minutes, quotes and the stream (at most 30 symbols),
calendar and clock converted to UTC, corporate actions. Without keys
nothing is sent and the reason is stated. Tests use the documentation's
examples and synthetic answers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 15:07:23 +01:00

196 lines
11 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Text.Json;
using Anubis.Brokers;
using Anubis.Data;
namespace Anubis.Tests;
/// <summary>
/// The data part of the Alpaca adapter on the documentation's examples and synthetic answers (issue #19). Without
/// the user's keys nothing here touches the network; the real check waits for them (SPEC 2.3).
/// </summary>
[TestClass]
public sealed class AlpacaTests
{
private static readonly DateTimeOffset _now = new(2026, 11, 10, 15, 0, 0, TimeSpan.Zero);
private static readonly AlpacaCredentials _keys = new("PKTEST", "test-secret-value");
private static (AlpacaClient Client, FakeHttp Http) Create(Action<FakeHttp> setup, AlpacaCredentials? keys = null)
{
var http = new FakeHttp();
setup(http);
return (new AlpacaClient(http.Client(), new FastClock(_now), keys ?? _keys), http);
}
private static string Query(HttpRequestMessage request, string name) =>
System.Web.HttpUtility.ParseQueryString(request.RequestUri!.Query)[name] ?? "";
[TestMethod]
[TestCategory(Category.Unit)]
public async Task WithoutKeysNothingIsSentAndTheReasonIsClear()
{
var http = new FakeHttp();
var alpaca = new AlpacaClient(http.Client(), new FastClock(_now), credentials: null);
Assert.IsFalse(alpaca.IsConfigured);
var error = await Assert.ThrowsAsync<MarketDataException>(() => alpaca.FetchQuoteAsync("AAPL", CancellationToken.None)).ConfigureAwait(false);
StringAssert.Contains(error.Message, "mancano le chiavi");
Assert.IsFalse(error.Retryable);
Assert.IsEmpty(http.Requests);
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task DailyBarsAreConsolidatedWithRealAndAdjustedPricesByNewYorkDate()
{
const string raw = """
{"bars":{"AAPL":[
{"t":"2023-09-29T04:00:00Z","o":172.02,"h":173.07,"l":170.341,"c":171.21,"v":51861083,"n":535134,"vw":171.599691},
{"t":"2024-01-02T05:00:00Z","o":187.15,"h":188.44,"l":183.885,"c":185.64,"v":82488674,"n":1009074,"vw":185.9}
]},"next_page_token":null}
""";
const string adjusted = """
{"bars":{"AAPL":[
{"t":"2023-09-29T04:00:00Z","o":170.0,"h":171.0,"l":168.3,"c":169.2,"v":51861083,"n":535134,"vw":169.6},
{"t":"2024-01-02T05:00:00Z","o":185.0,"h":186.2,"l":181.7,"c":183.4,"v":82488674,"n":1009074,"vw":183.7}
]},"next_page_token":null}
""";
var (alpaca, http) = Create(h => h.On("adjustment=raw", raw).On("adjustment=all", adjusted));
var bars = await alpaca.FetchDailyBarsAsync("AAPL", new DateOnly(2023, 9, 1), new DateOnly(2024, 1, 31), CancellationToken.None).ConfigureAwait(false);
// T04:00Z in summer and T05:00Z in winter are both midnight in New York.
CollectionAssert.AreEqual(new[] { new DateOnly(2023, 9, 29), new DateOnly(2024, 1, 2) }, bars.Select(b => b.Day).ToArray());
Assert.AreEqual((172.02, 171.21, 51861083.0), (bars[0].Open, bars[0].Close, bars[0].Volume));
Assert.AreEqual(new Ohlc(170.0, 171.0, 168.3, 169.2), bars[0].Adjusted);
foreach (var request in http.Requests)
{
// Consolidated volumes, never IEX (trap 8); the feed is always explicit.
Assert.AreEqual("sip", Query(request, "feed"));
Assert.AreEqual("1Day", Query(request, "timeframe"));
Assert.AreEqual("PKTEST", request.Headers.GetValues("APCA-API-KEY-ID").Single());
Assert.AreEqual("data.alpaca.markets", request.RequestUri!.Host);
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task RecentDaysWaitFifteenMinutesForTheConsolidatedTape()
{
var (alpaca, http) = Create(h => h.On("/v2/stocks/bars", """{"bars":{},"next_page_token":null}"""));
await alpaca.FetchDailyBarsAsync("AAPL", new DateOnly(2026, 11, 1), new DateOnly(2026, 11, 10), CancellationToken.None).ConfigureAwait(false);
var end = DateTimeOffset.Parse(Query(http.Requests[0], "end"), System.Globalization.CultureInfo.InvariantCulture);
Assert.IsLessThanOrEqualTo(_now.AddMinutes(-15), end, "a free plan may ask the SIP only for data at least 15 minutes old");
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task PagesAreFollowedUntilTheTokenIsNull()
{
var (alpaca, http) = Create(h => h
.On("page_token=", """{"bars":{},"next_page_token":null}""")
.On("/v2/stocks/bars", Fixture.Text("alpaca/stocks-bars.json")));
var from = new DateTimeOffset(2022, 1, 3, 9, 0, 0, TimeSpan.Zero);
var bars = await alpaca.FetchMinuteBarsAsync("AAPL", from, from.AddMinutes(1), CancellationToken.None).ConfigureAwait(false);
Assert.HasCount(2, http.Requests);
Assert.AreEqual("QUFQTHxNfDIwMjItMDEtMDNUMDk6MDA6MDAuMDAwMDAwMDAwWg==", Query(http.Requests[1], "page_token"));
Assert.AreEqual("sip", Query(http.Requests[0], "feed"), "old minutes come from the consolidated tape");
Assert.AreEqual(new Bar(from, 178.26, 178.26, 178.21, 178.21, 1118), bars.Single());
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task RecentMinutesAndQuotesComeFromIex()
{
var (alpaca, http) = Create(h => h
.On("/v2/stocks/bars", """{"bars":{},"next_page_token":null}""")
.On("/v2/stocks/quotes/latest", Fixture.Text("alpaca/quotes-latest.json")));
await alpaca.FetchMinuteBarsAsync("AAPL", _now.AddMinutes(-10), _now, CancellationToken.None).ConfigureAwait(false);
Assert.AreEqual("iex", Query(http.Requests[0], "feed"));
var quote = await alpaca.FetchQuoteAsync("AAPL", CancellationToken.None).ConfigureAwait(false);
Assert.AreEqual("iex", Query(http.Requests[1], "feed"));
Assert.AreEqual((172.62m, 172.7m, 2m, 1m), (quote.Bid, quote.Ask, quote.BidSize, quote.AskSize));
Assert.AreEqual(new DateTimeOffset(2022, 8, 17, 10, 7, 40, TimeSpan.Zero).AddTicks(2865874), quote.At);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void CorporateActionsOfTheDocumentation()
{
using var json = JsonDocument.Parse(Fixture.Text("alpaca/corporate-actions.json"));
var actions = AlpacaClient.ReadCorporateActions(json.RootElement).ToDictionary(a => a.Symbol);
Assert.AreEqual((CorporateActionKinds.Split, new DateOnly(2023, 8, 22), (decimal?)2m), (actions["SRE"].Kind, actions["SRE"].ExDate, actions["SRE"].Ratio));
Assert.AreEqual(0.02m, actions["MNTS"].Ratio, "1-for-50 reverse split");
Assert.AreEqual((CorporateActionKinds.CashDividend, (decimal?)0.125m), (actions["FCF"].Kind, actions["FCF"].CashAmount));
Assert.AreEqual((CorporateActionKinds.StockDividend, (decimal?)1.05m), (actions["MSBC"].Kind, actions["MSBC"].Ratio));
Assert.AreEqual((CorporateActionKinds.SymbolChange, "VFS"), (actions["BSAQ"].Kind, actions["BSAQ"].NewSymbol));
Assert.IsTrue(actions.Values.All(a => a.SourceKey.StartsWith("alpaca:", StringComparison.Ordinal)));
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task CalendarTimesAreNewYorkConvertedToUtc()
{
const string calendar = """
[{"date":"2026-07-02","open":"09:30","close":"16:00","session_open":"0400","session_close":"2000","settlement_date":"2026-07-06"},
{"date":"2026-11-27","open":"09:30","close":"13:00","session_open":"0400","session_close":"1700","settlement_date":"2026-11-30"}]
""";
var (alpaca, http) = Create(h => h.On("/v2/calendar", calendar));
var sessions = await alpaca.FetchCalendarAsync(new DateOnly(2026, 7, 1), new DateOnly(2026, 11, 30), CancellationToken.None).ConfigureAwait(false);
Assert.AreEqual("paper-api.alpaca.markets", http.Requests[0].RequestUri!.Host);
Assert.AreEqual(new DateTimeOffset(2026, 7, 2, 13, 30, 0, TimeSpan.Zero), sessions[0].OpenUtc, "summer: New York is UTC−4");
Assert.AreEqual(new DateTimeOffset(2026, 11, 27, 18, 0, 0, TimeSpan.Zero), sessions[1].CloseUtc, "short session after Thanksgiving, UTC−5");
using var clock = JsonDocument.Parse(Fixture.Text("alpaca/clock-v2.json"));
var read = AlpacaClient.ReadClock(clock.RootElement);
Assert.IsTrue(read.IsOpen);
Assert.AreEqual(new DateTimeOffset(2025, 6, 24, 20, 0, 0, TimeSpan.Zero), read.NextClose);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AssetsKeepExchangeStatusAndFractions()
{
using var json = JsonDocument.Parse(Fixture.Text("alpaca/assets.json"));
var spec = AlpacaClient.ReadAsset(json.RootElement);
Assert.AreEqual(("AAPL", "NASDAQ", "active", (bool?)true, "USD"), (spec.Symbol, spec.Exchange, spec.Status, spec.Fractionable, spec.QuoteCurrency));
Assert.IsNull(spec.IsFund, "Alpaca has no ETF flag: it comes from nasdaqtraded.txt");
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task StreamStaysWithinThirtySymbolsAndReadsBarsAndQuotes()
{
var socket = new FakeSocket();
var alpaca = new AlpacaClient(new FakeHttp().Client(), new FastClock(_now), _keys, sockets: () => socket);
var many = Enumerable.Range(0, 31).Select(i => "S" + i).ToList();
await Assert.ThrowsAsync<MarketDataException>(async () =>
{
await foreach (var unused in alpaca.StreamAsync(many, CancellationToken.None).ConfigureAwait(false))
{
_ = unused;
}
}).ConfigureAwait(false);
socket.Push("""[{"T":"success","msg":"connected"}]""");
socket.Push("""[{"T":"success","msg":"authenticated"}]""");
socket.Push("""[{"T":"subscription","trades":[],"quotes":["FAKEPACA"],"bars":["FAKEPACA"]}]""");
socket.Push("""[{"T":"q","S":"FAKEPACA","bx":"O","bp":133.85,"bs":4,"ax":"R","ap":135.77,"as":5,"c":["R"],"z":"A","t":"2024-07-24T07:56:53.639713735Z"},{"T":"b","S":"FAKEPACA","o":133.8,"h":134.1,"l":133.7,"c":134.0,"v":1200,"t":"2024-07-24T07:56:00Z","n":12,"vw":133.9}]""");
socket.Close();
var events = new List<MarketEvent>();
await foreach (var item in alpaca.StreamAsync(["FAKEPACA"], CancellationToken.None).ConfigureAwait(false))
{
events.Add(item);
}
Assert.AreEqual(new Uri("wss://stream.data.alpaca.markets/v2/iex"), socket.Url);
StringAssert.Contains(socket.Sent[0], "\"action\":\"auth\"");
StringAssert.Contains(socket.Sent[1], "\"bars\":[\"FAKEPACA\"]");
Assert.AreEqual(133.85m, events.OfType<QuoteEvent>().Single().Quote.Bid);
Assert.AreEqual(134.0, events.OfType<BarEvent>().Single().Bar.Close);
var error = Assert.Throws<MarketDataException>(() => AlpacaClient.ParseStreamMessage("""[{"T":"error","code":405,"msg":"symbol limit exceeded"}]"""));
StringAssert.Contains(error.Message, "405");
}
}