Fix the defects of the Phase 4 review (refs #34 #35 #36)
ci / test (postgres) (push) Successful in 2m41s
ci / test (sqlite) (push) Successful in 1m56s
ci / test (postgres) (pull_request) Successful in 3m45s
ci / test (sqlite) (pull_request) Successful in 2m22s
ci / image (push) Successful in 1m10s
ci / image (pull_request) Successful in 13s

- An error of the database (PostgreSQL restarting) no longer stops the
  laboratory until the next start: the queue logs it, waits 30 seconds
  on the injectable clock and tries the same trial again.
- Buy and hold, the comparison of every report, buys an instrument
  whose history starts later at its first close, with the share kept
  free for it; before, it was never bought and the others took its
  weight. Its version goes to 2.
- The comparison page reads a and b as text: a malformed id shows
  "two finished tests needed" instead of an error page.
- A trial re-checks the hash of its plan before running and refuses a
  plan that no longer matches it.
- Parameters that count days take whole numbers only (10.5 would run
  as 10 and count twice in the DSR); the capital starts from 1, as the
  message says.

ADR 0010 says so, and corrects the estimated minimum of the research
history: 5 does refuse smaller orders, like the exchanges' minimums.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-11 10:17:18 +01:00
1 parent af7528560f
commit f278ff4f67
10 files changed
+158 -28

No files matched your search

+22
View File
@@ -222,6 +222,28 @@ public sealed class BacktestTests
Assert.IsEmpty(run.Decisions[0].Final);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void BuyAndHoldKeepsTheShareOfAnInstrumentWhoseHistoryStartsLater()
{
// ETH has bars only from day 30: buy and hold buys it then, with half the equity, not never.
var data = new BacktestDataset(
[
new BacktestInstrument(BacktestData.Btc(), BacktestData.Walk(60, 3, start: 40_000, from: D1)),
new BacktestInstrument(BacktestData.Btc() with { Symbol = "ETH-EUR", BaseCurrency = "ETH" }, BacktestData.Walk(30, 5, start: 2_000, from: D1.AddDays(30))),
], "EUR");
var run = BacktestEngine.Run(new BuyAndHold(2), data);
Assert.HasCount(2, run.Fills);
var btc = run.Fills.Single(f => f.Symbol == "BTC-EUR");
var eth = run.Fills.Single(f => f.Symbol == "ETH-EUR");
Assert.AreEqual(D1.AddDays(1), btc.Day);
Assert.AreEqual(D1.AddDays(31), eth.Day);
Assert.AreEqual(0.4975, (double)(btc.Gross / run.InitialCapital), 0.005);
var before = run.Equity.Single(p => p.Day == D1.AddDays(30)).Equity;
Assert.AreEqual(0.4975, (double)(eth.Gross / before), 0.01);
Assert.IsTrue(run.Equity.All(e => e.Cash >= 0m));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void OneCycleRestartsFromARecordedBook()
@@ -62,6 +62,8 @@ public sealed class LaboratoryScreenTests
StringAssert.Contains(compare, "Stessi dati per entrambi");
StringAssert.Contains(compare, "non si applica", "The second test has one variant: no PBO.");
StringAssert.Contains(await server.TextAsync("/laboratorio/confronto?a=nonunid&b=" + first), "Servono due test completati.");
using var missing = await server.GetAsync($"/laboratorio/{Guid.NewGuid()}");
StringAssert.Contains(await missing.Content.ReadAsStringAsync(), "Test non trovato.");
}
+49
View File
@@ -116,8 +116,51 @@ public sealed class LaboratoryTests
await stop.CancelAsync().ConfigureAwait(false);
await Assert.ThrowsAsync<OperationCanceledException>(() => running).ConfigureAwait(false);
Assert.AreEqual(TrialStatuses.Done, (await lab.Trials.GetAsync(halfway.Id, CancellationToken.None).ConfigureAwait(false))!.Status);
// A plan changed after it was written no longer gives its hash: the trial does not run.
var tampered = await lab.PlanAsync(Request(), CancellationToken.None).ConfigureAwait(false);
await test.Db.WriteAsync(s => s.ExecuteAsync("UPDATE backtest_trials SET plan_hash = @h WHERE id = @id", CancellationToken.None, ("h", "0"), ("id", tampered.Id)),
CancellationToken.None).ConfigureAwait(false);
await lab.ProcessAsync(tampered.Id, CancellationToken.None).ConfigureAwait(false);
var refused = (await lab.Trials.GetAsync(tampered.Id, CancellationToken.None).ConfigureAwait(false))!;
Assert.IsFalse(refused.PlanIntact);
Assert.AreEqual(TrialStatuses.Failed, refused.Status);
StringAssert.Contains(refused.Error, "impronta");
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheQueueOutlivesTheDatabaseGoingAway()
{
var clock = new ManualClock(new DateTimeOffset(2026, 11, 11, 9, 0, 0, TimeSpan.Zero));
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
await SeedBitcoinAsync(test, clock, 60).ConfigureAwait(false);
using var lab = new Laboratory(test.Db, clock, Path.GetTempPath());
var trial = await lab.PlanAsync(Request(), CancellationToken.None).ConfigureAwait(false);
// The table is out of reach: every read and write of the queue fails, as when the database restarts.
await RenameAsync(test, "backtest_trials", "backtest_trials_away").ConfigureAwait(false);
using var stop = new CancellationTokenSource();
var running = lab.RunAsync(stop.Token);
await Task.Delay(300).ConfigureAwait(false);
Assert.IsFalse(running.IsCompleted, "An error of the database does not stop the laboratory.");
await RenameAsync(test, "backtest_trials_away", "backtest_trials").ConfigureAwait(false);
for (var i = 0; i < 600 && !(await lab.Trials.GetAsync(trial.Id, CancellationToken.None).ConfigureAwait(false))!.IsFinished; i++)
{
clock.Advance(Laboratory.RetryDelay);
await Task.Delay(50).ConfigureAwait(false);
}
await stop.CancelAsync().ConfigureAwait(false);
await Assert.ThrowsAsync<OperationCanceledException>(() => running).ConfigureAwait(false);
var done = (await lab.Trials.GetAsync(trial.Id, CancellationToken.None).ConfigureAwait(false))!;
Assert.AreEqual(TrialStatuses.Done, done.Status, done.Error);
}
private static Task<int> RenameAsync(TestDb test, string from, string to) =>
test.Db.WriteAsync(s => s.ExecuteAsync($"ALTER TABLE {from} RENAME TO {to}", CancellationToken.None), CancellationToken.None);
[TestMethod]
[TestCategory(Category.Unit)]
public void RequestsOutsideTheRulesAreRefusedBeforeAnythingIsWritten()
@@ -127,6 +170,12 @@ public sealed class LaboratoryTests
Assert.ThrowsExactly<TrialRequestException>(() => Laboratory.BuildPlan(Request() with { To = From }, now));
Assert.ThrowsExactly<TrialRequestException>(() => Laboratory.BuildPlan(Request() with { Symbols = [" "] }, now));
Assert.ThrowsExactly<TrialRequestException>(() => Laboratory.BuildPlan(Request() with { InitialCapital = 0m }, now));
Assert.ThrowsExactly<TrialRequestException>(() => Laboratory.BuildPlan(Request() with { InitialCapital = 0.5m }, now));
var half = Assert.ThrowsExactly<TrialRequestException>(() => Laboratory.BuildPlan(Request() with
{
Grid = new Dictionary<string, IReadOnlyList<decimal>> { ["fast"] = [10m, 10.5m] },
}, now));
StringAssert.Contains(half.Message, "numeri interi", "10,5 days would run as 10 and count twice in the DSR.");
var outOfRange = Assert.ThrowsExactly<TrialRequestException>(() => Laboratory.BuildPlan(Request() with
{
Grid = new Dictionary<string, IReadOnlyList<decimal>> { ["fast"] = [1m] },