using Anubis.Core; using Anubis.Data; using Anubis.Risk; using Anubis.Strategies; using Anubis.Trading; namespace Anubis.Server; /// A row of the limits table: what is used now against the threshold, and what happens beyond it. internal sealed record LimitRow(string Label, string Now, string? Detail, decimal? Usage, string Threshold, string Beyond, string Key); /// /// The protected restart of SPEC 15.1: since when, the accounts still to rebuild, what was rebuilt, the strategies /// that stay in exit only until they are confirmed again. /// internal sealed record ProtectedRestartView(DateTimeOffset Since, bool Working, IReadOnlyList Waiting, IReadOnlyList Rebuilt, IReadOnlyList ToReconfirm) { public bool CanRestart => !Working && Waiting.Count == 0; public static async Task LoadAsync(AppServices services, CancellationToken cancellationToken) { if (await Platform.Installation.ReadRowAsync(services.Db, cancellationToken).ConfigureAwait(false) is not { ProtectedRestart: true } row) { return null; } var rebuilt = await services.Db.ReadAsync(s => s.QueryAsync("SELECT message FROM journal WHERE code = 'ledger_rebuilt' AND occurred_at >= @f ORDER BY occurred_at, id", r => r.Text("message"), ("f", row.RenewedAt)), cancellationToken).ConfigureAwait(false); var stages = services.Trading is { } trading ? await trading.Stages.AllAsync(cancellationToken).ConfigureAwait(false) : []; return new ProtectedRestartView(row.RenewedAt, services.Trading is not { Started: true }, services.Trading?.AccountsToRebuild ?? [], rebuilt, [.. stages.Where(s => s.WaitsForReconfirmation).Select(s => StrategyNames.Label(s.Strategy, withMarket: true))]); } } /// A point of the fall from the high, as a fraction: 0 at the high, −0,03 three percent below. internal sealed record DrawdownPoint(DateTimeOffset At, decimal Drawdown); /// /// 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. /// internal sealed record RiskView( string BotState, bool StopFile, bool CloseAllPending, string World, WorldRisk Risk, RiskLimits Limits, IReadOnlyList Rows, IReadOnlyList Drawdown, IReadOnlyList 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, IReadOnlyList Tripped) { /// After a restore (SPEC 15.1): what the restart waits for, and what stays in exit only after it. public ProtectedRestartView? ProtectedRestart { get; init; } public bool AnyBlock => Tripped.Count > 0 || Risk.EntriesBlocked || Risk.Multiplier < 1m || BotState != "active"; /// The switch tripped by itself in a world (SPEC 9.2): it waits for the user's restart, like "Ferma tutto". public bool WaitsForRestart => BotState == "stopped" || Tripped.Count > 0; public static async Task 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(null), (_, _) => Task.FromResult(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); // Both worlds: a switch tripped in the simulation must show even when the page measures the real one. var tripped = new List(); foreach (var w in new[] { Worlds.Real, Worlds.Simulated }) { var each = w == world ? risk : await engine.WorldAsync(w, cancellationToken).ConfigureAwait(false); if (each.State.Tripped) { tripped.Add(each); } } // Weights, crypto and the risk of a trade are measured on the reference equity, as the risk engine does (SPEC 9.2). var reference = await engine.ReferenceAsync(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 { 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 || reference <= 0m ? "—" : Pct(biggest.ValueEur / reference, 1), biggest?.Symbol, biggest is null || reference <= 0m ? 0m : Use(biggest.ValueEur / reference, limits.MaxPosition), Pct(limits.MaxPosition, 0), "Riduco la posizione fino alla soglia", RiskSettings.MaxPosition.Key), new("Crypto sul totale", reference > 0m ? Pct(crypto / reference, 1) : "—", null, reference > 0m ? Use(crypto / reference, limits.MaxCrypto) : null, Pct(limits.MaxCrypto, 0), "Niente nuovi acquisti di crypto", RiskSettings.MaxCrypto.Key), new("Rischio di una singola operazione", atRisk.Count == 0 || reference <= 0m ? "—" : Pct(atRisk.Average() / reference), atRisk.Count == 0 ? null : "in media, oggi fino allo stop", atRisk.Count == 0 || reference <= 0m ? 0m : Use(atRisk.Average() / reference, limits.MaxTradeRisk), Pct(limits.MaxTradeRisk), "All'acquisto 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(); 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, tripped) { ProtectedRestart = await ProtectedRestartView.LoadAsync(services, cancellationToken).ConfigureAwait(false), }; } private static decimal? Worst(IReadOnlyList 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; } }