Files
Anubis/tests/Anubis.Tests/StrategyScreensTests.cs
T
Alby96andClaude Opus 5.5 13f9c42f61 Add the Operazioni, Strategie and Rischio screens (refs #45)
The three screens follow mockups 03, 04 and 07.

Operazioni shows the balance of the closed trades, filters, a CSV export,
and for each trade why it was bought and sold. The reasons come from the
decision codes through fixed Italian templates.

Strategie shows the four stages towards real money, a card per strategy
with its requirements, the procedure of SPEC 12.4, and why each strategy in
observation waits. A strategy that failed its backtest cannot be moved into
the simulation.

Rischio shows the emergency switch, the automatic blocks, the use of each
limit, the fall from the peak, the scenarios and the risk events. Stop,
close and restart now go through the risk engine. A restart is refused
while the STOP file exists.

Impostazioni gains the limits, the day-trade guard and the scenarios.
Lowering a limit is always allowed. Raising a limit or the entrusted capital
while a strategy uses real money needs the phrase and the password.

The demo now holds the decisions behind its trades, the 58 days of
simulation and the indices of its curves, so it matches the mockups.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 16:14:44 +01:00

180 lines
9.4 KiB
C#

using System.Net;
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()
{
await using 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" })
{
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
{
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.");
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);
}
[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;
// 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());
StringAssert.Contains(await server.TextAsync("/rischio"), "Riparti");
// 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());
}
}