using System.Globalization;
using Anubis.Brokers;
using Anubis.Core;
using Anubis.Trading;
namespace Anubis.Tests;
/// The executions of OKX after a long absence or a restore: recent and history, each counted once (issue #69).
[TestClass]
[TestCategory(Category.Unit)]
public sealed class OkxHistoryTests
{
private static readonly DateTimeOffset _now = TradingRig.Start;
private static string Fill(string trade, DateTimeOffset at, string client = "ANUtrnd00000000aE1") =>
"{\"side\":\"buy\",\"fillSz\":\"0.01\",\"fillPx\":\"50000\",\"fee\":\"-0.5\",\"feeCcy\":\"EUR\",\"ordId\":\"1" + trade + "\",\"instId\":\"BTC-EUR\",\"instType\":\"SPOT\",\"clOrdId\":\"" + client +
"\",\"billId\":\"b" + trade + "\",\"tradeId\":\"" + trade + "\",\"fillTime\":\"" + Ms(at) + "\",\"ts\":\"" + Ms(at) + "\"}";
private static string Ms(DateTimeOffset at) => at.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture);
private static string Envelope(IEnumerable items) => "{\"code\":\"0\",\"msg\":\"\",\"data\":[" + string.Join(',', items) + "]}";
private static OkxTrading Adapter(FakeHttp http) =>
new(http.Client(), new ManualClock(_now), new OkxCredentials("doc-key", "doc-secret", "doc-pass"), new OkxTradingOptions { Environment = TradingEnvironments.Demo },
TradingConsent.None);
private static FakeHttp Http(IReadOnlyList history, IReadOnlyList recent) => new FakeHttp()
.On(u => u.AbsolutePath == "/api/v5/trade/fills-history", r => FakeHttp.Respond(Envelope(
r.RequestUri!.Query.Contains("after=", StringComparison.Ordinal) ? history.Skip(100) : history.Take(100))))
.On(u => u.AbsolutePath == "/api/v5/trade/fills", _ => FakeHttp.Respond(Envelope(recent)))
.On(u => u.AbsolutePath == "/api/v5/trade/order", _ => FakeHttp.Respond("{\"code\":\"51603\",\"msg\":\"Order does not exist\",\"data\":[]}"));
[TestMethod]
public async Task AfterALongAbsenceTheHistoryIsReadTooAndEachExecutionCountsOnce()
{
var since = _now.AddDays(-20);
string[] history = [.. Enumerable.Range(0, 150).Select(i => Fill((1000 + i).ToString(CultureInfo.InvariantCulture), _now.AddDays(-5).AddMinutes(-i)))];
var http = Http(history, [Fill("2000", _now.AddHours(-1)), Fill("1000", _now.AddDays(-5))]);
var fills = await Adapter(http).GetFillsAsync(since, CancellationToken.None);
Assert.HasCount(151, fills);
Assert.HasCount(151, fills.Select(f => f.ExecutionId).Distinct().ToList());
var asked = http.Urls.Where(u => u.AbsolutePath.EndsWith("/fills-history", StringComparison.Ordinal)).ToList();
Assert.HasCount(2, asked, "Two pages of history.");
StringAssert.Contains(asked[0].Query, "instType=SPOT");
StringAssert.Contains(asked[0].Query, "begin=" + Ms(since));
StringAssert.Contains(asked[1].Query, "after=b1099");
}
[TestMethod]
public async Task TheRecentOnesAloneAreEnoughForTheEverydayReading()
{
var http = Http([], [Fill("2000", _now.AddHours(-1))]);
Assert.HasCount(1, await Adapter(http).GetFillsAsync(_now.AddHours(-48), CancellationToken.None));
Assert.IsTrue(http.Urls.All(u => u.AbsolutePath == "/api/v5/trade/fills"));
}
[TestMethod]
public async Task TheHistoryIsAskedOnlyAsFarAsOkxKeepsIt()
{
var http = Http([], []);
var adapter = Adapter(http);
await adapter.GetFillsAsync(_now.AddDays(-400), CancellationToken.None);
StringAssert.Contains(http.Urls.First().Query, "begin=" + Ms(_now - OkxTrading.HistoryReach));
Assert.AreEqual(OkxTrading.HistoryReach, adapter.FillHistory);
}
[TestMethod]
public async Task AnOldExecutionWhoseOrderOkxForgotIsReadWithoutAName()
{
var http = Http([Fill("1000", _now.AddDays(-10), client: "")], []);
Assert.AreEqual("", (await Adapter(http).GetFillsAsync(_now.AddDays(-20), CancellationToken.None)).Single().ClientOrderId);
}
}