Files
Anubis/tests/Anubis.Tests/StrategyScreensTests.cs
T
Alby96andClaude Opus 5.5 24e20584d4 Write the manuals and fix what following them found
The manual, the runbook and the go-live list are written and checked claim by
claim against the code, and the installation is done from zero by following
them on both engines. That found real defects, now fixed:

- with SQLite a missing database file left no way to restore a backup: the
  choices appear, and the file is created only by the user's choice;
- an account whose difference vanished after the 15 minutes stayed prudent
  with no button, a missing stop could be left out for good, and a choice
  made while the broker was silent used old numbers;
- after "Ferma tutto" the positions could not be closed without restarting;
- a refused key looked like a silent broker: it has its own notice now;
- the split of the capital between the strategies of a broker (SPEC 13.5)
  could not be changed from the interface.

refs #72 #68

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 21:38:33 +01:00

235 lines
14 KiB
C#

using System.Net;
using System.Net.Http.Json;
using Anubis.Core;
using Anubis.Db;
using Anubis.Risk;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>
/// The Operazioni, Strategie and Rischio screens and the risk part of Impostazioni (issue #45; mockups 03, 04, 07).
/// </summary>
[TestClass]
public sealed class StrategyScreensTests
{
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheDemoShowsTradesStrategiesAndRiskAsInTheMockups()
{
var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]);
var demoRoot = server.Host.Config.Data.Root;
try
{
// Mockup 03: the balance of the 41 trades of appendix F, and the "why" of each from the decisions.
var trades = await server.TextAsync("/operazioni");
foreach (var text in new[]
{
"1,62", "+239,27", "22 su 41", "53,7%", "+28,42", "20,31", "14,82", "Mostrate 20 di 41", "Tornata sopra la media a 5 giorni",
"Perché l'ho comprata", "Tutti i limiti di rischio rispettati", "Stop di protezione raggiunto",
})
{
StringAssert.Contains(trades, text, $"Missing {text} on Operazioni.");
}
StringAssert.Contains(await server.TextAsync("/operazioni?esito=perdite"), "Mostrate 19 di 19");
using (var csv = await server.GetAsync("/api/operazioni.csv"))
{
Assert.AreEqual(HttpStatusCode.OK, csv.StatusCode);
Assert.AreEqual("text/csv", csv.Content.Headers.ContentType?.MediaType);
var lines = System.Text.Encoding.UTF8.GetString((await csv.Content.ReadAsByteArrayAsync())[3..]).Split('\n', StringSplitOptions.RemoveEmptyEntries);
Assert.HasCount(42, lines, "a header and the 41 trades");
}
// Mockup 04: the four stages, 58 days of 60, the same result as on Conti.
var strategies = await server.TextAsync("/strategie");
foreach (var text in new[] { "Il percorso verso i soldi veri", "Reale ridotto", "3 strategie", "+231,60", "Giorni in simulazione", "58", "Disponibile tra 2 giorni", "1 strategia", "Nuovi massimi storici sulle azioni USA",
"Raccoglie segnali senza fare ordini: 14 in 31 giorni. Servono almeno 90 giorni per giudicarla.", "31 giorni su 90", "Momentum relativo tra crypto",
"Scartata nei test: tolti i costi, il risultato è vicino a zero. Resta in archivio, non riceve capitale.", "Non supera i test" })
{
StringAssert.Contains(strategies, text, $"Missing {text} on Strategie.");
}
Assert.IsFalse(strategies.Contains("/azioni/strategie/", StringComparison.Ordinal), "The demo changes no stage.");
// Mockup 07: no block, the limits with their use, the worst fall of the demo, the scenarios.
var risk = await server.TextAsync("/rischio");
foreach (var text in new[] { "Nessun blocco attivo", "64,1%", "2,82% il 5 set", "Se succedesse domani", "465", "Cosa il bot non può fare, mai" })
{
StringAssert.Contains(risk, text, $"Missing {text} on Rischio.");
}
var settings = await server.TextAsync("/impostazioni");
StringAssert.Contains(settings, "Perdita in un giorno (%)");
Assert.IsFalse(settings.Contains("/azioni/rischio/limiti", StringComparison.Ordinal), "No risk form in the demo.");
}
finally
{
// The server first: on Windows a database still open cannot be deleted.
await server.DisposeAsync();
TempFolder.Delete(demoRoot);
}
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AStrategyThatFailedItsBacktestCannotEnterTheSimulation()
{
var network = new FakeHttp().On(_ => true, _ => FakeHttp.Respond("not here", HttpStatusCode.NotFound));
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), marketHttp: network, trading: true);
await server.SignInFirstTimeAsync();
// The outcome file of crypto_trend says "not passed"; the stock ones wait for the Alpaca keys.
var page = await server.TextAsync("/strategie");
StringAssert.Contains(page, "Non supera i test");
StringAssert.Contains(page, "In attesa dei dati");
Assert.IsFalse(page.Contains("/azioni/strategie/crypto_trend/simulazione", StringComparison.Ordinal), "No button for a strategy that did not pass.");
// The candidates of 8.4: the discarded one with its verdict, the other waiting, no button for either, and none by hand.
foreach (var text in new[] { "Momentum relativo tra crypto", "Scartata nei test", "Nuovi massimi storici sulle azioni USA", "0 in 0 giorni" })
{
StringAssert.Contains(page, text);
}
foreach (var (candidate, _) in StrategyNames.Candidates)
{
Assert.IsFalse(page.Contains("/azioni/strategie/" + candidate, StringComparison.Ordinal), "A candidate has no button.");
using var post = await server.PostFormAsync("/strategie", $"/azioni/strategie/{candidate}/simulazione");
Assert.AreEqual(StrategyStages.Observation, (await server.Host.Services!.Trading!.Stages.GetAsync(candidate, CancellationToken.None))!.Stage);
}
using var refused = await server.PostFormAsync("/strategie", "/azioni/strategie/crypto_trend/simulazione");
Assert.AreEqual("/strategie?errore=backtest", ServerHarness.Location(refused));
Assert.AreEqual(StrategyStages.Observation, (await server.Host.Services!.Trading!.Stages.GetAsync(StrategyNames.CryptoTrend, CancellationToken.None))!.Stage);
// The outcome of a quarterly review is a page of the laboratory; the one of the program a file of the repository.
StringAssert.Contains(page, "<code>docs/backtests/crypto_trend.md</code>");
var review = Guid.NewGuid();
var measured = new Qualification { Passed = true, Verdict = "superata", Report = "/laboratorio/revisione/" + review };
await server.Host.Services!.Db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET qualification = @q WHERE strategy = 'crypto_trend'", CancellationToken.None,
("q", new DbJson(System.Text.Json.JsonSerializer.Serialize(measured, Qualification.Json)))), CancellationToken.None);
var after = await server.TextAsync("/strategie");
StringAssert.Contains(after, $"<a href=\"/laboratorio/revisione/{review}\">Rapporto</a>");
StringAssert.Contains(after, "dopo 90 giorni di osservazione può passare in simulazione");
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task LimitsGoDownFreelyAndUpOnlyWithThePhraseWhileAStrategyUsesRealMoney()
{
var network = new FakeHttp().On(_ => true, _ => FakeHttp.Respond("not here", HttpStatusCode.NotFound));
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), marketHttp: network, trading: true);
var password = await server.SignInFirstTimeAsync();
var services = server.Host.Services!;
var daily = RiskSettings.DailyLoss.Key;
// Not through the API: there the order of the limits and the procedure of SPEC 12.4 would be skipped.
var csrf = await server.Http.GetFromJsonAsync<Dictionary<string, string>>(new Uri("/api/antiforgery", UriKind.Relative));
using (var request = new HttpRequestMessage(HttpMethod.Put, new Uri("/api/settings/" + RiskSettings.DrawdownStop.Key, UriKind.Relative)) { Content = JsonContent.Create(new { value = "40" }) })
{
request.Headers.Add(csrf!["header"], csrf["token"]);
using var put = await server.Http.SendAsync(request);
Assert.AreEqual(HttpStatusCode.BadRequest, put.StatusCode);
}
Assert.AreEqual("15", (await services.Settings.GetAsync(RiskSettings.DrawdownStop.Key, CancellationToken.None)).Value);
// Out of range, or the halving after the switch: nothing changes.
using (var wrong = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (daily, "50")))
{
Assert.AreEqual("/impostazioni?errore=limite#rischio", ServerHarness.Location(wrong));
}
using (var order = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (RiskSettings.DrawdownHalf.Key, "20")))
{
Assert.AreEqual("/impostazioni?errore=ordine-limiti#rischio", ServerHarness.Location(order));
}
// Lower is always allowed.
using (var lower = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (daily, "1,5")))
{
Assert.AreEqual("/impostazioni?ok=limiti#rischio", ServerHarness.Location(lower));
}
Assert.AreEqual("1.5", (await services.Settings.GetAsync(daily, CancellationToken.None)).Value);
// A strategy with real money: raising needs the phrase and the password, and the form asks for them.
await services.Db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET stage = 'reduced' WHERE strategy = @s", CancellationToken.None,
("s", StrategyNames.CryptoTrend)), CancellationToken.None);
StringAssert.Contains(await server.TextAsync("/impostazioni"), StageBook.RaisePhrase);
using (var bare = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (daily, "2")))
{
Assert.AreEqual("/impostazioni?errore=frase-rischio#rischio", ServerHarness.Location(bare));
}
using (var badPassword = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (daily, "2"), ("frase", StageBook.RaisePhrase), ("password", "not-it")))
{
Assert.AreEqual("/impostazioni?errore=password-rischio#rischio", ServerHarness.Location(badPassword));
}
Assert.AreEqual("1.5", (await services.Settings.GetAsync(daily, CancellationToken.None)).Value, "Refused raises change nothing.");
using (var confirmed = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (daily, "2"), ("frase", StageBook.RaisePhrase), ("password", password)))
{
Assert.AreEqual("/impostazioni?ok=limiti#rischio", ServerHarness.Location(confirmed));
}
Assert.AreEqual("2", (await services.Settings.GetAsync(daily, CancellationToken.None)).Value);
// Lowering again needs nothing, even now.
using var lowerAgain = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (daily, "1"));
Assert.AreEqual("/impostazioni?ok=limiti#rischio", ServerHarness.Location(lowerAgain));
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task StopCloseAndRestartGoThroughTheRiskEngine()
{
var network = new FakeHttp().On(_ => true, _ => FakeHttp.Respond("not here", HttpStatusCode.NotFound));
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), marketHttp: network, trading: true);
await server.SignInFirstTimeAsync();
var services = server.Host.Services!;
async Task<string> StateAsync() => (await services.Settings.GetAsync(SettingsStore.BotState.Key, CancellationToken.None)).Value;
using (var stop = await server.PostFormAsync("/rischio", "/azioni/bot/ferma", ("ritorno", "/rischio")))
{
StringAssert.StartsWith(ServerHarness.Location(stop), "/rischio");
}
Assert.AreEqual("stopped", await StateAsync());
var stopped = await server.TextAsync("/rischio");
StringAssert.Contains(stopped, "Riparti");
StringAssert.Contains(stopped, "Chiudi tutte le posizioni", "Selling everything does not need a restart first.");
// With the STOP file in the data folder the restart is refused.
var stopFile = services.Trading!.Risk!.StopFile!;
await File.WriteAllTextAsync(stopFile, "");
using (var refused = await server.PostFormAsync("/rischio", "/azioni/bot/riattiva", ("ritorno", "/rischio")))
{
StringAssert.Contains(ServerHarness.Location(refused), "errore=file-stop");
}
Assert.AreEqual("stopped", await StateAsync());
File.Delete(stopFile);
using (var restart = await server.PostFormAsync("/rischio", "/azioni/bot/riattiva", ("ritorno", "/rischio")))
{
Assert.IsFalse(ServerHarness.Location(restart).Contains("errore", StringComparison.Ordinal), ServerHarness.Location(restart));
}
Assert.AreEqual("active", await StateAsync());
// The switch tripped by itself in the simulation: the bot stays "active" elsewhere, and the page offers the restart.
await services.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO risk_state (id, world, state, created_at, updated_at) VALUES (@id, 'simulated', @j, @t, @t)",
CancellationToken.None, ("id", Guid.NewGuid()), ("j", new DbJson("{\"tripped\":true}")), ("t", DateTimeOffset.UtcNow)), CancellationToken.None);
var page = await server.TextAsync("/rischio");
StringAssert.Contains(page, "Interruttore scattato nel mondo simulato");
StringAssert.Contains(page, "Riparti");
using (var again = await server.PostFormAsync("/rischio", "/azioni/bot/riattiva", ("ritorno", "/rischio")))
{
Assert.IsFalse(ServerHarness.Location(again).Contains("errore", StringComparison.Ordinal), ServerHarness.Location(again));
}
Assert.IsFalse(await services.Trading.Risk.AnyTrippedAsync(CancellationToken.None));
Assert.AreEqual("active", await StateAsync());
}
}