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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-11 16:14:44 +01:00
1 parent 7041533ce2
commit 13f9c42f61
16 files changed
+2085 -34

No files matched your search

+161 -2
View File
@@ -35,6 +35,9 @@ internal static partial class Forms
signed.MapPost("/chiavi/{broker}/togli", RemoveKeysAsync);
signed.MapPost("/capitale/{broker}", SetCapitalAsync);
signed.MapPost("/laboratorio", PlanTrialAsync);
signed.MapPost("/strategie/{strategy}/{choice}", StrategyStageAsync);
signed.MapPost("/rischio/limiti", SetLimitsAsync);
signed.MapPost("/rischio/{key}", SetRiskSettingAsync);
}
private static string Back(IFormCollection form, string fallback)
@@ -173,8 +176,8 @@ internal static partial class Forms
private static async Task<IResult> BotAsync(string command, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
var back = Back(form, "/");
var (ok, _) = await Endpoints.BotCommandAsync(host, command, context, ct).ConfigureAwait(false);
return Results.Redirect(ok ? back : With(back, "errore", "bot"));
var (ok, message) = await Endpoints.BotCommandAsync(host, command, context, ct).ConfigureAwait(false);
return Results.Redirect(ok ? back : With(back, "errore", message.Contains("STOP", StringComparison.Ordinal) ? "file-stop" : "bot"));
}
/// <summary>The user's choice for an account in prudent mode after the 15 minutes (SPEC 7.4): align or leave out.</summary>
@@ -309,6 +312,13 @@ internal static partial class Forms
return Results.Redirect(back + "?errore=importo#conti");
}
// More capital while a strategy of this broker has real money is more risk: it needs the procedure (SPEC 12.4).
if ((await trading.Capital.EntrustedAsync(broker, ct).ConfigureAwait(false))?.AmountEur is { } before && amount > before &&
await RaiseRefusalAsync(host.Services!, broker, form, ct).ConfigureAwait(false) is { } refusal)
{
return Results.Redirect(back + "?errore=" + refusal + "#conti");
}
try
{
await trading.SetCapitalAsync(broker, amount, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
@@ -325,6 +335,155 @@ internal static partial class Forms
return Results.Redirect(back + "?ok=capitale#conti");
}
/// <summary>
/// The user's choices on the Strategie screen (SPEC 12.3, 12.4): observation and simulation from a button, real
/// money only through the procedure, with the phrase, the password and the second factor checked by the stage book.
/// </summary>
private static async Task<IResult> StrategyStageAsync(string strategy, string choice, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
if (host.IsDemo || host.Services is not { } services || !Anubis.Trading.StrategyNames.Base.Any(b => b.Name == strategy))
{
return Results.Redirect("/strategie?errore=scelta");
}
if (services.Trading?.Stages is not { } stages)
{
return Results.Redirect("/strategie?errore=motore");
}
var by = context.User.Identity?.Name ?? "utente";
try
{
switch (choice)
{
case "simulazione":
var stage = await stages.GetAsync(strategy, ct).ConfigureAwait(false);
if (stage?.Qualification is not { Passed: true })
{
// A strategy that did not pass its backtest stays in observation (SPEC 12.3).
return Results.Redirect("/strategie?errore=backtest");
}
await stages.MoveAsync(strategy, Anubis.Trading.StrategyStages.Simulation, "user", by, ct).ConfigureAwait(false);
return Results.Redirect("/strategie?ok=simulazione");
case "osservazione":
var current = await stages.GetAsync(strategy, ct).ConfigureAwait(false);
if (current is not null && Anubis.Trading.StrategyStages.IsLive(current.Stage))
{
await stages.RevokeAsync(strategy, by, "user", ct).ConfigureAwait(false);
return Results.Redirect("/strategie?ok=simulazione");
}
await stages.MoveAsync(strategy, Anubis.Trading.StrategyStages.Observation, "user", by, ct).ConfigureAwait(false);
return Results.Redirect("/strategie?ok=osservazione");
case "reale" when Guid.TryParse(form["conto"].ToString(), out var account):
var code = form["codice"].ToString();
await stages.ConfirmLiveAsync(new Anubis.Trading.LiveConfirmation(strategy, account, form["frase"].ToString(), form["password"].ToString(),
string.IsNullOrWhiteSpace(code) ? null : code.Trim(), by), ct).ConfigureAwait(false);
return Results.Redirect("/strategie?ok=reale");
default:
return Results.Redirect("/strategie?errore=scelta");
}
}
catch (Anubis.Trading.LiveConfirmationException ex)
{
var error = ex.Code switch
{
"phrase" => "frase",
"password" => "password",
"requirements" => "requisiti",
"account" => "conto",
Anubis.Risk.RiskReasons.NoConsent => "consenso",
_ => "scelta",
};
return Results.Redirect("/strategie?errore=" + error);
}
}
/// <summary>
/// The risk limits (SPEC 9.2, 13.5), all at once. Lowering is always allowed; raising any of them while a strategy
/// has real money needs the phrase, the password and the second factor (SPEC 12.4).
/// </summary>
private static async Task<IResult> SetLimitsAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
const string back = "/impostazioni";
if (host.IsDemo || host.Services is not { } services)
{
return Results.Redirect(back + "?errore=motore#rischio");
}
var current = new Dictionary<string, string>(StringComparer.Ordinal);
var next = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var definition in Anubis.Risk.RiskSettings.Limits)
{
current[definition.Key] = (await services.Settings.GetAsync(definition.Key, ct).ConfigureAwait(false)).Value;
var typed = form[definition.Key].ToString().Trim().Replace(',', '.');
if (typed.Length == 0)
{
next[definition.Key] = current[definition.Key];
continue;
}
if (definition.Check?.Invoke(typed) is not null)
{
return Results.Redirect(back + "?errore=limite#rischio");
}
next[definition.Key] = typed;
}
var limits = Anubis.Risk.RiskSettings.From(k => next[k]);
if (limits.DrawdownHalf >= limits.DrawdownStop || limits.DailyLoss > limits.WeeklyLoss)
{
return Results.Redirect(back + "?errore=ordine-limiti#rischio");
}
if (Anubis.Risk.RiskSettings.From(k => current[k]).RaisedBy(limits))
{
if (await RaiseRefusalAsync(services, null, form, ct).ConfigureAwait(false) is { } refusal)
{
return Results.Redirect(back + "?errore=" + refusal + "#rischio");
}
}
var by = context.User.Identity?.Name ?? "utente";
foreach (var (key, value) in next.Where(n => n.Value != current[n.Key]))
{
await services.Settings.SetAsync(key, value, by, ct).ConfigureAwait(false);
}
return Results.Redirect(back + "?ok=limiti#rischio");
}
/// <summary>The day-trade guard and the scenarios of the Rischio screen: they change no limit, so no procedure.</summary>
private static async Task<IResult> SetRiskSettingAsync(string key, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
const string back = "/impostazioni";
if (key != Anubis.Risk.RiskSettings.PdtGuard.Key && key != Anubis.Risk.Scenarios.Setting.Key)
{
return Results.Redirect(back + "?errore=impostazione#rischio");
}
var result = await Endpoints.SetSettingAsync(host, key, form["valore"].ToString(), context, ct).ConfigureAwait(false);
return Results.Redirect(result is IStatusCodeHttpResult { StatusCode: StatusCodes.Status204NoContent } ? back + "?ok=rischio#rischio" : back + "?errore=scenari#rischio");
}
/// <summary>Null when more risk may go ahead; otherwise the error code for the page.</summary>
private static async Task<string?> RaiseRefusalAsync(AppServices services, string? broker, IFormCollection form, CancellationToken ct)
{
var stages = services.Trading?.Stages ?? new Anubis.Trading.StageBook(services.Db, new SystemClock(), Anubis.Trading.TradingConsent.None, (_, _, _) => Task.FromResult(false));
try
{
var code = form["codice"].ToString();
await stages.ConfirmRaiseAsync(broker, form["frase"].ToString(), form["password"].ToString(), string.IsNullOrWhiteSpace(code) ? null : code.Trim(), ct).ConfigureAwait(false);
return null;
}
catch (Anubis.Trading.LiveConfirmationException ex)
{
return ex.Code == "phrase" ? "frase-rischio" : "password-rischio";
}
}
/// <summary>
/// A new backtest trial (SPEC 12.2): the plan is written and queued at once, then the page of the trial follows it.
/// A field that cannot be read goes back as a code; the chosen strategy is kept, nothing typed travels in the address.