Fix the review findings of the basket engine, command and report

The independent review of Phase 14 found rules the engine applied
differently from the decisions, numbers the report labelled wrongly and
a command that left a trial "running" when interrupted.

Engine:
- The pause after the 9% account stop is read at the decision moment
  (the bar's close), like every other gate: on daily bars it no longer
  blocks one day past the server date change.
- In a one-pair basket, a level closed by the venue's mandatory stop
  closes the other levels at the next execution with their own reason,
  closed_with_stop (counted and labelled in the report); the basket's
  exit stays mandatory_stop, and a two-leg basket keeps orphan_leg.
- The cap of two entries per currency applies to new baskets only,
  never to the averagings of an open basket, and every leg is valued
  at the current mid: a Prudente long basket "come dal vivo" now makes
  its three averagings and Fedele writes no note on them.
- The surrogate of the control chains on the mid when the source has
  an ask, so each mid change keeps its size and the spread stays
  around the mid instead of moving the mid by a spread at each change
  of sign.
- The financing already charged on positions still open at the end is
  part of the run's fees (BacktestRun.AccruedFees, zero for the daily
  engine, kept in stored unit outcomes).

Report: the fee row says what it holds (commission and financing, the
spread is in the prices) and the cost-stress text matches what the
multiplier scales; baskets still open at the end are labelled as such
and left out of the share closed at the target; refusal labels say
what the engine checks; the ECB-price and cost limitations are no
longer printed twice; every count has the Italian thousands separator.

Command: Ctrl+C or SIGTERM cancels the run; the trial is recorded as
failed with "Prova interrotta prima della fine: rilancia «anubis
backtest baskets»." and the command exits 1; a trial that cannot start
is failed instead of thrown, and an unexpected error ends with an
Italian line, never a stack trace. The laboratory fails a leftover
basket trial with an accurate message instead of "Strategia non più
disponibile".

The Table 6.5 test comment no longer claims each price is the only one
that fits the row. The real report is regenerated on the same data and
database as the first run, which now counts as a prior trial.

refs #127 #129 #131

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-12-04 19:26:24 +01:00
1 parent 3bee136c74
commit a8defde572
15 files changed
+488 -143

No files matched your search

+79
View File
@@ -157,6 +157,85 @@ public sealed class BasketCommandTests
}
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AnInterruptedBasketTrialIsRecordedAsFailedWithAnItalianReason()
{
// Ctrl+C or the stop of the container while the trial runs: the command's token is cancelled as soon as it says the
// trial is planned. The trial is recorded as failed with a reason the user can act on, no report is written, exit 1.
var (env, postgres) = await ServerHarness.DockerOnEngineAsync().ConfigureAwait(false);
await using var engine = postgres;
var data = TempFolder.Create("baskets-stop");
var clock = new ManualClock(new DateTimeOffset(2026, 12, 4, 9, 0, 0, TimeSpan.Zero));
try
{
var config = ServerOptions.Parse(["--platform", "docker", "--data-dir", data], env).LoadConfig(env);
await using var db = Database.Open(config.Db!);
await Migrations.MigrateAsync(db, clock, null, CancellationToken.None).ConfigureAwait(false);
Directory.CreateDirectory(config.Data.Research);
await File.WriteAllBytesAsync(Ecb.HistoryPath(config.Data.Research), EcbZip()).ConfigureAwait(false);
var outDir = Path.Combine(data, "out");
using var stop = new CancellationTokenSource();
using var output = new StopOnLine(stop, "Prova ");
var code = await BasketCommand.RunAsync(
["--offline", "--to", "2001-12-31", "--control", "1", "--out", outDir, "--platform", "docker", "--data-dir", data], output, env, new FakeHttp(), clock,
stop.Token).ConfigureAwait(false);
const string Interrupted = "Prova interrotta prima della fine: rilancia «anubis backtest baskets».";
Assert.AreEqual(1, code, output.ToString());
StringAssert.Contains(output.ToString(), "Non riuscito: " + Interrupted);
Assert.IsFalse(output.ToString().Contains(" at ", StringComparison.Ordinal), "no stack trace");
var trial = (await new TrialStore(db, clock).ListAsync(10, CancellationToken.None).ConfigureAwait(false)).Single();
Assert.AreEqual(TrialStatuses.Failed, trial.Status);
Assert.AreEqual(Interrupted, trial.Error);
Assert.IsFalse(File.Exists(Path.Combine(outDir, BasketReport.Strategy + ".md")), "an interrupted trial writes no report");
}
finally
{
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
TempFolder.Delete(data);
}
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheLaboratoryFailsALeftoverBasketTrialWithAnAccurateReason()
{
// A basket trial left planned or running by a command that died is picked up by the laboratory at the next start. The
// family only runs from the command line: the trial fails with a reason that says so, not «no longer available».
var clock = new ManualClock(new DateTimeOffset(2026, 12, 4, 9, 0, 0, TimeSpan.Zero));
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
using var lab = new Laboratory(test.Db, clock, Path.GetTempPath());
var (plan, variants) = BasketProtocol.Plan(To, clock.UtcNow);
var left = await lab.Trials.PlanAsync(plan, variants, CancellationToken.None).ConfigureAwait(false);
await lab.ProcessAsync(left.Id, CancellationToken.None).ConfigureAwait(false);
var failed = (await lab.Trials.GetAsync(left.Id, CancellationToken.None).ConfigureAwait(false))!;
Assert.AreEqual(TrialStatuses.Failed, failed.Status);
Assert.AreEqual("Prova a panieri interrotta: si rilancia da riga di comando con «anubis backtest baskets».", failed.Error);
}
/// <summary>Console output that cancels the command's token at the first line starting with <c>start</c>.</summary>
private sealed class StopOnLine(CancellationTokenSource stop, string start) : StringWriter(System.Globalization.CultureInfo.InvariantCulture)
{
public override void WriteLine(string? value)
{
base.WriteLine(value);
if (value is not null && value.StartsWith(start, StringComparison.Ordinal))
{
stop.Cancel();
}
}
public override Task WriteLineAsync(string? value)
{
WriteLine(value);
return Task.CompletedTask;
}
}
/// <summary>A trigger that changes every plan as soon as it is written: someone touching the register behind the command.</summary>
private static async Task TamperAsync(Database db, string set)
{