using System.Text.Json; using Anubis.Backtest; using Anubis.Core; using Anubis.Data; using Anubis.Db; using Anubis.Learning; using Anubis.News; using Anubis.Strategies; using Anubis.Trading; namespace Anubis.Tests; /// The quarterly review of SPEC 12.2 and the balance of the restrictions of 10.5 (issue #74). [TestClass] public sealed class QuarterlyReviewTests { private static readonly CancellationToken _none = CancellationToken.None; private static readonly DateOnly Through = new(2026, 12, 31); private const string Crypto = StrategyNames.CryptoTrend; private static DateTimeOffset At(int year, int month, int day) => new(year, month, day, 2, 10, 0, TimeSpan.Zero); // ---- The rig ---------------------------------------------------------------------------------------------------- private static async Task WriteHistoryAsync(string folder) { var store = new ResearchStore(folder); var seed = 21u; foreach (var coin in new[] { "BTC", "ETH", "SOL", "XRP" }) { var bars = LiveRig.Synthetic(Through.AddDays(-799), 800, 100, seed++).Select(b => new ResearchBar(new DateTimeOffset(b.Day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero), (decimal)b.Open, (decimal)b.High, (decimal)b.Low, (decimal)b.Close, (decimal)b.Volume)).ToList(); await store.WriteAsync(EuroHistory.Venue, coin + "EUR", Timeframes.Day, bars, _none).ConfigureAwait(false); } } // A report of the protocol on those coins, whose verdict each test chooses. private static readonly Lazy> _report = new(async () => (await TrialAsync(null).ConfigureAwait(false)).Report); private static async Task<(BacktestReport Report, TrialSummary Summary)> TrialAsync(string? judged) { var folder = TempFolder.Create("review-report"); try { await WriteHistoryAsync(folder).ConfigureAwait(false); var plan = Laboratory.BuildPlan(new TrialRequest(Crypto, TrialSources.Research, EuroHistory.Venue, CryptoTrendProtocol.Narrow, CryptoTrendProtocol.From, Through, CryptoTrendProtocol.Capital, null), At(2027, 1, 5)).Plan with { Judged = judged }; var data = await Laboratory.LoadResearchAsync(folder, plan.Data, _none).ConfigureAwait(false); return TrialRunner.Run(Guid.Empty, plan, TrialPlan.Hash(plan.ToJson()), StrategyCatalog.Find(Crypto)!, data, PriorTrials.None, At(2027, 1, 5)); } finally { TempFolder.Delete(folder); } } private sealed class ReviewRig : IAsyncDisposable { public required LiveRig Live { get; init; } public required string Folder { get; init; } public required Laboratory Lab { get; set; } public required QuarterlyReview Review { get; set; } public string? Missing { get; set; } public Exception? Failure { get; set; } public List Prepared { get; } = []; public Database Db => Live.Rig.Db; public ManualClock Clock => Live.Rig.Clock; public static async Task CreateAsync(string stage = StrategyStages.Observation, DateOnly? since = null, Qualification? qualification = null, bool history = true) { var from = since ?? new DateOnly(2026, 9, 1); var live = await LiveRig.CreateAsync(from, from.AddDays(5), stage: stage).ConfigureAwait(false); live.UseFirst(Rates(new DateOnly(2026, 10, 31))); var folder = TempFolder.Create("review"); if (history) { await WriteHistoryAsync(folder).ConfigureAwait(false); } await live.Rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET qualification = @q", _none, ("q", new DbJson(JsonSerializer.Serialize(qualification ?? Old(false), Qualification.Json)))), _none) .ConfigureAwait(false); var rig = new ReviewRig { Live = live, Folder = folder, Lab = null!, Review = null! }; rig.Start(); return rig; } /// A new process on the same database. public void Start() { Lab?.Dispose(); Lab = new Laboratory(Db, Clock, Folder); Review = new QuarterlyReview(Db, Clock, Lab, Live.Stages, Live.Learning, Folder, (to, _) => { Prepared.Add(to); return Failure is { } failure ? Task.FromException(failure) : Task.FromResult(Missing); }); Lab.ReviewTrialEnded = Review.ConcludeAsync; } public async Task NightAsync(DateTimeOffset at) { Clock.Set(at); await Review.RunIfDueAsync(_none).ConfigureAwait(false); } /// The baseline in December, then the review of January. public async Task OpenAsync() { await NightAsync(At(2026, 12, 10)).ConfigureAwait(false); await NightAsync(At(2027, 1, 5)).ConfigureAwait(false); return (await QuarterlyReview.ListAsync(Db, _none).ConfigureAwait(false)).Single(); } /// The whole review, its trials ended with the given verdict. public async Task ReviewAsync(bool passed, Func? change = null) { var review = await OpenAsync().ConfigureAwait(false); await EndAsync(review, passed, change).ConfigureAwait(false); await Review.ConcludeAsync(_none).ConfigureAwait(false); return (await QuarterlyReview.ListAsync(Db, _none).ConfigureAwait(false)).Single(r => r.Id == review.Id); } public async Task EndAsync(Review review, bool passed, Func? change = null) { var report = await _report.Value.ConfigureAwait(false); report = report with { Passed = passed, Checks = [.. report.Checks.Select((c, i) => c with { Passed = passed || i > 0, Value = c.Value ?? 0 })], }; report = change?.Invoke(report) ?? report; foreach (var trial in await Lab.Trials.OfReviewAsync(review.Id, _none).ConfigureAwait(false)) { Assert.IsTrue(await Lab.Trials.StartAsync(trial.Id, _none).ConfigureAwait(false)); var summary = new TrialSummary("EUR", report.Chosen, 1m, 0.1, 1, 0.1, 10, 0.95, 0.1, [.. report.Variants.Select(v => v.Sharpe)]); await Lab.Trials.FinishAsync(trial.Id, "x", summary, (report with { TrialId = trial.Id }).ToJson(), passed, _none).ConfigureAwait(false); } } public async Task StageAsync() => (await Live.Stages.GetAsync(Crypto, _none).ConfigureAwait(false))!; public Task CountAsync(string sql) => Db.ReadAsync(async s => (int)await s.CountAsync(sql).ConfigureAwait(false), _none); public async ValueTask DisposeAsync() { Lab.Dispose(); await Live.DisposeAsync().ConfigureAwait(false); TempFolder.Delete(Folder); } } private static Qualification Old(bool passed) => new() { Passed = passed, Verdict = passed ? "superato" : "non superato", Report = CryptoTrendProtocol.ReportPath, Parameters = "coin_vol=10;max_stop=20", MaxDrawdown = 0.2m, ExpectedSlippageBp = 7m, Through = new DateOnly(2026, 10, 31), StrategyVersion = "1", }; private static FirstModelFile Rates(DateOnly through, double rate = 0.4) => new() { BaseRates = new Dictionary { [Crypto] = rate }, Through = through }; // ---- When ------------------------------------------------------------------------------------------------------- [TestMethod] [TestCategory(Category.Unit)] public void AReviewIsDueOnceAQuarterFromTheFifthDay() { Assert.AreEqual("2026-Q4", QuarterlyReview.QuarterOf(new DateOnly(2026, 12, 31))); Assert.AreEqual("2027-Q1", QuarterlyReview.QuarterOf(new DateOnly(2027, 1, 1))); Assert.IsFalse(QuarterlyReview.IsDue(new DateOnly(2027, 1, 20), null), "the first quarter is only noted"); Assert.IsFalse(QuarterlyReview.IsDue(new DateOnly(2027, 1, 4), "2026-Q4")); Assert.IsTrue(QuarterlyReview.IsDue(new DateOnly(2027, 1, 5), "2026-Q4")); Assert.IsTrue(QuarterlyReview.IsDue(new DateOnly(2027, 3, 31), "2026-Q4")); Assert.IsFalse(QuarterlyReview.IsDue(new DateOnly(2027, 1, 5), "2027-Q1")); Assert.IsTrue(QuarterlyReview.IsDue(new DateOnly(2027, 8, 1), "2026-Q4"), "several quarters missed"); Assert.AreEqual(new DateOnly(2027, 1, 5), QuarterlyReview.NextDue(new DateOnly(2026, 12, 1), "2026-Q4")); Assert.AreEqual(new DateOnly(2027, 1, 5), QuarterlyReview.NextDue(new DateOnly(2026, 12, 1), null)); Assert.AreEqual(new DateOnly(2027, 1, 5), QuarterlyReview.NextDue(new DateOnly(2027, 2, 1), "2026-Q4"), "already due"); } [TestMethod] [TestCategory(Category.Integration)] public async Task ItWaitsForTheArchiveUntilTheFifteenthThenPublishesWithoutIt() { await using var rig = await ReviewRig.CreateAsync(history: false); rig.Missing = "gli archivi di Binance non si scaricano"; await rig.NightAsync(At(2027, 1, 20)); Assert.IsEmpty(rig.Prepared, "the first night only notes the quarter"); await rig.NightAsync(At(2027, 4, 4)); Assert.IsEmpty(rig.Prepared); await rig.NightAsync(At(2027, 4, 5)); await rig.NightAsync(At(2027, 4, 15)); CollectionAssert.AreEqual(new[] { new DateOnly(2027, 3, 31), new DateOnly(2027, 3, 31) }, rig.Prepared); var waiting = (await QuarterlyReview.ListAsync(rig.Db, _none)).Single(); Assert.AreEqual(ReviewStatuses.Preparing, waiting.Status); Assert.AreEqual(0, await rig.CountAsync("SELECT COUNT(*) FROM journal WHERE code = 'quarterly_review'")); await rig.NightAsync(At(2027, 4, 16)); var done = (await QuarterlyReview.ListAsync(rig.Db, _none)).Single(); Assert.AreEqual((waiting.Id, ReviewStatuses.Done, "2027-Q2"), (done.Id, done.Status, done.Quarter)); var line = done.Report!.Strategies.Single(); Assert.AreEqual((ReviewVerdicts.Waiting, ReviewActions.None), (line.Verdict, line.Action)); Assert.Contains("dati mancanti: gli archivi di Binance non si scaricano", line.Text); Assert.IsNull(done.Report.RatesAfter); Assert.IsEmpty(await rig.Lab.Trials.ListAsync(10, _none)); Assert.AreEqual("non superato", (await rig.StageAsync()).Qualification!.Verdict, "the outcome before stays"); Assert.IsNull(await rig.Live.Stages.ReviewVerdictAsync(Crypto, _none)); // The same quarter never twice; three quarters off make one review. await rig.NightAsync(At(2027, 4, 20)); Assert.HasCount(4, rig.Prepared.Append(default).ToList()); rig.Missing = "mancano i cambi della BCE"; await rig.NightAsync(At(2028, 2, 20)); await rig.NightAsync(At(2028, 2, 21)); var all = await QuarterlyReview.ListAsync(rig.Db, _none); CollectionAssert.AreEqual(new[] { "2028-Q1", "2027-Q2" }, all.Select(r => r.Quarter).ToList()); Assert.AreEqual(new DateOnly(2028, 1, 31), all[0].Through); Assert.AreEqual(2, await rig.CountAsync("SELECT COUNT(*) FROM journal WHERE code = 'quarterly_review'")); } [TestMethod] [TestCategory(Category.Integration)] public async Task AnErrorWhilePreparingTheHistoryIsAMissingReasonLikeTheOthers() { await using var rig = await ReviewRig.CreateAsync(history: false); await rig.NightAsync(At(2026, 12, 10)); rig.Failure = new InvalidOperationException("broken archive at C:\\x"); await rig.NightAsync(At(2027, 1, 5)); Assert.AreEqual(ReviewStatuses.Preparing, (await QuarterlyReview.ListAsync(rig.Db, _none)).Single().Status); // A wait that ran out is an error too; the stop of the program is not, and the review stays as it is. rig.Failure = new TaskCanceledException(); await rig.NightAsync(At(2027, 1, 6)); rig.Clock.Set(At(2027, 1, 17)); using var stop = new CancellationTokenSource(); await stop.CancelAsync(); await Assert.ThrowsAsync(() => rig.Review.RunIfDueAsync(stop.Token)); Assert.AreEqual(ReviewStatuses.Preparing, (await QuarterlyReview.ListAsync(rig.Db, _none)).Single().Status); rig.Failure = new InvalidOperationException("broken archive at C:\\x"); await rig.NightAsync(At(2027, 1, 18)); var done = (await QuarterlyReview.ListAsync(rig.Db, _none)).Single(); Assert.AreEqual(ReviewStatuses.Done, done.Status); Assert.AreEqual("lo storico non si è potuto preparare per un errore", done.Report!.Missing); Assert.AreEqual("Non riprovata, dati mancanti: lo storico non si è potuto preparare per un errore. Resta valido l'esito precedente.", done.Report.Strategies.Single().Text); } // ---- The run ---------------------------------------------------------------------------------------------------- /// The real trials, with a restart in the middle: each trial counts once, the review concludes once. [TestMethod] [TestCategory(Category.Integration)] public async Task ARestartHalfwayGoesOnAndTheReviewConcludesOnce() { await using var rig = await ReviewRig.CreateAsync(); await rig.Db.WriteAsync(s => s.ExecuteAsync( "INSERT INTO cost_estimates (id, tier, status, previous_bp, bp, measured_bp, low_bp, high_bp, cases, created_at, updated_at) VALUES (@id, @tier, @st, 5, 12, 12, 10, 14, 40, @t, @t)", _none, ("id", Ids.NewId(rig.Clock)), ("tier", SlippageTiers.All[0]), ("st", CostStatuses.Applied), ("t", rig.Clock.UtcNow)), _none); var review = await rig.OpenAsync(); Assert.AreEqual(ReviewStatuses.Running, review.Status); Assert.AreEqual(Through, review.Through); var trials = await rig.Lab.Trials.OfReviewAsync(review.Id, _none); Assert.HasCount(2, trials); Assert.HasCount(4, trials[0].Plan.Data.Symbols); CollectionAssert.AreEqual(CryptoTrendProtocol.Narrow.ToList(), trials[1].Plan.Data.Symbols.ToList()); Assert.IsTrue(trials.All(t => t is { Status: TrialStatuses.Planned, Plan.Priors: ReviewPriors.All, Plan.Slippage: not null } && t.Plan.Slippage.Of(SlippageTiers.All[0]) == 12m && t.Plan.Data.From == CryptoTrendProtocol.From)); // The same night again plans nothing more. await rig.NightAsync(At(2027, 1, 6)); Assert.HasCount(2, await rig.Lab.Trials.ListAsync(10, _none)); // The process dies with the first trial done and the second running. await rig.Lab.ProcessAsync(trials[0].Id, _none); Assert.AreEqual(TrialStatuses.Done, (await rig.Lab.Trials.GetAsync(trials[0].Id, _none))!.Status); Assert.IsTrue(await rig.Lab.Trials.StartAsync(trials[1].Id, _none)); rig.Start(); using var stop = new CancellationTokenSource(); var run = rig.Lab.RunAsync(stop.Token); Review done; for (var deadline = DateTime.UtcNow.AddMinutes(4); ; await Task.Delay(100)) { done = (await QuarterlyReview.ListAsync(rig.Db, _none)).Single(); if (done.Status == ReviewStatuses.Done || DateTime.UtcNow > deadline) { break; } } Assert.AreEqual(ReviewStatuses.Done, done.Status); await Task.WhenAll(rig.Review.ConcludeAsync(_none), rig.Review.ConcludeAsync(_none)); await stop.CancelAsync(); try { await run; } catch (OperationCanceledException) { } Assert.HasCount(2, await rig.Lab.Trials.ListAsync(10, _none)); Assert.AreEqual(1, await rig.CountAsync("SELECT COUNT(*) FROM review_outcomes")); Assert.AreEqual(1, await rig.CountAsync("SELECT COUNT(*) FROM journal WHERE code = 'quarterly_review'")); Assert.AreEqual(1, await rig.CountAsync("SELECT COUNT(*) FROM notifications WHERE kind = 'quarterly_review'")); var reports = new List(); foreach (var t in trials) { reports.Add(BacktestReport.FromJson((await rig.Lab.Trials.ReportJsonAsync(t.Id, _none))!)); } var n = reports[0].Variants.Count; Assert.AreEqual(3 * n, reports[0].TrialsCounted, "in observation: its own and those of the protocol that turned it down"); Assert.AreEqual(4 * n, reports[1].TrialsCounted); var line = done.Report!.Strategies.Single(); Assert.AreEqual(reports.All(r => r.Passed) ? ReviewVerdicts.Passed : ReviewVerdicts.Rejected, line.Verdict); CollectionAssert.AreEqual(trials.Select(t => t.Id).ToList(), line.Trials.ToList()); Assert.AreEqual(reports[0].Chosen, line.Chosen!.Parameters); // The outcome of the strategy and the base rates come from the longer history. var q = (await rig.StageAsync()).Qualification!; Assert.AreEqual((Through, "/laboratorio/revisione/" + done.Id, reports[0].Chosen), (q.Through, q.Report, q.Parameters)); Assert.AreEqual(reports[0].ExpectedSlippageBp, q.ExpectedSlippageBp); var rates = await rig.Live.Learning.BaseRatesAsync(_none); Assert.AreEqual(0.4, done.Report.RatesBefore[Crypto]); Assert.AreEqual(done.Report.RatesAfter![Crypto], rates[Crypto]); var history = (await rig.Live.Learning.Store.AllAsync(_none)).Where(e => e.Source == CaseSources.History).ToList(); Assert.IsNotEmpty(history); Assert.AreEqual(Trainer.SharesOf(history)[Crypto], rates[Crypto], 1e-12); } [TestMethod] [TestCategory(Category.Integration)] public async Task ATrialThatFailsLeavesTheOutcomeInForce() { await using var rig = await ReviewRig.CreateAsync(); var review = await rig.OpenAsync(); var trials = await rig.Lab.Trials.OfReviewAsync(review.Id, _none); await rig.Lab.Trials.FailAsync(trials[0].Id, "guasto", _none); await rig.Review.ConcludeAsync(_none); Assert.AreEqual(ReviewStatuses.Running, (await QuarterlyReview.ListAsync(rig.Db, _none)).Single().Status, "one is still to run"); await rig.Lab.Trials.FailAsync(trials[1].Id, "guasto", _none); await rig.Review.ConcludeAsync(_none); var done = (await QuarterlyReview.ListAsync(rig.Db, _none)).Single(); Assert.AreEqual((ReviewVerdicts.Error, ReviewActions.None), (done.Report!.Strategies.Single().Verdict, done.Report.Strategies.Single().Action)); Assert.AreEqual("non superato", (await rig.StageAsync()).Qualification!.Verdict); Assert.IsNull(await rig.Live.Stages.ReviewVerdictAsync(Crypto, _none)); } // ---- What it does to a strategy --------------------------------------------------------------------------------- [TestMethod] [TestCategory(Category.Integration)] [DataRow("2026-11-01", false, ReviewActions.TooEarly)] [DataRow("2026-09-01", false, ReviewActions.Promoted)] [DataRow("2026-09-01", true, ReviewActions.UserChoice)] public async Task AStrategyInObservationThatPassesGoesToSimulationAfterNinetyDays(string since, bool byUser, string action) { await using var rig = await ReviewRig.CreateAsync(since: DateOnly.Parse(since, System.Globalization.CultureInfo.InvariantCulture)); if (byUser) { await rig.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO strategy_stage_history (id, strategy, from_stage, to_stage, reason, created_at) VALUES (@id, @s, 'simulation', 'observation', 'user · utente', @t)", _none, ("id", Ids.NewId(rig.Clock)), ("s", Crypto), ("t", rig.Clock.UtcNow)), _none); } var review = await rig.ReviewAsync(passed: true); Assert.AreEqual((ReviewVerdicts.Passed, action), (review.Report!.Strategies.Single().Verdict, review.Report.Strategies.Single().Action)); var stage = await rig.StageAsync(); Assert.AreEqual(action == ReviewActions.Promoted ? StrategyStages.Simulation : StrategyStages.Observation, stage.Stage); Assert.IsTrue(stage.Qualification!.Passed); Assert.AreEqual(Through, stage.Qualification.Through); Assert.AreEqual(action == ReviewActions.Promoted ? 1 : 0, await rig.CountAsync("SELECT COUNT(*) FROM strategy_stage_history WHERE reason LIKE 'quarterly_review%'")); StringAssert.Contains((await NewsRulesTests.DiaryAsync(rig.Db)).Single(m => m.StartsWith("Revisione trimestrale pronta", StringComparison.Ordinal)), QuarterlyReview.ActionText(review.Report.Strategies.Single())); } [TestMethod] [TestCategory(Category.Integration)] public async Task AStrategyInObservationThatDoesNotPassStaysWithTheNewVerdict() { await using var rig = await ReviewRig.CreateAsync(); var review = await rig.ReviewAsync(passed: false); Assert.AreEqual(ReviewActions.Stays, review.Report!.Strategies.Single().Action); var stage = await rig.StageAsync(); Assert.AreEqual(StrategyStages.Observation, stage.Stage); Assert.StartsWith("Revisione del 1º trimestre 2027: protocollo non superato. Universo ampio:", stage.Qualification!.Verdict); Assert.IsFalse(stage.Qualification.Verdict.Contains("Resta in osservazione", StringComparison.Ordinal)); // A restart with the older outcome of the program does not bring it back; a newer one, or new rules, do. await rig.Live.Stages.ApplyQualificationAsync(Crypto, Old(false), _none); await rig.Live.Stages.ApplyQualificationAsync(Crypto, Old(true) with { Through = null, StrategyVersion = null }, _none); Assert.AreEqual(Through, (await rig.StageAsync()).Qualification!.Through); await rig.Live.Stages.ApplyQualificationAsync(Crypto, Old(true) with { StrategyVersion = "2", Verdict = "regole nuove" }, _none); Assert.AreEqual("regole nuove", (await rig.StageAsync()).Qualification!.Verdict); Assert.AreEqual(StrategyStages.Observation, (await rig.StageAsync()).Stage, "only the first start moves a strategy by itself"); await rig.Live.Stages.ApplyQualificationAsync(Crypto, Old(false) with { Through = Through.AddMonths(3), Verdict = "storico più lungo" }, _none); Assert.AreEqual("storico più lungo", (await rig.StageAsync()).Qualification!.Verdict); // An outcome written before the reviews still reads. var old = JsonSerializer.Deserialize("""{"passed":true,"verdict":"x","report":"y"}""", Qualification.Json)!; Assert.IsNull(old.Through); Assert.IsFalse(old.Outlives(Old(false))); } [TestMethod] [TestCategory(Category.Integration)] public async Task AStrategyInSimulationKeepsItsFiguresAndCannotAdvanceUntilAReviewPasses() { await using var rig = await ReviewRig.CreateAsync(StrategyStages.Simulation, qualification: Old(true)); async Task DemotionAsync() => (await rig.Live.Stages.RequirementsAsync(Crypto, _none)).Single(r => r.Key == "demotion"); Assert.IsTrue((await DemotionAsync()).Met); var review = await rig.ReviewAsync(passed: false, r => r with { Variants = [.. r.Variants.Select((v, i) => v with { Parameters = i == 0 && !v.Chosen ? "coin_vol=10;max_stop=20" : v.Parameters })] }); var line = review.Report!.Strategies.Single(); Assert.AreEqual((StrategyStages.Simulation, ReviewActions.Held), (line.Stage, line.Action)); Assert.IsTrue((await rig.Lab.Trials.OfReviewAsync(review.Id, _none)).All(t => t.Plan.Priors == ReviewPriors.Review), "already qualified: the same grid measured again"); var stage = await rig.StageAsync(); Assert.AreEqual(StrategyStages.Simulation, stage.Stage); Assert.AreEqual(JsonSerializer.Serialize(Old(true), Qualification.Json), JsonSerializer.Serialize(stage.Qualification, Qualification.Json)); Assert.Contains("non è stata superata", (await DemotionAsync()).Value); Assert.IsFalse((await DemotionAsync()).Met); Assert.IsEmpty(await rig.Live.Stages.CheckDemotionsAsync(_none), "nothing to demote in simulation"); // The next one that waits for data leaves it in force; one that passes clears it. await NextAsync(rig, ReviewVerdicts.Waiting, new DateOnly(2027, 3, 31)); Assert.IsFalse((await DemotionAsync()).Met); await NextAsync(rig, ReviewVerdicts.Passed, new DateOnly(2027, 6, 30)); Assert.IsTrue((await DemotionAsync()).Met); } // ---- The variant in use ----------------------------------------------------------------------------------------- /// The grid says how much was searched; the figures, the checks and the curve are those of the variant the strategy works with. [TestMethod] [TestCategory(Category.Unit)] public async Task ATrialJudgesTheVariantInUseAndCountsTheSameTries() { var chosen = await _report.Value; Assert.IsNull(chosen.Judged); var used = chosen.Variants.First(v => !v.Chosen && v.NetResult != chosen.Metrics.NetResult); var (report, summary) = await TrialAsync(used.Parameters); Assert.AreEqual((used.Parameters, chosen.Chosen), (report.Judged, report.Chosen)); Assert.AreEqual((used.NetResult, used.MaxDrawdown), (report.Metrics.NetResult, report.Metrics.MaxDrawdown)); Assert.AreEqual(used.NetResult, report.Costs.Single(c => c.Multiplier == 1m).NetResult); Assert.AreNotEqual(chosen.Costs.Single(c => c.Multiplier == 2m).NetResult, report.Costs.Single(c => c.Multiplier == 2m).NetResult); Assert.AreEqual(used.MaxDrawdown, report.Checks.Single(c => c.Key == ReportCheckKeys.Drawdown).Value); Assert.AreEqual(used.Sharpe, report.DeflatedSharpe.Sharpe); Assert.AreEqual(report.DeflatedSharpe.Value, report.Checks.Single(c => c.Key == ReportCheckKeys.DeflatedSharpe).Value); Assert.AreEqual(CryptoTrendProtocol.Capital + used.NetResult, report.Curve[^1].Equity, 0.01m); CollectionAssert.AreNotEqual(chosen.ExpectedPathP5!.ToList(), report.ExpectedPathP5!.ToList()); Assert.AreEqual((used.Parameters, used.NetResult), (summary.Chosen, summary.NetResult)); // What the grid decided stays. CollectionAssert.AreEqual(chosen.Variants.ToList(), report.Variants.ToList()); Assert.AreEqual(chosen.Overfitting, report.Overfitting); Assert.AreEqual((chosen.TrialsCounted, chosen.DeflatedSharpe.Benchmark), (report.TrialsCounted, report.DeflatedSharpe.Benchmark)); Assert.IsFalse(report.Limitations.Any(l => l.Contains("griglia", StringComparison.Ordinal))); // Not among the variants of the grid: judged all the same, and it says so. var (outside, tries) = await TrialAsync("coin_vol=12;max_stop=20"); var added = outside.Variants.Single(v => v.OutsideGrid); Assert.AreEqual(("coin_vol=12;max_stop=20", false), (added.Parameters, added.Chosen)); Assert.AreEqual((added.NetResult, added.MaxDrawdown), (outside.Metrics.NetResult, outside.Metrics.MaxDrawdown)); CollectionAssert.AreEqual(chosen.Variants.ToList(), outside.Variants.Where(v => !v.OutsideGrid).ToList()); Assert.HasCount(chosen.Variants.Count, tries.VariantSharpes); Assert.AreEqual((chosen.TrialsCounted, chosen.DeflatedSharpe.Benchmark, chosen.Overfitting), (outside.TrialsCounted, outside.DeflatedSharpe.Benchmark, outside.Overfitting)); Assert.Contains("La variante in uso non è nella griglia", string.Join(" ", outside.Limitations)); } [TestMethod] [TestCategory(Category.Integration)] [DataRow(StrategyStages.Observation, "coin_vol=10;max_stop=20", null)] [DataRow(StrategyStages.Simulation, "coin_vol=10;max_stop=20", "coin_vol=10;max_stop=20")] [DataRow(StrategyStages.Simulation, "coin_vol=12.0;max_stop=20", "coin_vol=12;max_stop=20")] [DataRow(StrategyStages.Simulation, null, "coin_vol=15;max_stop=15")] public async Task ThePlanOfAReviewFixesTheVariantInUse(string stage, string? parameters, string? judged) { await using var rig = await ReviewRig.CreateAsync(stage, qualification: Old(true) with { Parameters = parameters }); var review = await rig.OpenAsync(); await rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET qualification = @q", _none, ("q", new DbJson(JsonSerializer.Serialize(Old(true) with { Parameters = "coin_vol=20;max_stop=20" }, Qualification.Json)))), _none); rig.Start(); var trials = await rig.Lab.Trials.OfReviewAsync(review.Id, _none); Assert.HasCount(2, trials); Assert.IsTrue(trials.All(t => t.PlanIntact && t.Plan.Judged == judged && t.Variants == 9), string.Join(" ", trials.Select(t => t.Plan.Judged))); } [TestMethod] [TestCategory(Category.Integration)] public async Task TheVerdictOnAStrategyWithCapitalIsOfTheVariantInUse() { const string used = "coin_vol=12;max_stop=20"; await using var rig = await ReviewRig.CreateAsync(StrategyStages.Simulation, qualification: Old(true) with { Parameters = used }); var review = await rig.ReviewAsync(passed: true, r => r with { Judged = used, Variants = [.. r.Variants, new ReportVariant(used, 0.05, 0, 321m, 0.11, 7, false) { OutsideGrid = true }] }); var line = review.Report!.Strategies.Single(); Assert.AreEqual((ReviewVerdicts.Passed, ReviewActions.Confirmed), (line.Verdict, line.Action)); Assert.AreEqual("Revisione del 1º trimestre 2027: protocollo superato su entrambi gli universi con la variante in uso. La variante in uso non è nella griglia: è giudicata lo stesso.", line.Text); Assert.AreEqual((used, 321m, true), (line.InUse!.Parameters, line.InUse.NetResult, line.InUse.OutsideGrid)); Assert.AreEqual((await _report.Value).Chosen, line.Chosen!.Parameters); var outcome = JsonSerializer.Deserialize((await rig.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT qualification FROM review_outcomes", r => r.Json("qualification").Text), _none))!, Qualification.Json)!; Assert.AreEqual(used, outcome.Parameters, "the parameters the figures are of"); } internal static Task NextAsync(Database db, IClock clock, string verdict, DateOnly through) => db.WriteAsync(async s => { var id = Ids.NewId(clock); await s.ExecuteAsync("INSERT INTO quarterly_reviews (id, quarter, through, status, created_at, updated_at) VALUES (@id, @q, @d, 'done', @t, @t)", _none, ("id", id), ("q", "x" + through.ToString("yyyyMM", System.Globalization.CultureInfo.InvariantCulture)), ("d", BarStore.DayText(through)), ("t", clock.UtcNow)).ConfigureAwait(false); await s.ExecuteAsync("INSERT INTO review_outcomes (id, review_id, strategy, stage, verdict, action, through, trials, data, created_at) VALUES (@id, @r, @s, 'x', @v, 'none', @d, @j, @o, @t)", _none, ("id", Ids.NewId(clock)), ("r", id), ("s", Crypto), ("v", verdict), ("d", BarStore.DayText(through)), ("j", new DbJson("[]")), ("o", new DbJson("{}")), ("t", clock.UtcNow)).ConfigureAwait(false); }, _none); private static Task NextAsync(ReviewRig rig, string verdict, DateOnly through) => NextAsync(rig.Db, rig.Clock, verdict, through); [TestMethod] [TestCategory(Category.Integration)] public async Task TheStockStrategiesWaitAndTheCandidatesAreLeftOut() { await using var rig = await ReviewRig.CreateAsync(); foreach (var (name, stage) in new[] { (StrategyNames.EquityMomentum, StrategyStages.Observation), (StrategyNames.Candidates[0].Name, StrategyStages.Observation) }) { await rig.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at, share, stage_since) VALUES (@id, @s, @a, @st, 0, @j, @t, @t, 0, @t)", _none, ("id", Ids.NewId(rig.Clock)), ("s", name), ("a", rig.Live.Okx.AccountId), ("st", stage), ("j", new DbJson("{}")), ("t", rig.Clock.UtcNow)), _none); } var review = await rig.ReviewAsync(passed: false); CollectionAssert.AreEquivalent(new[] { Crypto, StrategyNames.EquityMomentum }, review.Report!.Strategies.Select(l => l.Strategy).ToList()); var stock = review.Report.Strategies.Single(l => l.Strategy == StrategyNames.EquityMomentum); Assert.AreEqual((ReviewVerdicts.Waiting, ReviewActions.None), (stock.Verdict, stock.Action)); Assert.IsNull(await rig.Live.Stages.ReviewVerdictAsync(StrategyNames.EquityMomentum, _none)); Assert.AreEqual((false, "non riprovata, mancano i dati"), (stock.NoProtocol, QuarterlyReview.ActionText(stock))); // With the bars collected what is missing is the protocol, not the data. var share = await new InstrumentCatalog(rig.Db, rig.Clock).EnsureAsync(StrategyData.Share("AAA"), _none); await new BarStore(rig.Db, rig.Clock).UpsertDailyAsync(share.Id, [new DailyBar(new DateOnly(2027, 1, 4), 50, 51, 49, 50, 1000)], "test", _none); await rig.NightAsync(At(2027, 4, 5)); await rig.EndAsync((await QuarterlyReview.ListAsync(rig.Db, _none))[0], passed: false); await rig.Review.ConcludeAsync(_none); stock = (await QuarterlyReview.ListAsync(rig.Db, _none))[0].Report!.Strategies.Single(l => l.Strategy == StrategyNames.EquityMomentum); const string text = "non riprovata: il protocollo per le azioni arriva con una versione successiva"; Assert.AreEqual((ReviewVerdicts.Waiting, ReviewActions.None, true), (stock.Verdict, stock.Action, stock.NoProtocol)); Assert.AreEqual(text, QuarterlyReview.ActionText(stock)); Assert.StartsWith("Non riprovata: il protocollo per le azioni", stock.Text); Assert.Contains(text, (await NewsRulesTests.DiaryAsync(rig.Db)).Last(m => m.StartsWith("Revisione trimestrale pronta (2º", StringComparison.Ordinal))); Assert.AreEqual(1, await rig.CountAsync("SELECT COUNT(*) FROM notifications WHERE kind = 'quarterly_review' AND message LIKE '%versione successiva%'")); } // ---- Base rates ------------------------------------------------------------------------------------------------- [TestMethod] [TestCategory(Category.Integration)] public async Task TheBaseRatesOfAReviewSurviveARestartAndGiveWayToANewerProgram() { await using var rig = await ReviewRig.CreateAsync(StrategyStages.Simulation, qualification: Old(true)); var file = FirstModel.Train(LearningModelTests.Cases(300, x => Odds.Probability(x[1])), new DateOnly(2026, 10, 31), _none); rig.Live.UseFirst(file); rig.Start(); await rig.Live.Learning.PrepareHistoryAsync(_none); var champion = await rig.Live.Learning.Models.FindAsync(ModelStatuses.Champion, _none); await LearningStoreAddLiveAsync(rig); var review = await rig.ReviewAsync(passed: true); var rate = review.Report!.RatesAfter![Crypto]; Assert.AreNotEqual(file.BaseRates[Crypto], rate); var examples = (await rig.Live.Learning.Store.AllAsync(_none)).Where(e => e.Source == CaseSources.History).ToList(); Assert.IsTrue(examples.All(e => e.Strategy == Crypto && e.Day <= Through)); Assert.IsFalse(examples.Any(e => e.Symbol == "BTCEUR" && e.Day == _liveDay), "the same operation is there as a live one"); // A restart with the same program, or an older one, changes nothing. foreach (var first in new[] { file, FirstModel.Train(LearningModelTests.Cases(310, x => Odds.Probability(x[1])), new DateOnly(2026, 11, 30), _none) }) { var desk = new LearningDesk(rig.Db, rig.Clock) { First = first }; await desk.PrepareHistoryAsync(_none); Assert.AreEqual(rate, (await desk.BaseRatesAsync(_none))[Crypto]); Assert.AreEqual(examples.Count, await desk.Store.CountAsync(CaseSources.History, _none)); Assert.AreEqual(champion!.Id, (await desk.Models.FindAsync(ModelStatuses.Champion, _none))!.Id, "the model is not replaced"); } // One built on a longer history wins; a strategy only a review measured keeps its rate. var newer = new LearningDesk(rig.Db, rig.Clock) { First = FirstModel.Train(LearningModelTests.Cases(320, x => Odds.Probability(x[1])), new DateOnly(2027, 1, 31), _none) }; await newer.PrepareHistoryAsync(_none); Assert.AreEqual(newer.First.BaseRates[Crypto], (await newer.BaseRatesAsync(_none))[Crypto]); Assert.AreEqual(320, await newer.Store.CountAsync(CaseSources.History, _none)); Assert.AreEqual(0.3, LearningDesk.Merge(new Dictionary { ["a"] = 0.3, ["b"] = 0.2 }, new Dictionary { ["b"] = 0.5 })["a"]); } private static DateOnly _liveDay; // A live example equal to one the history will give. private static async Task LearningStoreAddLiveAsync(ReviewRig rig) { var data = await FirstModel.DataAsync(rig.Folder, Through, _none); var same = FirstModel.ExamplesOf(data, Old(true).Parameters, Through, null, _none).First(e => e.Symbol == "BTCEUR"); _liveDay = same.Day; await rig.Db.WriteAsync(s => LearningStore.AddAsync(s, rig.Clock, same with { Id = Guid.Empty, Symbol = "BTC-EUR", Source = CaseSources.Live, Stage = StrategyStages.Simulation }, _none), _none); } // ---- Priors, universe, archives --------------------------------------------------------------------------------- [TestMethod] [TestCategory(Category.Integration)] public async Task AQualifiedStrategyCountsTheSameTriesAtEveryReviewAndOneInObservationMore() { await using var rig = await ReviewRig.CreateAsync(StrategyStages.Simulation, qualification: Old(true)); var review = await rig.ReviewAsync(passed: true); async Task> CountsAsync(Guid id) { var counts = new List(); foreach (var t in await rig.Lab.Trials.OfReviewAsync(id, _none)) { // As each one was run: what came later does not exist yet. counts.Add((await rig.Lab.Trials.PriorOfAsync(t, _none)).Trials); } return counts; } CollectionAssert.AreEqual(new[] { 1, 1 }, await CountsAsync(review.Id), "the other of the same review, never the past"); await rig.NightAsync(At(2027, 4, 5)); var second = (await QuarterlyReview.ListAsync(rig.Db, _none))[0]; CollectionAssert.AreEqual(new[] { 0, 0 }, await CountsAsync(second.Id)); await rig.EndAsync(second, passed: false); await rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET stage = 'observation'", _none), _none); await rig.Review.ConcludeAsync(_none); await rig.NightAsync(At(2027, 7, 5)); var third = (await QuarterlyReview.ListAsync(rig.Db, _none))[0]; CollectionAssert.AreEqual(new[] { 6, 6 }, await CountsAsync(third.Id), "four in the register and two of the protocol"); } [TestMethod] [TestCategory(Category.Integration)] public async Task ASeriesOutsideTheArchivesNeverChangesTheUniverse() { var folder = TempFolder.Create("review-universe"); try { await WriteHistoryAsync(folder); var store = new ResearchStore(folder); var bars = new List { new(new DateTimeOffset(2026, 12, 1, 0, 0, 0, TimeSpan.Zero), 1m, 1m, 1m, 1m, 1m) }; foreach (var other in new[] { "ICP", "APT" }) { await store.WriteAsync(EuroHistory.Venue, other + "EUR", Timeframes.Day, bars, _none); await store.WriteAsync(Venues.Binance, other + "USDT", Timeframes.Day, bars, _none); } await store.WriteAsync(Venues.Binance, "BTCUSDT", Timeframes.Day, bars, _none); CollectionAssert.AreEqual(new[] { "BTCEUR", "ETHEUR", "SOLEUR", "XRPEUR" }, (await CryptoTrendProtocol.BroadAsync(store, Through, _none)).Order(StringComparer.Ordinal).ToList()); var rates = new List { new("EUR", "USD", new DateOnly(2026, 11, 30), 1.1m, "ecb") }; CollectionAssert.AreEqual(new[] { "BTCEUR" }, (await EuroHistory.ConvertAllAsync(store, rates, _none, CryptoTrendProtocol.Archives)).ToList()); } finally { TempFolder.Delete(folder); } } [TestMethod] [TestCategory(Category.Unit)] public async Task TheReportOfABaseStrategyKeepsItsExpectedPathAndSlippage() { var report = await _report.Value; Assert.IsTrue(report.ExpectedSlippageBp > 0m); Assert.HasCount(CryptoTrendProtocol.PathDays, report.ExpectedPathP5!); var plan = Laboratory.BuildPlan(new TrialRequest(Crypto, TrialSources.Research, EuroHistory.Venue, CryptoTrendProtocol.Narrow, CryptoTrendProtocol.From, Through, CryptoTrendProtocol.Capital, null), At(2027, 1, 5)).Plan; Assert.IsFalse(plan.ToJson().Contains("priors", StringComparison.OrdinalIgnoreCase), "a plan that is not of a review keeps its text, and its hash"); Assert.AreNotEqual(TrialPlan.Hash(plan.ToJson()), TrialPlan.Hash((plan with { Priors = ReviewPriors.All }).ToJson())); } // ---- The balance of the restrictions ---------------------------------------------------------------------------- private static readonly DateTimeOffset _t0 = new(2027, 1, 10, 0, 5, 0, TimeSpan.Zero); private static Example Case(string symbol, bool? win, double? result, int? closedIn, double multiplier = 1, string stage = StrategyStages.Simulation, bool labelled = true) => new(Guid.NewGuid(), Crypto, symbol, CaseSources.Live, new DateOnly(2027, 1, 9), _t0, "trend_entry", 0.2m, null, null, new Dictionary()) { Stage = stage, DecisionId = Guid.NewGuid(), Multiplier = multiplier, Label = labelled ? new CaseLabel(win, result, new DateOnly(2027, 1, 10), closedIn is { } d ? new DateOnly(2027, 1, 10).AddDays(d) : null, "x") : null, }; private static BlockedEntry Block(Example e, string code, bool postponed = false, int minutes = 0) => new(e.DecisionId!.Value, Crypto, e.Symbol, code, postponed, e.At.AddMinutes(minutes)); private static readonly Dictionary _capital = new() { [Crypto] = 4_000 }; [TestMethod] [TestCategory(Category.Unit)] public void TheBalanceSaysWhatWasAvoidedAndWhatItCost() { var lost = Case("AAA", false, -0.1, 5); var won = Case("BBB", true, 0.05, 5, multiplier: 0.5); var open = Case("CCC", null, null, null, labelled: false); var never = Case("DDD", null, null, null); var later = Case("EEE", false, -0.2, 5); var held = Case("FFF", false, -0.2, 5); var r = RestrictionBalance.Of( [ Block(lost, NewsReasons.Severe), Block(won, NewsReasons.Severe), Block(open, NewsReasons.Severe), Block(never, NewsReasons.Severe), Block(later, CorrectiveReasons.CalendarEvent, postponed: true), Block(held, NewsReasons.Negative), new BlockedEntry(Guid.NewGuid(), Crypto, "GGG", NewsReasons.Negative, false, _t0), Block(lost, "altro"), ], [lost, won, open, never, later, held], [new HeldTrade(Crypto, "EEE", _t0.AddMinutes(40), null), new HeldTrade(Crypto, "FFF", _t0.AddDays(-3), null)], _capital); var severe = r.Lines.Single(l => l.Code == NewsReasons.Severe); Assert.AreEqual(new RestrictionLine(NewsReasons.Severe, 2, 80m, 20m, 1, 1, 0, 0), severe); Assert.AreEqual(1, r.Lines.Single(l => l.Code == CorrectiveReasons.CalendarEvent).Delayed, "bought at the end of the window"); Assert.AreEqual(2, r.Lines.Single(l => l.Code == NewsReasons.Negative).Increases, "one already open, one without an example"); Assert.AreEqual((80m, 20m), (r.Avoided, r.GivenUp)); Assert.IsTrue(RestrictionBalance.Of([], [lost], [], _capital).IsEmpty, "a row switched off blocks nothing"); } [TestMethod] [TestCategory(Category.Unit)] public void ARepeatedBlockIsOneCaseUnderItsStrictestRow() { var e = Case("AAA", false, -0.033333, 9); var again = Block(e, NewsReasons.Severe, minutes: 24 * 60) with { DecisionId = Guid.NewGuid() }; var r = RestrictionBalance.Of([Block(e, CorrectiveReasons.CalendarEvent, postponed: true), again], [e], [], _capital); var line = r.Lines.Single(); Assert.AreEqual((NewsReasons.Severe, 1, 26.67m), (line.Code, line.Stopped, line.Avoided)); // After the simulated close a new block of the same instrument is no longer that example. var late = again with { At = _t0.AddDays(20) }; Assert.AreEqual(1, RestrictionBalance.Of([late], [e], [], _capital).Lines.Single().Increases); // In observation nothing is bought: an entry only put off is one made later, one stopped is out. var seen = Case("BBB", false, -0.1, 5, stage: StrategyStages.Observation); Assert.AreEqual(1, RestrictionBalance.Of([Block(seen, CorrectiveReasons.CalendarEvent, postponed: true)], [seen], [], _capital).Lines.Single().Delayed); Assert.AreEqual(1, RestrictionBalance.Of([Block(seen, NewsReasons.Negative)], [seen], [], _capital).Lines.Single().Stopped); } /// A block is of the period in which its outcome became known, so the periods add up to the whole. [TestMethod] [TestCategory(Category.Unit)] public void ThePeriodsOfTheBalanceAddUpToTheWhole() { var first = _t0.AddDays(3); var second = _t0.AddDays(30); var early = Case("AAA", true, 0.05, 2) with { LabelledAt = _t0.AddDays(2.5) }; var lost = Case("BBB", false, -0.1, 5) with { LabelledAt = _t0.AddDays(6) }; var off = Case("CCC", false, -0.2, 2) with { LabelledAt = first.AddDays(1) }; var open = Case("DDD", null, null, null, labelled: false); var bought = Case("EEE", false, -0.2, 5) with { LabelledAt = _t0.AddDays(6) }; var seen = Case("FFF", false, -0.2, 5, stage: StrategyStages.Observation) with { LabelledAt = _t0.AddDays(6) }; var never = Case("GGG", null, null, 1) with { LabelledAt = _t0.AddDays(1) }; IReadOnlyList blocks = [ .. new[] { early, lost, off, open, bought, never }.Select(e => Block(e, NewsReasons.Severe)), Block(seen, CorrectiveReasons.CalendarEvent, postponed: true), new BlockedEntry(Guid.NewGuid(), Crypto, "HHH", NewsReasons.Severe, false, _t0), new BlockedEntry(Guid.NewGuid(), Crypto, "HHH", NewsReasons.Severe, false, first.AddDays(2)), ]; RestrictionReport Of(DateTimeOffset from, DateTimeOffset until) => RestrictionBalance.Of(blocks, [early, lost, off, open, bought, seen, never], [new HeldTrade(Crypto, "EEE", _t0.AddDays(4), null)], _capital, from, until); RestrictionLine? Line(RestrictionReport r, string code) => r.Lines.SingleOrDefault(l => l.Code == code); var (one, two, ever) = (Of(DateTimeOffset.UnixEpoch, first), Of(first, second), Of(DateTimeOffset.UnixEpoch, second)); Assert.AreEqual(new RestrictionLine(NewsReasons.Severe, 1, 0m, 40m, 4, 1, 0, 1), Line(one, NewsReasons.Severe), "what was not known yet is open"); Assert.AreEqual(new RestrictionLine(NewsReasons.Severe, 2, 240m, 0m, 1, 0, 1, 1), Line(two, NewsReasons.Severe), "known after the first review, even what closed before it"); Assert.AreEqual(new RestrictionLine(NewsReasons.Severe, 3, 240m, 40m, 1, 1, 1, 2), Line(ever, NewsReasons.Severe)); Assert.AreEqual(1, Line(one, CorrectiveReasons.CalendarEvent)!.Open); Assert.AreEqual((1, 0), (Line(two, CorrectiveReasons.CalendarEvent)!.Delayed, Line(two, CorrectiveReasons.CalendarEvent)!.Open)); Assert.AreEqual(Line(two, CorrectiveReasons.CalendarEvent), Line(ever, CorrectiveReasons.CalendarEvent)); } [TestMethod] [TestCategory(Category.Integration)] public async Task TheFirstReviewCountsTheRestrictionsFromTheStart() { await using var rig = await ReviewRig.CreateAsync(); rig.Clock.Set(new DateTimeOffset(2026, 8, 15, 10, 0, 0, TimeSpan.Zero)); await rig.Db.WriteAsync(s => DecisionLog.WriteAsync(s, rig.Clock, new DecisionRow(Guid.NewGuid(), Crypto, null, "ETH-EUR", DecisionStages.Order, DecisionOutcomes.Refused, [NewsReasons.Severe], new Dictionary(), rig.Clock.UtcNow), _none), _none); var report = (await rig.ReviewAsync(passed: false)).Report!; Assert.AreEqual(1, report.RestrictionsEver.Lines.Single().Increases); Assert.AreEqual(report.RestrictionsEver.Lines.Single(), report.Restrictions.Lines.SingleOrDefault()); Assert.AreEqual(new DateOnly(2026, 8, 15), report.RestrictionsFrom); } /// The decisions of the live engine, as they are written, give the balance. [TestMethod] [TestCategory(Category.Integration)] public async Task ThePurchasesTheEngineHeldBackAreInTheBalance() { var day = new DateOnly(2026, 9, 1); await using var live = await LiveRig.CreateAsync(day, day.AddDays(39)); live.UseGate(new EntryGate(live.Rig.Db, live.Rig.Clock)); await NewsRulesTests.StoryAsync(live.Rig.Db, live.Rig.Clock, live.Instruments["ETH-EUR"].Spec, "Ethereum exchange hacked", new DateTimeOffset(2026, 8, 31, 20, 0, 0, TimeSpan.Zero), 4, -0.9, "CoinDesk", trusted: true); await NewsRulesTests.StoryAsync(live.Rig.Db, live.Rig.Clock, live.Instruments["SOL-EUR"].Spec, "Solana upgrade delayed by a week", new DateTimeOffset(2026, 8, 31, 23, 30, 0, TimeSpan.Zero), 3, -0.8, "CoinDesk", trusted: true); await live.DayAsync(day); var cases = (await live.Learning.Store.AllAsync(_none)).Where(e => e.Symbol is "ETH-EUR" or "SOL-EUR").ToList(); Assert.HasCount(2, cases); var first = live.Rig.Clock.UtcNow; var open = await RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, DateTimeOffset.UnixEpoch, first, _none); Assert.AreEqual(1, open.Lines.Single(l => l.Code == NewsReasons.Severe).Open); Assert.AreEqual(1, open.Lines.Single(l => l.Code == NewsReasons.Negative).Open); // The outcomes arrive after the first review. live.Rig.Clock.Set(first.AddDays(20)); foreach (var e in cases) { var loses = e.Symbol == "ETH-EUR"; await live.Rig.Db.WriteAsync(s => LearningStore.AddLabelAsync(s, live.Rig.Clock, e.Id, new CaseLabel(!loses, loses ? -0.1 : 0.04, e.Day.AddDays(1), e.Day.AddDays(9), "x"), _none), _none); } var capital = (decimal)(await LearningCycle.CapitalsAsync(live.Rig.Db, live.Rig.Clock, _none))[Crypto]; var now = live.Rig.Clock.UtcNow; var r = await RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, DateTimeOffset.UnixEpoch, now, _none); decimal Of(string symbol, decimal result) => Math.Round(cases.Single(e => e.Symbol == symbol).Weight * result * capital, 2); Assert.IsGreaterThan(0m, r.Avoided); Assert.AreEqual(Of("ETH-EUR", 0.1m), r.Avoided, 0.01m); Assert.AreEqual(Of("SOL-EUR", 0.04m), r.GivenUp, 0.01m); Assert.IsTrue((await RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, now, now.AddDays(1), _none)).IsEmpty, "each outcome in one period only"); var since = await RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, first, now, _none); Assert.AreEqual((r.Avoided, r.GivenUp), (since.Avoided, since.GivenUp), "blocked before the first review, known after it"); Assert.AreEqual(2, (await RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, DateTimeOffset.UnixEpoch, first, _none)).Lines.Sum(l => l.Open)); } }