using Anubis.Backtest; using Anubis.Core; using Anubis.Data; using Anubis.Learning; using Anubis.Strategies; using Anubis.Trading; namespace Anubis.Tests; /// The simpler things the bot learns: slippage, what news does to prices, discoveries in plain words (SPEC 11.6; issue #65). [TestClass] [TestCategory(Category.Integration)] public sealed class LearningMoreTests { private static readonly CancellationToken _none = CancellationToken.None; private static List Fills(string tier, int count, double mean, bool real, int seed = 1) { var gen = new Gen(seed); return [.. Enumerable.Range(0, count).Select(i => new PaidFill(tier, mean + gen.Normal(), real, TradingRig.Start.AddHours(i)))]; } /// A rise from any broker account, a fall only from real money, nothing from few cases or from noise. [TestMethod] [TestCategory(Category.Unit)] public void TheRegressionRisesByItselfAndFallsOnlyOnRealMoney() { var table = SlippageTable.Standard; var rise = CostRegression.Of(Fills(SlippageTiers.Major, 40, 8.2, real: false), table).Single(); Assert.IsTrue(rise.Rise); Assert.IsTrue(rise.Bp >= rise.Measured && rise.Bp - rise.Measured < CostRegression.Step && rise.Bp % CostRegression.Step == 0, $"{rise.Bp}"); Assert.HasCount(0, CostRegression.Of(Fills(SlippageTiers.Major, 29, 8.2, real: true), table), "too few"); Assert.HasCount(0, CostRegression.Of(Fills(SlippageTiers.Major, 40, 5.1, real: true), table), "noise around what is in force"); Assert.HasCount(0, CostRegression.Of(Fills(SlippageTiers.Minor, 200, 4, real: false), table), "a fall on a practice account"); var fall = CostRegression.Of(Fills(SlippageTiers.Minor, 40, 4, real: true), table).Single(); Assert.IsFalse(fall.Rise); Assert.IsTrue(fall.Bp is > 3m and < 5m); // Real money says less but everything together says more: the cautious side wins. var mixed = CostRegression.Of([.. Fills(SlippageTiers.Equity, 40, 4, real: true), .. Fills(SlippageTiers.Equity, 400, 9, real: false, seed: 2)], table).Single(); Assert.IsTrue(mixed.Rise); // Better than the middle price: never a negative or a zero slippage. Assert.AreEqual(CostRegression.Step, CostRegression.Of(Fills(SlippageTiers.Equity, 60, -4, real: true), table).Single().Bp); } private static async Task FillAsync(TradingRig rig, Guid account, Instrument instrument, decimal bp, int n, OrderPurpose purpose = OrderPurpose.Entry) { var order = Ids.NewId(rig.Clock); await rig.Db.WriteAsync(async s => { await s.ExecuteAsync("INSERT INTO orders (id, account_id, instrument_id, strategy, client_order_id, side, order_type, quantity, status, created_at, updated_at, purpose) " + "VALUES (@id, @a, @i, 'x', @c, 'buy', 'market', @q, 'filled', @now, @now, @p)", _none, ("id", order), ("a", account), ("i", instrument.Id), ("c", "O" + order), ("q", 1m), ("now", rig.Clock.UtcNow), ("p", Wire.Text(purpose))).ConfigureAwait(false); await s.ExecuteAsync("INSERT INTO fills (id, account_id, order_id, instrument_id, execution_id, side, quantity, price, fee, fee_currency, executed_at, created_at, strategy, reference_price, slippage_bp) " + "VALUES (@id, @a, @o, @i, @e, 'buy', @q, @q, @z, 'EUR', @at, @at, 'x', @q, @bp)", _none, ("id", Ids.NewId(rig.Clock)), ("a", account), ("o", order), ("i", instrument.Id), ("e", "E" + order), ("q", 1m), ("z", 0m), ("at", rig.Clock.UtcNow.AddDays(-1).AddMinutes(n)), ("bp", bp)).ConfigureAwait(false); }, _none).ConfigureAwait(false); } /// The month: the simulator and the stops never count, a rise is applied and said, it runs once. [TestMethod] public async Task TheMonthLooksOnlyAtTheExecutionsOfABroker() { await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); var simulated = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false); var demo = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Demo, "demo").ConfigureAwait(false); var btc = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false); var book = new CostBook(rig.Db, rig.Clock); for (var i = 0; i < 40; i++) { await FillAsync(rig, simulated.AccountId, btc, 40m, i).ConfigureAwait(false); await FillAsync(rig, demo.AccountId, btc, 60m, i, OrderPurpose.Stop).ConfigureAwait(false); } Assert.IsTrue(await book.MonthAsync(_none).ConfigureAwait(false)); Assert.HasCount(0, await book.ListAsync(_none).ConfigureAwait(false)); for (var i = 0; i < 40; i++) { await FillAsync(rig, demo.AccountId, btc, 7.2m, i).ConfigureAwait(false); } Assert.IsFalse(await book.MonthAsync(_none).ConfigureAwait(false), "once for each month"); rig.Clock.Advance(TimeSpan.FromDays(31)); Assert.IsTrue(await book.MonthAsync(_none).ConfigureAwait(false)); var row = (await book.ListAsync(_none).ConfigureAwait(false)).Single(); Assert.AreEqual((SlippageTiers.Major, CostStatuses.Applied, 5m, 7.5m, 40), (row.Tier, row.Status, row.PreviousBp, row.Bp, row.Cases)); Assert.AreEqual(SlippageTable.Standard with { Major = 7.5m }, await book.TableAsync(_none).ConfigureAwait(false)); Assert.AreEqual("Scostamento misurato su 40 esecuzioni (Bitcoin, Ethereum e Solana): 7,2 punti base invece dei 5,0 previsti. Da ora simulatore e backtest ne contano 7,5.", (await NewsRulesTests.DiaryAsync(rig.Db).ConfigureAwait(false))[^1]); // The next month the estimate in force is the new one: nothing to say. rig.Clock.Advance(TimeSpan.FromDays(31)); Assert.IsTrue(await book.MonthAsync(_none).ConfigureAwait(false)); Assert.HasCount(1, await book.ListAsync(_none).ConfigureAwait(false)); } /// A fall changes nothing until the user confirms it; refused, or grown old, it never will. [TestMethod] public async Task AFallWaitsForTheUser() { await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); var live = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Live).ConfigureAwait(false); var pepe = await rig.InstrumentAsync(TradingRig.Pepe).ConfigureAwait(false); for (var i = 0; i < 40; i++) { await FillAsync(rig, live.AccountId, pepe, 6m, i).ConfigureAwait(false); } var book = new CostBook(rig.Db, rig.Clock); await book.MonthAsync(_none).ConfigureAwait(false); var first = (await book.ListAsync(_none).ConfigureAwait(false)).Single(); Assert.AreEqual((CostStatuses.Pending, 6m), (first.Status, first.Bp)); Assert.AreEqual(SlippageTable.Standard, await book.TableAsync(_none).ConfigureAwait(false)); Assert.HasCount(1, await rig.QueryAsync("SELECT id FROM notifications WHERE kind = 'cost_pending'", r => r.Id("id")).ConfigureAwait(false)); // A month later the same proposal takes its place; the old one cannot be confirmed any more. rig.Clock.Advance(TimeSpan.FromDays(31)); await book.MonthAsync(_none).ConfigureAwait(false); Assert.IsFalse(await book.DecideAsync(first.Id, true, "utente", _none).ConfigureAwait(false)); var second = (await book.ListAsync(_none).ConfigureAwait(false)).Single(e => e.Status == CostStatuses.Pending); Assert.IsTrue(await book.DecideAsync(second.Id, false, "utente", _none).ConfigureAwait(false)); Assert.AreEqual(SlippageTable.Standard, await book.TableAsync(_none).ConfigureAwait(false)); rig.Clock.Advance(TimeSpan.FromDays(31)); await book.MonthAsync(_none).ConfigureAwait(false); var third = (await book.ListAsync(_none).ConfigureAwait(false)).Single(e => e.Status == CostStatuses.Pending); Assert.IsTrue(await book.DecideAsync(third.Id, true, "utente", _none).ConfigureAwait(false)); Assert.IsFalse(await book.DecideAsync(third.Id, false, "utente", _none).ConfigureAwait(false), "only once"); Assert.AreEqual(SlippageTable.Standard with { Minor = 6m }, await book.TableAsync(_none).ConfigureAwait(false)); Assert.AreEqual("utente", (await book.ListAsync(_none).ConfigureAwait(false))[^1].DecidedBy); } /// The table in force reaches the simulator and the plan of a backtest, where it stays written. [TestMethod] public async Task TheEstimatesReachTheSimulatorAndThePlanOfATest() { await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); var account = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false); await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false); var table = SlippageTable.Standard; using var paper = new PaperBroker(PaperOptions.Okx() with { MinLatency = TimeSpan.Zero, MaxLatency = TimeSpan.Zero }, rig.Clock, rig.QuoteAsync, rig.Spec) { Slippage = () => table }; await paper.DepositAsync(10000m, "EUR", _none).ConfigureAwait(false); rig.Quote("BTC-EUR", 60000m, 60000m); async Task BuyAsync(string id) { await paper.SubmitOrderAsync(new OrderRequest(id, "BTC-EUR", OrderSide.Buy, OrderKind.Market, 0.01m, TimeInForce.Ioc), _none).ConfigureAwait(false); await paper.PumpAsync(_none).ConfigureAwait(false); return (await paper.GetFillsAsync(TradingRig.Start, _none).ConfigureAwait(false)).Single(f => f.ClientOrderId == id).Price; } Assert.AreEqual(60030m, await BuyAsync("B1").ConfigureAwait(false)); table = table with { Major = 20m }; Assert.AreEqual(60120m, await BuyAsync("B2").ConfigureAwait(false)); Assert.AreEqual(60030m, CostModel.Standard.ExecutionPrice(TradingRig.Btc, OrderSide.Buy, 60000m)); Assert.AreEqual(60240m, new CostModel(2m) { Slippage = table }.ExecutionPrice(TradingRig.Btc, OrderSide.Buy, 60000m)); var request = new TrialRequest(StrategyCatalog.All[0].Id, TrialSources.Research, Venues.Binance, ["BTCEUR"], new DateOnly(2024, 1, 1), new DateOnly(2025, 1, 1), 1000m, null); var plain = Laboratory.BuildPlan(request, rig.Clock.UtcNow, SlippageTable.Standard).Plan; Assert.AreEqual(Laboratory.BuildPlan(request, rig.Clock.UtcNow).Plan.ToJson(), plain.ToJson(), "the plans written so far stay what they are"); var plan = Laboratory.BuildPlan(request, rig.Clock.UtcNow, table).Plan; Assert.AreEqual(table, TrialPlan.FromJson(plan.ToJson()).Slippage); Assert.AreNotEqual(TrialPlan.Hash(plain.ToJson()), TrialPlan.Hash(plan.ToJson())); } /// The mean return after each kind of event, from the first close after the publication. [TestMethod] public async Task TheTableOfTheNewsStartsFromTheFirstCloseAfter() { await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); var btc = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false); var first = new DateOnly(2026, 1, 1); await new BarStore(rig.Db, rig.Clock).UpsertDailyAsync(btc.Id, Enumerable.Range(0, 20).Select(i => { var close = i switch { < 4 => 100.0, 4 => 90, 5 => 81, _ => 45 }; return new DailyBar(first.AddDays(i), close, close, close, close, 1); }), "test", _none).ConfigureAwait(false); // Published during the fourth day (close 100): then 90 the day after, 45 five days after. await NewsRulesTests.StoryAsync(rig.Db, rig.Clock, btc.Spec, "Exchange hacked", new DateTimeOffset(2026, 1, 4, 10, 0, 0, TimeSpan.Zero), 4, -0.9, "A", trusted: true).ConfigureAwait(false); // Published when the fifth had already closed: the first close after is 81, then 45 and 45. await NewsRulesTests.StoryAsync(rig.Db, rig.Clock, btc.Spec, "Bridge hacked", new DateTimeOffset(2026, 1, 6, 0, 0, 0, TimeSpan.Zero), 4, -0.9, "A", trusted: true).ConfigureAwait(false); // Too recent, and of no known kind: they do not count. await NewsRulesTests.StoryAsync(rig.Db, rig.Clock, btc.Spec, "Wallet hacked", new DateTimeOffset(2026, 1, 18, 0, 0, 0, TimeSpan.Zero), 4, -0.9, "A", trusted: true).ConfigureAwait(false); await NewsRulesTests.StoryAsync(rig.Db, rig.Clock, btc.Spec, "Bitcoin quiet", new DateTimeOffset(2026, 1, 2, 0, 0, 0, TimeSpan.Zero), 2, 0.1, "A", trusted: true).ConfigureAwait(false); var desk = new DiscoveryDesk(rig.Db, rig.Clock, new LearningStore(rig.Db, rig.Clock)); await desk.RefreshAsync(_none).ConfigureAwait(false); var impact = (await desk.LatestAsync(_none).ConfigureAwait(false)).News.Single(); Assert.AreEqual(("security_incident", 2, "troppo pochi per fidarsi"), (impact.Kind, impact.Cases, impact.Trust)); Assert.AreEqual((-0.1 + ((45.0 / 81) - 1)) / 2, impact.OneDay, 1e-9); Assert.AreEqual((-0.55 + ((45.0 / 81) - 1)) / 2, impact.FiveDays, 1e-9); Assert.AreEqual("Attacco informatico", NewsEventNames.Label(impact.Kind)); foreach (var kind in News.NewsVerdicts.EventTypes.Where(k => k != "other")) { Assert.AreNotEqual("Altro", NewsEventNames.Label(kind), kind); } } /// The close of a stock is at four in New York, not at midnight. [TestMethod] [TestCategory(Category.Unit)] public void TheCloseOfAStockIsInNewYork() { var bars = Enumerable.Range(0, 8).Select(i => new DailyBar(new DateOnly(2026, 7, 1).AddDays(i), 1, 1, 1, 100 + i, 1)).ToList(); var before = DiscoveryDesk.AfterNews(bars, AssetClasses.Equity, new DateTimeOffset(2026, 7, 1, 19, 59, 0, TimeSpan.Zero)); var after = DiscoveryDesk.AfterNews(bars, AssetClasses.Equity, new DateTimeOffset(2026, 7, 1, 20, 0, 0, TimeSpan.Zero)); Assert.AreEqual(0.01, before!.Value.One, 1e-9); Assert.AreEqual(1.0 / 101, after!.Value.One, 1e-9); } private static IReadOnlyList Examples(int count, Func make, int perDay = 1) { var gen = new Gen(4); return [ .. Enumerable.Range(0, count).Select(i => { var (volatility, win) = make(i, gen); var day = new DateOnly(2021, 1, 1).AddDays(i / perDay * 3); return new Example(Guid.NewGuid(), StrategyNames.CryptoTrend, "C" + i, CaseSources.Live, day, new DateTimeOffset(day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero), "t", 0.1m, null, null, new Dictionary { [Clues.VolatilityRatio] = volatility }) { Label = new CaseLabel(win, win ? 0.1 : -0.1, day, day.AddDays(1), "x") }; }), ]; } /// A real relation is found and said with its cases; without one, the bot says that it does not matter. [TestMethod] [TestCategory(Category.Unit)] public void ARelationIsSaidWithItsCasesAndItsTrust() { var real = DiscoveryFinder.Of(Examples(900, (i, gen) => i % 3 == 0 ? (2, gen.Double() < 0.25) : (1, gen.Double() < 0.55))); var found = real[0]; Assert.AreEqual("I segnali di trend sulle crypto riescono meno quando i prezzi sono molto più agitati del solito", found.Title); Assert.AreEqual((300, "conclusione solida"), (found.Cases, found.Trust)); Assert.MatchesRegex(new System.Text.RegularExpressions.Regex("^[0-9]+% di riusciti contro il [0-9]+% degli altri$"), found.Detail); var hint = DiscoveryFinder.Of(Examples(200, (i, gen) => i % 5 == 0 ? (2, gen.Double() < 0.1) : (1, gen.Double() < 0.6))); Assert.AreEqual((40, "un indizio discreto"), (hint[0].Cases, hint[0].Trust)); var nothing = DiscoveryFinder.Of(Examples(900, (i, gen) => (i % 3 == 0 ? 2 : 1, gen.Double() < 0.4))); Assert.IsTrue(nothing.Any(d => d.Title == "Il giorno della settimana non conta per i segnali di trend sulle crypto" && d.Cases == 900)); Assert.IsTrue(nothing.All(d => d.Detail == "Le differenze stanno tutte dentro il margine d'errore"), string.Join('|', nothing.Select(d => d.Title))); // Too few to say anything at all. Assert.HasCount(0, DiscoveryFinder.Of(Examples(15, (i, gen) => (i % 2 == 0 ? 2 : 1, i % 2 == 0)))); Assert.AreEqual("troppo pochi per fidarsi", Discovery.TrustOf(19)); Assert.AreEqual("un indizio discreto", Discovery.TrustOf(99)); } /// On pure chance almost nothing is declared: the many questions and the coins that move together are counted. [TestMethod] [TestCategory(Category.Unit)] public void ChanceIsNotADiscovery() { var declared = 0; for (var seed = 0; seed < 60; seed++) { var gen = new Gen(seed); var months = new Dictionary(); // Whole months win or lose together, and whole months are agitated or calm, with no relation between the two. var examples = Examples(1200, (i, _) => { var month = i / 60; if (!months.TryGetValue(month, out var m)) { months[month] = m = (gen.Bool(), gen.Bool() ? 0.2 : 0.6); } return (m.High ? 2 : 1, gen.Double() < m.Chance); }, perDay: 6); declared += DiscoveryFinder.Of(examples).Any(d => d.Detail.Contains("contro", StringComparison.Ordinal)) ? 1 : 0; } Assert.IsLessThanOrEqualTo(6, declared, $"{declared} of 60"); } [TestMethod] [TestCategory(Category.Unit)] public void TheQuantileIsTheOneOfTheNormal() { Assert.AreEqual(1.959964, DiscoveryFinder.Quantile(0.05), 1e-4); Assert.AreEqual(2.575829, DiscoveryFinder.Quantile(0.01), 1e-4); } }