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

+134
View File
@@ -0,0 +1,134 @@
using Anubis.Core;
using Anubis.Data;
using Anubis.Risk;
using Anubis.Strategies;
using Anubis.Trading;
namespace Anubis.Server;
/// <summary>A row of the limits table: what is used now against the threshold, and what happens beyond it.</summary>
internal sealed record LimitRow(string Label, string Now, string? Detail, decimal? Usage, string Threshold, string Beyond, string Key);
/// <summary>A point of the fall from the high, as a fraction: 0 at the high, −0,03 three percent below.</summary>
internal sealed record DrawdownPoint(DateTimeOffset At, decimal Drawdown);
/// <summary>
/// The Rischio screen (SPEC 9, 13.6, mockup 07): the emergency switch, the automatic blocks, the limits with what
/// they use now, the fall from the high, the scenarios and the risk events. One world, as on Conti.
/// </summary>
internal sealed record RiskView(
string BotState,
bool StopFile,
bool CloseAllPending,
string World,
WorldRisk Risk,
RiskLimits Limits,
IReadOnlyList<LimitRow> Rows,
IReadOnlyList<DrawdownPoint> Drawdown,
IReadOnlyList<ScenarioResult> Scenarios,
IReadOnlyList<(DateTimeOffset At, string Kind, string Severity, string Message, string? World)> Events,
(DateTimeOffset From, DateTimeOffset To, string Title)? NextCalendarBlock,
(DateTimeOffset From, DateTimeOffset To, string Title)? LastCalendarBlock,
bool PdtGuard,
bool HasPositions)
{
public bool AnyBlock => Risk.State.Tripped || Risk.EntriesBlocked || Risk.Multiplier < 1m || BotState != "active";
public static async Task<RiskView> LoadAsync(AppServices services, IClock clock, TimeZoneInfo zone, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(services);
var engine = services.Trading?.Risk ?? new RiskEngine(services.Db, clock, new Ledger(services.Db, clock),
new StageBook(services.Db, clock, TradingConsent.None, (_, _, _) => Task.FromResult(false)), services.Settings, new FxStore(services.Db, clock),
(_, _) => Task.FromResult<Instrument?>(null), (_, _) => Task.FromResult<Quote?>(null));
var limits = await RiskSettings.LoadAsync(services.Settings, cancellationToken).ConfigureAwait(false);
var accounts = await AccountsView.LoadAsync(services, clock, zone, cancellationToken).ConfigureAwait(false);
var world = accounts.Accounts.Any(a => TradingEnvironments.World(a.Environment) == Worlds.Real) ? Worlds.Real : Worlds.Simulated;
var risk = await engine.WorldAsync(world, cancellationToken).ConfigureAwait(false);
var bot = (await services.Settings.GetAsync(SettingsStore.BotState.Key, cancellationToken).ConfigureAwait(false)).Value;
var now = clock.UtcNow;
var (index, sent) = await services.Db.ReadAsync(async s =>
{
var i = await s.QueryAsync("SELECT taken_at, twr_index FROM equity_snapshots WHERE scope = 'total' AND world = @w AND twr_index IS NOT NULL ORDER BY taken_at, id",
r => new IndexPoint(r.Moment("taken_at"), r.Money("twr_index")), ("w", world)).ConfigureAwait(false);
var o = await s.QueryAsync(
"SELECT o.account_id, COUNT(*) AS n FROM orders o WHERE o.submitted_at >= @f AND o.purpose IN ('entry', 'exit') GROUP BY o.account_id",
r => (Account: r.Id("account_id"), Count: r.Number("n")), ("f", now - TimeSpan.FromMinutes(1))).ConfigureAwait(false);
return (i, o);
}, cancellationToken).ConfigureAwait(false);
var shown = accounts.Accounts.Select(a => a.Id).ToHashSet();
var equity = accounts.TotalEur;
var positions = accounts.Positions;
var biggest = positions.MaxBy(p => p.ValueEur);
var crypto = positions.Where(p => p.Broker == Venues.Okx).Sum(p => p.ValueEur);
decimal Rate(PositionRow p) => p.Last == 0m ? 0m : p.ValueEur / (p.Quantity * p.Last);
var atRisk = positions.Select(p => p.Stop is { } stop ? Math.Max(0m, p.ValueEur - (p.Quantity * stop * Rate(p))) : p.ValueEur).ToList();
var perMinute = sent.Where(x => shown.Contains(x.Account)).Select(x => x.Count).DefaultIfEmpty(0).Max();
string Pct(decimal fraction, int decimals = 2, bool sign = false) => Format.Percent(fraction * 100m, decimals, sign);
decimal? Use(decimal value, decimal limit) => limit <= 0m ? null : Math.Clamp(value / limit, 0m, 1m);
var m = risk.Measures;
var rows = new List<LimitRow>
{
new("Perdita in un giorno", m.DayChange >= 0m ? "nessuna" : Pct(m.DayChange), m.DayChange >= 0m ? $"oggi {Pct(m.DayChange, 2, true)}" : null,
Use(-m.DayChange, limits.DailyLoss), Pct(-limits.DailyLoss), "Niente nuovi ingressi per 24 ore", RiskSettings.DailyLoss.Key),
new("Perdita in una settimana", m.WeekChange >= 0m ? "nessuna" : Pct(m.WeekChange), m.WeekChange >= 0m ? $"{Pct(m.WeekChange, 2, true)}" : null,
Use(-m.WeekChange, limits.WeeklyLoss), Pct(-limits.WeeklyLoss), "Rischio dimezzato per sette giorni", RiskSettings.WeeklyLoss.Key),
new("Calo dal massimo", Pct(m.Drawdown), Worst(index, risk.State.PeakFrom) is { } worst && worst < m.Drawdown ? $"peggiore {Pct(worst)}" : null,
Use(-m.Drawdown, limits.DrawdownStop), $"{Pct(-limits.DrawdownHalf, 0)} e {Pct(-limits.DrawdownStop, 0)}",
$"A {Pct(-limits.DrawdownHalf, 0)} dimezzo il rischio. A {Pct(-limits.DrawdownStop, 0)} fermo tutto e aspetto te", RiskSettings.DrawdownStop.Key),
new("Capitale investito", equity > 0m ? Pct(accounts.InvestedEur / equity, 1) : "—", null, equity > 0m ? Use(accounts.InvestedEur / equity, limits.MaxInvested) : null,
Pct(limits.MaxInvested, 0), "Non compro altro: non uso mai soldi presi in prestito", RiskSettings.MaxInvested.Key),
new("Peso di una sola posizione", biggest is null || equity <= 0m ? "—" : Pct(biggest.ValueEur / equity, 1), biggest?.Symbol,
biggest is null || equity <= 0m ? 0m : Use(biggest.ValueEur / equity, limits.MaxPosition), Pct(limits.MaxPosition, 0), "Riduco la posizione fino alla soglia",
RiskSettings.MaxPosition.Key),
new("Crypto sul totale", equity > 0m ? Pct(crypto / equity, 1) : "—", null, equity > 0m ? Use(crypto / equity, limits.MaxCrypto) : null, Pct(limits.MaxCrypto, 0),
"Niente nuovi acquisti di crypto", RiskSettings.MaxCrypto.Key),
new("Rischio di una singola operazione", atRisk.Count == 0 || equity <= 0m ? "—" : Pct(atRisk.Average() / equity), atRisk.Count == 0 ? null : "in media, fino allo stop",
atRisk.Count == 0 || equity <= 0m ? 0m : Use(atRisk.Average() / equity, limits.MaxTradeRisk), Pct(limits.MaxTradeRisk), "Rimpicciolisco l'ordine prima di inviarlo",
RiskSettings.MaxTradeRisk.Key),
new("Ordini al minuto", perMinute.ToString(System.Globalization.CultureInfo.InvariantCulture), null, Use(perMinute, limits.OrdersPerMinute),
limits.OrdersPerMinute.ToString(System.Globalization.CultureInfo.InvariantCulture), "Mi fermo e ti avviso: può essere un guasto", RiskSettings.OrdersPerMinute.Key),
new("Età dei prezzi", "controllata a ogni ordine", null, null, $"{(int)limits.MaxPriceAge.TotalSeconds} secondi", "Non apro posizioni finché i dati non tornano freschi",
RiskSettings.MaxPriceAge.Key),
};
var drawdown = new List<DrawdownPoint>();
var peak = 0m;
foreach (var p in index.Where(p => risk.State.PeakFrom is null || p.At >= risk.State.PeakFrom))
{
peak = Math.Max(peak, p.Index);
drawdown.Add(new DrawdownPoint(p.At, peak > 0m ? (p.Index / peak) - 1m : 0m));
}
var scenarioText = (await services.Settings.GetAsync(Anubis.Risk.Scenarios.Setting.Key, cancellationToken).ConfigureAwait(false)).Value;
var dollars = accounts.Accounts.Where(a => a.Currency == "USD").Sum(a => a.Eur(a.Equity));
var scenarios = Anubis.Risk.Scenarios.Compute(Anubis.Risk.Scenarios.Parse(scenarioText),
[.. positions.Select(p => new ScenarioPosition(p.Broker == Venues.Okx, p.ValueEur, p.Stop is { } stop ? p.Quantity * stop * Rate(p) : null))], dollars, equity);
var calendar = await new CalendarEventStore(services.Db, clock).BetweenAsync(now.AddDays(-14), now.AddDays(14), cancellationToken).ConfigureAwait(false);
var windows = calendar.Select(e => (Event: e, Window: CalendarBlocks.Window(e))).Where(x => x.Window is not null)
.Select(x => (x.Window!.Value.From, x.Window.Value.To, x.Event.Title)).OrderBy(x => x.From).ToList();
(DateTimeOffset, DateTimeOffset, string)? next = windows.FirstOrDefault(w => w.To > now) is { Title: not null } n ? n : null;
(DateTimeOffset, DateTimeOffset, string)? last = windows.LastOrDefault(w => w.To <= now) is { Title: not null } l ? l : null;
return new RiskView(bot, engine.StopRequested, (await engine.BotAsync(cancellationToken).ConfigureAwait(false)).CloseAll, world, risk, limits, rows, drawdown, scenarios,
await engine.EventsAsync(8, cancellationToken).ConfigureAwait(false), next, last, await RiskSettings.PdtGuardAsync(services.Settings, cancellationToken).ConfigureAwait(false),
positions.Count > 0);
}
private static decimal? Worst(IReadOnlyList<IndexPoint> index, DateTimeOffset? from)
{
decimal? worst = null;
var peak = 0m;
foreach (var p in index.Where(p => from is null || p.At >= from))
{
peak = Math.Max(peak, p.Index);
var d = peak > 0m ? (p.Index / peak) - 1m : 0m;
worst = worst is null ? d : Math.Min(worst.Value, d);
}
return worst;
}
}