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

+166
View File
@@ -0,0 +1,166 @@
using Anubis.Backtest;
using Anubis.Core;
using Anubis.Data;
using Anubis.Strategies;
using Anubis.Trading;
namespace Anubis.Server;
/// <summary>A strategy of the Strategie screen: its stage, results, requirements and what the user can do next.</summary>
internal sealed record StrategyCard(
StrategyStage Stage,
string Name,
string Description,
IReadOnlyList<string> Rules,
string Account,
string Currency,
decimal CapitalEur,
decimal ResultEur,
decimal ResultPercent,
decimal WorstFall,
int Closed,
int Winners,
IReadOnlyList<string> Open,
IReadOnlyList<(DateTimeOffset At, decimal Index)> Curve,
IReadOnlyList<Requirement> Requirements,
string Phrase,
int? DaysToGo)
{
public string Color => "var(--s-" + Stage.Strategy.Replace('_', '-') + ")";
public bool AllMet => Requirements.All(r => r.Met);
}
/// <summary>
/// The Strategie screen (SPEC 12.3, 13.6, mockup 04): the path to real money in four stages, a card for each base
/// strategy with its requirements, and the ones in observation with the reason.
/// </summary>
internal sealed record StrategiesView(IReadOnlyList<StrategyCard> Cards, bool LiveAllowed, IReadOnlyList<(Guid Id, string Name, string Broker)> LiveAccounts)
{
/// <summary>What each base strategy does, in four lines (SPEC 8).</summary>
public static readonly IReadOnlyDictionary<string, IReadOnlyList<string>> Rules = new Dictionary<string, IReadOnlyList<string>>(StringComparer.Ordinal)
{
[StrategyNames.CryptoTrend] =
[
"Guarda le 10 monete in euro più scambiate una volta al giorno, dopo la chiusura delle 00:00 UTC",
"Entra quando il prezzo segna nuovi massimi su più periodi, da 5 a 360 giorni",
"Più una moneta è agitata, meno ne compra",
"Mai a leva, mai al ribasso",
],
[StrategyNames.EquityMomentum] =
[
"Rifà la classifica ogni lunedì e tiene fino a 12 titoli",
"Vende chi esce dai primi 30 o tocca lo stop",
"Compra solo quando il mercato nel suo insieme sale",
"Solo azioni singole, nessun ETF americano",
],
[StrategyNames.EquityMeanrev] =
[
"Solo titoli sopra la loro media a 200 giorni",
"Esce al rimbalzo, oppure dopo 5 sedute",
"Salta i giorni prima delle trimestrali",
"Mai uscita nello stesso giorno dell'acquisto",
],
};
public static async Task<StrategiesView> LoadAsync(AppServices services, IClock clock, bool liveAllowed, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(services);
var stages = services.Trading?.Stages ?? new StageBook(services.Db, clock, TradingConsent.None, (_, _, _) => Task.FromResult(false));
var ledger = services.Trading?.Ledger ?? new Ledger(services.Db, clock);
var rate = (await new FxStore(services.Db, clock).LatestAsync("EUR", "USD", cancellationToken).ConfigureAwait(false))?.Rate ?? 0m;
var accounts = await services.Db.ReadAsync(s => s.QueryAsync("SELECT id, name, broker, environment, base_currency FROM accounts",
r => (Id: r.Id("id"), Name: r.Text("name"), Broker: r.Text("broker"), Environment: r.Text("environment"), Currency: r.Text("base_currency"))), cancellationToken)
.ConfigureAwait(false);
var equities = await ledger.EquitiesAsync(cancellationToken).ConfigureAwait(false);
var positions = await ledger.PositionsAsync(null, cancellationToken).ConfigureAwait(false);
var cards = new List<StrategyCard>();
foreach (var stage in await stages.AllAsync(cancellationToken).ConfigureAwait(false))
{
if (!StrategyNames.Base.Any(b => b.Name == stage.Strategy))
{
continue;
}
var family = StrategyCatalog.Find(stage.Strategy);
var ledgerAccount = stage.OrdersAccount ?? stage.AccountId;
var account = accounts.FirstOrDefault(a => a.Id == ledgerAccount);
var usd = account.Currency == "USD";
decimal Eur(decimal amount) => usd ? (rate > 0m ? amount / rate : 0m) : amount;
var equity = equities.FirstOrDefault(e => e.AccountId == ledgerAccount && e.Strategy == stage.Strategy);
// As on Conti: each position is valued to the cent before the sum, so both pages show the same figure.
var held = positions.Where(p => p.AccountId == ledgerAccount && p.Strategy == stage.Strategy).Sum(p => Math.Round(p.Value, 2, MidpointRounding.AwayFromZero));
var result = equity is null ? 0m : equity.Cash + held - equity.Flows;
var since = stage.StageSince ?? DateTimeOffset.MinValue;
var (curve, trades) = await services.Db.ReadAsync(async s =>
{
var c = await s.QueryAsync(
"SELECT taken_at, twr_index FROM equity_snapshots WHERE scope = 'strategy' AND account_id = @a AND strategy = @s AND twr_index IS NOT NULL ORDER BY taken_at, id",
r => (At: r.Moment("taken_at"), Index: r.Money("twr_index")), ("a", ledgerAccount), ("s", stage.Strategy)).ConfigureAwait(false);
var t = await s.QueryAsync("SELECT realized FROM trades WHERE account_id = @a AND strategy = @s AND status = 'closed'", r => r.Money("realized"),
("a", ledgerAccount), ("s", stage.Strategy)).ConfigureAwait(false);
return (c, t);
}, cancellationToken).ConfigureAwait(false);
var peak = 0m;
var worst = 0m;
foreach (var p in curve)
{
peak = Math.Max(peak, p.Index);
worst = Math.Min(worst, peak > 0m ? (p.Index / peak) - 1m : 0m);
}
var symbols = new List<string>();
foreach (var p in positions.Where(p => p.AccountId == ledgerAccount && p.Strategy == stage.Strategy))
{
symbols.Add(await services.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT symbol FROM instruments WHERE id = @id", r => r.Text("symbol"), ("id", p.InstrumentId)),
cancellationToken).ConfigureAwait(false) ?? "?");
}
var requirements = await stages.RequirementsAsync(stage.Strategy, cancellationToken).ConfigureAwait(false);
var next = stage.Stage == StrategyStages.Reduced ? StrategyStages.Real : StrategyStages.Reduced;
var days = requirements.FirstOrDefault(r => r.Key == "days");
int? toGo = days is { Met: false } && stage.StageSince is { } from
? Math.Max(1, (int)Math.Ceiling(((stage.Stage == StrategyStages.Reduced ? StageBook.ReducedDays : StageBook.SimulationDays) - (clock.UtcNow - from).TotalDays)))
: null;
var flows = equity?.Flows ?? 0m;
cards.Add(new StrategyCard(stage, StrategyNames.Label(stage.Strategy, withMarket: true) + (stage.Strategy == StrategyNames.CryptoTrend ? "" : " USA"),
family?.Description ?? "", Rules.GetValueOrDefault(stage.Strategy) ?? [], account.Name ?? "—", account.Currency ?? "EUR", Eur(flows), Eur(result),
flows > 0m ? result / flows * 100m : 0m, worst, trades.Count, trades.Count(r => r >= 0m), symbols, [.. curve.Where(p => p.At >= since || stage.StageSince is null)],
requirements, StageBook.Phrase(stage.Strategy, next), toGo));
}
var live = accounts.Where(a => a.Environment == TradingEnvironments.Live).Select(a => (a.Id, a.Name, a.Broker)).ToList();
return new StrategiesView([.. cards.OrderBy(c => StrategyNames.Base.ToList().FindIndex(b => b.Name == c.Stage.Strategy))], liveAllowed, live);
}
/// <summary>A requirement not met yet only because time has to pass or nothing could be measured so far.</summary>
public static bool IsPending(Requirement requirement)
{
ArgumentNullException.ThrowIfNull(requirement);
return !requirement.Met && (requirement.Key is "days" or "trades" || requirement.Value is "da misurare" or "nessuna esecuzione");
}
/// <summary>Why a strategy is in observation, in words: the outcome of its backtest, or the user's choice.</summary>
public static string ObservationReason(StrategyStage stage)
{
ArgumentNullException.ThrowIfNull(stage);
if (stage.Qualification is { Passed: false } q)
{
return q.Verdict;
}
if (stage.Qualification is null)
{
return "Il backtest non è ancora stato fatto: finché manca resta in osservazione.";
}
return stage.StageReason switch
{
"user" or null => "Superato il backtest: puoi portarla in simulazione quando vuoi.",
var r => "Tornata in osservazione: " + ReasonTexts.Text(r) + ".",
};
}
/// <summary>The report of a strategy's backtest in the repository, for the link.</summary>
public static string? ReportOf(StrategyStage stage) => stage.Qualification?.Report ?? BacktestOutcomes.Find(stage.Strategy)?.Report;
}