Files
Anubis/tests/Anubis.Tests/LaboratoryScreenTests.cs
T
Alby96andClaude Opus 5.5 8def84e122 Add the risk engine, correctives and strategy stages (refs #41 #42 #43)
Every intent of a strategy now crosses a risk engine that only refuses or
shrinks: loss limits per world with the 24-hour block, the weekly halving,
the halving and the switch on the fall from the high, the size limits on
invested capital, single position, crypto share and trade risk, the
technical checks, no short sales and no leverage, the day-trade guard
(off by default). The switch, "Ferma tutto", "Ferma e chiudi", the STOP
file and the orders-per-minute anomaly stop the bot until the user
confirms a restart, and a restart after a trip measures the high from
then on.

The correctives of SPEC 8.5 (crypto regime, economic calendar) and the
risk rules also run inside the backtests of the base strategies, so the
reports show what would happen live. Each stage of a decision is written
to a new decisions table with reason codes.

The stage book is the only way to real money: an order on a real account
needs the startup consent, every requirement of SPEC 12.3 met, the typed
phrase and a fresh password and second factor. Order managers on real
accounts fail closed and ask again before each order leaves. A demoted or
revoked strategy keeps its real positions in exit only, with stops, until
they are at zero. The simulated twin stays out of totals and of the
reference equity.

Tests cover each rule of 9.1 and 9.2, with property tests for "never
larger than asked" and "never larger after a loss", and both proofs on a
fake real account: nothing reaches it without the procedure, and a
demoted strategy manages exits and stops down to zero.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:22:35 +01:00

140 lines
6.3 KiB
C#

using System.Net;
using Anubis.Backtest;
using Anubis.Core;
using Anubis.Data;
using Anubis.Server;
namespace Anubis.Tests;
/// <summary>The Laboratorio screen (issue #36): a new test from the form, its report, the comparison.</summary>
[TestClass]
public sealed class LaboratoryScreenTests
{
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheReportOpensFromTheLaboratory()
{
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite());
await server.SignInFirstTimeAsync();
var db = server.Host.Services!.Db;
var btc = await new InstrumentCatalog(db, SystemClock.Instance).EnsureAsync(MarketDataStoreTests.Okx("BTC-EUR"), CancellationToken.None);
await new BarStore(db, SystemClock.Instance).UpsertDailyAsync(btc.Id,
BacktestData.Walk(400, 3, start: 40_000, drift: 0.001, volatility: 0.03, from: new DateOnly(2024, 1, 1)), "test", CancellationToken.None);
var empty = await server.TextAsync("/laboratorio");
StringAssert.Contains(empty, "Nessun test eseguito.");
StringAssert.Contains(empty, "Scrivi il piano e avvia il test");
StringAssert.Contains(empty, "Migliorie in osservazione");
StringAssert.Contains(empty, "Stime di costo da confermare");
// A grid value out of range goes back to the form with the reason, and nothing is planned.
using (var wrong = await server.PostFormAsync("/laboratorio", "/azioni/laboratorio", Fields(("griglia_fast", "1, 5"))))
{
Assert.AreEqual("/laboratorio?errore=griglia&strategia=sma_cross#nuovo", ServerHarness.Location(wrong));
}
StringAssert.Contains(await server.TextAsync("/laboratorio?errore=griglia&strategia=sma_cross"), "fuori dall'intervallo del parametro");
Assert.HasCount(0, await new TrialStore(db, SystemClock.Instance).ListAsync(10, CancellationToken.None));
var first = await PlanAsync(server, Fields());
var second = await PlanAsync(server, Fields(("griglia_fast", "10"), ("griglia_slow", "30")));
await WaitAsync(db, first);
await WaitAsync(db, second);
var list = await server.TextAsync("/laboratorio");
StringAssert.Contains(list, $"href=\"/laboratorio/{first}\"");
StringAssert.Contains(list, "Completato");
StringAssert.Contains(list, "Confronta");
var report = await server.TextAsync($"/laboratorio/{first}");
foreach (var part in new[]
{
"Esito del protocollo", "Risultato netto con costi doppi", "Deflated Sharpe Ratio", "Probabilità di sovra-adattamento (PBO)",
"Risultato della variante scelta", "Comprare e tenere", "Risultato per anno", "Sensibilità ai costi", "Finestre che avanzano",
"K-fold purgato combinatorio", "Nessuno sguardo in avanti", "nessuna è cambiata", "Tutte le varianti", "Cosa questo test non considera",
"esempio: correttivi e limiti di rischio non si applicano", "Impronta dei dati", "Vedi i numeri in una tabella",
})
{
StringAssert.Contains(report, part, $"Missing \"{part}\" in the report.");
}
var compare = await server.TextAsync($"/laboratorio/confronto?a={first}&b={second}");
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.");
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheDemoRunsNoTests()
{
string demoRoot;
{
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]);
demoRoot = server.Host.Config.Data.Root;
var page = await server.TextAsync("/laboratorio");
StringAssert.Contains(page, "Il laboratorio non esegue test in questa modalità.");
Assert.IsFalse(page.Contains("/azioni/laboratorio", StringComparison.Ordinal), "No form in the demo.");
using var post = await server.PostFormAsync("/laboratorio", "/azioni/laboratorio", Fields());
Assert.AreEqual("/laboratorio?errore=motore&strategia=sma_cross#nuovo", ServerHarness.Location(post));
}
// After the server has stopped, so the demo database is closed.
TempFolder.Delete(demoRoot);
}
private static (string, string)[] Fields(params (string Name, string Value)[] overrides)
{
var fields = new Dictionary<string, string>(StringComparer.Ordinal)
{
["strategia"] = "sma_cross",
["origine"] = TrialSources.Database,
["mercato"] = Venues.Okx,
["strumenti"] = "btc-eur",
["dal"] = "2024-01-01",
["al"] = "2025-02-03",
["capitale"] = "10.000",
["griglia_fast"] = "5, 10",
["griglia_slow"] = "20, 40",
};
foreach (var (name, value) in overrides)
{
fields[name] = value;
}
return [.. fields.Select(f => (f.Key, f.Value))];
}
private static async Task<Guid> PlanAsync(ServerHarness server, (string, string)[] fields)
{
using var response = await server.PostFormAsync("/laboratorio", "/azioni/laboratorio", fields);
Assert.AreEqual(HttpStatusCode.Redirect, response.StatusCode);
var location = ServerHarness.Location(response);
StringAssert.StartsWith(location, "/laboratorio/");
return Guid.Parse(location["/laboratorio/".Length..]);
}
private static async Task WaitAsync(Anubis.Db.Database db, Guid id)
{
var store = new TrialStore(db, SystemClock.Instance);
for (var i = 0; i < 600; i++)
{
var trial = await store.GetAsync(id, CancellationToken.None);
if (trial!.IsFinished)
{
Assert.AreEqual(TrialStatuses.Done, trial.Status, trial.Error);
return;
}
await Task.Delay(50);
}
Assert.Fail("The trial did not finish in 30 seconds.");
}
}