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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-10 15:07:23 +01:00
1 parent 3b13a4258d
commit 956306a8fa
6 files changed
+1700

No files matched your search

+195
View File
@@ -0,0 +1,195 @@
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");
}
}
+146
View File
@@ -0,0 +1,146 @@
using System.Net;
using System.Text;
using System.Threading.Channels;
using Anubis.Brokers;
namespace Anubis.Tests;
/// <summary>Recorded responses saved under Fixtures/ (trap 12: no network in tests).</summary>
internal static class Fixture
{
public static string Path(string relative) => System.IO.Path.Combine(AppContext.BaseDirectory, "Fixtures", relative);
public static string Text(string relative) => File.ReadAllText(Path(relative));
public static byte[] Bytes(string relative) => File.ReadAllBytes(Path(relative));
}
/// <summary>
/// An HTTP handler that answers from a list of rules (first match wins) and records every request.
/// A request no rule matches fails the test with its address.
/// </summary>
internal sealed class FakeHttp : HttpMessageHandler
{
private readonly List<(Func<Uri, bool> Match, Func<HttpRequestMessage, HttpResponseMessage> Answer)> _rules = [];
public List<HttpRequestMessage> Requests { get; } = [];
public HttpClient Client() => new(this, disposeHandler: false);
public FakeHttp On(Func<Uri, bool> match, Func<HttpRequestMessage, HttpResponseMessage> answer)
{
_rules.Add((match, answer));
return this;
}
public FakeHttp On(string contains, string body, HttpStatusCode status = HttpStatusCode.OK) =>
On(u => u.ToString().Contains(contains, StringComparison.Ordinal), _ => Respond(body, status));
public FakeHttp OnBytes(string contains, byte[] body) =>
On(u => u.ToString().Contains(contains, StringComparison.Ordinal), _ => new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(body) });
public static HttpResponseMessage Respond(string body, HttpStatusCode status = HttpStatusCode.OK) =>
new(status) { Content = new StringContent(body, Encoding.UTF8, "application/json") };
public IEnumerable<Uri> Urls => Requests.Select(r => r.RequestUri!);
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
lock (Requests)
{
Requests.Add(request);
}
foreach (var (match, answer) in _rules)
{
if (match(request.RequestUri!))
{
return Task.FromResult(answer(request));
}
}
throw new AssertFailedException("Unexpected request: " + request.RequestUri);
}
}
/// <summary>A WebSocket that plays messages pushed by the test and records what the client sends.</summary>
internal sealed class FakeSocket : IWebSocketTransport
{
private readonly Channel<string?> _incoming = Channel.CreateUnbounded<string?>();
public Uri? Url { get; private set; }
public IReadOnlyDictionary<string, string>? Headers { get; private set; }
public List<string> Sent { get; } = [];
public TaskCompletionSource Connected { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public bool Disposed { get; private set; }
public void Push(string message) => _incoming.Writer.TryWrite(message);
/// <summary>The server closes the connection.</summary>
public void Close() => _incoming.Writer.TryWrite(null);
public Task ConnectAsync(Uri url, IReadOnlyDictionary<string, string>? headers, CancellationToken cancellationToken)
{
Url = url;
Headers = headers;
Connected.TrySetResult();
return Task.CompletedTask;
}
public Task SendAsync(string text, CancellationToken cancellationToken)
{
lock (Sent)
{
Sent.Add(text);
}
return Task.CompletedTask;
}
public async Task<string?> ReceiveAsync(CancellationToken cancellationToken) =>
await _incoming.Reader.ReadAsync(cancellationToken).ConfigureAwait(false);
public ValueTask DisposeAsync()
{
Disposed = true;
return ValueTask.CompletedTask;
}
}
/// <summary>A clock whose waits finish at once by moving time forward: back-offs and rate limits cost nothing in tests.</summary>
internal sealed class FastClock(DateTimeOffset start) : Anubis.Core.IClock
{
private readonly Lock _gate = new();
private DateTimeOffset _now = start;
public DateTimeOffset UtcNow
{
get
{
lock (_gate)
{
return _now;
}
}
}
public TimeSpan Waited { get; private set; }
public Task WaitUntilAsync(DateTimeOffset dueUtc, CancellationToken cancellationToken)
{
lock (_gate)
{
if (dueUtc > _now)
{
Waited += dueUtc - _now;
_now = dueUtc;
}
}
return Task.CompletedTask;
}
}
+246
View File
@@ -0,0 +1,246 @@
using System.Security.Cryptography;
using System.Text;
using Anubis.Brokers;
using Anubis.Core;
using Anubis.Data;
namespace Anubis.Tests;
/// <summary>The data part of the OKX Europe adapter on recorded responses (issue #18).</summary>
[TestClass]
public sealed class OkxTests
{
private static readonly DateTimeOffset _now = new(2026, 11, 10, 13, 45, 0, TimeSpan.Zero);
private static (OkxClient Client, FakeHttp Http) Create(Action<FakeHttp> setup, IClock? clock = null, OkxOptions? options = null)
{
var http = new FakeHttp();
setup(http);
return (new OkxClient(http.Client(), clock ?? new FastClock(_now), options), http);
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task InstrumentsAreOnlyEuroPairsWithTheirRules()
{
var (okx, http) = Create(h => h.On("/api/v5/public/instruments?instType=SPOT", Fixture.Text("okx/instruments-spot.json")));
var list = await okx.ListInstrumentsAsync(CancellationToken.None).ConfigureAwait(false);
// USDT is not tradable in Europe (trap 14); USDC and PLN pairs are not used (SPEC 8.1).
CollectionAssert.AreEqual(new[] { "BTC-EUR", "ETH-EUR", "SOL-EUR" }, list.Select(i => i.Symbol).ToArray());
var btc = list[0];
Assert.AreEqual(new InstrumentSpec(Venues.Okx, "BTC-EUR", "BTC/EUR", AssetClasses.Crypto, "EUR")
{
BaseCurrency = "BTC",
TickSize = 0.1m,
LotSize = 0.00000001m,
MinSize = 0.0001m,
Status = "live",
ListedAt = new DateTimeOffset(2023, 11, 21, 4, 11, 0, TimeSpan.Zero),
}, btc);
Assert.IsTrue(http.Requests.All(r => r.RequestUri!.Host == "eea.okx.com"), "the European host");
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task DailyCandlesCloseAtMidnightUtcAndSkipTheRunningDay()
{
var (okx, http) = Create(h => h.On("history-candles", Fixture.Text("okx/candles-1Dutc-btc-eur.json")));
var bars = await okx.FetchDailyBarsAsync("BTC-EUR", new DateOnly(2026, 11, 6), new DateOnly(2026, 11, 10), CancellationToken.None).ConfigureAwait(false);
var request = http.Requests.Single().RequestUri!.ToString();
StringAssert.Contains(request, "bar=1Dutc", "never 1D, which opens at 16:00 UTC (trap 23)");
StringAssert.Contains(request, "after=" + new DateTimeOffset(2026, 11, 11, 0, 0, 0, TimeSpan.Zero).ToUnixTimeMilliseconds());
// 10 November is still running (confirm 0) and is left out.
CollectionAssert.AreEqual(
new[] { new DateOnly(2026, 11, 6), new DateOnly(2026, 11, 7), new DateOnly(2026, 11, 8), new DateOnly(2026, 11, 9) },
bars.Select(b => b.Day).ToArray());
var last = bars[^1];
Assert.AreEqual((67102.9, 67730.8, 65957.5, 67058.9, 87.03419039), (last.Open, last.High, last.Low, last.Close, last.Volume));
Assert.AreEqual(5799147.867285542, last.QuoteVolume);
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task HistoryPagesBackwardsUntilTheFirstCandle()
{
var first = new DateTimeOffset(2023, 11, 21, 0, 0, 0, TimeSpan.Zero).ToUnixTimeMilliseconds();
var (okx, http) = Create(h => h
.On("after=" + first, """{"code":"0","data":[],"msg":""}""")
.On("history-candles", Fixture.Text("okx/history-candles-1Dutc-btc-eur-first.json")));
var bars = await okx.FetchDailyBarsAsync("BTC-EUR", new DateOnly(2017, 1, 1), new DateOnly(2023, 11, 25), CancellationToken.None).ConfigureAwait(false);
Assert.HasCount(2, http.Requests, "the second page is empty: the history starts on 21 November 2023");
Assert.AreEqual(new DateOnly(2023, 11, 21), bars[0].Day);
Assert.AreEqual(new DateOnly(2023, 11, 25), bars[^1].Day);
Assert.HasCount(5, bars);
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task ACandleThatDoesNotOpenAtMidnightIsRefused()
{
var sixteen = new DateTimeOffset(2026, 11, 8, 16, 0, 0, TimeSpan.Zero).ToUnixTimeMilliseconds();
var (okx, _) = Create(h => h.On("history-candles", $$"""{"code":"0","data":[["{{sixteen}}","1","2","0.5","1.5","3","4","4","1"]],"msg":""}"""));
var error = await Assert.ThrowsAsync<MarketDataException>(() =>
okx.FetchDailyBarsAsync("BTC-EUR", new DateOnly(2026, 11, 8), new DateOnly(2026, 11, 8), CancellationToken.None)).ConfigureAwait(false);
StringAssert.Contains(error.Message, "16:00");
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task MinuteCandlesUseTheRecentEndpointForTheLastDay()
{
var (okx, http) = Create(h => h.On("/market/candles?", Fixture.Text("okx/candles-1m-btc-eur.json")));
var start = DateTimeOffset.FromUnixTimeMilliseconds(1794318000000);
var bars = await okx.FetchMinuteBarsAsync("BTC-EUR", start, start.AddMinutes(5), CancellationToken.None).ConfigureAwait(false);
Assert.HasCount(4, bars, "the running minute is left out");
Assert.AreEqual(start, bars[0].OpensAt);
StringAssert.Contains(http.Requests[0].RequestUri!.ToString(), "bar=1m");
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task ErrorsArriveWithStatus200AndBusyAnswersAreRetried()
{
var calls = 0;
var clock = new FastClock(_now);
var (okx, _) = Create(h => h.On(_ => true, _ => ++calls == 1
? FakeHttp.Respond("""{"code":"50011","data":[],"msg":"Rate limit reached"}""")
: FakeHttp.Respond(Fixture.Text("okx/ticker-btc-eur.json"))), clock);
var quote = await okx.FetchQuoteAsync("BTC-EUR", CancellationToken.None).ConfigureAwait(false);
Assert.AreEqual(2, calls);
Assert.IsGreaterThanOrEqualTo(TimeSpan.FromSeconds(2), clock.Waited, "waits before trying again");
Assert.AreEqual((65986.1m, 65998.6m), (quote.Bid, quote.Ask));
Assert.AreEqual(0.02600011m, quote.BidSize);
Assert.AreEqual(DateTimeOffset.FromUnixTimeMilliseconds(1794318312368), quote.At);
Assert.AreEqual(1.894, quote.SpreadBp!.Value, 0.001);
var (unknown, _) = Create(h => h.On("ticker", """{"code":"51001","data":[],"msg":"Instrument ID, Instrument ID code, or Spread ID doesn't exist."}"""));
var error = await Assert.ThrowsAsync<MarketDataException>(() => unknown.FetchQuoteAsync("XXX-EUR", CancellationToken.None)).ConfigureAwait(false);
Assert.IsFalse(error.Retryable);
StringAssert.Contains(error.Message, "51001");
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task DemoAddsTheSimulatedTradingHeader()
{
var (okx, http) = Create(h => h.On("ticker", Fixture.Text("okx/ticker-btc-eur.json")), options: OkxOptions.ForDemo());
await okx.FetchQuoteAsync("BTC-EUR", CancellationToken.None).ConfigureAwait(false);
Assert.AreEqual("1", http.Requests[0].Headers.GetValues("x-simulated-trading").Single());
Assert.AreEqual("wseeapap.okx.com", OkxOptions.ForDemo().BusinessStreamUrl.Host);
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task FundingRateAndOpenInterestOfBitcoin()
{
var (okx, _) = Create(h => h
.On("funding-rate", Fixture.Text("okx/funding-rate-btc.json"))
.On("open-interest", Fixture.Text("okx/open-interest-btc.json")));
var funding = await okx.FetchFundingRateAsync("BTC-USDT-SWAP", CancellationToken.None).ConfigureAwait(false);
Assert.AreEqual(-0.0000009390698834, funding.Rate);
Assert.AreEqual(TimeSpan.FromHours(8), funding.Interval);
var interest = await okx.FetchOpenInterestAsync("BTC-USDT-SWAP", CancellationToken.None).ConfigureAwait(false);
Assert.AreEqual(36006.7700000001675, interest.Coins, 1e-6);
Assert.AreEqual(2659809297.869, interest.Usd, 0.01);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void SignatureIsHmacSha256OfTimestampMethodPathAndBody()
{
var at = new DateTimeOffset(2026, 11, 10, 13, 45, 1, 234, TimeSpan.Zero);
var credentials = new OkxCredentials("key-id", "secret-value", "pass-phrase");
var headers = OkxSigner.Headers(credentials, at, "get", "/api/v5/account/balance?ccy=EUR", "", demo: true);
Assert.AreEqual("2026-11-10T13:45:01.234Z", headers["OK-ACCESS-TIMESTAMP"]);
var expected = Convert.ToBase64String(HMACSHA256.HashData(Encoding.UTF8.GetBytes("secret-value"),
Encoding.UTF8.GetBytes("2026-11-10T13:45:01.234ZGET/api/v5/account/balance?ccy=EUR")));
Assert.AreEqual(expected, headers["OK-ACCESS-SIGN"]);
Assert.AreEqual("1", headers["x-simulated-trading"]);
Assert.AreEqual("OkxCredentials(***)", credentials.ToString(), "never printed");
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task StreamSubscribesTickersAndCandlesOnTheirHostsAndPingsWhenSilent()
{
var clock = new ManualClock(_now);
var sockets = new List<FakeSocket>();
var okx = new OkxClient(new FakeHttp().Client(), clock, sockets: () =>
{
var socket = new FakeSocket();
lock (sockets)
{
sockets.Add(socket);
}
return socket;
});
using var stop = new CancellationTokenSource(TimeSpan.FromSeconds(20));
var events = new List<MarketEvent>();
var reading = Task.Run(async () =>
{
await foreach (var item in okx.StreamAsync(["BTC-EUR", "ETH-EUR"], stop.Token).ConfigureAwait(false))
{
lock (events)
{
events.Add(item);
}
}
});
await WaitForAsync(() => sockets.Count == 2 && sockets.All(s => s.Sent.Count == 1)).ConfigureAwait(false);
var publicSocket = sockets.Single(s => s.Url!.AbsolutePath.EndsWith("/public", StringComparison.Ordinal));
var businessSocket = sockets.Single(s => s.Url!.AbsolutePath.EndsWith("/business", StringComparison.Ordinal));
StringAssert.Contains(publicSocket.Sent[0], "\"channel\":\"tickers\",\"instId\":\"ETH-EUR\"");
StringAssert.Contains(businessSocket.Sent[0], "\"channel\":\"candle1m\",\"instId\":\"BTC-EUR\"");
publicSocket.Push("""{"id":"1","event":"subscribe","arg":{"channel":"tickers","instId":"BTC-EUR"},"connId":"53efe456"}""");
publicSocket.Push("""{"arg":{"channel":"tickers","instId":"BTC-EUR"},"data":[{"instType":"SPOT","instId":"BTC-EUR","last":"66148.9","lastSz":"0.00010133","askPx":"66134.7","askSz":"0.01847","bidPx":"66129.6","bidSz":"0.0193605","ts":"1794318514123"}]}""");
businessSocket.Push("""{"arg":{"channel":"candle1m","instId":"BTC-EUR"},"data":[["1794318180000","65999.8","66069.8","65999.8","66050.5","0.0523422","3457.08","3457.08","1"]]}""");
await WaitForAsync(() => events.Count == 2).ConfigureAwait(false);
var quote = events.OfType<QuoteEvent>().Single().Quote;
Assert.AreEqual((66129.6m, 66134.7m), (quote.Bid, quote.Ask));
var bar = events.OfType<BarEvent>().Single();
Assert.IsTrue(bar.Closed);
Assert.AreEqual(66050.5, bar.Bar.Close);
// Twenty seconds of silence: "ping". The public side answers, the business side does not and is dropped.
await WaitForAsync(() => clock.Waiting >= 2).ConfigureAwait(false);
clock.Advance(TimeSpan.FromSeconds(21));
await WaitForAsync(() => publicSocket.Sent.Contains("ping") && businessSocket.Sent.Contains("ping")).ConfigureAwait(false);
publicSocket.Push("pong");
await WaitForAsync(() => clock.Waiting >= 2).ConfigureAwait(false);
clock.Advance(TimeSpan.FromSeconds(21));
await reading.WaitAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false);
Assert.IsTrue(sockets.All(s => s.Disposed), "both connections are closed when the feed ends");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void StreamErrorsStopTheFeed()
{
var error = Assert.Throws<MarketDataException>(() => OkxClient.ParseStreamMessage(
"""{"event":"error","msg":"Subscribe failed, wrong URL or channel:candle1m,instId:BTC-EUR doesn't exist.","code":"60018","connId":"53efe456","id":"2"}"""));
StringAssert.Contains(error.Message, "60018");
Assert.IsEmpty(OkxClient.ParseStreamMessage("""{"event":"notice","msg":"WebSocket port 8443 will be retired soon.","code":"64010"}"""));
}
internal static async Task WaitForAsync(Func<bool> condition)
{
var deadline = DateTime.UtcNow.AddSeconds(10);
while (!condition())
{
if (DateTime.UtcNow > deadline)
{
Assert.Fail("Condition not reached in time.");
}
await Task.Delay(10).ConfigureAwait(false);
}
}
}