From 98ee504dab346dfea6b67d9aac890172c2d897fc Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 11 Nov 2026 17:46:28 +0100 Subject: [PATCH 01/12] Write the diary from fixed templates and add the "senza bot" comparison (refs #50) The diary needs sentences in the tone of appendix B, built only from what happened. DiaryText holds the templates the live engine will use: fills with the result of the trade they close, raised stops, the daily crypto close, the stock signals, observation signals, recovery and absence. The reason-code sentences move from the server into the library (ReasonCatalog) so the engine and the screens share them; a test checks that every reason constant has its sentence. The diary gets the kinds of the Diario screen: Ordini, Decisioni, Sistema, Notizie, Apprendimento. The comparison of SPEC 7.5 invests each capital flow on its day, 40% in BTC/EUR and 60% in SPY adjusted and converted at the ECB rate, and never touches it; a withdrawal sells both in the proportion they reached. Prices are the closes of the day before, so a deposit is never a gain. Without the SPY history (no Alpaca keys) the photograph leaves it empty rather than show half a comparison. The Panoramica now takes the flows out of the "Senza bot" result, as it already did for the bot. Co-Authored-By: Claude Opus 5.5 --- src/Anubis.Server/Overview.cs | 8 +- src/Anubis.Server/ReasonTexts.cs | 59 +------ src/Anubis/Trading/Diary.cs | 5 + src/Anubis/Trading/DiaryText.cs | 237 ++++++++++++++++++++++++++++ src/Anubis/Trading/Equity.cs | 44 +++++- src/Anubis/Trading/NoBot.cs | 113 +++++++++++++ src/Anubis/Trading/OrderManager.cs | 23 ++- src/Anubis/Trading/ReasonCatalog.cs | 83 ++++++++++ tests/Anubis.Tests/DiaryTests.cs | 136 ++++++++++++++++ 9 files changed, 636 insertions(+), 72 deletions(-) create mode 100644 src/Anubis/Trading/DiaryText.cs create mode 100644 src/Anubis/Trading/NoBot.cs create mode 100644 src/Anubis/Trading/ReasonCatalog.cs create mode 100644 tests/Anubis.Tests/DiaryTests.cs diff --git a/src/Anubis.Server/Overview.cs b/src/Anubis.Server/Overview.cs index 8a0f0fc..d0943f3 100644 --- a/src/Anubis.Server/Overview.cs +++ b/src/Anubis.Server/Overview.cs @@ -95,9 +95,13 @@ internal sealed record Overview( }; var series = daily.Where(p => p.Day >= start.Day).ToList(); var cells = new List { Between("Oggi", Since(1)), Between("Ultimi 7 giorni", Since(7)), Between("Ultimi 30 giorni", Since(30)) }; - if (daily[0].Benchmark is { } firstBenchmark && latest.Benchmark is { } lastBenchmark && firstBenchmark != 0) + // "Senza bot" since the first day it is known, with the same flows taken out as for the bot (SPEC 7.5). + if (daily.FirstOrDefault(p => p.Benchmark is not null) is { Benchmark: { } firstBenchmark } first && latest.Benchmark is { } lastBenchmark) { - cells.Add(new PeriodResult("Senza bot", lastBenchmark - firstBenchmark, (lastBenchmark - firstBenchmark) / firstBenchmark * 100m)); + var flows = latest.Flows - first.Flows; + var amount = lastBenchmark - firstBenchmark - flows; + var basis = firstBenchmark + flows; + cells.Add(new PeriodResult("Senza bot", amount, basis == 0m ? 0m : amount / basis * 100m)); } return new Overview(daily, series, Between("", start), start.Day, start.Equity, cells, (int)positions, (int)withoutStop, (int)orders, next, last, capitalSet); diff --git a/src/Anubis.Server/ReasonTexts.cs b/src/Anubis.Server/ReasonTexts.cs index 8f4fbd5..2b5fd40 100644 --- a/src/Anubis.Server/ReasonTexts.cs +++ b/src/Anubis.Server/ReasonTexts.cs @@ -12,63 +12,6 @@ namespace Anubis.Server; /// internal static class ReasonTexts { - private static readonly Dictionary Texts = new(StringComparer.Ordinal) - { - // Strategies. - ["trend_entry"] = "La chiusura ha superato i massimi recenti su almeno un orizzonte: è iniziata una tendenza al rialzo.", - ["trend_increase"] = "Più orizzonti erano d'accordo sulla tendenza: il peso è salito.", - ["trend_reduce"] = "La tendenza si è indebolita, o la moneta è diventata più agitata: il peso è sceso.", - ["trend_exit"] = "La tendenza si è interrotta: il prezzo è finito sotto lo stop mobile.", - ["trend_stop"] = "Lo stop mobile è salito con il prezzo.", - ["momentum_entry"] = "Era tra i titoli più forti degli ultimi mesi, con il mercato in salita.", - ["momentum_increase"] = "Il peso obiettivo è salito alla revisione settimanale.", - ["momentum_reduce"] = "Il peso obiettivo è sceso alla revisione settimanale.", - ["momentum_exit_rank"] = "Non era più tra i 30 titoli più forti.", - ["momentum_exit_trend"] = "Il mercato nel suo insieme è girato al ribasso: niente più azioni.", - ["momentum_stop"] = "Lo stop di protezione è stato aggiornato.", - ["meanrev_entry"] = "Era sceso per qualche seduta di fila ma restava sopra la sua media a 200 giorni: un ribasso breve di un titolo che nel lungo periodo sale.", - ["meanrev_exit_average"] = "Il prezzo è tornato sopra la media a 5 giorni: il rimbalzo cercato è arrivato.", - ["meanrev_exit_rsi"] = "L'indicatore di forza è tornato alto: il rimbalzo è avvenuto.", - ["meanrev_exit_earnings"] = "Uscita prima della trimestrale.", - ["meanrev_exit_time"] = "Tempo scaduto: nessun rimbalzo in 5 sedute.", - // Exits recorded on the trade. - ["stop"] = "Stop di protezione raggiunto.", - ["exit"] = "Uscita decisa dalla strategia.", - ["signal"] = "Uscita sul segnale della strategia.", - ["residue"] = "Resto troppo piccolo per essere venduto, tolto dal registro.", - ["adjustment"] = "Rettifica dopo l'allineamento con il conto.", - // Correctives. - ["crypto_regime_below_average"] = "Il mercato crypto era sotto la sua media: acquisti ridotti.", - ["crypto_regime_high_volatility"] = "Il mercato crypto era molto agitato: acquisti ridotti.", - ["calendar_event"] = "Un dato economico importante era vicino: niente nuove posizioni in quell'ora.", - // Risk. - ["risk_reduction"] = "Ordine rimpicciolito dai limiti di rischio.", - ["daily_loss_block"] = "Perdita del giorno oltre il limite: niente nuovi ingressi per 24 ore.", - ["switch_tripped"] = "Interruttore scattato: il bot aspetta la tua conferma.", - ["bot_paused"] = "Bot in pausa: niente nuovi ingressi.", - ["bot_stopped"] = "Bot fermato con \"Ferma tutto\".", - ["invested_limit"] = "Capitale investito al limite: niente soldi presi in prestito.", - ["position_limit"] = "Ridotto al peso massimo di una posizione.", - ["crypto_limit"] = "Quota delle crypto sul totale al limite.", - ["trade_risk_limit"] = "Ridotto perché il rischio dell'operazione restasse entro il limite.", - ["stop_above_price"] = "Stop sopra il prezzo: ordine rifiutato.", - ["stale_price"] = "Prezzo troppo vecchio: niente acquisti finché i dati non tornano freschi.", - ["price_gap"] = "Prezzo dell'ordine troppo lontano dall'ultimo prezzo.", - ["clock_skew"] = "Orologio non allineato con quello del broker.", - ["owned_by_other_strategy"] = "La posizione appartiene a un'altra strategia.", - ["no_short_selling"] = "Niente vendite allo scoperto: venduto solo quanto posseduto.", - ["no_leverage"] = "Niente leva: l'ordine sta nella liquidità disponibile.", - ["not_owned_by_bot"] = "La posizione non è del bot: non la tocca.", - ["live_not_confirmed"] = "Soldi veri non confermati per questa strategia.", - ["exit_only"] = "Strategia in sola uscita: niente nuovi acquisti.", - ["live_not_allowed"] = "Soldi veri non permessi dalla configurazione d'avvio.", - ["observation"] = "Strategia in osservazione: produce segnali, nessun ordine.", - ["orders_per_minute"] = "Troppi ordini in un minuto: il bot si è fermato.", - ["pdt_guard"] = "Guardia sulle operazioni in giornata: niente posizioni in più oggi.", - ["no_fx_rate"] = "Manca il cambio euro-dollaro: niente acquisti in dollari.", - ["unknown_instrument"] = "Strumento sconosciuto.", - }; - // The exits in the few words of a table column; the full sentence stays for the "why" card. private static readonly Dictionary ShortExits = new(StringComparer.Ordinal) { @@ -85,7 +28,7 @@ internal static class ReasonTexts /// Why a trade was closed, in a short sentence. public static string Exit(string? code) => code is null ? "Chiusa" : ShortExits.TryGetValue(code, out var text) ? text : Text(code).TrimEnd('.'); - public static string Text(string code) => Texts.TryGetValue(code, out var text) ? text : code; + public static string Text(string code) => ReasonCatalog.Text(code); /// The lines of one stage of a decision. is the JSON of the numbers the stage used. public static IEnumerable Stage(string stage, string outcome, IReadOnlyList reasons, string? data) diff --git a/src/Anubis/Trading/Diary.cs b/src/Anubis/Trading/Diary.cs index 451d8db..39e9f7c 100644 --- a/src/Anubis/Trading/Diary.cs +++ b/src/Anubis/Trading/Diary.cs @@ -8,7 +8,12 @@ namespace Anubis.Trading; public static class DiaryKinds { public const string Orders = "Ordini"; + public const string Decisions = "Decisioni"; public const string System = "Sistema"; + public const string News = "Notizie"; + public const string Learning = "Apprendimento"; + + public static readonly IReadOnlyList All = [Orders, Decisions, System, News, Learning]; } /// diff --git a/src/Anubis/Trading/DiaryText.cs b/src/Anubis/Trading/DiaryText.cs new file mode 100644 index 0000000..eea8cbd --- /dev/null +++ b/src/Anubis/Trading/DiaryText.cs @@ -0,0 +1,237 @@ +using Anubis.Core; +using Anubis.Data; + +namespace Anubis.Trading; + +/// +/// The fixed templates of the diary (SPEC 5.2, 13.3, appendix B): one main sentence and, when it helps, a second +/// one with the reason. Short form without a subject for what was done ("Alzato lo stop di BTC/EUR"), first person +/// for what the bot does or did ("Sono stato fermo"). Never free text written at decision time. +/// +public static class DiaryText +{ + /// A symbol as the user reads it: BTC/EUR for the pair BTC-EUR, AAPL as it is. + public static string Shown(string symbol) + { + ArgumentNullException.ThrowIfNull(symbol); + return symbol.Replace('-', '/'); + } + + /// The coin of a pair: BTC for BTC-EUR. + public static string Coin(string symbol) + { + ArgumentNullException.ThrowIfNull(symbol); + var dash = symbol.IndexOf('-', StringComparison.Ordinal); + return dash > 0 ? symbol[..dash] : symbol; + } + + /// "BTC, ETH e SOL". + public static string List(IEnumerable items) + { + ArgumentNullException.ThrowIfNull(items); + var list = items.ToList(); + return list.Count switch + { + 0 => "", + 1 => list[0], + _ => string.Join(", ", list.Take(list.Count - 1)) + " e " + list[^1], + }; + } + + /// A stop or a price level in a sentence: no decimals from 1,000 up (65.400 €), the price's own below. + public static string Level(decimal value, string currency) => + Math.Abs(value) >= 1000m ? Format.Money(value, currency, decimals: 0) : Format.Number(value, Math.Abs(value) >= 1m ? 2 : 4) + " " + Format.CurrencySymbol(currency); + + /// + /// A fill: "Comprate 2 AAPL a 259,80 $." and, for a sale that closes the trade, its result: "Venduta 1 MSFT a + /// 522,14 $: +9,84 $ in 3 giorni." is the second sentence, from a reason code. + /// + public static string Fill(OrderSide side, decimal quantity, string symbol, bool crypto, decimal price, string currency, string? reason = null, ClosedTrade? closed = null) + { + var buy = side == OrderSide.Buy; + var one = quantity == 1m; + var verb = (buy, crypto, one) switch + { + (true, true, true) => "Comprato", + (true, true, false) => "Comprati", + (true, false, true) => "Comprata", + (true, false, false) => "Comprate", + (false, true, true) => "Venduto", + (false, true, false) => "Venduti", + (false, false, true) => "Venduta", + (false, false, false) => "Vendute", + }; + var text = $"{verb} {Format.Quantity(quantity)} {Shown(symbol)} a {Format.Price(price)} {Format.CurrencySymbol(currency)}"; + if (closed is not null) + { + text += $": {Format.Money(closed.Result, currency, withSign: true)} {Days(closed.Days)}"; + } + + return text + "." + (string.IsNullOrWhiteSpace(reason) ? "" : " " + reason.Trim()); + } + + /// "in 3 giorni", "in 1 giorno", "in giornata". + public static string Days(int days) => days switch + { + <= 0 => "in giornata", + 1 => "in 1 giorno", + _ => $"in {days} giorni", + }; + + public static string StopRaised(string symbol, decimal from, decimal to, string currency) => + $"Alzato lo stop di {Shown(symbol)} da {Level(from, currency)} a {Level(to, currency)}. Lo stop segue il prezzo quando sale."; + + public static string StopsReplaced(int count) => count == 1 + ? "Rimesso 1 stop giornaliero sulle frazioni di azione." + : $"Rimessi {count} stop giornalieri sulle frazioni di azione."; + + /// + /// The daily crypto close (SPEC 5.5): what changes, what stays in trend, what stays out. "Chiusura giornaliera + /// crypto: nessun cambio. BTC, ETH e SOL restano in tendenza. Le altre 7 monete restano fuori: nessuna ha segnato + /// nuovi massimi." + /// + public static string CryptoClose(DecisionSummary summary) + { + ArgumentNullException.ThrowIfNull(summary); + var head = "Chiusura giornaliera crypto: " + Changes(summary, Coin) + "."; + var staying = summary.Held.Select(Coin).ToList(); + if (staying.Count > 0) + { + head += staying.Count == 1 ? $" {staying[0]} resta in tendenza." : $" {List(staying)} restano in tendenza."; + } + + if (summary.Outside > 0) + { + head += summary.Outside == 1 + ? " L'altra moneta resta fuori: non ha segnato nuovi massimi." + : $" {(staying.Count + summary.Bought.Count > 0 ? "Le altre" : "Le")} {summary.Outside} monete restano fuori: nessuna ha segnato nuovi massimi."; + } + + return head; + } + + /// + /// The stock signals after the close: "Azioni: nessun nuovo acquisto. AAPL resta aperta." or "Azioni: domani + /// compro AAPL e MSFT, vendo JPM." + /// + public static string StockSignals(DecisionSummary summary) + { + ArgumentNullException.ThrowIfNull(summary); + var head = summary.HasChanges ? "Azioni: domani " + Changes(summary, s => s) + "." : "Azioni: nessun nuovo acquisto."; + if (summary.Held.Count > 0) + { + head += summary.Held.Count == 1 ? $" {summary.Held[0]} resta aperta." : $" {List(summary.Held)} restano aperte."; + } + + return head; + } + + /// A strategy in observation: the signal is recorded, no order leaves (SPEC 12.3). + public static string Observed(string strategy, DecisionSummary summary) + { + ArgumentNullException.ThrowIfNull(summary); + var label = StrategyNames.Label(strategy, withMarket: true); + return summary.HasChanges + ? $"{label}, in osservazione: avrei {Conditional(summary)}. Nessun ordine: registro solo il segnale." + : $"{label}, in osservazione: nessun cambio. Registro solo il segnale."; + } + + /// A strategy whose decision could not be made: the data was missing, nothing was bought. + public static string NoData(string strategy, string what) => + $"{StrategyNames.Label(strategy, withMarket: true)}: nessuna decisione oggi. Mancano {what}: non apro nuove posizioni."; + + /// A missed job done at the restart (SPEC 5.6). + public static string Recovered(string what, DateTimeOffset due, TimeZoneInfo zone) => + $"Recuperato un lavoro saltato: {what} (previsto alle {TimeZoneInfo.ConvertTime(due, zone):HH:mm})."; + + /// A missed job left out at the restart, with its reason (SPEC 5.6). + public static string Skipped(string what, string reason) => $"Saltato: {what}. {reason}"; + + /// An entry left out because the price moved too far from the planned one (SPEC 5.6). + public static string EntryDropped(string symbol, decimal movedPercent, decimal limitPercent) => + $"Scartato l'acquisto di {Shown(symbol)}: il prezzo si è mosso del {Format.Percent(movedPercent, 1)} dall'orario previsto, oltre il limite del {Format.Percent(limitPercent, 0)}."; + + /// The restart after an absence (SPEC 5.6, 9.4). + public static string Absence(TimeSpan absence) => $"Sono stato fermo per {Duration(absence)}. Ho ripreso i lavori saltati con le regole del recupero."; + + /// "3 ore e 5 minuti", "2 giorni e 4 ore", "12 minuti". + public static string Duration(TimeSpan span) + { + static string Unit(int n, string one, string many) => n == 1 ? $"1 {one}" : $"{n} {many}"; + if (span.TotalDays >= 1) + { + var days = (int)span.TotalDays; + return span.Hours > 0 ? $"{Unit(days, "giorno", "giorni")} e {Unit(span.Hours, "ora", "ore")}" : Unit(days, "giorno", "giorni"); + } + + if (span.TotalHours >= 1) + { + var hours = (int)span.TotalHours; + return span.Minutes > 0 ? $"{Unit(hours, "ora", "ore")} e {Unit(span.Minutes, "minuto", "minuti")}" : Unit(hours, "ora", "ore"); + } + + return Unit(Math.Max(1, (int)Math.Round(span.TotalMinutes)), "minuto", "minuti"); + } + + private static string Changes(DecisionSummary s, Func name) + { + var parts = new List(); + if (s.Bought.Count > 0) + { + parts.Add("compro " + List(s.Bought.Select(name))); + } + + if (s.Increased.Count > 0) + { + parts.Add("aumento " + List(s.Increased.Select(name))); + } + + if (s.Reduced.Count > 0) + { + parts.Add("riduco " + List(s.Reduced.Select(name))); + } + + if (s.Sold.Count > 0) + { + parts.Add("vendo " + List(s.Sold.Select(name))); + } + + return parts.Count == 0 ? "nessun cambio" : string.Join(", ", parts); + } + + private static string Conditional(DecisionSummary s) + { + var parts = new List(); + if (s.Bought.Count > 0) + { + parts.Add("comprato " + List(s.Bought.Select(Shown))); + } + + if (s.Increased.Count > 0) + { + parts.Add("aumentato " + List(s.Increased.Select(Shown))); + } + + if (s.Reduced.Count > 0) + { + parts.Add("ridotto " + List(s.Reduced.Select(Shown))); + } + + if (s.Sold.Count > 0) + { + parts.Add("venduto " + List(s.Sold.Select(Shown))); + } + + return string.Join(", ", parts); + } +} + +/// The result of a trade a sale has just closed: for the diary line of the fill. +public sealed record ClosedTrade(decimal Result, int Days); + +/// What one decision changes, by symbol: the material of the diary's decision lines. +public sealed record DecisionSummary(IReadOnlyList Bought, IReadOnlyList Increased, IReadOnlyList Reduced, IReadOnlyList Sold, + IReadOnlyList Held, int Outside) +{ + public bool HasChanges => Bought.Count + Increased.Count + Reduced.Count + Sold.Count > 0; +} diff --git a/src/Anubis/Trading/Equity.cs b/src/Anubis/Trading/Equity.cs index 768dbbf..a7a8945 100644 --- a/src/Anubis/Trading/Equity.cs +++ b/src/Anubis/Trading/Equity.cs @@ -55,7 +55,10 @@ public static class Returns public sealed class EquityBook(Database db, IClock clock, Ledger ledger, FxStore fx) { private sealed record Shot(string Scope, string World, Guid? AccountId, string? Strategy, string Currency, decimal Equity, decimal Cash, decimal Invested, decimal Flows, - decimal? FxEffect); + decimal? FxEffect) + { + public decimal? Benchmark { get; init; } + } public async Task TakeAsync(CancellationToken cancellationToken) { @@ -84,10 +87,13 @@ public sealed class EquityBook(Database db, IClock clock, Ledger ledger, FxStore } var rate = await UsdRateAsync(DateOnly.FromDateTime(now.UtcDateTime), cancellationToken).ConfigureAwait(false); - var flowRows = await db.ReadAsync(s => s.QueryAsync("SELECT account_id, kind, amount, currency, created_at FROM cash_ledger WHERE strategy IS NOT NULL", - r => (Account: r.Id("account_id"), Kind: r.Text("kind"), Amount: r.Money("amount"), Currency: r.Text("currency"), At: r.Moment("created_at"))), cancellationToken) + var flowRows = await db.ReadAsync(s => s.QueryAsync("SELECT account_id, strategy, kind, amount, currency, created_at FROM cash_ledger WHERE strategy IS NOT NULL", + r => (Account: r.Id("account_id"), Strategy: r.Text("strategy"), Kind: r.Text("kind"), Amount: r.Money("amount"), Currency: r.Text("currency"), At: r.Moment("created_at"))), cancellationToken) .ConfigureAwait(false); - foreach (var world in shots.Where(s => s.Scope == "account").GroupBy(s => s.World)) + Func? prices = null; + var pricesLoaded = false; + var today = DateOnly.FromDateTime(now.UtcDateTime); + foreach (var world in shots.Where(s => s.Scope == "account").GroupBy(s => s.World).ToList()) { var usd = world.Where(s => s.Currency == "USD").ToList(); if (usd.Count > 0 && rate is null) @@ -102,11 +108,33 @@ public sealed class EquityBook(Database db, IClock clock, Ledger ledger, FxStore usdFlows.Add((row.Amount, await UsdRateAsync(DateOnly.FromDateTime(row.At.UtcDateTime), cancellationToken).ConfigureAwait(false) ?? rate!.Value)); } + // The "senza bot" comparison gets the same flows, each on its day and in euro at that day's rate (SPEC 7.5). + var included = shots.Where(s => s.Scope == "strategy" && s.World == world.Key && !twins.Contains((s.Strategy!, s.AccountId!.Value))) + .Select(s => (s.AccountId!.Value, s.Strategy!)).ToHashSet(); + var dated = new List<(DateOnly Day, decimal AmountEur)>(); + foreach (var row in flowRows.Where(f => LedgerKinds.IsFlow(f.Kind) && included.Contains((f.Account, f.Strategy)))) + { + var day = DateOnly.FromDateTime(row.At.UtcDateTime); + var amount = row.Currency == "USD" + ? row.Amount / (await UsdRateAsync(day, cancellationToken).ConfigureAwait(false) ?? rate!.Value) + : row.Amount; + dated.Add((day, amount)); + } + + if (!pricesLoaded && dated.Count > 0) + { + pricesLoaded = true; + prices = await NoBot.PricesAsync(db, clock, dated.Min(d => d.Day), today, cancellationToken).ConfigureAwait(false); + } + + var benchmark = prices is null ? null : NoBot.Value(dated, prices, today); + decimal ToEur(Shot s, decimal value) => s.Currency == "USD" ? value / rate!.Value : value; var eurFlows = world.Where(s => s.Currency != "USD").Sum(s => s.Flows) + usdFlows.Sum(f => f.AmountUsd / f.Rate); shots.Add(new Shot("total", world.Key, null, null, "EUR", DbValues.Money(world.Sum(s => ToEur(s, s.Equity))), DbValues.Money(world.Sum(s => ToEur(s, s.Cash))), DbValues.Money(world.Sum(s => ToEur(s, s.Invested))), - DbValues.Money(eurFlows), usd.Count > 0 ? DbValues.Money(Returns.FxEffect(usdFlows, rate!.Value)) : null)); + DbValues.Money(eurFlows), usd.Count > 0 ? DbValues.Money(Returns.FxEffect(usdFlows, rate!.Value)) : null) + { Benchmark = benchmark }); } await db.WriteAsync(async s => @@ -119,10 +147,10 @@ public sealed class EquityBook(Database db, IClock clock, Ledger ledger, FxStore var peak = Math.Max(previous?.Peak ?? index, index); var drawdown = peak <= 0m ? 0m : Math.Round((index / peak - 1m) * 100m, 4, MidpointRounding.AwayFromZero); await s.ExecuteAsync( - "INSERT INTO equity_snapshots (id, taken_at, scope, account_id, strategy, equity, cash, invested, drawdown_pct, created_at, world, currency, flows, twr_index, peak_index, fx_effect) " + - "VALUES (@id, @now, @sc, @a, @st, @e, @c, @i, @d, @now, @w, @cur, @f, @x, @p, @fx)", cancellationToken, + "INSERT INTO equity_snapshots (id, taken_at, scope, account_id, strategy, equity, cash, invested, drawdown_pct, created_at, world, currency, flows, twr_index, peak_index, fx_effect, benchmark) " + + "VALUES (@id, @now, @sc, @a, @st, @e, @c, @i, @d, @now, @w, @cur, @f, @x, @p, @fx, @b)", cancellationToken, ("id", Ids.NewId(clock)), ("now", now), ("sc", shot.Scope), ("a", shot.AccountId), ("st", shot.Strategy), ("e", shot.Equity), ("c", shot.Cash), ("i", shot.Invested), - ("d", drawdown), ("w", shot.World), ("cur", shot.Currency), ("f", shot.Flows), ("x", index), ("p", peak), ("fx", shot.FxEffect)).ConfigureAwait(false); + ("d", drawdown), ("w", shot.World), ("cur", shot.Currency), ("f", shot.Flows), ("x", index), ("p", peak), ("fx", shot.FxEffect), ("b", shot.Benchmark)).ConfigureAwait(false); } }, cancellationToken).ConfigureAwait(false); return shots.Count; diff --git a/src/Anubis/Trading/NoBot.cs b/src/Anubis/Trading/NoBot.cs new file mode 100644 index 0000000..1bfe8b2 --- /dev/null +++ b/src/Anubis/Trading/NoBot.cs @@ -0,0 +1,113 @@ +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; + +namespace Anubis.Trading; + +/// +/// The "senza bot" comparison (SPEC 7.5): the same capital, with the same flows, put 40% in Bitcoin (BTC/EUR) and +/// 60% in the S&P 500 (SPY adjusted for dividends and splits, in euro at the ECB rate) and never touched. Every +/// deposit buys the two in that proportion on its day; a withdrawal sells both in the proportion they have reached. +/// Prices are the daily closes of the days before: a deposit on Tuesday buys at Monday's close, and the value on +/// Wednesday uses Tuesday's. A close is final only when its day is over, so the comparison moves once a day. +/// +public static class NoBot +{ + public const decimal BitcoinShare = 0.40m; + + public const decimal StockShare = 0.60m; + + public const string BitcoinSymbol = "BTC-EUR"; + + public const string StockSymbol = "SPY"; + + /// + /// The value in euro on of the untouched portfolio. Null when there are no flows or a + /// price is missing on a day that needs it: a comparison with a hole would not be honest. + /// + public static decimal? Value(IEnumerable<(DateOnly Day, decimal AmountEur)> flows, Func prices, DateOnly today) + { + ArgumentNullException.ThrowIfNull(flows); + ArgumentNullException.ThrowIfNull(prices); + decimal bitcoin = 0m, stock = 0m; + var any = false; + foreach (var (day, amount) in flows.Where(f => f.AmountEur != 0m).OrderBy(f => f.Day)) + { + if (prices(day) is not { Bitcoin: > 0m, Stock: > 0m } p) + { + return null; + } + + any = true; + if (amount > 0m) + { + bitcoin += BitcoinShare * amount / p.Bitcoin; + stock += StockShare * amount / p.Stock; + continue; + } + + var value = bitcoin * p.Bitcoin + stock * p.Stock; + var keep = value <= 0m ? 0m : Math.Max(0m, 1m + amount / value); + bitcoin *= keep; + stock *= keep; + } + + return any && prices(today) is { Bitcoin: > 0m, Stock: > 0m } now ? DbValues.Money(bitcoin * now.Bitcoin + stock * now.Stock) : null; + } + + /// + /// The daily closes the comparison needs, from the database: BTC-EUR on OKX, SPY on Alpaca with its corporate + /// actions, the ECB rate. Null when one of the series is missing (no Alpaca keys means no SPY history). + /// + public static async Task?> PricesAsync(Database db, IClock clock, DateOnly from, DateOnly to, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(db); + var catalog = new InstrumentCatalog(db, clock); + var bars = new BarStore(db, clock); + var btc = await catalog.FindAsync(Venues.Okx, BitcoinSymbol, cancellationToken).ConfigureAwait(false); + var spy = await catalog.FindAsync(Venues.Alpaca, StockSymbol, cancellationToken).ConfigureAwait(false); + if (btc is null || spy is null) + { + return null; + } + + // A week before the first flow: a deposit on a Monday uses Friday's close. + var start = from.AddDays(-10); + var bitcoin = (await bars.DailyAsync(btc.Id, start, to, cancellationToken).ConfigureAwait(false)).Select(b => (b.Day, Close: (decimal)b.Close)).ToList(); + var rawStock = await bars.DailyAsync(spy.Id, start, to, cancellationToken).ConfigureAwait(false); + var actions = await new CorporateActionStore(db, clock).ForSymbolAsync(StockSymbol, cancellationToken).ConfigureAwait(false); + var stock = rawStock.Count == 0 ? [] : Adjustments.Anchored(rawStock, actions, rawStock[^1].Day).Select(b => (b.Day, Close: (decimal)(b.Adjusted?.Close ?? b.Close))).ToList(); + var rates = await db.ReadAsync(s => s.QueryAsync("SELECT rate_date, rate FROM fx_rates WHERE base = 'EUR' AND quote = 'USD' AND rate_date >= @f AND rate_date <= @t ORDER BY rate_date", + r => (Day: BarStore.ParseDay(r.Text("rate_date")), Rate: r.Money("rate")), ("f", BarStore.DayText(start.AddDays(-10))), ("t", BarStore.DayText(to))), cancellationToken).ConfigureAwait(false); + if (bitcoin.Count == 0 || stock.Count == 0 || rates.Count == 0) + { + return null; + } + + var rateSeries = rates.Select(x => (x.Day, x.Rate)).ToList(); + return day => + { + var known = day.AddDays(-1); + var b = OnOrBefore(bitcoin, known); + var s = OnOrBefore(stock, known); + var r = OnOrBefore(rateSeries, known); + return b is null || s is null || r is not > 0m ? null : (b.Value, s.Value / r.Value); + }; + } + + private static decimal? OnOrBefore(List<(DateOnly Day, decimal Value)> series, DateOnly day) + { + decimal? found = null; + foreach (var (d, v) in series) + { + if (d > day) + { + break; + } + + found = v; + } + + return found; + } +} diff --git a/src/Anubis/Trading/OrderManager.cs b/src/Anubis/Trading/OrderManager.cs index ae01c7f..8c68e48 100644 --- a/src/Anubis/Trading/OrderManager.cs +++ b/src/Anubis/Trading/OrderManager.cs @@ -766,10 +766,25 @@ public sealed partial class OrderManager : IDisposable recorded++; var instrument = await _instruments(row.InstrumentId, cancellationToken).ConfigureAwait(false); - await _db.WriteAsync(s => Diary.WriteAsync(s, _clock, DiaryKinds.Orders, "fill", - string.Create(CultureInfo.InvariantCulture, - $"{(fill.Side == OrderSide.Buy ? "Comprati" : "Venduti")} {Format.Quantity(fill.Quantity)} {instrument?.Symbol} a {Format.Price(fill.Price)} su {_account.Name}."), - new { fill.ExecutionId, row.ClientOrderId, outcome.SlippageBp }, cancellationToken), cancellationToken).ConfigureAwait(false); + await _db.WriteAsync(async s => + { + // A sale that closes the trade says its result (appendix F.10: "Venduta 1 MSFT a 522,14 $: +9,84 $ in 3 giorni"). + ClosedTrade? closed = null; + if (outcome.TradeClosed && outcome.TradeId is { } tradeId) + { + var trade = await s.FirstOrDefaultAsync("SELECT realized, opened_at, closed_at FROM trades WHERE id = @id", + r => (Realized: r.Money("realized"), Opened: r.Moment("opened_at"), Closed: r.MomentOrNull("closed_at")), ("id", tradeId)).ConfigureAwait(false); + if (trade.Closed is { } closedAt) + { + closed = new ClosedTrade(trade.Realized, (DateOnly.FromDateTime(closedAt.UtcDateTime).DayNumber - DateOnly.FromDateTime(trade.Opened.UtcDateTime).DayNumber)); + } + } + + var reason = fill.Side == OrderSide.Sell && row.Purpose is OrderPurpose.Stop or OrderPurpose.Protective ? ReasonCatalog.Text("stop") : null; + await Diary.WriteAsync(s, _clock, DiaryKinds.Orders, "fill", + DiaryText.Fill(fill.Side, fill.Quantity, instrument?.Symbol ?? "?", instrument?.IsCrypto ?? false, fill.Price, _account.Currency, reason, closed), + new { fill.ExecutionId, row.ClientOrderId, outcome.SlippageBp, outcome.TradeId, Account = _account.Name }, cancellationToken).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); if (row.Purpose == OrderPurpose.Stop && outcome.Quantity > 0m && instrument is not null) { // A stop that fired only in part, or one of Alpaca's two stops: the rest is sold at once (SPEC 7.2). diff --git a/src/Anubis/Trading/ReasonCatalog.cs b/src/Anubis/Trading/ReasonCatalog.cs new file mode 100644 index 0000000..d1227bd --- /dev/null +++ b/src/Anubis/Trading/ReasonCatalog.cs @@ -0,0 +1,83 @@ +namespace Anubis.Trading; + +/// +/// The fixed sentences of the reason codes of the decisions table (SPEC 5.2): the "why" card of a trade and the +/// diary use these, never free text written at decision time. An unknown code is shown as it is, so nothing is ever +/// hidden. +/// +public static class ReasonCatalog +{ + private static readonly Dictionary Texts = new(StringComparer.Ordinal) + { + // Strategies. + ["trend_entry"] = "La chiusura ha superato i massimi recenti su almeno un orizzonte: è iniziata una tendenza al rialzo.", + ["trend_increase"] = "Più orizzonti erano d'accordo sulla tendenza: il peso è salito.", + ["trend_reduce"] = "La tendenza si è indebolita, o la moneta è diventata più agitata: il peso è sceso.", + ["trend_exit"] = "La tendenza si è interrotta: il prezzo è finito sotto lo stop mobile.", + ["trend_stop"] = "Lo stop mobile è salito con il prezzo.", + ["momentum_entry"] = "Era tra i titoli più forti degli ultimi mesi, con il mercato in salita.", + ["momentum_increase"] = "Il peso obiettivo è salito alla revisione settimanale.", + ["momentum_reduce"] = "Il peso obiettivo è sceso alla revisione settimanale.", + ["momentum_exit_rank"] = "Non era più tra i 30 titoli più forti.", + ["momentum_exit_trend"] = "Il mercato nel suo insieme è girato al ribasso: niente più azioni.", + ["momentum_stop"] = "Lo stop di protezione è stato aggiornato.", + ["meanrev_entry"] = "Era sceso per qualche seduta di fila ma restava sopra la sua media a 200 giorni: un ribasso breve di un titolo che nel lungo periodo sale.", + ["meanrev_exit_average"] = "Il prezzo è tornato sopra la media a 5 giorni: il rimbalzo cercato è arrivato.", + ["meanrev_exit_rsi"] = "L'indicatore di forza è tornato alto: il rimbalzo è avvenuto.", + ["meanrev_exit_earnings"] = "Uscita prima della trimestrale.", + ["meanrev_exit_time"] = "Tempo scaduto: nessun rimbalzo in 5 sedute.", + // Exits recorded on the trade. + ["stop"] = "Stop di protezione raggiunto.", + ["exit"] = "Uscita decisa dalla strategia.", + ["signal"] = "Uscita sul segnale della strategia.", + ["residue"] = "Resto troppo piccolo per essere venduto, tolto dal registro.", + ["adjustment"] = "Rettifica dopo l'allineamento con il conto.", + // Correctives. + ["crypto_regime_below_average"] = "Il mercato crypto era sotto la sua media: acquisti ridotti.", + ["crypto_regime_high_volatility"] = "Il mercato crypto era molto agitato: acquisti ridotti.", + ["calendar_event"] = "Un dato economico importante era vicino: niente nuove posizioni in quell'ora.", + // Risk. + ["risk_reduction"] = "Ordine rimpicciolito dai limiti di rischio.", + ["daily_loss_block"] = "Perdita del giorno oltre il limite: niente nuovi ingressi per 24 ore.", + ["switch_tripped"] = "Interruttore scattato: il bot aspetta la tua conferma.", + ["bot_paused"] = "Bot in pausa: niente nuovi ingressi.", + ["bot_stopped"] = "Bot fermato con \"Ferma tutto\".", + ["invested_limit"] = "Capitale investito al limite: niente soldi presi in prestito.", + ["position_limit"] = "Ridotto al peso massimo di una posizione.", + ["crypto_limit"] = "Quota delle crypto sul totale al limite.", + ["trade_risk_limit"] = "Ridotto perché il rischio dell'operazione restasse entro il limite.", + ["stop_above_price"] = "Stop sopra il prezzo: ordine rifiutato.", + ["stale_price"] = "Prezzo troppo vecchio: niente acquisti finché i dati non tornano freschi.", + ["price_gap"] = "Prezzo dell'ordine troppo lontano dall'ultimo prezzo.", + ["clock_skew"] = "Orologio non allineato con quello del broker.", + ["owned_by_other_strategy"] = "La posizione appartiene a un'altra strategia.", + ["no_short_selling"] = "Niente vendite allo scoperto: venduto solo quanto posseduto.", + ["no_leverage"] = "Niente leva: l'ordine sta nella liquidità disponibile.", + ["not_owned_by_bot"] = "La posizione non è del bot: non la tocca.", + ["live_not_confirmed"] = "Soldi veri non confermati per questa strategia.", + ["exit_only"] = "Strategia in sola uscita: niente nuovi acquisti.", + ["live_not_allowed"] = "Soldi veri non permessi dalla configurazione d'avvio.", + ["observation"] = "Strategia in osservazione: produce segnali, nessun ordine.", + ["orders_per_minute"] = "Troppi ordini in un minuto: il bot si è fermato.", + ["pdt_guard"] = "Guardia sulle operazioni in giornata: niente posizioni in più oggi.", + ["no_fx_rate"] = "Manca il cambio euro-dollaro: niente acquisti in dollari.", + ["unknown_instrument"] = "Strumento sconosciuto.", + ["unknown_symbol"] = "Strumento sconosciuto.", + // Orders. + ["zero_quantity"] = "Quantità troppo piccola: nessun ordine.", + ["below_min_size"] = "Sotto la quantità minima del broker: nessun ordine.", + ["below_min_notional"] = "Sotto l'importo minimo del broker: nessun ordine.", + ["no_price"] = "Nessun prezzo recente: nessun ordine.", + ["instrument_not_live"] = "Lo strumento non si può negoziare in questo momento.", + ["account_prudent"] = "Conto in modalità prudente: niente nuovi ingressi.", + ["not_ours"] = "L'ordine non è del bot: non lo tocca.", + ["no_cash"] = "Liquidità insufficiente per l'acquisto.", + ["stop_gap"] = "Il prezzo ha aperto sotto lo stop: venduto all'apertura.", + ["residue_written_off"] = "Resto troppo piccolo per essere venduto, tolto dal registro.", + ["dividend"] = "Dividendo accreditato.", + }; + + public static string Text(string code) => Texts.TryGetValue(code, out var text) ? text : code; + + public static bool Has(string code) => Texts.ContainsKey(code); +} diff --git a/tests/Anubis.Tests/DiaryTests.cs b/tests/Anubis.Tests/DiaryTests.cs new file mode 100644 index 0000000..a7256c3 --- /dev/null +++ b/tests/Anubis.Tests/DiaryTests.cs @@ -0,0 +1,136 @@ +using System.Reflection; +using Anubis.Core; +using Anubis.Data; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// The diary from reason codes and the "senza bot" comparison (issue #50, SPEC 5.2, 7.5, appendix B and F.10). +[TestClass] +public sealed class DiaryTests +{ + private static readonly CancellationToken _none = CancellationToken.None; + + // The appendix writes plain spaces; the bot puts a non-breaking one between a number and its currency. + private static string Plain(string text) => text.Replace(' ', ' '); + + [TestMethod] + public void TheTemplatesWriteTheSentencesOfTheAppendix() + { + Assert.AreEqual("Alzato lo stop di BTC/EUR da 65.400 € a 66.180 €. Lo stop segue il prezzo quando sale.", + Plain(DiaryText.StopRaised("BTC-EUR", 65400m, 66180m, "EUR"))); + Assert.AreEqual( + "Chiusura giornaliera crypto: nessun cambio. BTC, ETH e SOL restano in tendenza. Le altre 7 monete restano fuori: nessuna ha segnato nuovi massimi.", + DiaryText.CryptoClose(new DecisionSummary([], [], [], [], ["BTC-EUR", "ETH-EUR", "SOL-EUR"], 7))); + Assert.AreEqual("Venduta 1 MSFT a 522,14 $: +9,84 $ in 3 giorni.", + Plain(DiaryText.Fill(OrderSide.Sell, 1m, "MSFT", crypto: false, 522.14m, "USD", closed: new ClosedTrade(9.84m, 3)))); + Assert.AreEqual("Comprate 2 AAPL a 259,80 $. Mean reversion: tre sedute di ribasso, titolo sopra la media a 200 giorni.", + Plain(DiaryText.Fill(OrderSide.Buy, 2m, "AAPL", crypto: false, 259.80m, "USD", "Mean reversion: tre sedute di ribasso, titolo sopra la media a 200 giorni."))); + Assert.AreEqual("Rimessi 6 stop giornalieri sulle frazioni di azione.", DiaryText.StopsReplaced(6)); + Assert.AreEqual("Azioni: nessun nuovo acquisto. AAPL resta aperta.", DiaryText.StockSignals(new DecisionSummary([], [], [], [], ["AAPL"], 0))); + + // Changes, coins and agreement. + Assert.AreEqual("Chiusura giornaliera crypto: compro ETH, vendo SOL. BTC resta in tendenza. Le altre 7 monete restano fuori: nessuna ha segnato nuovi massimi.", + DiaryText.CryptoClose(new DecisionSummary(["ETH-EUR"], [], [], ["SOL-EUR"], ["BTC-EUR"], 7))); + Assert.AreEqual("Azioni: domani compro AAPL e MSFT, vendo JPM.", DiaryText.StockSignals(new DecisionSummary(["AAPL", "MSFT"], [], [], ["JPM"], [], 0))); + Assert.AreEqual("Comprati 0,0512 BTC/EUR a 66.180,00 €.", Plain(DiaryText.Fill(OrderSide.Buy, 0.0512m, "BTC-EUR", crypto: true, 66180m, "EUR"))); + Assert.AreEqual("Venduto 1 ETH/EUR a 3.010,50 €: −42,10 € in giornata. Stop di protezione raggiunto.", + Plain(DiaryText.Fill(OrderSide.Sell, 1m, "ETH-EUR", crypto: true, 3010.50m, "EUR", ReasonCatalog.Text("stop"), new ClosedTrade(-42.10m, 0)))); + Assert.AreEqual("Trend crypto, in osservazione: avrei comprato BTC/EUR. Nessun ordine: registro solo il segnale.", + DiaryText.Observed(StrategyNames.CryptoTrend, new DecisionSummary(["BTC-EUR"], [], [], [], [], 0))); + Assert.AreEqual("3 ore", DiaryText.Duration(TimeSpan.FromHours(3))); + Assert.AreEqual("20 ore e 5 minuti", DiaryText.Duration(new TimeSpan(20, 5, 0))); + Assert.AreEqual("3 giorni", DiaryText.Duration(TimeSpan.FromDays(3))); + Assert.AreEqual("1 giorno e 1 ora", DiaryText.Duration(TimeSpan.FromHours(25))); + + // No jargon and no exclamation marks (appendix B). + foreach (var sentence in new[] { DiaryText.Absence(TimeSpan.FromHours(20)), DiaryText.EntryDropped("AAPL", 1.4m, 1m), DiaryText.NoData(StrategyNames.EquityMomentum, "le barre di chiusura") }) + { + Assert.DoesNotContain("!", sentence); + Assert.DoesNotContain("stop loss", sentence, StringComparison.OrdinalIgnoreCase); + } + } + + [TestMethod] + public void EveryReasonCodeHasItsSentence() + { + // Every code a strategy, a corrective, the risk engine or the order rules can write: the diary never shows a bare code. + var holders = typeof(DiaryText).Assembly.GetTypes().Where(t => t.Name == "Reasons" || (t.Name.EndsWith("Reasons", StringComparison.Ordinal) && t.IsAbstract && t.IsSealed)); + var codes = holders.SelectMany(t => t.GetFields(BindingFlags.Public | BindingFlags.Static)) + .Where(f => f.IsLiteral && f.FieldType == typeof(string) && !f.Name.EndsWith("Prefix", StringComparison.Ordinal)) + .Select(f => (string)f.GetRawConstantValue()!) + .ToList(); + Assert.IsGreaterThan(40, codes.Count, "The reason classes were found."); + var missing = codes.Where(c => !ReasonCatalog.Has(c)).ToList(); + Assert.IsEmpty(missing, "Codes without a sentence: " + string.Join(", ", missing)); + Assert.IsTrue(codes.All(c => !ReasonCatalog.Text(c).Contains('!', StringComparison.Ordinal))); + } + + [TestMethod] + public void TheComparisonInvestsEveryFlowOnItsDayAndNeverTouchesIt() + { + var d1 = new DateOnly(2026, 1, 5); + var d2 = new DateOnly(2026, 2, 2); + var d3 = new DateOnly(2026, 3, 2); + var prices = new Dictionary + { + [d1] = (50000m, 500m), + [d2] = (60000m, 500m), + [d3] = (60000m, 550m), + }; + (decimal Bitcoin, decimal Stock)? At(DateOnly day) => prices.TryGetValue(day, out var p) ? p : null; + + // 10,000 € on day 1: 4,000 in Bitcoin, 6,000 in the S&P 500. Bitcoin +20%: 4,800 + 6,000. + Assert.AreEqual(10800m, NoBot.Value([(d1, 10000m)], At, d2)); + + // A deposit of 1,000 € on day 2 buys at day 2's prices: it is not a gain. S&P +10% on day 3. + // Units: 0.08 + 0.0066667 BTC = 0.0866667 × 60,000 = 5,200; 12 + 1.2 SPY = 13.2 × 550 = 7,260. + Assert.AreEqual(12460m, NoBot.Value([(d1, 10000m), (d2, 1000m)], At, d3)); + + // A withdrawal sells both in the proportion they reached: half of 10,800 out leaves 5,400, then S&P +10%. + Assert.AreEqual(5700m, NoBot.Value([(d1, 10000m), (d2, -5400m)], At, d3)); + + // No flows, or a missing price: no comparison rather than a wrong one. + Assert.IsNull(NoBot.Value([], At, d3)); + Assert.IsNull(NoBot.Value([(new DateOnly(2025, 12, 1), 10000m)], At, d3)); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task ThePhotographOfTheTotalCarriesTheComparisonOnlyWithBothSeries() + { + await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); + var fx = new FxStore(rig.Db, rig.Clock); + var okx = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false); + await rig.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at, share) VALUES (@id, @s, @a, 'observation', 0, @j, @now, @now, 1)", + _none, ("id", Ids.NewId(rig.Clock)), ("s", StrategyNames.CryptoTrend), ("a", okx.AccountId), ("j", new Anubis.Db.DbJson("{}")), ("now", rig.Clock.UtcNow)), _none).ConfigureAwait(false); + var today = DateOnly.FromDateTime(rig.Clock.UtcNow.UtcDateTime); + var capital = new Capital(rig.Db, rig.Clock, rig.Ledger, fx); + await fx.UpsertAsync([new FxRate("EUR", "USD", today.AddDays(-3), 1.10m, "ecb")], _none).ConfigureAwait(false); + await capital.SetAsync(Venues.Okx, 10000m, "test", _none).ConfigureAwait(false); + var book = new EquityBook(rig.Db, rig.Clock, rig.Ledger, fx); + + // Without the SPY history (no Alpaca keys) there is no comparison: null, never a half one. + await book.TakeAsync(_none).ConfigureAwait(false); + Assert.IsNull(await BenchmarkAsync(rig).ConfigureAwait(false)); + + // With both: BTC-EUR on OKX, SPY on Alpaca in dollars at 1.10 $/€. + var btc = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false); + var spy = await rig.InstrumentAsync(TradingRig.Stock("SPY")).ConfigureAwait(false); + var bars = new BarStore(rig.Db, rig.Clock); + await bars.UpsertDailyAsync(btc.Id, [new DailyBar(today.AddDays(-1), 50000, 50000, 50000, 50000, 1)], "test", _none).ConfigureAwait(false); + await bars.UpsertDailyAsync(spy.Id, [new DailyBar(today.AddDays(-1), 550, 550, 550, 550, 1)], "test", _none).ConfigureAwait(false); + rig.Clock.Advance(TimeSpan.FromMinutes(5)); + await book.TakeAsync(_none).ConfigureAwait(false); + Assert.AreEqual(10000m, await BenchmarkAsync(rig).ConfigureAwait(false), "Invested today at today's prices: worth what was put in."); + + // The next day Bitcoin is up 10%: 4,000 € become 4,400 €. + rig.Clock.Advance(TimeSpan.FromDays(1)); + await bars.UpsertDailyAsync(btc.Id, [new DailyBar(today, 55000, 55000, 55000, 55000, 1)], "test", _none).ConfigureAwait(false); + await book.TakeAsync(_none).ConfigureAwait(false); + Assert.AreEqual(10400m, await BenchmarkAsync(rig).ConfigureAwait(false)); + } + + private static async Task BenchmarkAsync(TradingRig rig) => + (await rig.QueryAsync("SELECT benchmark FROM equity_snapshots WHERE scope = 'total' ORDER BY taken_at DESC, id DESC LIMIT 1", r => r.MoneyOrNull("benchmark")).ConfigureAwait(false))[0]; +} From 41e067e7d17d0e43b0375f03d694cbacb733e6ac Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 11 Nov 2026 18:28:08 +0100 Subject: [PATCH 02/12] Run the strategies live in simulation with the live engine (refs #47) The live engine makes each decision at its time of SPEC 5.5 through the same DecideOnce call the backtest uses, so live and backtest cannot drift: the crypto close at 00:05 UTC, the stock signals 20 minutes after the close, the meanrev exits 5 minutes before it, the stock orders and the daily stops at the open. Each decision has a run key written in the same transaction as its decision rows, planned orders and diary lines, and each planned order's id gives the order key, so a restart never decides or sends anything twice. Entries recovered late are dropped when the price has moved too far. The engine runs from the scheduler once the accounts are reconciled. The IEX stream follows held stocks, planned orders and SPY during the session, and the stock simulator's day orders now expire at the close. Tests: parity with the backtest for crypto_trend (40 days) and equity_meanrev (6 weeks), and a 14-day run with the network down, a lost answer, a restart mid-order and the database unreachable, ending reconciled with no duplicate orders, on SQLite and PostgreSQL. Co-Authored-By: Claude Opus 5.5 --- src/Anubis/Backtest/Engine.cs | 10 +- src/Anubis/Core/Scheduling.cs | 10 +- src/Anubis/Data/MarketDataService.cs | 87 +- src/Anubis/Db/Database.cs | 27 + src/Anubis/Db/Migrations/0006_live.sql | 65 ++ src/Anubis/Trading/Capital.cs | 3 + src/Anubis/Trading/DiaryText.cs | 3 + src/Anubis/Trading/LiveEngine.cs | 1171 ++++++++++++++++++++++++ src/Anubis/Trading/ReasonCatalog.cs | 9 + src/Anubis/Trading/TradingService.cs | 33 + tests/Anubis.Tests/LiveEngineTests.cs | 156 ++++ tests/Anubis.Tests/LiveStockSupport.cs | 217 +++++ tests/Anubis.Tests/LiveSupport.cs | 287 ++++++ 13 files changed, 2073 insertions(+), 5 deletions(-) create mode 100644 src/Anubis/Db/Migrations/0006_live.sql create mode 100644 src/Anubis/Trading/LiveEngine.cs create mode 100644 tests/Anubis.Tests/LiveEngineTests.cs create mode 100644 tests/Anubis.Tests/LiveStockSupport.cs create mode 100644 tests/Anubis.Tests/LiveSupport.cs diff --git a/src/Anubis/Backtest/Engine.cs b/src/Anubis/Backtest/Engine.cs index ad10bc4..bfffa01 100644 --- a/src/Anubis/Backtest/Engine.cs +++ b/src/Anubis/Backtest/Engine.cs @@ -162,9 +162,12 @@ public static class BacktestEngine /// /// One decision cycle from a recorded book (SPEC 12.1, 12.3): the strategy decides on the close of - /// with the data known then and the book given, and nothing else runs. + /// with the data known then and the book given, and nothing else runs. The live engine + /// decides with this same call (SPEC 5.2): is the strategy's equity at each close up to + /// , which the risk stage walks as it does in a whole run. /// - public static DecisionRecord DecideOnce(IStrategy strategy, BacktestDataset data, PortfolioState state, DateOnly day, BacktestOptions? options = null) + public static DecisionRecord DecideOnce(IStrategy strategy, BacktestDataset data, PortfolioState state, DateOnly day, BacktestOptions? options = null, + IReadOnlyList? history = null) { ArgumentNullException.ThrowIfNull(strategy); ArgumentNullException.ThrowIfNull(data); @@ -172,6 +175,7 @@ public static class BacktestEngine CheckSchedule(strategy); var simulation = new Simulation(strategy, data.Through(day), options ?? new BacktestOptions(), state); simulation.MarkThrough(day); + simulation.SeedHistory(history ?? []); return simulation.Decide(day, data.SessionTimes(day).Closes); } @@ -263,6 +267,8 @@ public static class BacktestEngine } } + public void SeedHistory(IReadOnlyList history) => _history.AddRange(history); + public void MarkThrough(DateOnly day) { foreach (var i in _data.Instruments) diff --git a/src/Anubis/Core/Scheduling.cs b/src/Anubis/Core/Scheduling.cs index 6ca717e..40b371c 100644 --- a/src/Anubis/Core/Scheduling.cs +++ b/src/Anubis/Core/Scheduling.cs @@ -118,6 +118,9 @@ public sealed record ScheduledJob(string Name, string Description, Schedule Sche /// skipped and reported instead of executed blindly (trap 21, SPEC 5.6). /// public TimeSpan MaxLateness { get; init; } = TimeSpan.FromMinutes(15); + + /// A move of the bot the user reads in "Prossime mosse" (SPEC 13.6), not a housekeeping job. + public bool IsMove { get; init; } } public enum JobOutcome @@ -131,7 +134,10 @@ public enum JobOutcome public sealed record JobRun(string Name, DateTimeOffset DueUtc, DateTimeOffset StartedUtc, DateTimeOffset FinishedUtc, JobOutcome Outcome, string? Error); /// A run coming up, for "Prossime mosse" and the jobs list. -public sealed record UpcomingRun(string Name, string Description, DateTimeOffset DueUtc); +public sealed record UpcomingRun(string Name, string Description, DateTimeOffset DueUtc) +{ + public bool IsMove { get; init; } +} /// /// Runs jobs at fixed times, at intervals, or relative to market open and close (SPEC 5.5). @@ -164,7 +170,7 @@ public sealed partial class Scheduler(IClock clock, EventBus bus, ILogger j.Due is not null) .OrderBy(j => j.Due) .Take(count) - .Select(j => new UpcomingRun(j.Job.Name, j.Job.Description, j.Due!.Value)) + .Select(j => new UpcomingRun(j.Job.Name, j.Job.Description, j.Due!.Value) { IsMove = j.Job.IsMove }) .ToList(); } } diff --git a/src/Anubis/Data/MarketDataService.cs b/src/Anubis/Data/MarketDataService.cs index cace228..fb3b492 100644 --- a/src/Anubis/Data/MarketDataService.cs +++ b/src/Anubis/Data/MarketDataService.cs @@ -130,7 +130,8 @@ public sealed partial class MarketDataService : IDisposable { await UsCalendar.LoadAsync(cancellationToken).ConfigureAwait(false); _work.Release(); - await Task.WhenAll(WorkerAsync(cancellationToken), LiveAsync(cancellationToken), FreshnessAsync(cancellationToken)).ConfigureAwait(false); + await Task.WhenAll(WorkerAsync(cancellationToken), LiveAsync(cancellationToken), StockLiveAsync(cancellationToken), FreshnessAsync(cancellationToken)) + .ConfigureAwait(false); } public Task WakeWorker() @@ -491,6 +492,90 @@ public sealed partial class MarketDataService : IDisposable } } + /// + /// The stock feed (IEX, issue #47): during the US session only, the stocks held, those with an order planned and the + /// market index, at most symbols as the free feed allows. Outside the session the + /// quotes come by REST when asked, and no stock is followed for freshness. + /// + private async Task StockLiveAsync(CancellationToken cancellationToken) + { + while (!cancellationToken.IsCancellationRequested) + { + try + { + var now = _clock.UtcNow; + var today = DateOnly.FromDateTime(now.UtcDateTime); + var session = UsCalendar.Sessions(today.AddDays(-1), today.AddDays(10)).FirstOrDefault(s => s.CloseUtc + StockStreamMargin > now); + if (session is null || session.OpenUtc - StockStreamMargin > now) + { + var next = session is null ? now.AddHours(1) : Min(session.OpenUtc - StockStreamMargin, now.AddHours(1)); + await _clock.WaitUntilAsync(next, cancellationToken).ConfigureAwait(false); + continue; + } + + var alpaca = await AlpacaAsync(cancellationToken).ConfigureAwait(false); + var instruments = alpaca is null ? [] : await StockLiveInstrumentsAsync(cancellationToken).ConfigureAwait(false); + if (alpaca is null || instruments.Count == 0) + { + await _clock.WaitUntilAsync(now.AddMinutes(5), cancellationToken).ConfigureAwait(false); + continue; + } + + var end = session.CloseUtc + StockStreamMargin; + using var round = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + var collector = new MarketCollector(alpaca, _db, _clock, _bus, Freshness, logger: _logger); + var run = collector.RunLiveAsync(instruments, round.Token); + var ids = instruments.Select(i => i.Id).ToHashSet(); + while (!run.IsCompleted) + { + using var nap = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + var wait = _clock.WaitUntilAsync(Min(_clock.UtcNow.AddMinutes(5), end), nap.Token); + await Task.WhenAny(run, wait).ConfigureAwait(false); + await nap.CancelAsync().ConfigureAwait(false); + if (!run.IsCompleted && (_clock.UtcNow >= end + || !(await StockLiveInstrumentsAsync(cancellationToken).ConfigureAwait(false)).Select(i => i.Id).ToHashSet().SetEquals(ids))) + { + await round.CancelAsync().ConfigureAwait(false); + } + } + + await run.ConfigureAwait(false); + foreach (var id in ids) + { + Freshness.Unfollow(id); + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + break; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + LogStepFailed(_logger, ex, "live azioni"); + await _clock.WaitUntilAsync(_clock.UtcNow.AddMinutes(1), cancellationToken).ConfigureAwait(false); + } + } + } + + /// The free IEX feed follows at most 30 symbols. + public const int StockStreamLimit = 30; + + private static readonly TimeSpan StockStreamMargin = TimeSpan.FromMinutes(5); + + private static DateTimeOffset Min(DateTimeOffset a, DateTimeOffset b) => a <= b ? a : b; + + private async Task> StockLiveInstrumentsAsync(CancellationToken cancellationToken) + { + var symbols = await _db.ReadAsync(s => s.QueryAsync( + "SELECT DISTINCT i.symbol FROM instruments i WHERE i.venue = @v AND (i.symbol = @m" + + " OR i.id IN (SELECT instrument_id FROM positions WHERE quantity <> 0)" + + " OR i.id IN (SELECT instrument_id FROM planned_orders WHERE status = @p)) ORDER BY i.symbol", + r => r.Text("symbol"), ("v", Venues.Alpaca), ("m", Trading.StrategyNames.MarketSymbol), ("p", "pending")), cancellationToken).ConfigureAwait(false); + var wanted = symbols.OrderBy(s => s == Trading.StrategyNames.MarketSymbol ? 0 : 1).ThenBy(s => s, StringComparer.Ordinal).Take(StockStreamLimit).ToHashSet(StringComparer.Ordinal); + var all = await _catalog.ListAsync(Venues.Alpaca, cancellationToken).ConfigureAwait(false); + return all.Where(i => wanted.Contains(i.Symbol) && i.IsLive).ToList(); + } + private async Task> LiveInstrumentsAsync(CancellationToken cancellationToken) { var today = DateOnly.FromDateTime(_clock.UtcNow.UtcDateTime); diff --git a/src/Anubis/Db/Database.cs b/src/Anubis/Db/Database.cs index 2da0f35..dc75d8b 100644 --- a/src/Anubis/Db/Database.cs +++ b/src/Anubis/Db/Database.cs @@ -117,8 +117,16 @@ public sealed class Database : IAsyncDisposable return builder.ToString(); } + /// Fault tests only (issue #47): while true every new connection fails as if the server could not be reached. + internal bool Unreachable { get; set; } + public async Task OpenConnectionAsync(CancellationToken cancellationToken) { + if (Unreachable) + { + throw new DatabaseUnreachableException(); + } + if (_postgres is not null) { return await _postgres.OpenConnectionAsync(cancellationToken).ConfigureAwait(false); @@ -239,6 +247,25 @@ public sealed class Database : IAsyncDisposable } /// One open transaction. Parameters are named @name on both engines. +/// The database could not be reached (fault tests). +public sealed class DatabaseUnreachableException : DbException +{ + public DatabaseUnreachableException() + : base("Database non raggiungibile.") + { + } + + public DatabaseUnreachableException(string message) + : base(message) + { + } + + public DatabaseUnreachableException(string message, Exception innerException) + : base(message, innerException) + { + } +} + public sealed class DbSession(DbEngine engine, DbConnection connection, DbTransaction transaction) { public DbEngine Engine => engine; diff --git a/src/Anubis/Db/Migrations/0006_live.sql b/src/Anubis/Db/Migrations/0006_live.sql new file mode 100644 index 0000000..dc3cdea --- /dev/null +++ b/src/Anubis/Db/Migrations/0006_live.sql @@ -0,0 +1,65 @@ +-- Phase 6 schema (SPEC 5.5, 5.6, 9.3, 9.4, 14, ADR 0012): the live engine, recovery after an absence, Telegram. + +-- One row for each decision the live engine makes: run_key names the strategy and the close it decides on, so a +-- decision is made once even across restarts. The row is written in the same transaction as its planned orders, +-- its decision rows and its diary lines: either all of it exists or none. state is the book the strategy decided +-- from, for the one-step comparison of SPEC 12.3 the next day. +CREATE TABLE engine_runs ( + id {uuid} PRIMARY KEY, + strategy TEXT NOT NULL, + run_key TEXT NOT NULL UNIQUE, + decision_day TEXT NOT NULL, + decision_id {uuid} NOT NULL, + mode TEXT NOT NULL, + state {json}, + proposed {json}, + created_at {timestamp} NOT NULL +){strict}; + +CREATE INDEX engine_runs_strategy ON engine_runs (strategy, decision_day); + +-- Orders decided and not yet handed to the order manager (SPEC 5.5: the stock orders decided after the close go at +-- the next open; SPEC 5.6: an entry has a deadline and a reference price it must not drift from). The planned +-- order's id is the decision id of the trade intent: the order key derives from it, so a restart that finds the +-- execution already there never sends it twice. +CREATE TABLE planned_orders ( + id {uuid} PRIMARY KEY, + decision_id {uuid} NOT NULL, + strategy TEXT NOT NULL, + account_id {uuid} NOT NULL REFERENCES accounts (id), + instrument_id {uuid} NOT NULL REFERENCES instruments (id), + side TEXT NOT NULL, + purpose TEXT NOT NULL, + quantity {money} NOT NULL, + exit_all {bool} NOT NULL, + stop_level {money}, + stop_offset {money}, + reference_price {money} NOT NULL, + reason TEXT NOT NULL, + due_at {timestamp} NOT NULL, + valid_until {timestamp}, + status TEXT NOT NULL, + outcome TEXT, + execution_id {uuid}, + created_at {timestamp} NOT NULL, + updated_at {timestamp} NOT NULL +){strict}; + +CREATE INDEX planned_orders_due ON planned_orders (status, due_at); + +-- Absences (SPEC 5.6): measured at the restart from the last heartbeat. One longer than 24 hours is declared on the +-- Panoramica until the user acknowledges it. +CREATE TABLE absences ( + id {uuid} PRIMARY KEY, + started_at {timestamp} NOT NULL, + ended_at {timestamp} NOT NULL, + acknowledged_at {timestamp}, + created_at {timestamp} NOT NULL +){strict}; + +-- Every notification has its state (SPEC 14): pending, sent or failed, with the attempts and the last error. +ALTER TABLE notifications ADD COLUMN attempts INTEGER; +ALTER TABLE notifications ADD COLUMN next_attempt_at {timestamp}; +ALTER TABLE notifications ADD COLUMN last_error TEXT; + +CREATE INDEX notifications_status ON notifications (status, created_at); diff --git a/src/Anubis/Trading/Capital.cs b/src/Anubis/Trading/Capital.cs index 1aa5df5..21aa684 100644 --- a/src/Anubis/Trading/Capital.cs +++ b/src/Anubis/Trading/Capital.cs @@ -11,6 +11,9 @@ public static class StrategyNames public const string EquityMomentum = "equity_momentum"; public const string EquityMeanrev = "equity_meanrev"; + /// The market filter of the stock strategies (SPEC 8.2): read, never traded unless it is in the universe. + public const string MarketSymbol = "SPY"; + public static readonly IReadOnlyList<(string Name, string Broker, decimal Share)> Base = [ (CryptoTrend, Venues.Okx, 1m), diff --git a/src/Anubis/Trading/DiaryText.cs b/src/Anubis/Trading/DiaryText.cs index eea8cbd..c1103e7 100644 --- a/src/Anubis/Trading/DiaryText.cs +++ b/src/Anubis/Trading/DiaryText.cs @@ -81,6 +81,9 @@ public static class DiaryText public static string StopRaised(string symbol, decimal from, decimal to, string currency) => $"Alzato lo stop di {Shown(symbol)} da {Level(from, currency)} a {Level(to, currency)}. Lo stop segue il prezzo quando sale."; + public static string StopLowered(string symbol, decimal from, decimal to, string currency) => + $"Spostato lo stop di {Shown(symbol)} da {Level(from, currency)} a {Level(to, currency)}."; + public static string StopsReplaced(int count) => count == 1 ? "Rimesso 1 stop giornaliero sulle frazioni di azione." : $"Rimessi {count} stop giornalieri sulle frazioni di azione."; diff --git a/src/Anubis/Trading/LiveEngine.cs b/src/Anubis/Trading/LiveEngine.cs new file mode 100644 index 0000000..27b2cdc --- /dev/null +++ b/src/Anubis/Trading/LiveEngine.cs @@ -0,0 +1,1171 @@ +using System.Globalization; +using System.Text.Json; +using Anubis.Backtest; +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; +using Anubis.Risk; +using Anubis.Strategies; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; + +namespace Anubis.Trading; + +/// Reason codes of the live engine (SPEC 5.5, 5.6). +public static class LiveReasons +{ + public const string LateExitsOnly = "late_exits_only"; + public const string EntryExpired = "entry_expired"; + public const string PriceMoved = "price_moved"; + public const string MissingBars = "missing_bars"; + public const string Superseded = "superseded"; + public const string OrderInProgress = "order_in_progress"; + public const string NothingHeld = "nothing_held"; + public const string Recovered = "recovered"; +} + +/// States of a planned order. +public static class PlannedStates +{ + public const string Pending = "pending"; + public const string Submitted = "submitted"; + public const string Refused = "refused"; + public const string Expired = "expired"; + public const string Dropped = "dropped"; + public const string Superseded = "superseded"; +} + +/// Modes of a live decision. +public static class DecisionModes +{ + public const string Full = "full"; + public const string ExitsOnly = "exits_only"; + public const string Observation = "observation"; + public const string NoData = "no_data"; +} + +/// The times of SPEC 5.5 and the limits of SPEC 5.6. +public sealed record LiveEngineOptions +{ + /// The daily crypto close: 00:05 UTC. + public TimeOnly CryptoDecision { get; init; } = new(0, 5); + + /// A crypto decision is valid until 12:00 UTC of the same day; later only exits and stops (SPEC 5.6). + public TimeOnly CryptoDeadline { get; init; } = new(12, 0); + + public TimeSpan OrdersAfterOpen { get; init; } = TimeSpan.FromMinutes(5); + + public TimeSpan ExitsBeforeClose { get; init; } = TimeSpan.FromMinutes(5); + + public TimeSpan SignalsAfterClose { get; init; } = TimeSpan.FromMinutes(20); + + /// An entry of equity_meanrev is valid until 60 minutes after the open (SPEC 5.6). + public TimeSpan MeanrevEntryWindow { get; init; } = TimeSpan.FromMinutes(60); + + /// An order released later than this after its time is a recovered one: the drift rule applies. + public TimeSpan Late { get; init; } = TimeSpan.FromMinutes(10); + + /// A crypto decision made this long after 00:05 is a recovered one: the bars come at 00:20, the absence is longer. + public TimeSpan RecoveredAfter { get; init; } = TimeSpan.FromHours(1); + + public decimal StockDrift { get; init; } = 0.01m; + + public decimal CryptoDrift { get; init; } = 0.02m; + + public int WarmupDays { get; init; } = TrialData.WarmupDays; +} + +/// +/// The live engine (SPEC 5.2, 5.5): at the time of each strategy it loads the bars from the database, rebuilds the +/// strategy's book from the ledger and decides with , the call the backtest +/// uses, with the same correctives and risk stage: live and backtest differ only in the data and the book they get. +/// Orders are planned in the same transaction as the decision and handed to the order manager when due, sales first; +/// every decision has a key, so a restart never makes it twice. A strategy in observation records its signals only. +/// Each pulse does what is due now, which is also how missed work is caught up after an absence (SPEC 5.6). +/// +public sealed partial class LiveEngine : IDisposable +{ + private static readonly JsonSerializerOptions Json = new() { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower }; + private static readonly TimeZoneInfo NewYork = TimeZoneInfo.FindSystemTimeZoneById("America/New_York"); + + private readonly Database _db; + private readonly IClock _clock; + private readonly Ledger _ledger; + private readonly StageBook _stages; + private readonly InstrumentCatalog _catalog; + private readonly BarStore _bars; + private readonly UniverseStore _universes; + private readonly CorporateActionStore _actions; + private readonly Func _managers; + private readonly Func> _quotes; + private readonly IMarketCalendar? _calendar; + private readonly ILogger _logger; + private readonly Dictionary _dataAsked = new(StringComparer.Ordinal); + private readonly SemaphoreSlim _gate = new(1, 1); + + public LiveEngine(Database db, IClock clock, Ledger ledger, StageBook stages, Func managers, Func> quotes, + IMarketCalendar? calendar = null, LiveEngineOptions? options = null, ILogger? logger = null) + { + _db = db ?? throw new ArgumentNullException(nameof(db)); + _clock = clock ?? throw new ArgumentNullException(nameof(clock)); + _ledger = ledger ?? throw new ArgumentNullException(nameof(ledger)); + _stages = stages ?? throw new ArgumentNullException(nameof(stages)); + _managers = managers ?? throw new ArgumentNullException(nameof(managers)); + _quotes = quotes ?? throw new ArgumentNullException(nameof(quotes)); + _calendar = calendar; + Options = options ?? new LiveEngineOptions(); + _logger = logger ?? NullLogger.Instance; + _catalog = new InstrumentCatalog(db, clock); + _bars = new BarStore(db, clock); + _universes = new UniverseStore(db, clock); + _actions = new CorporateActionStore(db, clock); + } + + public LiveEngineOptions Options { get; } + + /// Asks the data service for the bars a decision is waiting for (the history step). Called at most every few minutes. + public Func? WantData { get; init; } + + /// The time zone of the diary's times: Italian time. + public TimeZoneInfo Zone { get; init; } = Zones.Rome; + + /// + /// False until the accounts are ready: the order managers exist, the simulator has caught up and every account is + /// reconciled (SPEC 9.4). Until then the pulse does nothing, so no decision is made on a book not yet checked. + /// + public Func Ready { get; init; } = () => true; + + /// + /// The jobs of SPEC 5.5. The pulse every minute does the work; the others are the same pulse at the times the + /// user reads in "Prossime mosse", so the work starts on time. + /// + public IReadOnlyList Jobs() + { + var jobs = new List + { + new("motore", "Lavori dovuti del motore", Schedule.Every(TimeSpan.FromMinutes(1)), PulseAsync) { MaxLateness = TimeSpan.FromMinutes(5) }, + new("crypto-chiusura", "Chiusura giornaliera crypto: ricalcolo i trend", Schedule.Daily(Options.CryptoDecision, TimeZoneInfo.Utc), PulseAsync) { IsMove = true }, + }; + if (_calendar is not null) + { + jobs.Add(new("azioni-apertura", "Rimetto gli stop del giorno e mando gli ordini decisi ieri", Schedule.Market(MarketAnchor.Open, Options.OrdersAfterOpen, _calendar), PulseAsync) + { IsMove = true }); + jobs.Add(new("azioni-uscite", "Uscite della mean reversion prima della chiusura", Schedule.Market(MarketAnchor.Close, -Options.ExitsBeforeClose, _calendar), PulseAsync) + { IsMove = true }); + jobs.Add(new("azioni-segnali", "Wall Street ha chiuso: calcolo i segnali sulle azioni", Schedule.Market(MarketAnchor.Close, Options.SignalsAfterClose, _calendar), PulseAsync) + { IsMove = true }); + } + + return jobs; + } + + /// Everything due now: decisions whose time has come, the stock open and close, planned orders. + public async Task PulseAsync(CancellationToken cancellationToken) + { + if (!Ready()) + { + return; + } + + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + var now = _clock.UtcNow; + await CryptoAsync(now, cancellationToken).ConfigureAwait(false); + if (_calendar is not null) + { + await StocksAsync(now, cancellationToken).ConfigureAwait(false); + } + + await ReleaseAsync(now, cancellationToken).ConfigureAwait(false); + } + finally + { + _gate.Release(); + } + } + + // ---- Crypto ------------------------------------------------------------------------------------------------- + + private async Task CryptoAsync(DateTimeOffset now, CancellationToken cancellationToken) + { + var today = DateOnly.FromDateTime(now.UtcDateTime); + var due = At(today, Options.CryptoDecision); + if (now < due) + { + return; + } + + var deadline = At(today, Options.CryptoDeadline); + var day = today.AddDays(-1); + + // The orders go at once. A decision made long after 00:05 (the bot was off) keeps 00:05 as its time, so its + // entries are checked against the price they were decided on (SPEC 5.6); waiting for the bars is not an absence. + var ordersDue = now - due > Options.RecoveredAfter ? due : now; + await DecideAsync(new Moment(StrategyNames.CryptoTrend, day, Key(StrategyNames.CryptoTrend, day), due, now > deadline, deadline, now, ordersDue, deadline), cancellationToken) + .ConfigureAwait(false); + } + + private static DateTimeOffset At(DateOnly day, TimeOnly time) => new(day.ToDateTime(time), TimeSpan.Zero); + + private static string Key(string strategy, DateOnly day) => strategy + ":" + BarStore.DayText(day); + + // ---- Stocks ------------------------------------------------------------------------------------------------- + + private async Task StocksAsync(DateTimeOffset now, CancellationToken cancellationToken) + { + var local = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(now, NewYork).DateTime); + var today = _calendar!.SessionOn(local); + + // The open: the daily stops on fractions go back first, then the orders decided at the last close (SPEC 5.5). + if (today is not null && now >= today.OpenUtc + Options.OrdersAfterOpen && now < today.CloseUtc) + { + await OpenAsync(today, cancellationToken).ConfigureAwait(false); + } + + // Five minutes before the close: the exits of equity_meanrev. + if (today is not null && now >= today.CloseUtc - Options.ExitsBeforeClose && now < today.CloseUtc) + { + await MeanrevCloseAsync(today, now, cancellationToken).ConfigureAwait(false); + } + + // The signals of the last closed session, valid until the next open. + var last = LastClosed(local, now); + if (last is null || now < last.CloseUtc + Options.SignalsAfterClose) + { + return; + } + + var next = NextSession(last.Date); + if (next is null) + { + return; + } + + foreach (var strategy in new[] { StrategyNames.EquityMomentum, StrategyNames.EquityMeanrev }) + { + var ordersDue = next.OpenUtc + Options.OrdersAfterOpen; + var entriesUntil = strategy == StrategyNames.EquityMeanrev ? next.OpenUtc + Options.MeanrevEntryWindow : SecondSessionOfWeek(next).CloseUtc; + await DecideAsync(new Moment(strategy, last.Date, Key(strategy, last.Date), last.CloseUtc + Options.SignalsAfterClose, false, next.OpenUtc, now, ordersDue, + entriesUntil), cancellationToken).ConfigureAwait(false); + } + } + + private MarketSession? LastClosed(DateOnly local, DateTimeOffset now) + { + for (var day = local; day >= local.AddDays(-10); day = day.AddDays(-1)) + { + if (_calendar!.SessionOn(day) is { } session && session.CloseUtc <= now) + { + return session; + } + } + + return null; + } + + private MarketSession? NextSession(DateOnly after) + { + for (var day = after.AddDays(1); day <= after.AddDays(10); day = day.AddDays(1)) + { + if (_calendar!.SessionOn(day) is { } session) + { + return session; + } + } + + return null; + } + + // equity_momentum's weekly entries are valid for the first two sessions of the week (SPEC 5.6). + private MarketSession SecondSessionOfWeek(MarketSession session) + { + var monday = session.Date.AddDays(-(((int)session.Date.DayOfWeek + 6) % 7)); + var sessions = Enumerable.Range(0, 7).Select(i => _calendar!.SessionOn(monday.AddDays(i))).OfType().ToList(); + var second = sessions.Count > 1 ? sessions[1] : session; + return second.Date < session.Date ? session : second; + } + + private async Task OpenAsync(MarketSession session, CancellationToken cancellationToken) + { + var key = "apertura:" + BarStore.DayText(session.Date); + if (await RunExistsAsync(key, cancellationToken).ConfigureAwait(false)) + { + return; + } + + var replaced = 0; + foreach (var manager in await AlpacaManagersAsync(cancellationToken).ConfigureAwait(false)) + { + await manager.AlignStopsAsync(cancellationToken).ConfigureAwait(false); + var positions = await _ledger.PositionsAsync(manager.Account.AccountId, cancellationToken).ConfigureAwait(false); + replaced += positions.Count(p => p.Quantity > 0m && p.Quantity != decimal.Truncate(p.Quantity)); + } + + await _db.WriteAsync(async s => + { + if (!await ClaimAsync(s, "sistema", key, session.Date, Guid.Empty, "open", null, null, cancellationToken).ConfigureAwait(false)) + { + return; + } + + if (replaced > 0) + { + await Diary.WriteAsync(s, _clock, DiaryKinds.Orders, "stops_replaced", DiaryText.StopsReplaced(replaced), null, cancellationToken).ConfigureAwait(false); + } + }, cancellationToken).ConfigureAwait(false); + } + + private async Task> AlpacaManagersAsync(CancellationToken cancellationToken) + { + var accounts = await _db.ReadAsync(s => s.QueryAsync("SELECT id FROM accounts WHERE broker = @b", r => r.Id("id"), ("b", Venues.Alpaca)), cancellationToken) + .ConfigureAwait(false); + return [.. accounts.Select(_managers).OfType()]; + } + + /// + /// The exits of equity_meanrev five minutes before the close (SPEC 5.5): the strategy decides on today's bar as it + /// stands, with the last price as its close, and only its exits at the close are used. They leave at once as + /// aggressive limits: there are five minutes left. + /// + private async Task MeanrevCloseAsync(MarketSession session, DateTimeOffset now, CancellationToken cancellationToken) + { + var key = "chiusura:" + Key(StrategyNames.EquityMeanrev, session.Date); + if (await RunExistsAsync(key, cancellationToken).ConfigureAwait(false)) + { + return; + } + + var stage = await _stages.GetAsync(StrategyNames.EquityMeanrev, cancellationToken).ConfigureAwait(false); + if (stage?.OrdersAccount is not { } accountId || _managers(accountId) is not { } manager) + { + await ClaimOnlyAsync(StrategyNames.EquityMeanrev, key, session.Date, cancellationToken).ConfigureAwait(false); + return; + } + + var book = await BookAsync(accountId, StrategyNames.EquityMeanrev, cancellationToken).ConfigureAwait(false); + if (book.Holdings.Count == 0) + { + await ClaimOnlyAsync(StrategyNames.EquityMeanrev, key, session.Date, cancellationToken).ConfigureAwait(false); + return; + } + + var data = await LoadAsync(StrategyNames.EquityMeanrev, session.Date, book, provisional: true, cancellationToken).ConfigureAwait(false); + if (data.Data is null) + { + return; + } + + var strategy = CreateStrategy(StrategyNames.EquityMeanrev, stage.Qualification?.Parameters); + var options = StrategyPipeline.For(StrategyNames.EquityMeanrev, data.Data, new BacktestOptions()); + var record = BacktestEngine.DecideOnce(strategy, data.Data, book.State, session.Date, options); + var decisionId = Ids.NewId(_clock); + var exits = record.Final.Where(i => i.AtClose && i.TargetWeight == 0m && book.Holdings.ContainsKey(i.Symbol)).ToList(); + var submitted = new List<(Intent Intent, Guid? Execution, string? Refusal)>(); + foreach (var exit in exits) + { + var held = book.Holdings[exit.Symbol]; + var (execution, refusal) = await manager.SubmitAsync(new TradeIntent(held.InstrumentId, StrategyNames.EquityMeanrev, OrderSide.Sell, held.Holding.Quantity, OrderPurpose.Exit, + decisionId) + { StartAggressive = true }, cancellationToken).ConfigureAwait(false); + submitted.Add((exit, execution, refusal)); + } + + await _db.WriteAsync(async s => + { + if (!await ClaimAsync(s, StrategyNames.EquityMeanrev, key, session.Date, decisionId, DecisionModes.Full, null, null, cancellationToken).ConfigureAwait(false)) + { + return; + } + + foreach (var (intent, execution, refusal) in submitted) + { + await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, StrategyNames.EquityMeanrev, accountId, intent.Symbol, DecisionStages.Strategy, DecisionOutcomes.Proposed, + [intent.Reason], new Dictionary { ["weight"] = 0m, ["at_close"] = true }, now), cancellationToken).ConfigureAwait(false); + await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, StrategyNames.EquityMeanrev, accountId, intent.Symbol, DecisionStages.Order, + refusal is null ? DecisionOutcomes.Passed : DecisionOutcomes.Refused, refusal is null ? [] : [refusal], + new Dictionary { ["execution"] = execution }, now), cancellationToken).ConfigureAwait(false); + } + }, cancellationToken).ConfigureAwait(false); + } + + // ---- Decisions ---------------------------------------------------------------------------------------------- + + /// + /// A decision moment: the strategy, the close it decides on, its key, when it was due, whether it is late (only + /// exits and stops), until when it may wait for its bars, now, when its orders are due and until when its entries + /// stay valid. + /// + private sealed record Moment(string Strategy, DateOnly Day, string Key, DateTimeOffset Due, bool Late, DateTimeOffset WaitUntil, DateTimeOffset Now, + DateTimeOffset OrdersDue, DateTimeOffset EntriesUntil); + + private async Task DecideAsync(Moment m, CancellationToken cancellationToken) + { + if (await RunExistsAsync(m.Key, cancellationToken).ConfigureAwait(false)) + { + return; + } + + var stage = await _stages.GetAsync(m.Strategy, cancellationToken).ConfigureAwait(false); + if (stage is null) + { + return; + } + + var observation = stage.Stage == StrategyStages.Observation; + var accountId = observation ? stage.AccountId : stage.OrdersAccount; + if (accountId is not { } account) + { + return; + } + + var book = observation ? Book.Empty : await BookAsync(account, m.Strategy, cancellationToken).ConfigureAwait(false); + var loaded = await LoadAsync(m.Strategy, m.Day, book, provisional: false, cancellationToken).ConfigureAwait(false); + if (loaded.Data is null || loaded.Missing.Count > 0) + { + if (m.Now < m.WaitUntil && !m.Late) + { + // The bars of the close have not arrived yet: ask for them and try again at the next pulse (SPEC 5.5). + await AskForDataAsync(m.Key, m.Now, m.Due, cancellationToken).ConfigureAwait(false); + return; + } + + if (loaded.Data is null || loaded.MarketMissing) + { + await NoDataAsync(m, stage, cancellationToken).ConfigureAwait(false); + return; + } + } + + var strategy = CreateStrategy(m.Strategy, stage.Qualification?.Parameters); + var data = loaded.Data; + var options = StrategyPipeline.For(m.Strategy, data, new BacktestOptions()); + DecisionRecord record; + if (observation) + { + // Signals only (SPEC 12.3): the backtest run from the start of the observation, on the strategy's capital. + var from = DateOnly.FromDateTime((stage.StageSince ?? m.Now).UtcDateTime); + from = from > m.Day ? m.Day : from; + var run = BacktestEngine.Run(strategy, data, options with { From = from, To = m.Day, InitialCapital = stage.Capital > 0m ? stage.Capital : 10_000m }); + record = run.Decisions.LastOrDefault(d => d.Day == m.Day) ?? new DecisionRecord(m.Day, [], []); + book = Book.FromRun(run, data, m.Day); + } + else + { + var history = await HistoryAsync(account, m.Strategy, m.Day, book.EquityAt(data, m.Day), cancellationToken).ConfigureAwait(false); + record = BacktestEngine.DecideOnce(strategy, data, book.State, m.Day, options, history); + } + + var mode = observation ? DecisionModes.Observation : m.Late || stage.ExitOnly ? DecisionModes.ExitsOnly : DecisionModes.Full; + var plan = Plan(m, mode, record, book, data, loaded.Missing, account); + if (!observation) + { + plan = plan with { Working = await WorkingAsync(account, m.Strategy, cancellationToken).ConfigureAwait(false) }; + } + + var oneStep = observation ? null : await OneStepAsync(m.Strategy, CreateStrategy(m.Strategy, stage.Qualification?.Parameters), data, cancellationToken).ConfigureAwait(false); + var specs = data.Instruments.ToDictionary(i => i.Symbol, i => i.Spec, StringComparer.Ordinal); + await WriteDecisionAsync(m, stage, account, mode, record, plan, book, specs, oneStep, cancellationToken).ConfigureAwait(false); + } + + private async Task AskForDataAsync(string key, DateTimeOffset now, DateTimeOffset due, CancellationToken cancellationToken) + { + // Every 5 minutes for the first 45, then every hour (SPEC 5.5). + var every = now - due < TimeSpan.FromMinutes(45) ? TimeSpan.FromMinutes(5) : TimeSpan.FromHours(1); + if (WantData is null || (_dataAsked.TryGetValue(key, out var last) && now - last < every)) + { + return; + } + + _dataAsked[key] = now; + try + { + await WantData(cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + LogDataRequestFailed(_logger, ex); + } + } + + private async Task NoDataAsync(Moment m, StrategyStage stage, CancellationToken cancellationToken) + { + var observation = stage.Stage == StrategyStages.Observation; + await _db.WriteAsync(async s => + { + if (!await ClaimAsync(s, m.Strategy, m.Key, m.Day, Ids.NewId(_clock), DecisionModes.NoData, null, null, cancellationToken).ConfigureAwait(false)) + { + return; + } + + var what = m.Strategy == StrategyNames.CryptoTrend ? "le barre giornaliere delle crypto" : "le barre di chiusura delle azioni"; + var text = DiaryText.NoData(m.Strategy, what); + if (observation) + { + await Diary.WriteAsync(s, _clock, DiaryKinds.Decisions, LiveReasons.MissingBars, text, null, cancellationToken).ConfigureAwait(false); + } + else + { + // A strategy that trades and cannot decide is something the user must know (SPEC 5.5: "e avvisa"). + await Diary.NotifyAsync(s, _clock, LiveReasons.MissingBars, text, cancellationToken).ConfigureAwait(false); + } + }, cancellationToken).ConfigureAwait(false); + } + + /// What one decision turns into: planned orders, stops to move, notes on what was left out. + private sealed record PlanResult(IReadOnlyList Orders, IReadOnlyList<(string Symbol, decimal From, decimal To)> Stops, IReadOnlyList<(string Symbol, string Reason)> Notes, + DecisionSummary Summary, decimal Equity) + { + public IReadOnlySet Working { get; init; } = new HashSet(); + } + + private sealed record PlannedOrder(Guid InstrumentId, string Symbol, OrderSide Side, OrderPurpose Purpose, decimal Quantity, bool ExitAll, decimal? StopLevel, decimal? StopOffset, + decimal Reference, string Reason, DateTimeOffset Due, DateTimeOffset? ValidUntil, bool Crypto); + + /// + /// The intents become orders as the backtest plans them (BacktestEngine.Plan): target quantity from the weight and + /// the equity at the close, the difference bought or sold, a full exit when the weight is zero, stops moved on what + /// is held. In exits-only mode entries and increases are left out. + /// + private PlanResult Plan(Moment m, string mode, DecisionRecord record, Book book, BacktestDataset data, IReadOnlySet missing, Guid account) + { + var equity = book.EquityAt(data, m.Day); + var orders = new List(); + var stops = new List<(string, decimal, decimal)>(); + var notes = new List<(string, string)>(); + List bought = [], increased = [], reduced = [], sold = []; + var changed = new HashSet(StringComparer.Ordinal); + foreach (var intent in record.Final.GroupBy(i => i.Symbol, StringComparer.Ordinal).Select(g => g.Last())) + { + var instrument = data[intent.Symbol]; + if (instrument is null || data.DataOnly.Contains(intent.Symbol)) + { + continue; + } + + if (missing.Contains(intent.Symbol)) + { + notes.Add((intent.Symbol, LiveReasons.MissingBars)); + continue; + } + + book.Holdings.TryGetValue(intent.Symbol, out var held); + var current = held?.Holding.Quantity ?? 0m; + var stop = intent.Stop is { } level ? OrderRules.StopPrice(level, OrderRules.TickOf(instrument.Spec, level)) : (decimal?)null; + if (held is not null && stop is { } newStop && newStop != held.Holding.Stop) + { + stops.Add((intent.Symbol, held.Holding.Stop ?? 0m, newStop)); + } + + if (intent.TargetWeight is not { } weight || weight < 0m) + { + continue; + } + + var close = Close(instrument, m.Day); + if (close is not > 0m) + { + notes.Add((intent.Symbol, BacktestReasons.NoPrice)); + continue; + } + + var crypto = instrument.Spec.AssetClass == AssetClasses.Crypto; + var due = m.OrdersDue; + if (weight == 0m) + { + if (current > 0m) + { + orders.Add(new PlannedOrder(held!.InstrumentId, intent.Symbol, OrderSide.Sell, OrderPurpose.Exit, current, true, null, null, close.Value, intent.Reason, due, null, crypto)); + sold.Add(intent.Symbol); + changed.Add(intent.Symbol); + } + + continue; + } + + var target = weight * equity / close.Value; + var difference = target - current; + if (difference > 0m) + { + if (mode == DecisionModes.ExitsOnly) + { + notes.Add((intent.Symbol, LiveReasons.LateExitsOnly)); + continue; + } + + var id = held?.InstrumentId ?? InstrumentIdOf(data, intent.Symbol); + orders.Add(new PlannedOrder(id, intent.Symbol, OrderSide.Buy, OrderPurpose.Entry, difference, false, stop, intent.StopOffset, close.Value, intent.Reason, due, + m.EntriesUntil, crypto)); + (current > 0m ? increased : bought).Add(intent.Symbol); + changed.Add(intent.Symbol); + } + else if (difference < 0m && current > 0m) + { + orders.Add(new PlannedOrder(held!.InstrumentId, intent.Symbol, OrderSide.Sell, OrderPurpose.Exit, -difference, false, null, null, close.Value, intent.Reason, due, null, crypto)); + reduced.Add(intent.Symbol); + changed.Add(intent.Symbol); + } + } + + var heldUnchanged = book.Holdings.Keys.Where(s => !changed.Contains(s)).Order(StringComparer.Ordinal).ToList(); + var universe = data.Tradable.Count(); + var outside = Math.Max(0, universe - heldUnchanged.Count - bought.Count - increased.Count - reduced.Count); + return new PlanResult(orders, stops, notes, new DecisionSummary(bought, increased, reduced, sold, heldUnchanged, outside), equity); + } + + private Guid InstrumentIdOf(BacktestDataset data, string symbol) => _instrumentIds.TryGetValue(symbol, out var id) ? id : Guid.Empty; + + private readonly Dictionary _instrumentIds = new(StringComparer.Ordinal); + + private static decimal? Close(BacktestInstrument instrument, DateOnly day) + { + var n = instrument.CountThrough(day); + return n > 0 ? DbValues.Money((decimal)instrument.Bars[n - 1].Close) : null; + } + + private async Task> WorkingAsync(Guid account, string strategy, CancellationToken cancellationToken) => + (await _db.ReadAsync(s => s.QueryAsync("SELECT instrument_id FROM executions WHERE account_id = @a AND strategy = @s AND status = @w", + r => r.Id("instrument_id"), ("a", account), ("s", strategy), ("w", ExecutionStates.Working)), cancellationToken).ConfigureAwait(false)).ToHashSet(); + + private async Task WriteDecisionAsync(Moment m, StrategyStage stage, Guid account, string mode, DecisionRecord record, PlanResult plan, Book book, + IReadOnlyDictionary specs, (Guid DecisionId, bool Same, IReadOnlyList Different)? oneStep, CancellationToken cancellationToken) + { + var decisionId = Ids.NewId(_clock); + var now = m.Now; + var observation = mode == DecisionModes.Observation; + var state = observation ? null : JsonSerializer.Serialize(book.Snapshot(), Json); + var proposed = JsonSerializer.Serialize(record.Proposed.Select(i => new ProposedIntent(i.Symbol, i.TargetWeight, i.Stop)).ToList(), Json); + var currency = StrategyNames.CurrencyOf(StrategyNames.BrokerOf(m.Strategy)); + await _db.WriteAsync(async s => + { + if (!await ClaimAsync(s, m.Strategy, m.Key, m.Day, decisionId, mode, state, proposed, cancellationToken).ConfigureAwait(false)) + { + return; + } + + // The older orders of the strategy not yet sent are replaced by this decision (the backtest keeps one per symbol). + await s.ExecuteAsync("UPDATE planned_orders SET status = @st, outcome = @o, updated_at = @now WHERE strategy = @s AND status = @p", cancellationToken, + ("st", PlannedStates.Superseded), ("o", LiveReasons.Superseded), ("now", now), ("s", m.Strategy), ("p", PlannedStates.Pending)).ConfigureAwait(false); + + // The stages of the decision (SPEC 5.2): what the strategy proposed, what correctives and risk changed. + foreach (var intent in record.Proposed) + { + await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, m.Strategy, account, intent.Symbol, DecisionStages.Strategy, DecisionOutcomes.Proposed, [intent.Reason], + new Dictionary { ["weight"] = intent.TargetWeight, ["stop"] = intent.Stop, ["stop_offset"] = intent.StopOffset, ["day"] = BarStore.DayText(m.Day) }, now), + cancellationToken).ConfigureAwait(false); + } + + foreach (var intent in record.Final.Where(i => i.Adjustments.Count > 0)) + { + var asked = record.Proposed.LastOrDefault(p => p.Symbol == intent.Symbol)?.TargetWeight; + var corrective = intent.Adjustments.Where(IsCorrective).ToList(); + var risk = intent.Adjustments.Where(a => !IsCorrective(a)).ToList(); + var data = new Dictionary { ["asked"] = asked, ["allowed"] = intent.TargetWeight ?? 0m }; + if (corrective.Count > 0) + { + await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, m.Strategy, account, intent.Symbol, DecisionStages.Correctives, + intent.TargetWeight is > 0m ? DecisionOutcomes.Reduced : DecisionOutcomes.Refused, corrective, data, now), cancellationToken).ConfigureAwait(false); + } + + if (risk.Count > 0) + { + await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, m.Strategy, account, intent.Symbol, DecisionStages.Risk, + intent.TargetWeight is > 0m ? DecisionOutcomes.Reduced : DecisionOutcomes.Refused, risk, data, now), cancellationToken).ConfigureAwait(false); + } + } + + foreach (var (symbol, reason) in plan.Notes) + { + await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, m.Strategy, account, symbol, DecisionStages.Order, DecisionOutcomes.Refused, [reason], null, now), + cancellationToken).ConfigureAwait(false); + } + + if (oneStep is { } check) + { + await DecisionLog.WriteAsync(s, _clock, new DecisionRow(check.DecisionId, m.Strategy, account, null, DecisionStages.OneStep, + check.Same ? DecisionOutcomes.Same : DecisionOutcomes.Different, [], new Dictionary { ["different"] = check.Different }, now), cancellationToken) + .ConfigureAwait(false); + } + + if (observation) + { + foreach (var order in plan.Orders) + { + await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, m.Strategy, account, order.Symbol, DecisionStages.Order, DecisionOutcomes.Refused, + [RiskReasons.Observation], new Dictionary { ["side"] = Wire.Text(order.Side), ["quantity"] = order.Quantity }, now), cancellationToken) + .ConfigureAwait(false); + } + + await Diary.WriteAsync(s, _clock, DiaryKinds.Decisions, "observed", DiaryText.Observed(m.Strategy, plan.Summary), + new { decision = decisionId }, cancellationToken).ConfigureAwait(false); + return; + } + + foreach (var order in plan.Orders) + { + if (order.InstrumentId == Guid.Empty) + { + continue; + } + + if (plan.Working.Contains(order.InstrumentId)) + { + await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, m.Strategy, account, order.Symbol, DecisionStages.Order, DecisionOutcomes.Refused, + [LiveReasons.OrderInProgress], null, now), cancellationToken).ConfigureAwait(false); + continue; + } + + var id = Ids.NewId(_clock); + await s.ExecuteAsync( + "INSERT INTO planned_orders (id, decision_id, strategy, account_id, instrument_id, side, purpose, quantity, exit_all, stop_level, stop_offset, reference_price, reason, due_at, valid_until, status, created_at, updated_at) " + + "VALUES (@id, @d, @s, @a, @i, @side, @p, @q, @all, @stop, @off, @ref, @r, @due, @until, @st, @now, @now)", cancellationToken, + ("id", id), ("d", decisionId), ("s", m.Strategy), ("a", account), ("i", order.InstrumentId), ("side", Wire.Text(order.Side)), ("p", Wire.Text(order.Purpose)), + ("q", DbValues.Money(order.Quantity)), ("all", order.ExitAll), ("stop", order.StopLevel), ("off", order.StopOffset), ("ref", order.Reference), ("r", order.Reason), + ("due", order.Due), ("until", order.ValidUntil), ("st", PlannedStates.Pending), ("now", now)).ConfigureAwait(false); + await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, m.Strategy, account, order.Symbol, DecisionStages.Sizing, DecisionOutcomes.Passed, [], + new Dictionary { ["side"] = Wire.Text(order.Side), ["quantity"] = order.Quantity, ["equity"] = plan.Equity, ["close"] = order.Reference, ["planned"] = id }, + now), cancellationToken).ConfigureAwait(false); + } + + foreach (var (symbol, from, to) in plan.Stops) + { + if (!book.Holdings.TryGetValue(symbol, out var held)) + { + continue; + } + + await s.ExecuteAsync("UPDATE positions SET stop_price = @p, updated_at = @now WHERE account_id = @a AND instrument_id = @i AND strategy = @s", cancellationToken, + ("p", to), ("now", now), ("a", account), ("i", held.InstrumentId), ("s", m.Strategy)).ConfigureAwait(false); + if (from > 0m) + { + var text = to > from ? DiaryText.StopRaised(symbol, from, to, currency) : DiaryText.StopLowered(symbol, from, to, currency); + await Diary.WriteAsync(s, _clock, DiaryKinds.Orders, "stop_moved", text, new { decision = decisionId, symbol, from, to }, cancellationToken).ConfigureAwait(false); + } + } + + var summary = m.Strategy == StrategyNames.CryptoTrend ? DiaryText.CryptoClose(plan.Summary) : DiaryText.StockSignals(plan.Summary); + if (mode == DecisionModes.ExitsOnly && plan.Notes.Any(n => n.Reason == LiveReasons.LateExitsOnly)) + { + summary += " " + ReasonCatalog.Text(LiveReasons.LateExitsOnly); + } + + await Diary.WriteAsync(s, _clock, DiaryKinds.Decisions, "decision", summary, new { decision = decisionId }, cancellationToken).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); + } + + private static bool IsCorrective(string code) => code is CorrectiveReasons.CryptoRegimeAverage or CorrectiveReasons.CryptoRegimeVolatility or CorrectiveReasons.CalendarEvent; + + private sealed record ProposedIntent(string Symbol, decimal? Weight, decimal? Stop); + + // ---- One-step comparison (SPEC 12.3) ------------------------------------------------------------------------ + + /// + /// The previous decision of the strategy again, from the book recorded then and with the data as it is now: the + /// strategy's intents (before correctives and risk) must match. An intent differs when its action differs or its + /// size by more than 10%. + /// + private async Task<(Guid, bool, IReadOnlyList)?> OneStepAsync(string strategyName, IStrategy strategy, BacktestDataset data, CancellationToken cancellationToken) + { + var previous = await _db.ReadAsync(s => s.FirstOrDefaultAsync( + "SELECT decision_day, decision_id, state, proposed FROM engine_runs WHERE strategy = @s AND state IS NOT NULL ORDER BY decision_day DESC, created_at DESC LIMIT 1", + r => (Day: BarStore.ParseDay(r.Text("decision_day")), Id: r.Id("decision_id"), State: r.TextOrNull("state"), Proposed: r.TextOrNull("proposed")), ("s", strategyName)), + cancellationToken).ConfigureAwait(false); + if (previous.State is null || previous.Proposed is null || data.Instruments.All(i => i.IndexOf(previous.Day) < 0)) + { + return null; + } + + var snapshot = JsonSerializer.Deserialize(previous.State, Json); + var recorded = JsonSerializer.Deserialize>(previous.Proposed, Json) ?? []; + if (snapshot is null) + { + return null; + } + + var state = snapshot.ToState(); + var again = BacktestEngine.DecideOnce(strategy, data, state, previous.Day).Proposed; + var different = OneStep.Compare(state, recorded.Select(p => (p.Symbol, p.Weight)).ToList(), again.Select(i => (i.Symbol, i.TargetWeight)).ToList(), data, previous.Day); + return (previous.Id, different.Count == 0, different); + } + + // ---- Releasing planned orders ------------------------------------------------------------------------------- + + private sealed record Planned(Guid Id, Guid DecisionId, string Strategy, Guid AccountId, Guid InstrumentId, OrderSide Side, OrderPurpose Purpose, decimal Quantity, bool ExitAll, + decimal? StopLevel, decimal? StopOffset, decimal Reference, string Reason, DateTimeOffset Due, DateTimeOffset? ValidUntil); + + /// + /// The planned orders whose time has come go to the order manager, sales first (SPEC 5.5). An entry past its + /// deadline is dropped, and one released late is dropped when the price moved more than 1% (stocks) or 2% + /// (crypto) from the planned one (SPEC 5.6). The order's key comes from the planned order: a restart that finds + /// the execution already there marks it sent and never sends it again. + /// + private async Task ReleaseAsync(DateTimeOffset now, CancellationToken cancellationToken) + { + var due = await _db.ReadAsync(s => s.QueryAsync( + "SELECT id, decision_id, strategy, account_id, instrument_id, side, purpose, quantity, exit_all, stop_level, stop_offset, reference_price, reason, due_at, valid_until " + + "FROM planned_orders WHERE status = @p AND due_at <= @now ORDER BY due_at, id", + r => new Planned(r.Id("id"), r.Id("decision_id"), r.Text("strategy"), r.Id("account_id"), r.Id("instrument_id"), Wire.Side(r.Text("side")), Wire.Purpose(r.Text("purpose")), + r.Money("quantity"), r.Bool("exit_all"), r.MoneyOrNull("stop_level"), r.MoneyOrNull("stop_offset"), r.Money("reference_price"), r.Text("reason"), r.Moment("due_at"), + r.MomentOrNull("valid_until")), ("p", PlannedStates.Pending), ("now", now)), cancellationToken).ConfigureAwait(false); + foreach (var order in due.OrderBy(o => o.Side == OrderSide.Buy).ThenBy(o => o.Due)) + { + try + { + await ReleaseOneAsync(order, now, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + // One order that fails stays pending for the next pulse: the others still go. + LogReleaseFailed(_logger, ex, order.Id); + } + } + } + + private async Task ReleaseOneAsync(Planned order, DateTimeOffset now, CancellationToken cancellationToken) + { + var instrument = await _catalog.GetAsync(order.InstrumentId, cancellationToken).ConfigureAwait(false); + if (instrument is null) + { + await CloseAsync(order, PlannedStates.Dropped, BacktestReasons.UnknownSymbol, null, null, cancellationToken).ConfigureAwait(false); + return; + } + + var key = ClientOrderIds.Key(order.Id); + var existing = await _db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT id FROM executions WHERE account_id = @a AND order_key = @k", r => r.IdOrNull("id"), + ("a", order.AccountId), ("k", key)), cancellationToken).ConfigureAwait(false); + if (existing is { } already) + { + // Sent before a restart: the execution is there, nothing goes twice. + await CloseAsync(order, PlannedStates.Submitted, null, already, null, cancellationToken).ConfigureAwait(false); + return; + } + + if (order.Side == OrderSide.Buy && order.ValidUntil is { } until && now > until) + { + await CloseAsync(order, PlannedStates.Expired, LiveReasons.EntryExpired, null, + DiaryText.Skipped($"l'acquisto di {DiaryText.Shown(instrument.Symbol)}", ReasonCatalog.Text(LiveReasons.EntryExpired)), cancellationToken).ConfigureAwait(false); + return; + } + + if (_managers(order.AccountId) is not { } manager) + { + return; + } + + if (manager.MarketOpen is { } open && !await open(instrument, cancellationToken).ConfigureAwait(false)) + { + return; + } + + var quantity = order.Quantity; + if (order.Side == OrderSide.Sell) + { + var position = (await _ledger.PositionsAsync(order.AccountId, cancellationToken).ConfigureAwait(false)) + .FirstOrDefault(p => p.InstrumentId == order.InstrumentId && p.Strategy == order.Strategy); + var held = position?.Quantity ?? 0m; + quantity = order.ExitAll ? held : Math.Min(quantity, held); + if (quantity <= 0m) + { + await CloseAsync(order, PlannedStates.Dropped, LiveReasons.NothingHeld, null, null, cancellationToken).ConfigureAwait(false); + return; + } + } + + var late = now - order.Due > Options.Late; + decimal? stopLevel = order.StopLevel; + if (order.Side == OrderSide.Buy) + { + var quote = await _quotes(instrument.Symbol, cancellationToken).ConfigureAwait(false); + if (quote is not { Bid: > 0m, Ask: > 0m }) + { + return; + } + + var limit = instrument.IsCrypto ? Options.CryptoDrift : Options.StockDrift; + var moved = Math.Abs((quote.Mid / order.Reference) - 1m); + if (late && moved > limit) + { + await CloseAsync(order, PlannedStates.Dropped, LiveReasons.PriceMoved, null, + DiaryText.EntryDropped(instrument.Symbol, Math.Round(moved * 100m, 1), limit * 100m), cancellationToken).ConfigureAwait(false); + return; + } + + if (stopLevel is null && order.StopOffset is > 0m and var offset && quote.Ask - offset > 0m) + { + // A distance from the price: the stop of a new position goes that far below the price now (SPEC 8.2, 8.3). + stopLevel = OrderRules.StopPrice(quote.Ask - offset, OrderRules.TickOf(instrument.Spec, quote.Ask - offset)); + } + } + + var (execution, refusal) = await manager.SubmitAsync(new TradeIntent(order.InstrumentId, order.Strategy, order.Side, quantity, order.Purpose, order.Id) { StopLevel = stopLevel }, + cancellationToken).ConfigureAwait(false); + var recovered = late ? DiaryText.Recovered(OrderWords(order, instrument.Symbol), order.Due, Zone) : null; + await CloseAsync(order, refusal is null ? PlannedStates.Submitted : PlannedStates.Refused, refusal, execution, recovered, cancellationToken).ConfigureAwait(false); + } + + private static string OrderWords(Planned order, string symbol) => + (order.Side == OrderSide.Buy ? "l'acquisto di " : "la vendita di ") + DiaryText.Shown(symbol); + + private Task CloseAsync(Planned order, string status, string? reason, Guid? execution, string? diary, CancellationToken cancellationToken) => + _db.WriteAsync(async s => + { + var now = _clock.UtcNow; + await s.ExecuteAsync("UPDATE planned_orders SET status = @st, outcome = @o, execution_id = @e, updated_at = @now WHERE id = @id AND status = @p", cancellationToken, + ("st", status), ("o", reason), ("e", execution), ("now", now), ("id", order.Id), ("p", PlannedStates.Pending)).ConfigureAwait(false); + await DecisionLog.WriteAsync(s, _clock, new DecisionRow(order.DecisionId, order.Strategy, order.AccountId, null, DecisionStages.Order, + status == PlannedStates.Submitted ? DecisionOutcomes.Passed : DecisionOutcomes.Refused, reason is null ? [] : [reason], + new Dictionary { ["planned"] = order.Id, ["execution"] = execution, ["side"] = Wire.Text(order.Side) }, now), cancellationToken).ConfigureAwait(false); + if (diary is not null) + { + await Diary.WriteAsync(s, _clock, DiaryKinds.Orders, reason ?? LiveReasons.Recovered, diary, new { planned = order.Id }, cancellationToken).ConfigureAwait(false); + } + }, cancellationToken); + + // ---- Books, data and history ------------------------------------------------------------------------------ + + private sealed record Held(Guid InstrumentId, Holding Holding); + + /// The strategy's book from the ledger: its cash and what it holds, by symbol. + private sealed record Book(decimal Cash, IReadOnlyDictionary Holdings) + { + public static Book Empty { get; } = new(0m, new Dictionary(StringComparer.Ordinal)); + + public PortfolioState State => new(Cash, Holdings.ToDictionary(h => h.Key, h => h.Value.Holding, StringComparer.Ordinal)); + + public decimal EquityAt(BacktestDataset data, DateOnly day) => Cash + Holdings.Sum(h => + h.Value.Holding.Quantity * (data[h.Key] is { } i && Close(i, day) is { } close ? close : h.Value.Holding.AveragePrice)); + + public BookSnapshot Snapshot() => new(Cash, Holdings.ToDictionary(h => h.Key, h => new HoldingSnapshot(h.Value.Holding.Quantity, h.Value.Holding.AveragePrice, + h.Value.Holding.Stop, BarStore.DayText(h.Value.Holding.EnteredOn)), StringComparer.Ordinal)); + + // The observation book is the backtest's: what the run held after the decision's close, for the diary's summary. + public static Book FromRun(BacktestRun run, BacktestDataset data, DateOnly day) + { + var holdings = new Dictionary(StringComparer.Ordinal); + foreach (var group in run.Fills.Where(f => f.Day <= day).GroupBy(f => f.Symbol, StringComparer.Ordinal)) + { + var quantity = group.Sum(f => f.Side == OrderSide.Buy ? f.Quantity : -f.Quantity); + if (quantity > 0m) + { + holdings[group.Key] = new Held(Guid.Empty, new Holding(quantity, group.Last().Price, null, group.First().Day)); + } + } + + return new Book(run.Equity.LastOrDefault(e => e.Day <= day)?.Cash ?? 0m, holdings); + } + } + + private sealed record HoldingSnapshot(decimal Quantity, decimal Price, decimal? Stop, string Entered); + + private sealed record BookSnapshot(decimal Cash, Dictionary Holdings) + { + public PortfolioState ToState() => new(Cash, Holdings.ToDictionary(h => h.Key, h => new Holding(h.Value.Quantity, h.Value.Price, h.Value.Stop, BarStore.ParseDay(h.Value.Entered)), + StringComparer.Ordinal)); + } + + private async Task BookAsync(Guid account, string strategy, CancellationToken cancellationToken) + { + var equities = await _ledger.EquitiesAsync(cancellationToken).ConfigureAwait(false); + var cash = equities.FirstOrDefault(e => e.AccountId == account && e.Strategy == strategy)?.Cash ?? 0m; + var holdings = new Dictionary(StringComparer.Ordinal); + foreach (var p in (await _ledger.PositionsAsync(account, cancellationToken).ConfigureAwait(false)).Where(p => p.Strategy == strategy && p.Quantity > 0m)) + { + if (await _catalog.GetAsync(p.InstrumentId, cancellationToken).ConfigureAwait(false) is { } instrument) + { + holdings[instrument.Symbol] = new Held(p.InstrumentId, new Holding(p.Quantity, p.AveragePrice, p.StopPrice, DateOnly.FromDateTime(p.OpenedAt.UtcDateTime))); + } + } + + return new Book(cash, holdings); + } + + /// The bars of a decision, its universe and what is missing on the day of the close. + private sealed record Loaded(BacktestDataset? Data, IReadOnlySet Missing, bool MarketMissing); + + private async Task LoadAsync(string strategy, DateOnly day, Book book, bool provisional, CancellationToken cancellationToken) + { + var crypto = strategy == StrategyNames.CryptoTrend; + var venue = crypto ? Venues.Okx : Venues.Alpaca; + var members = await _universes.AsOfAsync(crypto ? Universes.Crypto : Universes.Equity, day, cancellationToken).ConfigureAwait(false); + var symbols = new SortedSet(members.Select(m => m.Symbol), StringComparer.Ordinal); + if (crypto && symbols.Count == 0) + { + symbols.UnionWith(MarketDataService.CoreCrypto); + } + + symbols.UnionWith(book.Holdings.Keys); + var market = crypto ? NoBot.BitcoinSymbol : StrategyNames.MarketSymbol; + var dataOnly = new HashSet(StringComparer.Ordinal); + if (symbols.Add(market) && !crypto) + { + dataOnly.Add(market); + } + + // The crypto trend follows a path through its bars: from the first one held, as a run of the backtest. The + // stock strategies read windows: the warm-up of a trial is enough. + var from = crypto ? MarketDataService.HistoryFrom : day.AddDays(-Options.WarmupDays); + var instruments = new List(); + var missing = new HashSet(StringComparer.Ordinal); + var currency = crypto ? "EUR" : "USD"; + foreach (var symbol in symbols) + { + var instrument = await _catalog.FindAsync(venue, symbol, cancellationToken).ConfigureAwait(false); + if (instrument is null || (instrument.Spec.QuoteCurrency != currency && !dataOnly.Contains(symbol))) + { + missing.Add(symbol); + continue; + } + + _instrumentIds[symbol] = instrument.Id; + var bars = (await _bars.DailyAsync(instrument.Id, from, day, cancellationToken).ConfigureAwait(false)).ToList(); + if (provisional && bars.All(b => b.Day < day) && await _quotes(symbol, cancellationToken).ConfigureAwait(false) is { Bid: > 0m, Ask: > 0m } quote) + { + // Before the close: today's bar as it stands, the last price as its close. + var mid = (double)quote.Mid; + bars.Add(new DailyBar(day, mid, mid, mid, mid, 0)); + } + + if (bars.Count == 0 || bars[^1].Day < day) + { + missing.Add(symbol); + } + + if (bars.Count == 0) + { + continue; + } + + var events = instrument.IsCrypto ? [] : (await _actions.ForSymbolAsync(symbol, cancellationToken).ConfigureAwait(false)).Where(a => a.ExDate > from && a.ExDate <= day).ToList(); + instruments.Add(new BacktestInstrument(instrument.Spec, bars, events, "barre raccolte")); + } + + if (instruments.Count == 0) + { + return new Loaded(null, missing, true); + } + + IEnumerable? calendar = null; + if (!crypto && _calendar is not null) + { + // The sessions ahead, so the strategy knows the next one (earnings before it, SPEC 8.3). + calendar = instruments.SelectMany(i => i.Bars.Select(b => b.Day)).Concat(Enumerable.Range(1, 14).Select(i => day.AddDays(i)).Where(d => _calendar.SessionOn(d) is not null)) + .Distinct().Order(); + } + + var data = new BacktestDataset(instruments, currency, calendar, dataOnly); + return new Loaded(data, missing, missing.Contains(market)); + } + + /// The strategy's equity at each close before , from the photographs, and at from its closes. + private async Task> HistoryAsync(Guid account, string strategy, DateOnly day, decimal equityNow, CancellationToken cancellationToken) + { + var rows = await _db.ReadAsync(s => s.QueryAsync( + "SELECT taken_at, equity, invested FROM equity_snapshots WHERE scope = 'strategy' AND account_id = @a AND strategy = @s ORDER BY taken_at", + r => (At: r.Moment("taken_at"), Equity: r.Money("equity"), Invested: r.Money("invested")), ("a", account), ("s", strategy)), cancellationToken).ConfigureAwait(false); + var marks = rows.GroupBy(r => DateOnly.FromDateTime(r.At.UtcDateTime)).Where(g => g.Key < day) + .Select(g => new EquityMark(g.Key, g.Last().Equity, g.Last().Invested)).ToList(); + marks.Add(new EquityMark(day, equityNow, 0m)); + return marks; + } + + /// A strategy with its parameters: those of the backtest it qualified with, otherwise the defaults. + public static IStrategy CreateStrategy(string strategy, string? parameters) + { + var family = StrategyCatalog.Find(strategy) ?? throw new ArgumentException("Unknown strategy " + strategy, nameof(strategy)); + var defaults = family.Parameters.ToDictionary(p => p.Name, p => p.Default, StringComparer.Ordinal); + var values = new Dictionary(defaults, StringComparer.Ordinal); + foreach (var part in (parameters ?? "").Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + var pair = part.Split('=', 2); + if (pair.Length == 2 && values.ContainsKey(pair[0]) && decimal.TryParse(pair[1], NumberStyles.Number, CultureInfo.InvariantCulture, out var value)) + { + values[pair[0]] = value; + } + } + + var chosen = new StrategyParameters(values); + return family.Accepts(chosen) ? family.Create(chosen) : family.Create(new StrategyParameters(defaults)); + } + + // ---- Runs --------------------------------------------------------------------------------------------------- + + private Task RunExistsAsync(string key, CancellationToken cancellationToken) => + _db.ReadAsync(async s => await s.CountAsync("SELECT COUNT(*) FROM engine_runs WHERE run_key = @k", ("k", key)).ConfigureAwait(false) > 0, cancellationToken); + + private Task ClaimOnlyAsync(string strategy, string key, DateOnly day, CancellationToken cancellationToken) => + _db.WriteAsync(s => ClaimAsync(s, strategy, key, day, Guid.Empty, "none", null, null, cancellationToken), cancellationToken); + + private async Task ClaimAsync(DbSession s, string strategy, string key, DateOnly day, Guid decisionId, string mode, string? state, string? proposed, + CancellationToken cancellationToken) => + await s.ExecuteAsync( + "INSERT INTO engine_runs (id, strategy, run_key, decision_day, decision_id, mode, state, proposed, created_at) VALUES (@id, @s, @k, @d, @dec, @m, @st, @p, @now) " + + "ON CONFLICT (run_key) DO NOTHING", cancellationToken, + ("id", Ids.NewId(_clock)), ("s", strategy), ("k", key), ("d", BarStore.DayText(day)), ("dec", decisionId), ("m", mode), + ("st", state is null ? null : new DbJson(state)), ("p", proposed is null ? null : new DbJson(proposed)), ("now", _clock.UtcNow)).ConfigureAwait(false) > 0; + + public void Dispose() => _gate.Dispose(); + + [LoggerMessage(Level = LogLevel.Warning, Message = "Asking for the missing bars failed")] + private static partial void LogDataRequestFailed(ILogger logger, Exception exception); + + [LoggerMessage(Level = LogLevel.Error, Message = "Planned order {Id} could not be released")] + private static partial void LogReleaseFailed(ILogger logger, Exception exception, Guid id); +} + +/// The comparison of two sets of intents (SPEC 12.3): same action and size within 10%, for what is held and what either version enters. +public static class OneStep +{ + public const decimal SizeTolerance = 0.10m; + + public static IReadOnlyList Compare(PortfolioState state, IReadOnlyList<(string Symbol, decimal? Weight)> live, IReadOnlyList<(string Symbol, decimal? Weight)> again, + BacktestDataset data, DateOnly day) + { + ArgumentNullException.ThrowIfNull(state); + ArgumentNullException.ThrowIfNull(live); + ArgumentNullException.ThrowIfNull(again); + ArgumentNullException.ThrowIfNull(data); + var equity = state.Cash + state.Holdings.Sum(h => h.Value.Quantity * Price(data, h.Key, day, h.Value.AveragePrice)); + decimal Current(string symbol) => equity <= 0m || !state.Holdings.TryGetValue(symbol, out var h) ? 0m : h.Quantity * Price(data, symbol, day, h.AveragePrice) / equity; + string Action(string symbol, decimal? weight) => weight switch + { + null => "keep", + 0m => Current(symbol) > 0m ? "exit" : "none", + { } w when w > Current(symbol) => "buy", + { } w when w < Current(symbol) => "reduce", + _ => "keep", + }; + + var a = live.GroupBy(i => i.Symbol, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.Last().Weight, StringComparer.Ordinal); + var b = again.GroupBy(i => i.Symbol, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.Last().Weight, StringComparer.Ordinal); + var symbols = new SortedSet(state.Holdings.Keys, StringComparer.Ordinal); + symbols.UnionWith(a.Where(x => Action(x.Key, x.Value) == "buy").Select(x => x.Key)); + symbols.UnionWith(b.Where(x => Action(x.Key, x.Value) == "buy").Select(x => x.Key)); + var different = new List(); + foreach (var symbol in symbols) + { + var wa = a.GetValueOrDefault(symbol); + var wb = b.GetValueOrDefault(symbol); + var actionA = Action(symbol, wa); + var actionB = Action(symbol, wb); + if (actionA != actionB) + { + different.Add(symbol); + continue; + } + + if (wa is { } x && wb is { } y && Math.Max(Math.Abs(x), Math.Abs(y)) > 0m && Math.Abs(x - y) / Math.Max(Math.Abs(x), Math.Abs(y)) > SizeTolerance) + { + different.Add(symbol); + } + } + + return different; + } + + private static decimal Price(BacktestDataset data, string symbol, DateOnly day, decimal fallback) + { + var i = data[symbol]; + var n = i?.CountThrough(day) ?? 0; + return n > 0 ? (decimal)i!.Bars[n - 1].Close : fallback; + } +} diff --git a/src/Anubis/Trading/ReasonCatalog.cs b/src/Anubis/Trading/ReasonCatalog.cs index d1227bd..7571e11 100644 --- a/src/Anubis/Trading/ReasonCatalog.cs +++ b/src/Anubis/Trading/ReasonCatalog.cs @@ -75,6 +75,15 @@ public static class ReasonCatalog ["stop_gap"] = "Il prezzo ha aperto sotto lo stop: venduto all'apertura.", ["residue_written_off"] = "Resto troppo piccolo per essere venduto, tolto dal registro.", ["dividend"] = "Dividendo accreditato.", + // Live engine. + ["late_exits_only"] = "Decisione in ritardo: solo uscite e stop, gli ingressi aspettano la prossima chiusura.", + ["entry_expired"] = "Ingresso scaduto: oltre l'orario in cui era valido.", + ["price_moved"] = "Il prezzo si è mosso troppo dall'orario previsto: ingresso scartato.", + ["missing_bars"] = "Mancano le barre di chiusura: niente nuove posizioni.", + ["superseded"] = "Sostituito da una decisione più recente.", + ["order_in_progress"] = "Un ordine sullo stesso strumento era ancora in corso.", + ["nothing_held"] = "Niente da vendere: la posizione era già chiusa.", + ["recovered"] = "Recuperato dopo un'assenza.", }; public static string Text(string code) => Texts.TryGetValue(code, out var text) ? text : code; diff --git a/src/Anubis/Trading/TradingService.cs b/src/Anubis/Trading/TradingService.cs index bd18c80..7948674 100644 --- a/src/Anubis/Trading/TradingService.cs +++ b/src/Anubis/Trading/TradingService.cs @@ -183,8 +183,18 @@ public sealed partial class TradingService : IDisposable Stages = new StageBook(db, clock, consent, reauthenticate ?? ((_, _, _) => Task.FromResult(false))); Risk = settings is null ? null : new RiskEngine(db, clock, Ledger, Stages, settings, fx, _catalog.GetAsync, Quotes.GetAsync) { StopFile = stopFile }; _settings = settings; + Engine = new LiveEngine(db, clock, Ledger, Stages, ManagerOf, Quotes.GetAsync, market?.UsCalendar, null, _logger) + { + WantData = market is null ? null : _ => market.WakeWorker(), + Ready = () => _started, + }; } + private volatile bool _started; + + /// The live engine (SPEC 5.5, issue #47): the decisions at their times, the planned orders, the recovery. + public LiveEngine Engine { get; } + private readonly SettingsStore? _settings; public StageBook Stages { get; } @@ -271,6 +281,7 @@ public sealed partial class TradingService : IDisposable } await GuardAsync("patrimonio", () => PhotographAsync(cancellationToken), cancellationToken).ConfigureAwait(false); + _started = true; } /// @@ -295,8 +306,29 @@ public sealed partial class TradingService : IDisposable new ScheduledJob("azioni_societarie", "Dividendi e frazionamenti nei registri", Schedule.Every(TimeSpan.FromHours(1)), CorporateActionsAsync), new ScheduledJob("rischio", "Controllo del rischio e dell'interruttore", Schedule.Every(TimeSpan.FromMinutes(1)), CheckRiskAsync), new ScheduledJob("stadi", "Retrocessioni e sola uscita delle strategie", Schedule.Every(TimeSpan.FromHours(1)), CheckStagesAsync), + .. Engine.Jobs(), + .. _market is null ? Array.Empty() : + [ + new ScheduledJob("fine-seduta", "Scadenza degli ordini giornalieri del simulatore azioni", + Schedule.Market(MarketAnchor.Close, TimeSpan.FromMinutes(1), _market.UsCalendar), ExpireDayOrdersAsync) { MaxLateness = TimeSpan.FromHours(12) }, + ], ]; + /// + /// The day orders of the stock simulator end at the close, as on the broker: the daily stops on fractions go back + /// at the next open (SPEC 5.5, 7.2). + /// + public async Task ExpireDayOrdersAsync(CancellationToken cancellationToken) + { + foreach (var manager in _managers.Values.Where(m => m.Account.Broker == Venues.Alpaca)) + { + if (manager.Broker is PaperBroker paper) + { + await paper.ExpireDayOrdersAsync(cancellationToken).ConfigureAwait(false); + } + } + } + /// The risk check of every minute (SPEC 9.2, 9.3): limits of each world, orders per minute, the STOP file. public async Task CheckRiskAsync(CancellationToken cancellationToken) { @@ -707,6 +739,7 @@ public sealed partial class TradingService : IDisposable public void Dispose() { + Engine.Dispose(); foreach (var manager in _managers.Values) { manager.Dispose(); diff --git a/tests/Anubis.Tests/LiveEngineTests.cs b/tests/Anubis.Tests/LiveEngineTests.cs new file mode 100644 index 0000000..a8ad544 --- /dev/null +++ b/tests/Anubis.Tests/LiveEngineTests.cs @@ -0,0 +1,156 @@ +using Anubis.Core; +using Anubis.Data; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// The live engine in simulation (issue #47, SPEC 5.5, 5.6, 12.3, 17 phase 6). +[TestClass] +public sealed class LiveEngineTests +{ + private static readonly DateOnly LiveFrom = new(2026, 9, 1); + + [TestMethod] + public async Task TheLiveEngineMakesTheSameTradesAsTheBacktest() + { + var last = LiveFrom.AddDays(39); + await using var live = await LiveRig.CreateAsync(LiveFrom, last).ConfigureAwait(false); + for (var day = LiveFrom; day <= last; day = day.AddDays(1)) + { + await live.DayAsync(day).ConfigureAwait(false); + } + + // The backtest decides on the close of the day before the first live morning and fills on the live days, with + // the same correctives (crypto regime) and the same risk stage. + var expected = LiveRig.Grouped(live.Backtest(LiveFrom.AddDays(-1), last), LiveFrom); + Assert.IsGreaterThanOrEqualTo(8, expected.Count, "The synthetic path should make the backtest trade: " + expected.Count); + LiveRig.AssertSameTrades(expected, await live.LiveFillsAsync().ConfigureAwait(false)); + + // Every decision was written once, with its run key. + var runs = await live.Rig.QueryAsync("SELECT run_key FROM engine_runs", r => r.Text("run_key")).ConfigureAwait(false); + Assert.HasCount(runs.Distinct(StringComparer.Ordinal).Count(), runs); + Assert.HasCount(40, runs); + Assert.AreEqual(0, live.Failures); + } + + /// + /// The stock side (SPEC 5.5): equity_meanrev decides after the close, buys at the next open, leaves five minutes + /// before the close; the trades are the backtest's, which buys at the open and sells at the close. + /// + [TestMethod] + public async Task TheStockSideMakesTheSameTradesAsTheBacktest() + { + var last = LiveFrom.AddDays(41); + await using var live = await StockRig.CreateAsync(LiveFrom, last).ConfigureAwait(false); + for (var day = LiveFrom; day <= last; day = day.AddDays(1)) + { + await live.SessionAsync(day).ConfigureAwait(false); + } + + var run = live.Backtest(StrategyNames.EquityMeanrev, LiveFrom.AddDays(-1), last); + var expected = LiveRig.Grouped(run, LiveFrom); + Assert.IsGreaterThanOrEqualTo(8, expected.Count, "The synthetic stocks should make the backtest trade: " + expected.Count); + LiveRig.AssertSameTrades(expected, await live.LiveFillsAsync().ConfigureAwait(false)); + + // One decision per session, each written once: the close of the day before the first one included, made at the + // first start as a recovered decision. + var runs = await live.Rig.QueryAsync("SELECT run_key FROM engine_runs", r => r.Text("run_key")).ConfigureAwait(false); + Assert.HasCount(runs.Distinct(StringComparer.Ordinal).Count(), runs); + var sessions = WeekdayCalendar.Sessions(LiveFrom.AddDays(-1), last).Count(); + Assert.HasCount(sessions, runs.Where(r => r.StartsWith(StrategyNames.EquityMeanrev + ":", StringComparison.Ordinal)).ToList()); + } + + /// + /// SPEC 17 phase 6: an accelerated run of at least 10 market days with faults injected (network, a restart + /// halfway through an order, the database unreachable) ends with ledger and account reconciled and no order sent + /// twice; the trades are still the backtest's. + /// + [TestMethod] + public async Task TenDaysWithFaultsEndReconciledWithoutDuplicateOrders() + { + var last = LiveFrom.AddDays(13); + await using var live = await LiveRig.CreateAsync(LiveFrom, last).ConfigureAwait(false); + var restarted = false; + for (var day = LiveFrom; day <= last; day = day.AddDays(1)) + { + var index = day.DayNumber - LiveFrom.DayNumber; + Func? faults = index switch + { + // Network down for the first minutes of the decision: no quotes, no broker. When it comes back, the + // answer to the first order is lost on the way back. + 0 => minute => + { + live.Rig.QuotesDown = live.Broker.Down = minute < 4; + if (minute == 4) + { + live.Broker.LoseNextAnswer = true; + } + + return Task.CompletedTask; + } + , + + // The process dies with a purchase working at the broker and starts again. + 11 => async minute => + { + if (!restarted && await live.WorkingOrdersAsync().ConfigureAwait(false) > 0) + { + restarted = true; + await live.RestartAsync().ConfigureAwait(false); + } + } + , + + // The database cannot be reached around the decision. + 12 => minute => + { + live.DatabaseDown = minute < 6; + return Task.CompletedTask; + } + , + _ => null, + }; + await live.DayAsync(day, faults).ConfigureAwait(false); + if (index == 0) + { + Assert.IsFalse(live.Broker.LoseNextAnswer, "An answer must have been lost."); + } + } + + Assert.IsTrue(restarted, "The run must restart halfway through an order."); + Assert.AreEqual(1, live.Restarts); + Assert.IsGreaterThan(0, live.Failures, "The faults must have hit the work."); + + // The trades are the backtest's: the faults delayed them by minutes, never changed or repeated them. + var expected = LiveRig.Grouped(live.Backtest(LiveFrom.AddDays(-1), last), LiveFrom); + LiveRig.AssertSameTrades(expected, await live.LiveFillsAsync().ConfigureAwait(false)); + + // No order twice: one order per client id, one execution per order key, one decision per run key. + var orders = await live.Rig.QueryAsync("SELECT client_order_id FROM orders", r => r.Text("client_order_id")).ConfigureAwait(false); + Assert.HasCount(orders.Distinct(StringComparer.Ordinal).Count(), orders); + foreach (var id in live.Sent.Select(r => r.ClientOrderId).Distinct(StringComparer.Ordinal)) + { + Assert.Contains(id, orders, "Every order sent is in the ledger."); + } + + var keys = await live.Rig.QueryAsync("SELECT order_key FROM executions", r => r.Text("order_key")).ConfigureAwait(false); + Assert.HasCount(keys.Distinct(StringComparer.Ordinal).Count(), keys); + var runs = await live.Rig.QueryAsync("SELECT run_key FROM engine_runs", r => r.Text("run_key")).ConfigureAwait(false); + Assert.HasCount(14, runs.Distinct(StringComparer.Ordinal)); + Assert.HasCount(14, runs); + + // Ledger and account agree; the account may keep dust below the lot that the ledger wrote off (SPEC 7.2). + var report = await live.Reconciler.ReconcileAsync(live.Manager, CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual(ReconcileOutcomes.Clean, report.Outcome, string.Join("; ", report.Differences)); + var ledger = (await live.Rig.Ledger.PositionsAsync(live.Okx.AccountId, CancellationToken.None).ConfigureAwait(false)) + .Where(p => p.Quantity != 0m) + .GroupBy(p => p.InstrumentId).ToDictionary(g => live.Instruments.Values.Single(i => i.Id == g.Key).Symbol, g => g.Sum(p => p.Quantity), StringComparer.Ordinal); + var account = (await live.Paper.GetPositionsAsync(CancellationToken.None).ConfigureAwait(false)).Where(p => p.Quantity != 0m) + .ToDictionary(p => p.Symbol, p => p.Quantity, StringComparer.Ordinal); + CollectionAssert.AreEquivalent(account.Where(a => a.Value >= (live.Instruments[a.Key].Spec.LotSize ?? 0m)).Select(a => a.Key).ToList(), ledger.Keys.ToList()); + foreach (var (symbol, quantity) in account.Where(a => ledger.ContainsKey(a.Key))) + { + Assert.IsLessThan(live.Instruments[symbol].Spec.LotSize ?? 0m, Math.Abs(quantity - ledger[symbol]), symbol); + } + } +} diff --git a/tests/Anubis.Tests/LiveStockSupport.cs b/tests/Anubis.Tests/LiveStockSupport.cs new file mode 100644 index 0000000..98f2a2b --- /dev/null +++ b/tests/Anubis.Tests/LiveStockSupport.cs @@ -0,0 +1,217 @@ +using Anubis.Backtest; +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// Every weekday is a session, 9:30–16:00 in New York (13:30–20:00 UTC in September and October). +internal sealed class WeekdayCalendar : IMarketCalendar +{ + public MarketSession? SessionOn(DateOnly day) => day.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday + ? null + : new MarketSession(day, new DateTimeOffset(day.ToDateTime(new TimeOnly(13, 30)), TimeSpan.Zero), new DateTimeOffset(day.ToDateTime(new TimeOnly(20, 0)), TimeSpan.Zero)); + + public static IEnumerable Sessions(DateOnly from, DateOnly to) + { + for (var day = from; day <= to; day = day.AddDays(1)) + { + if (day.DayOfWeek is not (DayOfWeek.Saturday or DayOfWeek.Sunday)) + { + yield return day; + } + } + } +} + +/// +/// The stock side of the live engine on the internal Alpaca simulator (issue #47, SPEC 5.5): signals after the close, +/// the orders at the next open, the exits of equity_meanrev five minutes before the close, with synthetic stocks that +/// dip for three sessions and recover. +/// +internal sealed class StockRig : IAsyncDisposable +{ + public static readonly string[] Stocks = ["AAA", "BBB", "CCC", "DDD", "EEE", "FFF"]; + + /// Dollars for a euro: the capital is entrusted in euro (SPEC 7.1). + public const decimal Rate = 1.10m; + + private readonly Dictionary _instruments = new(StringComparer.Ordinal); + private readonly WeekdayCalendar _calendar = new(); + + private StockRig(TradingRig rig) => Rig = rig; + + public TradingRig Rig { get; } + + public AccountContext Alpaca { get; private set; } = null!; + + public PaperBroker Paper { get; private set; } = null!; + + public OrderManager Manager { get; private set; } = null!; + + public LiveEngine Engine { get; private set; } = null!; + + public EquityBook Equity { get; private set; } = null!; + + public Dictionary> Bars { get; } = new(StringComparer.Ordinal); + + public static async Task CreateAsync(DateOnly liveFrom, DateOnly last, string strategy = StrategyNames.EquityMeanrev, decimal capital = 10_000m) + { + var rig = new StockRig(await TradingRig.CreateAsync().ConfigureAwait(false)); + await rig.SetUpAsync(liveFrom, last, strategy, capital).ConfigureAwait(false); + return rig; + } + + private async Task SetUpAsync(DateOnly liveFrom, DateOnly last, string strategy, decimal capital) + { + var none = CancellationToken.None; + Rig.Clock.Set(new DateTimeOffset(liveFrom.AddDays(-1).ToDateTime(new TimeOnly(12, 0)), TimeSpan.Zero)); + Alpaca = await Rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Simulation).ConfigureAwait(false); + var sessions = WeekdayCalendar.Sessions(last.AddDays(-700), last).ToList(); + var store = new BarStore(Rig.Db, Rig.Clock); + var members = new List(); + for (var i = 0; i < Stocks.Length; i++) + { + var symbol = Stocks[i]; + _instruments[symbol] = await Rig.InstrumentAsync(TradingRig.Stock(symbol)).ConfigureAwait(false); + Bars[symbol] = Path(sessions, 50 + (i * 20), phase: i * 3, seed: (uint)(i + 11)); + members.Add(new UniverseMember(_instruments[symbol].Id, symbol, i + 1, 1e9)); + } + + _instruments[StrategyNames.MarketSymbol] = await Rig.InstrumentAsync(TradingRig.Stock(StrategyNames.MarketSymbol) with { IsFund = true }).ConfigureAwait(false); + Bars[StrategyNames.MarketSymbol] = Path(sessions, 400, phase: 5, seed: 3, dips: false); + foreach (var (symbol, bars) in Bars) + { + await store.UpsertDailyAsync(_instruments[symbol].Id, bars.Where(b => b.Day < liveFrom), "test", none).ConfigureAwait(false); + } + + await new UniverseStore(Rig.Db, Rig.Clock).SaveAsync(Universes.Equity, liveFrom.AddDays(-30), members, none).ConfigureAwait(false); + await Rig.Db.WriteAsync(s => s.ExecuteAsync( + "INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at, share, stage_since) VALUES (@id, @s, @a, @st, 0, @j, @now, @now, 1, @now)", + none, ("id", Ids.NewId(Rig.Clock)), ("s", strategy), ("a", Alpaca.AccountId), ("st", StrategyStages.Simulation), ("j", new DbJson("{}")), ("now", Rig.Clock.UtcNow)), none) + .ConfigureAwait(false); + var fx = new FxStore(Rig.Db, Rig.Clock); + await fx.UpsertAsync(WeekdayCalendar.Sessions(liveFrom.AddDays(-10), last).Select(d => new FxRate("EUR", "USD", d, Rate, "test")), none).ConfigureAwait(false); + await new Capital(Rig.Db, Rig.Clock, Rig.Ledger, fx).SetAsync(Venues.Alpaca, capital, "test", none).ConfigureAwait(false); + Paper = Rig.Paper(PaperOptions.Alpaca(), Alpaca.AccountId); + await Paper.DepositAsync(capital * Rate, "USD", none).ConfigureAwait(false); + Manager = Rig.Manager(Paper, Alpaca); + var stages = new StageBook(Rig.Db, Rig.Clock, TradingConsent.None, (_, _, _) => Task.FromResult(false)); + Engine = new LiveEngine(Rig.Db, Rig.Clock, Rig.Ledger, stages, id => id == Alpaca.AccountId ? Manager : null, Rig.QuoteAsync, _calendar); + Equity = new EquityBook(Rig.Db, Rig.Clock, Rig.Ledger, fx); + } + + /// + /// A slow rise with noise and, every 17 sessions, three sessions down of 2.5% each: RSI(2) falls under 10 and the + /// close under its 5-session average, so equity_meanrev buys and sells a few sessions later. + /// + public static List Path(IReadOnlyList sessions, double start, int phase, uint seed, bool dips = true) + { + var bars = new List(sessions.Count); + var price = start; + var state = (seed * 2654435761u) + 1u; + double Next() + { + state = (state * 1664525u) + 1013904223u; + return (state >> 8) / (double)(1 << 24); + } + + for (var i = 0; i < sessions.Count; i++) + { + var cycle = (i + phase) % 17; + var change = dips && cycle >= 14 ? -0.025 : (dips ? 0.008 : 0.003) + ((Next() - 0.5) * 0.012); + var open = Math.Round(price * (1 + ((Next() - 0.5) * 0.004)), 2); + var close = Math.Round(open * (1 + change), 2); + var low = Math.Round(Math.Min(open, close) * (1 - (Next() * 0.006)), 2); + var high = Math.Round(Math.Max(open, close) * (1 + (Next() * 0.006)), 2); + bars.Add(new DailyBar(sessions[i], open, high, low, close, 5_000_000)); + price = close; + } + + return bars; + } + + private DailyBar? Bar(string symbol, DateOnly day) => Bars[symbol].SingleOrDefault(b => b.Day == day); + + private void Quotes(DateOnly day, Func pick) + { + foreach (var symbol in Bars.Keys) + { + if (Bar(symbol, day) is { } bar) + { + var price = (decimal)pick(bar); + Rig.Quote(symbol, price - 0.01m, price + 0.01m, 1000m); + } + } + } + + private async Task MinutesAsync(int count) + { + for (var i = 0; i < count; i++) + { + await Engine.PulseAsync(CancellationToken.None).ConfigureAwait(false); + await Rig.TurnsAsync(Manager, 1, TimeSpan.FromMinutes(1)).ConfigureAwait(false); + } + } + + /// + /// One session: the orders decided last night go at 9:35 with the open as price; at midday the quotes touch the + /// low (stops); at 15:55 the price is the close and the meanrev exits leave; at 16:16 the bar of the day arrives and + /// at 16:20 the signals are computed; the day orders expire and the equity is photographed. + /// + public async Task SessionAsync(DateOnly day) + { + if (_calendar.SessionOn(day) is not { } session) + { + return; + } + + var none = CancellationToken.None; + Rig.Clock.Set(session.OpenUtc.AddMinutes(5)); + Quotes(day, b => b.Open); + await MinutesAsync(15).ConfigureAwait(false); + Rig.Clock.Set(session.OpenUtc.AddHours(3)); + Quotes(day, b => b.Low); + await MinutesAsync(3).ConfigureAwait(false); + Rig.Clock.Set(session.CloseUtc.AddMinutes(-5)); + Quotes(day, b => b.Close); + await MinutesAsync(4).ConfigureAwait(false); + Rig.Clock.Set(session.CloseUtc.AddMinutes(1)); + await Paper.ExpireDayOrdersAsync(none).ConfigureAwait(false); + Rig.Clock.Set(session.CloseUtc.AddMinutes(16)); + await Task.WhenAll(Bars.Select(b => new BarStore(Rig.Db, Rig.Clock).UpsertDailyAsync(_instruments[b.Key].Id, b.Value.Where(x => x.Day == day), "test", none))) + .ConfigureAwait(false); + Rig.Clock.Set(session.CloseUtc.AddMinutes(20)); + await MinutesAsync(3).ConfigureAwait(false); + foreach (var symbol in Stocks) + { + await Rig.Ledger.MarkAsync(_instruments[symbol].Id, (decimal)Bar(symbol, day)!.Close, none).ConfigureAwait(false); + } + + await Equity.TakeAsync(none).ConfigureAwait(false); + } + + public BacktestRun Backtest(string strategy, DateOnly from, DateOnly to, decimal capital = 10_000m * Rate) + { + var instruments = Bars.Select(b => new BacktestInstrument(_instruments[b.Key].Spec, b.Value.Where(x => x.Day <= to && x.Day >= to.AddDays(-700)).ToList())); + var calendar = Bars[Stocks[0]].Select(b => b.Day).Where(d => d <= to.AddDays(14)); + var data = new BacktestDataset(instruments, "USD", calendar, [StrategyNames.MarketSymbol]); + var options = StrategyPipeline.For(strategy, data, new BacktestOptions { InitialCapital = capital, From = from, To = to }); + return BacktestEngine.Run(LiveEngine.CreateStrategy(strategy, null), data, options); + } + + /// The live fills by New York day, symbol and side. + public async Task> LiveFillsAsync() + { + var rows = await Rig.QueryAsync("SELECT f.executed_at, i.symbol, f.side, f.quantity FROM fills f JOIN instruments i ON i.id = f.instrument_id ORDER BY f.executed_at", + r => (At: r.Moment("executed_at"), Symbol: r.Text("symbol"), Side: Wire.Side(r.Text("side")), Quantity: r.Money("quantity"))).ConfigureAwait(false); + return [.. rows.GroupBy(r => (DateOnly.FromDateTime(r.At.UtcDateTime), r.Symbol, r.Side)).Select(g => (g.Key.Item1, g.Key.Symbol, g.Key.Side, g.Sum(x => x.Quantity)))]; + } + + public ValueTask DisposeAsync() + { + Engine.Dispose(); + return Rig.DisposeAsync(); + } +} diff --git a/tests/Anubis.Tests/LiveSupport.cs b/tests/Anubis.Tests/LiveSupport.cs new file mode 100644 index 0000000..46a538b --- /dev/null +++ b/tests/Anubis.Tests/LiveSupport.cs @@ -0,0 +1,287 @@ +using Anubis.Backtest; +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// +/// The live engine on the internal simulator, driven by a manual clock through synthetic days (issue #47): the bars +/// of each day arrive at its end, the quotes follow the open, the low and the close of the day, and the engine and +/// the order manager work minute by minute. The same bars run through the backtest for the parity test; the broker, +/// the quotes and the database can fail, and the process can restart, for the fault run. +/// +internal sealed class LiveRig : IAsyncDisposable +{ + public static readonly string[] Coins = ["BTC-EUR", "ETH-EUR", "SOL-EUR"]; + + private readonly Dictionary _instruments = new(StringComparer.Ordinal); + private readonly List _sent = []; + + private LiveRig(TradingRig rig) => Rig = rig; + + public TradingRig Rig { get; } + + public AccountContext Okx { get; private set; } = null!; + + public PaperBroker Paper { get; private set; } = null!; + + /// The simulator behind a broker that can lose answers or go down (network faults). + public FaultyBroker Broker { get; private set; } = null!; + + public OrderManager Manager { get; private set; } = null!; + + public StageBook Stages { get; private set; } = null!; + + public LiveEngine Engine { get; private set; } = null!; + + public EquityBook Equity { get; private set; } = null!; + + public Reconciler Reconciler { get; private set; } = null!; + + public Dictionary> Bars { get; } = new(StringComparer.Ordinal); + + public IReadOnlyDictionary Instruments => _instruments; + + /// Work that failed as the scheduler would see it: a pulse or a turn during a fault. + public int Failures { get; private set; } + + public int Restarts { get; private set; } + + /// Every order request that reached the broker, across restarts. + public IReadOnlyList Sent => [.. _sent, .. Broker.Sent]; + + /// Every new database connection fails while this is true. + public bool DatabaseDown + { + get => Rig.Db.Unreachable; + set => Rig.Db.Unreachable = value; + } + + /// + /// synthetic daily bars for each coin up to ; those before + /// are stored at once, the others arrive one per day. + /// + public static async Task CreateAsync(DateOnly liveFrom, DateOnly last, int days = 700, string stage = StrategyStages.Simulation, decimal capital = 10_000m) + { + var rig = new LiveRig(await TradingRig.CreateAsync().ConfigureAwait(false)); + await rig.SetUpAsync(liveFrom, last, days, stage, capital).ConfigureAwait(false); + return rig; + } + + private async Task SetUpAsync(DateOnly liveFrom, DateOnly last, int days, string stage, decimal capital) + { + var none = CancellationToken.None; + Rig.Clock.Set(new DateTimeOffset(liveFrom.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero)); + Okx = await Rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false); + var store = new BarStore(Rig.Db, Rig.Clock); + var seed = 7u; + foreach (var (symbol, start) in new[] { ("BTC-EUR", 30000.0), ("ETH-EUR", 2000.0), ("SOL-EUR", 60.0) }) + { + var spec = MarketDataStoreTests.Okx(symbol) with { ListedAt = null }; + _instruments[symbol] = await Rig.InstrumentAsync(spec).ConfigureAwait(false); + Bars[symbol] = Synthetic(last.AddDays(1 - days), days, start, seed++); + await store.UpsertDailyAsync(_instruments[symbol].Id, Bars[symbol].Where(b => b.Day < liveFrom.AddDays(-1)), "test", none).ConfigureAwait(false); + } + + await Rig.Db.WriteAsync(s => s.ExecuteAsync( + "INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at, share, stage_since) VALUES (@id, @s, @a, @st, 0, @j, @now, @now, 1, @now)", + none, ("id", Ids.NewId(Rig.Clock)), ("s", StrategyNames.CryptoTrend), ("a", Okx.AccountId), ("st", stage), ("j", new DbJson("{}")), ("now", Rig.Clock.UtcNow)), none) + .ConfigureAwait(false); + var fx = new FxStore(Rig.Db, Rig.Clock); + await new Capital(Rig.Db, Rig.Clock, Rig.Ledger, fx).SetAsync(Venues.Okx, capital, "test", none).ConfigureAwait(false); + Paper = Rig.Paper(PaperOptions.Okx(), Okx.AccountId); + await Paper.DepositAsync(capital, "EUR", none).ConfigureAwait(false); + Stages = new StageBook(Rig.Db, Rig.Clock, TradingConsent.None, (_, _, _) => Task.FromResult(false)); + Equity = new EquityBook(Rig.Db, Rig.Clock, Rig.Ledger, fx); + Reconciler = new Reconciler(Rig.Db, Rig.Clock, Rig.Ledger); + Build(); + } + + private void Build() + { + Broker = new FaultyBroker(Paper); + Manager = Rig.Manager(Broker, Okx); + Engine = new LiveEngine(Rig.Db, Rig.Clock, Rig.Ledger, Stages, id => id == Okx.AccountId ? Manager : null, Rig.QuoteAsync); + } + + /// + /// The process dies and starts again: a new simulator on its saved book, a new order manager and engine on the same + /// database, the account reconciled before the first pulse as at a real start (SPEC 9.4). + /// + public async Task RestartAsync() + { + _sent.AddRange(Broker.Sent); + Engine.Dispose(); + Paper = Rig.Paper(PaperOptions.Okx(), Okx.AccountId); + Build(); + Restarts++; + await Reconciler.ReconcileAsync(Manager, CancellationToken.None).ConfigureAwait(false); + } + + /// + /// A deterministic path with regimes: long rises, falls and flat stretches with noise, so the trend strategy enters, + /// moves its stops and leaves. The open of each day is the close of the day before; the volume makes the coin + /// liquid enough for the universe. + /// + public static List Synthetic(DateOnly first, int days, double start, uint seed) + { + var bars = new List(days); + var price = start; + var state = (seed * 2654435761u) + 1u; + double Next() + { + state = (state * 1664525u) + 1013904223u; + return (state >> 8) / (double)(1 << 24); + } + + for (var i = 0; i < days; i++) + { + var regime = ((i / 45) + (int)seed) % 4; + var drift = regime switch { 0 => 0.009, 1 => -0.008, 2 => 0.002, _ => 0.012 }; + var change = drift + ((Next() - 0.5) * 0.04); + var open = price; + var close = Math.Round(price * (1 + change), 2); + var low = Math.Round(Math.Min(open, close) * (1 - (Next() * 0.01)), 2); + var high = Math.Round(Math.Max(open, close) * (1 + (Next() * 0.01)), 2); + bars.Add(new DailyBar(first.AddDays(i), open, high, low, close, 50_000_000 / close)); + price = close; + } + + return bars; + } + + public DailyBar Bar(string symbol, DateOnly day) => Bars[symbol].Single(b => b.Day == day); + + /// The bar of a day reaches the database, as the history step stores it after midnight. + public Task StoreBarAsync(DateOnly day) => Task.WhenAll(Coins.Select(c => + new BarStore(Rig.Db, Rig.Clock).UpsertDailyAsync(_instruments[c].Id, Bars[c].Where(b => b.Day == day), "test", CancellationToken.None))); + + public void Quotes(DateOnly day, Func pick) + { + foreach (var coin in Coins) + { + var price = (decimal)pick(Bar(coin, day)); + Rig.Quote(coin, price * 0.9999m, price * 1.0001m, 1000m); + } + } + + /// + /// One UTC day, minute by minute where it matters: yesterday's bar arrives, from 00:05 the engine pulses every + /// minute with the open as price and the orders are worked; at noon the quotes go to the day's low (stops), at the + /// end of the day to the close, where positions are valued and the equity photographed. + /// runs before each morning minute with its index: the fault tests break and mend things there. + /// + public async Task DayAsync(DateOnly day, Func? minute = null, int morning = 20) + { + var none = CancellationToken.None; + var midnight = new DateTimeOffset(day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero); + Rig.Clock.Set(midnight.AddMinutes(1)); + await StoreBarAsync(day.AddDays(-1)).ConfigureAwait(false); + Rig.Clock.Set(midnight.AddMinutes(5)); + Quotes(day, b => b.Open); + for (var i = 0; i < morning; i++) + { + if (minute is not null) + { + await minute(i).ConfigureAwait(false); + } + + await MinuteAsync().ConfigureAwait(false); + } + + Rig.Clock.Set(midnight.AddHours(12)); + Quotes(day, b => b.Low); + for (var i = 0; i < 3; i++) + { + await MinuteAsync().ConfigureAwait(false); + } + + Rig.Clock.Set(midnight.AddHours(23).AddMinutes(55)); + Quotes(day, b => b.Close); + for (var i = 0; i < 2; i++) + { + await MinuteAsync().ConfigureAwait(false); + } + + foreach (var coin in Coins) + { + await Rig.Ledger.MarkAsync(_instruments[coin].Id, (decimal)Bar(coin, day).Close, none).ConfigureAwait(false); + } + + await Equity.TakeAsync(none).ConfigureAwait(false); + } + + /// One minute of the process: the engine's pulse, then a turn of the simulator and of the order manager. + private async Task MinuteAsync() + { + await SafeAsync(() => Engine.PulseAsync(CancellationToken.None)).ConfigureAwait(false); + await SafeAsync(async () => + { + Rig.Refresh(); + await Paper.PumpAsync(CancellationToken.None).ConfigureAwait(false); + await Manager.TickAsync(CancellationToken.None).ConfigureAwait(false); + }).ConfigureAwait(false); + Rig.Clock.Advance(TimeSpan.FromMinutes(1)); + } + + /// A failure the scheduler would log and retry at the next run: counted, never thrown. + private async Task SafeAsync(Func work) + { + try + { + await work().ConfigureAwait(false); + } + catch (Exception ex) when (ex is System.Data.Common.DbException or BrokerException) + { + Failures++; + } + } + + /// Orders other than the protective stops still working at the simulator. + public async Task WorkingOrdersAsync() => + (await Paper.GetOpenOrdersAsync(CancellationToken.None).ConfigureAwait(false)).Count(o => o.StopPrice is null); + + /// The same bars through the backtest, with the same correctives and risk stage, from . + public BacktestRun Backtest(DateOnly from, DateOnly to, decimal capital = 10_000m) + { + var data = new BacktestDataset(Coins.Select(c => new BacktestInstrument(_instruments[c].Spec, Bars[c].Where(b => b.Day <= to).ToList())), "EUR"); + var options = StrategyPipeline.For(StrategyNames.CryptoTrend, data, new BacktestOptions { InitialCapital = capital, From = from, To = to }); + return BacktestEngine.Run(LiveEngine.CreateStrategy(StrategyNames.CryptoTrend, null), data, options); + } + + /// The backtest fills from , by day, symbol and side. + public static List<(DateOnly Day, string Symbol, OrderSide Side, decimal Quantity)> Grouped(BacktestRun run, DateOnly from) => + [.. run.Fills.Where(f => f.Day >= from).GroupBy(f => (f.Day, f.Symbol, f.Side)).Select(g => (g.Key.Day, g.Key.Symbol, g.Key.Side, g.Sum(f => f.Quantity)))]; + + /// The live fills by UTC day, symbol and side. + public async Task> LiveFillsAsync() + { + var rows = await Rig.QueryAsync("SELECT f.executed_at, i.symbol, f.side, f.quantity FROM fills f JOIN instruments i ON i.id = f.instrument_id ORDER BY f.executed_at", + r => (At: r.Moment("executed_at"), Symbol: r.Text("symbol"), Side: Wire.Side(r.Text("side")), Quantity: r.Money("quantity"))).ConfigureAwait(false); + return [.. rows.GroupBy(r => (DateOnly.FromDateTime(r.At.UtcDateTime), r.Symbol, r.Side)).Select(g => (g.Key.Item1, g.Key.Symbol, g.Key.Side, g.Sum(x => x.Quantity)))]; + } + + /// The live fills match the backtest's: the same days, symbols and sides, quantities within 1%. + public static void AssertSameTrades(IReadOnlyList<(DateOnly Day, string Symbol, OrderSide Side, decimal Quantity)> expected, + IReadOnlyList<(DateOnly Day, string Symbol, OrderSide Side, decimal Quantity)> actual) + { + var report = "backtest:\n" + string.Join("\n", expected.Select(e => " " + e)) + "\nlive:\n" + string.Join("\n", actual.Select(a => " " + a)); + Console.WriteLine(report); + Assert.HasCount(expected.Count, actual, report); + foreach (var e in expected) + { + var match = actual.SingleOrDefault(a => a.Day == e.Day && a.Symbol == e.Symbol && a.Side == e.Side); + Assert.AreNotEqual(default, match, "Missing live fill " + e + "\n" + report); + Assert.IsLessThanOrEqualTo(0.01m, Math.Abs(match.Quantity - e.Quantity) / e.Quantity, "Quantity apart: " + e + " vs " + match + "\n" + report); + } + } + + public ValueTask DisposeAsync() + { + DatabaseDown = false; + Engine.Dispose(); + return Rig.DisposeAsync(); + } +} From 680cab4bb681f0c60b6707b178dd41951437d11b Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 11 Nov 2026 18:38:50 +0100 Subject: [PATCH 03/12] Recover missed work after an absence by the rules of SPEC 5.6 (refs #49) At the start the host measures how long the bot was away from the last job that finished, records the absence and writes it in the diary; one longer than a day is kept for the Panoramica until the user has seen it. A job can now say how a run missed while the bot was off is treated: the nightly backup, the exchange rates, the market calendar and the cleanup run once at the restart, queued, however late; a job with a deadline is skipped past it and the diary says so. Corporate actions are read before the reconciliation puts any stop back. A decision the engine makes late because of an absence is written in the diary as recovered, as are the orders it releases late; entries that moved too far or expired are dropped with their reason. Tests switch the bot off for 3 hours, 20 hours and 3 days with a manual clock and check each of those rows. Co-Authored-By: Claude Opus 5.5 --- src/Anubis.Server/AnubisHost.cs | 42 +++++- src/Anubis/Core/Scheduling.cs | 98 +++++++++++- src/Anubis/Data/MarketDataService.cs | 12 +- src/Anubis/Trading/Absences.cs | 92 ++++++++++++ src/Anubis/Trading/LiveEngine.cs | 8 + src/Anubis/Trading/TradingService.cs | 8 + tests/Anubis.Tests/AbsenceTests.cs | 199 +++++++++++++++++++++++++ tests/Anubis.Tests/LiveStockSupport.cs | 4 +- tests/Anubis.Tests/LiveSupport.cs | 9 ++ 9 files changed, 454 insertions(+), 18 deletions(-) create mode 100644 src/Anubis/Trading/Absences.cs create mode 100644 tests/Anubis.Tests/AbsenceTests.cs diff --git a/src/Anubis.Server/AnubisHost.cs b/src/Anubis.Server/AnubisHost.cs index ef1eec2..cc5be12 100644 --- a/src/Anubis.Server/AnubisHost.cs +++ b/src/Anubis.Server/AnubisHost.cs @@ -312,7 +312,28 @@ internal sealed partial class AnubisHost( // The laboratory computes on its own thread and reads only local data; the demo shows appendix F and runs none. _lab = options.Demo ? null : new Laboratory(_db, clock, Config.Data.Research, logger); _services = new AppServices(_db, settings, secrets, access, backups, scheduler, _market, _trading, _lab); - StartScheduler(scheduler, backups); + + // Before the scheduler writes its first run: how long the bot was away, and which runs it missed (SPEC 5.6). + var lastDues = new Dictionary(StringComparer.Ordinal); + try + { + if (!options.Demo) + { + await new AbsenceBook(_db, clock) { Zone = Config.TimeZone }.RecordAsync(cancellationToken).ConfigureAwait(false); + } + + foreach (var (name, due) in await _db.ReadAsync(s => s.QueryAsync("SELECT name, last_due_at FROM jobs WHERE last_due_at IS NOT NULL", + r => (r.Text("name"), r.Moment("last_due_at"))), cancellationToken).ConfigureAwait(false)) + { + lastDues[name] = due; + } + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + LogStepFailed(logger, ex); + } + + StartScheduler(scheduler, backups, lastDues); SetStatus(HostMode.Ready, null); } @@ -431,14 +452,15 @@ internal sealed partial class AnubisHost( !options.Demo && (overrides is null ? true : overrides.Trading == true) && environment.GetValueOrDefault("ANUBIS_TRADING") is not ("0" or "off" or "false"); - private void StartScheduler(Scheduler scheduler, Backups backups) + private void StartScheduler(Scheduler scheduler, Backups backups, Dictionary lastDues) { - scheduler.Add(new ScheduledJob("backup", "Salvataggio del database", Schedule.Daily(new TimeOnly(3, 30), Config.TimeZone), + // A backup missed while the bot was off is taken once at the restart, whenever it comes (SPEC 5.6). + var backup = new ScheduledJob("backup", "Salvataggio del database", Schedule.Daily(new TimeOnly(3, 30), Config.TimeZone), async ct => await backups.TakeAsync(_db!, "notturno", ct).ConfigureAwait(false)) - { MaxLateness = TimeSpan.FromHours(2) }); - foreach (var job in (_market?.Jobs() ?? []).Concat(_trading?.Jobs() ?? [])) + { MaxLateness = TimeSpan.FromHours(2), CatchUpWithin = TimeSpan.FromDays(3650) }; + foreach (var job in new[] { backup }.Concat(_market?.Jobs() ?? []).Concat(_trading?.Jobs() ?? [])) { - scheduler.Add(job); + scheduler.Add(job, lastDues.TryGetValue(job.Name, out var due) ? due : null); } _schedulerStop = new CancellationTokenSource(); @@ -525,7 +547,13 @@ internal sealed partial class AnubisHost( { await _db!.WriteAsync(async s => { - var description = _services?.Scheduler.Upcoming(100).FirstOrDefault(u => u.Name == run.Name)?.Description ?? run.Name; + var description = run.Description ?? _services?.Scheduler.Upcoming(100).FirstOrDefault(u => u.Name == run.Name)?.Description ?? run.Name; + if (AbsenceBook.MissedLine(run with { Description = description }, Config.TimeZone) is { } line) + { + await Diary.WriteAsync(s, clock, DiaryKinds.System, run.Outcome == JobOutcome.Completed ? "job_recovered" : "job_skipped", line, + new { job = run.Name, due = run.DueUtc }, cancellationToken).ConfigureAwait(false); + } + var updated = await s.ExecuteAsync( "UPDATE jobs SET last_due_at = @d, last_started_at = @s, last_finished_at = @f, last_outcome = @o, last_error = @e, updated_at = @f WHERE name = @n", ("d", run.DueUtc), ("s", run.StartedUtc), ("f", run.FinishedUtc), ("o", run.Outcome.ToString().ToLowerInvariant()), ("e", run.Error), ("n", run.Name)).ConfigureAwait(false); diff --git a/src/Anubis/Core/Scheduling.cs b/src/Anubis/Core/Scheduling.cs index 40b371c..c927fb9 100644 --- a/src/Anubis/Core/Scheduling.cs +++ b/src/Anubis/Core/Scheduling.cs @@ -121,6 +121,12 @@ public sealed record ScheduledJob(string Name, string Description, Schedule Sche /// A move of the bot the user reads in "Prossime mosse" (SPEC 13.6), not a housekeeping job. public bool IsMove { get; init; } + + /// + /// A run missed while the bot was off is made once at the restart, queued, when the restart comes within this + /// time of the missed run; later it is skipped and reported (SPEC 5.6). Null: a missed run is simply not made. + /// + public TimeSpan? CatchUpWithin { get; init; } } public enum JobOutcome @@ -131,7 +137,13 @@ public enum JobOutcome } /// Published on the bus after every run, skip or failure. -public sealed record JobRun(string Name, DateTimeOffset DueUtc, DateTimeOffset StartedUtc, DateTimeOffset FinishedUtc, JobOutcome Outcome, string? Error); +public sealed record JobRun(string Name, DateTimeOffset DueUtc, DateTimeOffset StartedUtc, DateTimeOffset FinishedUtc, JobOutcome Outcome, string? Error) +{ + /// The run was missed while the bot was off and made, or skipped, at the restart (SPEC 5.6). + public bool Missed { get; init; } + + public string? Description { get; init; } +} /// A run coming up, for "Prossime mosse" and the jobs list. public sealed record UpcomingRun(string Name, string Description, DateTimeOffset DueUtc) @@ -148,21 +160,60 @@ public sealed partial class Scheduler(IClock clock, EventBus bus, ILogger.Instance; private readonly Lock _gate = new(); private readonly Dictionary _jobs = new(StringComparer.Ordinal); + private readonly Dictionary _recovering = new(StringComparer.Ordinal); + private readonly List _missed = []; private TaskCompletionSource _changed = new(TaskCreationOptions.RunContinuationsAsynchronously); /// Moment of the last loop iteration; the health check uses it to see the loop is alive. public DateTimeOffset? LastBeatUtc { get; private set; } - public void Add(ScheduledJob job) + public void Add(ScheduledJob job) => Add(job, null); + + /// + /// Adds a job whose last run, from an earlier life of the process, was due at . A job with + /// that missed a run since then makes it once at the start, or reports it + /// skipped when the restart is too late (SPEC 5.6). + /// + public void Add(ScheduledJob job, DateTimeOffset? lastDue) { ArgumentNullException.ThrowIfNull(job); + var now = clock.UtcNow; + var missed = job.CatchUpWithin is not null && lastDue is { } last ? LastMissed(job.Schedule, last, now) : null; lock (_gate) { - _jobs[job.Name] = (job, job.Schedule.NextAfter(clock.UtcNow)); + if (missed is { } due && now - due <= job.CatchUpWithin) + { + _jobs[job.Name] = (job, now); + _recovering[job.Name] = due; + } + else + { + _jobs[job.Name] = (job, job.Schedule.NextAfter(now)); + if (missed is { } skipped) + { + _missed.Add(new JobRun(job.Name, skipped, now, now, JobOutcome.Skipped, "Saltato al riavvio: oltre l'orario utile.") + { Missed = true, Description = job.Description }); + } + } + _changed.TrySetResult(); } } + /// The last due time after and not after : the run the absence took. + private static DateTimeOffset? LastMissed(Schedule schedule, DateTimeOffset last, DateTimeOffset now) + { + DateTimeOffset? missed = null; + var at = schedule.NextAfter(last); + for (var i = 0; i < 100_000 && at is { } due && due <= now; i++) + { + missed = due; + at = schedule.NextAfter(due); + } + + return missed; + } + public IReadOnlyList Upcoming(int count = 10) { lock (_gate) @@ -224,8 +275,13 @@ public sealed partial class Scheduler(IClock clock, EventBus bus, ILogger due; + List missed; lock (_gate) { + // The runs an absence took and the restart came too late for: reported once, at the first round. + missed = [.. _missed]; + _missed.Clear(); + due = _jobs.Values.Where(j => j.Due is { } d && d <= now).Select(j => (j.Job, j.Due!.Value)).OrderBy(j => j.Value).ToList(); foreach (var (job, _) in due) { @@ -233,9 +289,28 @@ public sealed partial class Scheduler(IClock clock, EventBus bus, ILogger job.MaxLateness) { LogSkipped(_logger, job.Name, dueAt); @@ -256,6 +331,21 @@ public sealed partial class Scheduler(IClock clock, EventBus bus, ILoggerA run missed while the bot was off, made once now: never skipped for lateness, reported as recovered. + private async Task RecoverAsync(ScheduledJob job, DateTimeOffset dueAt, DateTimeOffset started, CancellationToken cancellationToken) + { + try + { + await job.Run(cancellationToken).ConfigureAwait(false); + bus.Publish(new JobRun(job.Name, dueAt, started, clock.UtcNow, JobOutcome.Completed, null) { Missed = true, Description = job.Description }); + } + catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + LogFailed(_logger, ex, job.Name); + bus.Publish(new JobRun(job.Name, dueAt, started, clock.UtcNow, JobOutcome.Failed, ex.Message) { Missed = true, Description = job.Description }); + } + } + [LoggerMessage(Level = LogLevel.Warning, Message = "Job {Job} skipped: it was due at {Due} and is too late to run")] private static partial void LogSkipped(ILogger logger, string job, DateTimeOffset due); diff --git a/src/Anubis/Data/MarketDataService.cs b/src/Anubis/Data/MarketDataService.cs index fb3b492..8430066 100644 --- a/src/Anubis/Data/MarketDataService.cs +++ b/src/Anubis/Data/MarketDataService.cs @@ -105,21 +105,22 @@ public sealed partial class MarketDataService : IDisposable { MaxLateness = TimeSpan.FromHours(6) }, new("dati-azioni-chiusura", "Barre giornaliere delle azioni dopo la chiusura", Schedule.Market(MarketAnchor.Close, TimeSpan.FromMinutes(30), UsCalendar), _ => WakeWorker()) { MaxLateness = TimeSpan.FromHours(6) }, + // SPEC 5.6: after an absence the last rate available is downloaded at once. new("dati-cambi-mattina", "Cambi di riferimento della BCE", Schedule.Daily(new TimeOnly(8, 0), Zones.Rome), References.RefreshFxAsync) - { MaxLateness = TimeSpan.FromHours(4) }, + { MaxLateness = TimeSpan.FromHours(4), CatchUpWithin = TimeSpan.FromDays(3650) }, new("dati-cambi-pomeriggio", "Cambi di riferimento della BCE", Schedule.Daily(new TimeOnly(16, 30), Zones.Rome), References.RefreshFxAsync) - { MaxLateness = TimeSpan.FromHours(4) }, + { MaxLateness = TimeSpan.FromHours(4), CatchUpWithin = TimeSpan.FromDays(3650) }, new("dati-calendario", "Calendario economico, riunioni e trimestrali", Schedule.Every(TimeSpan.FromHours(1)), RefreshCalendarAsync) { MaxLateness = TimeSpan.FromMinutes(50) }, new("dati-umore", "Umore del mercato", Schedule.Every(TimeSpan.FromHours(1)), References.RefreshMoodAsync) { MaxLateness = TimeSpan.FromMinutes(50) }, new("dati-spread", "Campione orario degli spread delle crypto", Schedule.Every(TimeSpan.FromHours(1)), SampleSpreadsAsync) { MaxLateness = TimeSpan.FromMinutes(50) }, new("dati-calendario-borsa", "Calendario di borsa di Alpaca", Schedule.Daily(new TimeOnly(4, 0), Zones.Rome), RefreshUsCalendarAsync) - { MaxLateness = TimeSpan.FromHours(12) }, + { MaxLateness = TimeSpan.FromHours(12), CatchUpWithin = TimeSpan.FromDays(3650) }, new("dati-azioni-societarie", "Frazionamenti e dividendi prima dell'apertura", Schedule.Market(MarketAnchor.Open, TimeSpan.FromHours(-1), UsCalendar), RefreshCorporateActionsAsync) { MaxLateness = TimeSpan.FromMinutes(50) }, new("dati-pulizia", "Pulizia delle barre al minuto e degli spread vecchi", Schedule.Daily(new TimeOnly(3, 45), Zones.Rome), PruneAsync) - { MaxLateness = TimeSpan.FromHours(12) }, + { MaxLateness = TimeSpan.FromHours(12), CatchUpWithin = TimeSpan.FromDays(3650) }, ]; /// @@ -420,7 +421,8 @@ public sealed partial class MarketDataService : IDisposable await UsCalendar.SaveAsync(sessions, today.AddDays(-30), today.AddDays(90), cancellationToken).ConfigureAwait(false); } - private async Task RefreshCorporateActionsAsync(CancellationToken cancellationToken) + /// Splits and dividends of the stock universe from Alpaca; read first at a restart, before any stop is touched (SPEC 5.6, 6.10). + public async Task RefreshCorporateActionsAsync(CancellationToken cancellationToken) { if (await AlpacaAsync(cancellationToken).ConfigureAwait(false) is not { } alpaca) { diff --git a/src/Anubis/Trading/Absences.cs b/src/Anubis/Trading/Absences.cs new file mode 100644 index 0000000..82732de --- /dev/null +++ b/src/Anubis/Trading/Absences.cs @@ -0,0 +1,92 @@ +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; + +namespace Anubis.Trading; + +/// A time the bot was off: from its last sign of life to the restart (SPEC 5.6). +public sealed record Absence(Guid Id, DateTimeOffset StartedAt, DateTimeOffset EndedAt, DateTimeOffset? AcknowledgedAt) +{ + public TimeSpan Length => EndedAt - StartedAt; +} + +/// +/// The absences of the bot (SPEC 5.6): measured at the restart from the last job that ran, written in the diary, and +/// declared at the top of the Panoramica when longer than a day, until the user has seen it. +/// +public sealed class AbsenceBook(Database db, IClock clock) +{ + /// Shorter than this is a restart, not an absence: the minute pulse runs every minute. + public static readonly TimeSpan Threshold = TimeSpan.FromMinutes(5); + + /// An absence longer than this is declared on the Panoramica. + public static readonly TimeSpan Declared = TimeSpan.FromHours(24); + + public TimeZoneInfo Zone { get; init; } = Zones.Rome; + + /// + /// At the start, before the scheduler: the time since the last job finished. An absence is recorded and written in + /// the diary; null when the bot was not away (or never ran before). + /// + public async Task RecordAsync(CancellationToken cancellationToken) + { + var now = clock.UtcNow; + return await db.WriteAsync(async s => + { + var last = await s.FirstOrDefaultAsync("SELECT MAX(last_finished_at) AS last FROM jobs", r => r.IsNull("last") ? (DateTimeOffset?)null : r.Moment("last")) + .ConfigureAwait(false); + if (last is not { } since || now - since < Threshold) + { + return null; + } + + var absence = new Absence(Ids.NewId(clock), since, now, null); + await s.ExecuteAsync("INSERT INTO absences (id, started_at, ended_at, acknowledged_at, created_at) VALUES (@id, @s, @e, NULL, @now)", cancellationToken, + ("id", absence.Id), ("s", since), ("e", now), ("now", now)).ConfigureAwait(false); + await Diary.WriteAsync(s, clock, DiaryKinds.System, "absence", DiaryText.Absence(absence.Length), new { started = since, ended = now }, cancellationToken) + .ConfigureAwait(false); + return absence; + }, cancellationToken).ConfigureAwait(false); + } + + /// The absence the Panoramica declares: the last one longer than a day the user has not acknowledged. + public async Task DeclaredAsync(CancellationToken cancellationToken) + { + var rows = await db.ReadAsync(s => s.QueryAsync( + "SELECT id, started_at, ended_at, acknowledged_at FROM absences WHERE acknowledged_at IS NULL ORDER BY ended_at DESC", + r => new Absence(r.Id("id"), r.Moment("started_at"), r.Moment("ended_at"), r.MomentOrNull("acknowledged_at"))), cancellationToken).ConfigureAwait(false); + return rows.FirstOrDefault(a => a.Length > Declared); + } + + /// The user has seen the notice: every absence up to this one stops being declared. + public Task AcknowledgeAsync(Guid id, CancellationToken cancellationToken) => + db.WriteAsync(async s => + { + var ended = await s.FirstOrDefaultAsync("SELECT ended_at FROM absences WHERE id = @id", r => (DateTimeOffset?)r.Moment("ended_at"), ("id", id)).ConfigureAwait(false); + if (ended is { } until) + { + await s.ExecuteAsync("UPDATE absences SET acknowledged_at = @now WHERE acknowledged_at IS NULL AND ended_at <= @e", cancellationToken, ("now", clock.UtcNow), ("e", until)) + .ConfigureAwait(false); + } + }, cancellationToken); + + /// The diary line of a run missed while the bot was off: made at the restart, or skipped with its reason. + public static string? MissedLine(JobRun run, TimeZoneInfo zone) + { + ArgumentNullException.ThrowIfNull(run); + if (!run.Missed) + { + return null; + } + + var what = Lower(run.Description ?? run.Name); + return run.Outcome switch + { + JobOutcome.Completed => DiaryText.Recovered(what, run.DueUtc, zone), + JobOutcome.Skipped => DiaryText.Skipped($"{what} (previsto alle {TimeZoneInfo.ConvertTime(run.DueUtc, zone):HH:mm})", "Il riavvio è arrivato oltre l'orario utile."), + _ => null, + }; + } + + private static string Lower(string text) => text.Length == 0 ? text : char.ToLowerInvariant(text[0]) + text[1..]; +} diff --git a/src/Anubis/Trading/LiveEngine.cs b/src/Anubis/Trading/LiveEngine.cs index 27b2cdc..932aace 100644 --- a/src/Anubis/Trading/LiveEngine.cs +++ b/src/Anubis/Trading/LiveEngine.cs @@ -749,6 +749,14 @@ public sealed partial class LiveEngine : IDisposable summary += " " + ReasonCatalog.Text(LiveReasons.LateExitsOnly); } + if (m.Now - m.Due > Options.RecoveredAfter) + { + // Made late because the bot was off (SPEC 5.6): said before what was decided. + var what = m.Strategy == StrategyNames.CryptoTrend ? "la chiusura giornaliera crypto" : "il calcolo dei segnali sulle azioni"; + await Diary.WriteAsync(s, _clock, DiaryKinds.Decisions, LiveReasons.Recovered, DiaryText.Recovered(what, m.Due, Zone), new { decision = decisionId }, + cancellationToken).ConfigureAwait(false); + } + await Diary.WriteAsync(s, _clock, DiaryKinds.Decisions, "decision", summary, new { decision = decisionId }, cancellationToken).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false); } diff --git a/src/Anubis/Trading/TradingService.cs b/src/Anubis/Trading/TradingService.cs index 7948674..14a45bc 100644 --- a/src/Anubis/Trading/TradingService.cs +++ b/src/Anubis/Trading/TradingService.cs @@ -263,6 +263,14 @@ public sealed partial class TradingService : IDisposable } await GuardAsync("simulatore", () => FundSimulatorsAsync(cancellationToken), cancellationToken).ConfigureAwait(false); + + // SPEC 5.6: corporate actions come first, so the stops the reconciliation puts back already know about a split. + if (_market is not null) + { + await GuardAsync("azioni societarie", () => _market.RefreshCorporateActionsAsync(cancellationToken), cancellationToken).ConfigureAwait(false); + } + + await GuardAsync("azioni societarie nei registri", () => CorporateActionsAsync(cancellationToken), cancellationToken).ConfigureAwait(false); foreach (var manager in _managers.Values) { await GuardAsync("avvio " + manager.Account.Name, async () => diff --git a/tests/Anubis.Tests/AbsenceTests.cs b/tests/Anubis.Tests/AbsenceTests.cs new file mode 100644 index 0000000..baa204c --- /dev/null +++ b/tests/Anubis.Tests/AbsenceTests.cs @@ -0,0 +1,199 @@ +using Anubis.Core; +using Anubis.Data; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// +/// Recovery after an absence (issue #49, SPEC 5.6): the bot is switched off for 3 hours, 20 hours and 3 days with a +/// simulated clock, and the rows of 5.6 whose jobs exist in this phase are checked at the restart. +/// +[TestClass] +public sealed class AbsenceTests +{ + private static readonly CancellationToken _none = CancellationToken.None; + private static readonly DateOnly LiveFrom = new(2026, 9, 1); + + // The bot is switched off the evening before the first live day, at 23:00 UTC. + private static readonly DateTimeOffset Off = new(2026, 8, 31, 23, 0, 0, TimeSpan.Zero); + + /// + /// Off from 23:00 to 02:00 UTC: the crypto decision of 00:05 is made at the restart and its purchases go if the + /// price is within 2% of the one at 00:05; one that moved more is dropped. Both end in the diary with the reason. + /// The missed backup is taken once; the morning summary is not due yet; no notice on the Panoramica. + /// + [TestMethod] + public async Task ThreeHoursOffRecoverTheCryptoDecisionAndDropAnEntryThatMovedTooFar() + { + await using var live = await LiveRig.CreateAsync(LiveFrom, LiveFrom.AddDays(39)).ConfigureAwait(false); + var jobs = await RestartAsync(live.Rig, Off.AddHours(3)).ConfigureAwait(false); + Assert.AreEqual("Sono stato fermo per 3 ore. Ho ripreso i lavori saltati con le regole del recupero.", await LastDiaryAsync(live.Rig, "absence").ConfigureAwait(false)); + Assert.IsNull(await new AbsenceBook(live.Rig.Db, live.Rig.Clock).DeclaredAsync(_none).ConfigureAwait(false)); + Assert.AreEqual(1, jobs.Backups); + Assert.AreEqual(0, jobs.Summaries); + Assert.AreEqual(0, jobs.Plain, "A job without recovery rules is not run for the time it missed."); + + // The data step brings yesterday's bar; SOL has moved 3% from the price of 00:05, ETH has not. + await live.StoreBarAsync(LiveFrom.AddDays(-1)).ConfigureAwait(false); + live.Quotes(LiveFrom, b => b.Open); + var sol = (decimal)live.Bar("SOL-EUR", LiveFrom).Open * 1.03m; + live.Rig.Quote("SOL-EUR", sol * 0.9999m, sol * 1.0001m, 1000m); + await live.MinutesAsync(10).ConfigureAwait(false); + + var runs = await live.Rig.QueryAsync("SELECT run_key, mode FROM engine_runs", r => (r.Text("run_key"), r.Text("mode"))).ConfigureAwait(false); + CollectionAssert.AreEqual(new[] { ("crypto_trend:2026-08-31", DecisionModes.Full) }, runs.ToList()); + var fills = await live.LiveFillsAsync().ConfigureAwait(false); + Assert.IsTrue(fills.Any(f => f.Symbol == "ETH-EUR" && f.Side == OrderSide.Buy), "The recovered purchase goes."); + Assert.IsFalse(fills.Any(f => f.Symbol == "SOL-EUR"), "The purchase whose price moved 3% is dropped."); + var diary = await DiaryAsync(live.Rig).ConfigureAwait(false); + Assert.Contains("Recuperato un lavoro saltato: la chiusura giornaliera crypto (previsto alle 02:05).", diary); + Assert.Contains("Recuperato un lavoro saltato: l'acquisto di ETH/EUR (previsto alle 02:05).", diary); + Assert.IsTrue(diary.Any(d => d.StartsWith("Scartato l'acquisto di SOL/EUR: il prezzo si è mosso del 3", StringComparison.Ordinal)), string.Join("\n", diary)); + var planned = await live.Rig.QueryAsync("SELECT outcome FROM planned_orders WHERE status = @s", r => r.Text("outcome"), ("s", PlannedStates.Dropped)).ConfigureAwait(false); + CollectionAssert.AreEqual(new[] { LiveReasons.PriceMoved }, planned.ToList()); + } + + /// + /// Off for 20 hours, back at 19:00 UTC: the crypto decision is past 12:00 and only exits and stops are updated; + /// the meanrev purchase decided at the last close expired an hour after the open; the morning summary is + /// skipped (past 12:00 in Italy) and said so in the diary; the backup is taken once; no notice on the Panoramica. + /// + [TestMethod] + public async Task TwentyHoursOffLetTheLateDecisionsUpdateOnlyExitsAndDropExpiredEntries() + { + await using (var live = await LiveRig.CreateAsync(LiveFrom, LiveFrom.AddDays(39)).ConfigureAwait(false)) + { + var jobs = await RestartAsync(live.Rig, Off.AddHours(20)).ConfigureAwait(false); + Assert.AreEqual(1, jobs.Backups); + Assert.AreEqual(0, jobs.Summaries); + Assert.HasCount(1, jobs.Skipped); + Assert.AreEqual("Saltato: riepilogo del mattino (previsto alle 08:00). Il riavvio è arrivato oltre l'orario utile.", + AbsenceBook.MissedLine(jobs.Skipped[0], Zones.Rome)); + Assert.IsNull(await new AbsenceBook(live.Rig.Db, live.Rig.Clock).DeclaredAsync(_none).ConfigureAwait(false)); + + await live.StoreBarAsync(LiveFrom.AddDays(-1)).ConfigureAwait(false); + live.Quotes(LiveFrom, b => b.Close); + await live.MinutesAsync(10).ConfigureAwait(false); + var runs = await live.Rig.QueryAsync("SELECT mode FROM engine_runs", r => r.Text("mode")).ConfigureAwait(false); + CollectionAssert.AreEqual(new[] { DecisionModes.ExitsOnly }, runs.ToList()); + Assert.IsEmpty(await live.LiveFillsAsync().ConfigureAwait(false), "No purchase after 12:00 UTC: the next close decides."); + var decision = await LastDiaryAsync(live.Rig, "decision").ConfigureAwait(false); + Assert.Contains(ReasonCatalog.Text(LiveReasons.LateExitsOnly), decision!); + } + + // The stock side: the bot goes off after the signals of the close and comes back the next day at 12:30 in New + // York, past the hour after the open in which a meanrev purchase is valid. + await using var stocks = await StockRig.CreateAsync(LiveFrom, LiveFrom.AddDays(41)).ConfigureAwait(false); + await stocks.SessionAsync(LiveFrom).ConfigureAwait(false); + var pending = await stocks.Rig.QueryAsync("SELECT id FROM planned_orders WHERE status = @s", r => r.Id("id"), ("s", PlannedStates.Pending)).ConfigureAwait(false); + Assert.HasCount(1, pending, "The close of the first day plans a purchase for the next open."); + stocks.Rig.Clock.Set(new DateTimeOffset(2026, 9, 2, 16, 30, 0, TimeSpan.Zero)); + stocks.Quotes(LiveFrom.AddDays(1), b => b.Open); + await stocks.MinutesAsync(3).ConfigureAwait(false); + var expired = await stocks.Rig.QueryAsync("SELECT outcome FROM planned_orders WHERE status = @s", r => r.Text("outcome"), ("s", PlannedStates.Expired)).ConfigureAwait(false); + CollectionAssert.AreEqual(new[] { LiveReasons.EntryExpired }, expired.ToList()); + Assert.IsEmpty(await stocks.LiveFillsAsync().ConfigureAwait(false)); + Assert.IsTrue((await DiaryAsync(stocks.Rig).ConfigureAwait(false)).Any(d => d.StartsWith("Saltato: l'acquisto di BBB. Ingresso scaduto", StringComparison.Ordinal))); + } + + /// + /// Off for 3 days: only the decision of the restart day is made (the missed ones are not replayed), the backup is + /// taken once and not three times, and the Panoramica declares the absence until the user has seen it. + /// + [TestMethod] + public async Task ThreeDaysOffAreDeclaredUntilSeenAndMissedRunsAreMadeOnce() + { + await using var live = await LiveRig.CreateAsync(LiveFrom, LiveFrom.AddDays(39)).ConfigureAwait(false); + var back = Off.AddDays(3); + var jobs = await RestartAsync(live.Rig, back).ConfigureAwait(false); + Assert.AreEqual(1, jobs.Backups, "Three nights missed, one backup at the restart."); + Assert.AreEqual("Sono stato fermo per 3 giorni. Ho ripreso i lavori saltati con le regole del recupero.", await LastDiaryAsync(live.Rig, "absence").ConfigureAwait(false)); + + var book = new AbsenceBook(live.Rig.Db, live.Rig.Clock); + var declared = await book.DeclaredAsync(_none).ConfigureAwait(false); + Assert.IsNotNull(declared); + Assert.AreEqual(TimeSpan.FromDays(3), declared.Length); + await book.AcknowledgeAsync(declared.Id, _none).ConfigureAwait(false); + Assert.IsNull(await book.DeclaredAsync(_none).ConfigureAwait(false)); + + for (var day = LiveFrom.AddDays(-1); day <= LiveFrom.AddDays(2); day = day.AddDays(1)) + { + await live.StoreBarAsync(day).ConfigureAwait(false); + } + + live.Quotes(LiveFrom.AddDays(2), b => b.Close); + await live.MinutesAsync(5).ConfigureAwait(false); + var runs = await live.Rig.QueryAsync("SELECT run_key FROM engine_runs", r => r.Text("run_key")).ConfigureAwait(false); + CollectionAssert.AreEqual(new[] { "crypto_trend:2026-09-02" }, runs.ToList()); + } + + private sealed class Counts + { + public int Backups { get; set; } + + public int Summaries { get; set; } + + public int Plain { get; set; } + + public List Skipped { get; } = []; + } + + /// + /// The restart: the last sign of life was at ; the clock is now . The + /// absence is recorded, then the scheduler starts with three jobs that ran last at : the nightly + /// backup (made once whenever the restart comes), the morning summary (only until 12:00 in Italy) and a job without + /// recovery rules. + /// + private static async Task RestartAsync(TradingRig rig, DateTimeOffset back) + { + await rig.Db.WriteAsync(s => s.ExecuteAsync( + "INSERT INTO jobs (id, name, description, last_due_at, last_started_at, last_finished_at, last_outcome, created_at, updated_at) VALUES (@id, 'motore', 'Motore', @t, @t, @t, 'completed', @t, @t)", + _none, ("id", Ids.NewId(rig.Clock)), ("t", Off)), _none).ConfigureAwait(false); + rig.Clock.Set(back); + await new AbsenceBook(rig.Db, rig.Clock).RecordAsync(_none).ConfigureAwait(false); + + var counts = new Counts(); + var bus = new EventBus(); + using var runs = bus.Subscribe(); + var scheduler = new Scheduler(rig.Clock, bus); + scheduler.Add(new ScheduledJob("backup", "Salvataggio del database", Schedule.Daily(new TimeOnly(3, 30), Zones.Rome), _ => + { + counts.Backups++; + return Task.CompletedTask; + }) + { MaxLateness = TimeSpan.FromHours(2), CatchUpWithin = TimeSpan.FromDays(3650) }, Off); + scheduler.Add(new ScheduledJob("riepilogo", "Riepilogo del mattino", Schedule.Daily(new TimeOnly(8, 0), Zones.Rome), _ => + { + counts.Summaries++; + return Task.CompletedTask; + }) + { CatchUpWithin = TimeSpan.FromHours(4) }, Off); + scheduler.Add(new ScheduledJob("pulizia", "Pulizia", Schedule.Daily(new TimeOnly(1, 0), Zones.Rome), _ => + { + counts.Plain++; + return Task.CompletedTask; + }), Off); + await scheduler.RunDueAsync(_none).ConfigureAwait(false); + await scheduler.RunDueAsync(_none).ConfigureAwait(false); + while (runs.TryRead(out var run)) + { + if (run!.Missed && run.Outcome == JobOutcome.Skipped) + { + counts.Skipped.Add(run); + } + else if (run.Missed) + { + Assert.AreEqual(JobOutcome.Completed, run.Outcome); + StringAssert.StartsWith(AbsenceBook.MissedLine(run, Zones.Rome), "Recuperato un lavoro saltato: salvataggio del database (previsto alle 03:30)"); + } + } + + return counts; + } + + private static async Task> DiaryAsync(TradingRig rig) => + [.. await rig.QueryAsync("SELECT message FROM journal ORDER BY occurred_at, id", r => r.Text("message")).ConfigureAwait(false)]; + + private static async Task LastDiaryAsync(TradingRig rig, string code) => + (await rig.QueryAsync("SELECT message FROM journal WHERE code = @c ORDER BY occurred_at DESC, id DESC", r => r.Text("message"), ("c", code)).ConfigureAwait(false)) is { Count: > 0 } rows ? rows[0] : null; +} diff --git a/tests/Anubis.Tests/LiveStockSupport.cs b/tests/Anubis.Tests/LiveStockSupport.cs index 98f2a2b..bd6e2e6 100644 --- a/tests/Anubis.Tests/LiveStockSupport.cs +++ b/tests/Anubis.Tests/LiveStockSupport.cs @@ -134,7 +134,7 @@ internal sealed class StockRig : IAsyncDisposable private DailyBar? Bar(string symbol, DateOnly day) => Bars[symbol].SingleOrDefault(b => b.Day == day); - private void Quotes(DateOnly day, Func pick) + public void Quotes(DateOnly day, Func pick) { foreach (var symbol in Bars.Keys) { @@ -146,7 +146,7 @@ internal sealed class StockRig : IAsyncDisposable } } - private async Task MinutesAsync(int count) + public async Task MinutesAsync(int count) { for (var i = 0; i < count; i++) { diff --git a/tests/Anubis.Tests/LiveSupport.cs b/tests/Anubis.Tests/LiveSupport.cs index 46a538b..cb7fcd9 100644 --- a/tests/Anubis.Tests/LiveSupport.cs +++ b/tests/Anubis.Tests/LiveSupport.cs @@ -213,6 +213,15 @@ internal sealed class LiveRig : IAsyncDisposable await Equity.TakeAsync(none).ConfigureAwait(false); } + /// Several minutes of the process from the clock's time. + public async Task MinutesAsync(int count) + { + for (var i = 0; i < count; i++) + { + await MinuteAsync().ConfigureAwait(false); + } + } + /// One minute of the process: the engine's pulse, then a turn of the simulator and of the order manager. private async Task MinuteAsync() { From d00dfbd32f1bf621fc33e3700e52ec88351cae7a Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 11 Nov 2026 19:36:32 +0100 Subject: [PATCH 04/12] Add the guard that watches the engine and protects positions (refs #48) The guard (SPEC 9.3, 9.4) is now the container's main process and the parent of the engine. It listens on a named pipe for the engine's heartbeat and startup steps, and steps in after two minutes of silence, ten minutes of a startup that does not move, or an exit without notice. It stops the engine, cancels our purchases and sales left open on demo accounts, puts back the stops the positions need from the state file the engine writes every ten seconds, writes a note, warns the user and restarts the engine without any injected fault. The third forced restart within an hour writes the STOP file. The container's stop is passed on to the engine, which closes in order. At restart the engine adopts the guard's stops before reconciling, cancels the orders it left open and plans again the exits already decided, so the rules of SPEC 5.6 apply to them. The acceptance test blocks the main loop right after a sale leaves: in process on a demo-like broker, and with real processes in the drill, which also runs inside the Docker image (tasks ci and the CI workflow). The guard uses the ASP.NET shared runtime so both programs share /app. Co-Authored-By: Claude Opus 5.5 --- .gitea/workflows/ci.yml | 3 + deploy/docker/Dockerfile | 10 +- deploy/docker/entrypoint.sh | 5 +- docker-compose.yml | 2 + src/Anubis.Guard/Anubis.Guard.csproj | 2 + src/Anubis.Guard/Program.cs | 52 ++- src/Anubis.Server/AnubisHost.cs | 37 +- src/Anubis.Server/ServerApp.cs | 14 +- src/Anubis/Data/MarketDataService.cs | 4 +- src/Anubis/Notifications/TelegramClient.cs | 117 +++++ src/Anubis/Supervision/ChildEngine.cs | 158 +++++++ src/Anubis/Supervision/GuardBrokers.cs | 53 +++ src/Anubis/Supervision/GuardDrill.cs | 419 +++++++++++++++++ src/Anubis/Supervision/GuardLink.cs | 170 +++++++ src/Anubis/Supervision/GuardProtocol.cs | 120 +++++ src/Anubis/Supervision/GuardRepair.cs | 130 ++++++ src/Anubis/Supervision/GuardState.cs | 116 +++++ src/Anubis/Supervision/Guardian.cs | 499 +++++++++++++++++++++ src/Anubis/Trading/DiaryText.cs | 5 + src/Anubis/Trading/LiveEngine.cs | 52 +++ src/Anubis/Trading/OrderManager.Guard.cs | 84 ++++ src/Anubis/Trading/OrderManager.cs | 15 +- src/Anubis/Trading/ReasonCatalog.cs | 1 + src/Anubis/Trading/TradingService.cs | 135 +++++- tests/Anubis.Tests/GuardTests.cs | 414 +++++++++++++++++ tools/Anubis.Tasks/Program.cs | 9 +- 26 files changed, 2607 insertions(+), 19 deletions(-) create mode 100644 src/Anubis/Notifications/TelegramClient.cs create mode 100644 src/Anubis/Supervision/ChildEngine.cs create mode 100644 src/Anubis/Supervision/GuardBrokers.cs create mode 100644 src/Anubis/Supervision/GuardDrill.cs create mode 100644 src/Anubis/Supervision/GuardLink.cs create mode 100644 src/Anubis/Supervision/GuardProtocol.cs create mode 100644 src/Anubis/Supervision/GuardRepair.cs create mode 100644 src/Anubis/Supervision/GuardState.cs create mode 100644 src/Anubis/Supervision/Guardian.cs create mode 100644 src/Anubis/Trading/OrderManager.Guard.cs create mode 100644 tests/Anubis.Tests/GuardTests.cs diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 96bc28f..5e424b3 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -63,3 +63,6 @@ jobs: git checkout -q FETCH_HEAD - name: Build image (no publish) run: docker build -f deploy/docker/Dockerfile -t anubis:ci . + # The guard drill inside the image (issue #48): offline, its own SQLite database in a temporary folder. + - name: Guard drill in the image + run: docker run --rm anubis:ci drill diff --git a/deploy/docker/Dockerfile b/deploy/docker/Dockerfile index f1bc33a..4dcff4e 100644 --- a/deploy/docker/Dockerfile +++ b/deploy/docker/Dockerfile @@ -6,14 +6,19 @@ WORKDIR /src COPY global.json Directory.Build.props Directory.Packages.props ./ COPY src/Anubis/Anubis.csproj src/Anubis/packages.lock.json src/Anubis/ COPY src/Anubis.Server/Anubis.Server.csproj src/Anubis.Server/packages.lock.json src/Anubis.Server/ -RUN dotnet restore src/Anubis.Server/Anubis.Server.csproj --locked-mode +COPY src/Anubis.Guard/Anubis.Guard.csproj src/Anubis.Guard/packages.lock.json src/Anubis.Guard/ +RUN dotnet restore src/Anubis.Server/Anubis.Server.csproj --locked-mode && \ + dotnet restore src/Anubis.Guard/Anubis.Guard.csproj --locked-mode COPY src/Anubis/ src/Anubis/ COPY src/Anubis.Server/ src/Anubis.Server/ +COPY src/Anubis.Guard/ src/Anubis.Guard/ # The logo is embedded from docs/design/logo, its only source (ADR 0005). COPY docs/design/logo/ docs/design/logo/ # The backtest outcomes are read at the first start (SPEC 12.3); .dockerignore lets only their JSON files through. COPY docs/backtests/ docs/backtests/ RUN dotnet publish src/Anubis.Server/Anubis.Server.csproj -c Release --no-restore -o /app +# The guard (SPEC 9.3, ADR 0012) is the main process and starts the engine next to it, from the same folder. +RUN dotnet publish src/Anubis.Guard/Anubis.Guard.csproj -c Release --no-restore -o /app FROM mcr.microsoft.com/dotnet/aspnet:10.0 WORKDIR /app @@ -27,7 +32,8 @@ ENV ANUBIS_PLATFORM=docker \ PGID=100 EXPOSE 8787 VOLUME /data -# Starts as root only to give /data to PUID:PGID, then runs the app as that user (entrypoint.sh). +# Starts as root only to give /data to PUID:PGID, then runs the guard as that user (entrypoint.sh); the guard starts +# the engine. "docker run --rm drill" runs the guard drill instead (issue #48). # Health through bash's /dev/tcp: no curl or wget in the image. 503 (database down) counts as unhealthy. HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 \ CMD ["bash", "-c", "exec 3<>/dev/tcp/127.0.0.1/${PORT:-8787} && printf 'GET /health HTTP/1.0\r\nHost: localhost\r\n\r\n' >&3 && head -n 1 <&3 | grep -q ' 200 '"] diff --git a/deploy/docker/entrypoint.sh b/deploy/docker/entrypoint.sh index fb91c16..ec68e96 100644 --- a/deploy/docker/entrypoint.sh +++ b/deploy/docker/entrypoint.sh @@ -1,9 +1,10 @@ #!/bin/sh # Container start (SPEC 15.2, issue #16). As root: prepare /data for PUID:PGID (99:100 on Unraid), then drop to that # user with setpriv, which is part of the base image (no gosu). Started as another user (docker run --user): go straight on. +# The process is the guard (SPEC 9.3, ADR 0012): it starts the engine, watches it and passes the stop on to it. set -eu -app="/app/Anubis.Server.dll" +app="/app/Anubis.Guard.dll" if [ "$(id -u)" != "0" ]; then exec dotnet "$app" "$@" @@ -19,7 +20,7 @@ case "$uid$gid" in esac mkdir -p /data -for folder in db models research import backups logs web-keys; do +for folder in db models research import backups logs web-keys guard; do mkdir -p "/data/$folder" done # Only what does not already belong to PUID:PGID, so a large data folder does not slow every start. diff --git a/docker-compose.yml b/docker-compose.yml index db8b85a..f78ab76 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -7,6 +7,8 @@ services: context: . dockerfile: deploy/docker/Dockerfile image: gitea.encke-hake.ts.net/balbosoft/anubis:dev + # The guard gives the engine up to 55 seconds to close in order (SPEC 9.3). + stop_grace_period: 60s ports: - "8787:8787" environment: diff --git a/src/Anubis.Guard/Anubis.Guard.csproj b/src/Anubis.Guard/Anubis.Guard.csproj index c231f26..39dcc68 100644 --- a/src/Anubis.Guard/Anubis.Guard.csproj +++ b/src/Anubis.Guard/Anubis.Guard.csproj @@ -4,6 +4,8 @@ Anubis.Guard + + diff --git a/src/Anubis.Guard/Program.cs b/src/Anubis.Guard/Program.cs index 4dfc043..445c81b 100644 --- a/src/Anubis.Guard/Program.cs +++ b/src/Anubis.Guard/Program.cs @@ -1,3 +1,49 @@ -// Placeholder: the guard process (SPEC 9.3) arrives in phase 6 (ADR 0003). -await Console.Error.WriteLineAsync("Anubis.Guard non è ancora disponibile: arriva nella Fase 6.").ConfigureAwait(false); -return 2; +using System.Collections; +using System.Runtime.InteropServices; +using Anubis.Core; +using Anubis.Platform; +using Anubis.Supervision; + +// The guard (SPEC 9.3, ADR 0012): the main process of the container and the parent of the engine. Its arguments go to +// the engine as they are. "drill" runs the guard drill in a temporary folder instead. +if (args is ["drill", ..]) +{ + return await GuardDrill.RunAsync(GuardLaunch.Server(), Console.Out, CancellationToken.None).ConfigureAwait(false); +} + +var environment = Environment.GetEnvironmentVariables().Cast() + .ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal); +var paths = new GuardPaths(DataRoot(args, environment)); +var logger = new LineLogger(Console.Out.WriteLine); +using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(20) }; +var clock = SystemClock.Instance; +var guardian = new Guardian(paths, clock, new GuardOptions(), + start => ChildEngine.Start(GuardLaunch.Dotnet(), [GuardLaunch.Server(), .. args], environment, start), + (account, keys) => GuardBrokers.Create(http, clock, account, keys), + (text, keys, ct) => GuardBrokers.AlertAsync(http, logger, keys, text, ct), + logger); + +// The stop of the container (SIGTERM) or Ctrl+C: passed on to the engine, which closes in order and is not restarted. +using var shutdown = new CancellationTokenSource(); +using var terminate = PosixSignalRegistration.Create(PosixSignal.SIGTERM, Stop); +using var interrupt = PosixSignalRegistration.Create(PosixSignal.SIGINT, Stop); +return await guardian.RunAsync(shutdown.Token).ConfigureAwait(false); + +void Stop(PosixSignalContext context) +{ + context.Cancel = true; + shutdown.Cancel(); +} + +// The engine's data folder: --data-dir when given, /data in Docker, the user's folder on desktop (SPEC 15.2, 15.6). +static string DataRoot(string[] args, Dictionary environment) +{ + var index = Array.IndexOf(args, "--data-dir"); + if (index >= 0 && index + 1 < args.Length) + { + return Path.GetFullPath(args[index + 1]); + } + + var platform = Array.IndexOf(args, "--platform") is var p and >= 0 && p + 1 < args.Length ? args[p + 1] : environment.GetValueOrDefault("ANUBIS_PLATFORM"); + return platform == "docker" ? "/data" : DataDirectory.ForCurrentUser().Root; +} diff --git a/src/Anubis.Server/AnubisHost.cs b/src/Anubis.Server/AnubisHost.cs index cc5be12..88144f8 100644 --- a/src/Anubis.Server/AnubisHost.cs +++ b/src/Anubis.Server/AnubisHost.cs @@ -5,6 +5,7 @@ using Anubis.Data; using Anubis.Db; using Anubis.Demo; using Anubis.Platform; +using Anubis.Supervision; using Anubis.Trading; namespace Anubis.Server; @@ -72,6 +73,9 @@ internal sealed partial class AnubisHost( public StartupConfig Config { get; private set; } = initialConfig; + /// The channel to the guard that started this engine (SPEC 9.3); null without one. + public GuardLink? Guard { get; init; } + public bool IsDemo => options.Demo; public HostStatus Status => _status; @@ -176,6 +180,12 @@ internal sealed partial class AnubisHost( SetStatus(HostMode.DatabaseUnavailable, Redactor.Redact(ex.Message)); } + // With trading the beat of a running engine comes from the trading loop, so a blocked loop is noticed. + if (_status.Mode != HostMode.Ready || _trading is null) + { + Guard?.Beat(); + } + await Task.WhenAny(wake, Task.Delay(_interval, stoppingToken)).ConfigureAwait(false); } @@ -213,6 +223,7 @@ internal sealed partial class AnubisHost( } Config.Data.Ensure(); + Guard?.Step("database"); // A data folder that belongs to an installation never gets a new empty SQLite file by itself (trap 20). _db ??= Database.Open(Config.Db!, allowCreate: !File.Exists(Config.Data.InstallationFile)); @@ -234,6 +245,8 @@ internal sealed partial class AnubisHost( return; } + Guard?.Step("migrazioni e identità"); + // Identity first, migration after: a database that belongs elsewhere is never written to, and an empty one stays // empty, so a backup taken with an older schema can still be restored into it. var backups = new Backups(Config.Data, clock); @@ -271,6 +284,7 @@ internal sealed partial class AnubisHost( return; } + Guard?.Step("servizi"); var key = Config.SecretKey.GetOrCreateKey(); var settings = new SettingsStore(_db, clock, bus, StartupOverrides()); var secrets = new SecretStore(_db, clock, key, Config.EnvironmentKeys); @@ -288,12 +302,20 @@ internal sealed partial class AnubisHost( var scheduler = new Scheduler(clock, bus); _market = MarketDataEnabled - ? new MarketDataService(_db, clock, bus, settings, secrets, Config.Data, overrides?.MarketHttp, overrides?.MarketSockets, logger) + ? new MarketDataService(_db, clock, bus, settings, secrets, Config.Data, overrides?.MarketHttp, overrides?.MarketSockets, logger, + Guard is null ? null : GuardDrill.DrillOkx(environment)) : null; _trading = TradingEnabled && (identity.File ?? Installation.ReadFile(Config.Data)) is { } file ? new TradingService(_db, clock, bus, secrets, _market, new FxStore(_db, clock), TradingConsent.From(Config), file.InstallationId, overrides?.MarketHttp, overrides?.MarketSockets, logger, settings, (password, code, ct) => access.ReauthenticateAsync(password, code, ct), Path.Combine(Config.Data.Root, "STOP")) + { + Guard = Guard, + GuardFiles = Guard is null ? null : new GuardPaths(Config.Data.Root), + + // The drill's fault is honored only under a guard, which never passes it to an engine it restarts. + Fault = Guard is null ? null : environment.GetValueOrDefault(GuardChannel.FaultVariable), + } : null; if (_trading is not null) { @@ -610,6 +632,19 @@ internal sealed partial class AnubisHost( var attempts = previous.Mode == mode ? previous.Attempts + 1 : 1; var since = previous.Mode == mode ? previous.Since : clock.UtcNow; _status = new HostStatus(mode, detail, identity, since, attempts); + if (mode == HostMode.Ready) + { + // Trading tells the guard by itself when its own startup steps are done. + if (_trading is null || _trading.IsStarted) + { + Guard?.Set(GuardStages.Running); + } + } + else + { + Guard?.Set(mode == HostMode.Starting ? GuardStages.Starting : GuardStages.Waiting); + } + if (previous.Mode != mode) { LogMode(logger, mode); diff --git a/src/Anubis.Server/ServerApp.cs b/src/Anubis.Server/ServerApp.cs index 413755f..d03cff5 100644 --- a/src/Anubis.Server/ServerApp.cs +++ b/src/Anubis.Server/ServerApp.cs @@ -4,6 +4,7 @@ using Anubis.Core; using Anubis.Demo; using Anubis.Platform; using Anubis.Server.Components; +using Anubis.Supervision; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.DataProtection; @@ -52,8 +53,12 @@ internal static class ServerApp services.AddSingleton(clock); services.AddSingleton(overrides ?? new ServerOverrides()); services.AddSingleton(); + // Started by the guard (SPEC 9.3): the channel to it. Never in demo mode, which protects nothing. services.AddSingleton(sp => new AnubisHost(options, config, environment, clock, sp.GetRequiredService(), - sp.GetRequiredService>(), overrides)); + sp.GetRequiredService>(), overrides) + { + Guard = options.Demo ? null : GuardLink.FromEnvironment(environment, sp.GetRequiredService>()), + }); services.AddHostedService(sp => sp.GetRequiredService()); services.AddSingleton(new LoginLimiter(clock)); services.AddSingleton(); @@ -82,6 +87,13 @@ internal static class ServerApp var app = builder.Build(); var host = app.Services.GetRequiredService(); + if (host.Guard is { } guard) + { + // The guard asks for an orderly stop when the container stops; every stop of the engine is announced to it. + guard.StopRequested = app.Lifetime.StopApplication; + app.Lifetime.ApplicationStopping.Register(() => guard.AnnounceAsync("uscita").GetAwaiter().GetResult()); + app.Lifetime.ApplicationStopped.Register(() => guard.DisposeAsync().AsTask().GetAwaiter().GetResult()); + } app.Use(SecurityHeaders); app.Use((context, next) => LocalOnly(context, next, options, config)); diff --git a/src/Anubis/Data/MarketDataService.cs b/src/Anubis/Data/MarketDataService.cs index 8430066..16883dc 100644 --- a/src/Anubis/Data/MarketDataService.cs +++ b/src/Anubis/Data/MarketDataService.cs @@ -54,7 +54,7 @@ public sealed partial class MarketDataService : IDisposable private (string Key, string Secret, AlpacaClient Client)? _alpaca; public MarketDataService(Database db, IClock clock, EventBus bus, SettingsStore settings, SecretStore secrets, DataDirectory? data, - HttpMessageHandler? handler = null, Func? sockets = null, ILogger? logger = null) + HttpMessageHandler? handler = null, Func? sockets = null, ILogger? logger = null, OkxOptions? okx = null) { _db = db; _clock = clock; @@ -73,7 +73,7 @@ public sealed partial class MarketDataService : IDisposable _http.Timeout = TimeSpan.FromSeconds(60); _http.DefaultRequestHeaders.UserAgent.ParseAdd($"{AnubisInfo.Name}/{AnubisInfo.Version}"); - Okx = new OkxClient(_http, clock, null, sockets); + Okx = new OkxClient(_http, clock, okx, sockets); Freshness = new FreshnessMonitor(clock, bus); References = new ReferenceSources(new ApiHttp(_http, clock, "reference"), db, clock, settings, secrets.RevealAsync, Okx); UsCalendar = new StoredMarketCalendar(db, clock, "us_equity"); diff --git a/src/Anubis/Notifications/TelegramClient.cs b/src/Anubis/Notifications/TelegramClient.cs new file mode 100644 index 0000000..469d859 --- /dev/null +++ b/src/Anubis/Notifications/TelegramClient.cs @@ -0,0 +1,117 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +using Anubis.Core; + +namespace Anubis.Notifications; + +/// A refusal or failure of the Telegram Bot API. : the network, a 429 or a 5xx. +public sealed class TelegramException : Exception +{ + public TelegramException() + { + } + + public TelegramException(string message) + : base(message) + { + } + + public TelegramException(string message, Exception innerException) + : base(message, innerException) + { + } + + public TelegramException(string message, bool retryable, TimeSpan? retryAfter = null) + : base(message) + { + Retryable = retryable; + RetryAfter = retryAfter; + } + + public bool Retryable { get; } + + /// The wait Telegram asks for after a 429. + public TimeSpan? RetryAfter { get; } +} + +/// +/// The Telegram Bot API (SPEC 14): plain text messages to the user's chat. The token is part of the address, so the +/// address is never logged; errors carry only Telegram's own description. +/// +public sealed class TelegramClient +{ + public static readonly Uri DefaultBase = new("https://api.telegram.org/"); + + private readonly HttpClient _http; + private readonly string _token; + private readonly Uri _base; + + public TelegramClient(HttpClient http, string token, Uri? baseUrl = null) + { + _http = http ?? throw new ArgumentNullException(nameof(http)); + _token = token ?? throw new ArgumentNullException(nameof(token)); + _base = baseUrl ?? DefaultBase; + Redactor.Register(token); + } + + /// Telegram's limit for one message; longer texts are cut with an ellipsis. + public const int MaxLength = 4096; + + public async Task SendAsync(string chatId, string text, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(text); + if (text.Length > MaxLength) + { + text = text[..(MaxLength - 1)] + "…"; + } + + using var answer = await CallAsync("sendMessage", new Dictionary { ["chat_id"] = chatId, ["text"] = text, ["disable_web_page_preview"] = true }, + cancellationToken).ConfigureAwait(false); + } + + /// One call of the Bot API; the answer's result when Telegram says ok. + public async Task CallAsync(string method, object body, CancellationToken cancellationToken) + { + HttpResponseMessage response; + try + { + response = await _http.PostAsJsonAsync(new Uri(_base, $"bot{_token}/{method}"), body, cancellationToken).ConfigureAwait(false); + } + catch (HttpRequestException ex) + { + throw new TelegramException("Telegram non risponde: " + Redactor.Redact(ex.Message), retryable: true); + } + catch (TaskCanceledException) when (!cancellationToken.IsCancellationRequested) + { + throw new TelegramException("Telegram non ha risposto in tempo.", retryable: true); + } + + using (response) + { + var text = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + JsonDocument? json = null; + try + { + json = JsonDocument.Parse(text); + } + catch (JsonException) + { + } + + if (response.IsSuccessStatusCode && json is not null && json.RootElement.TryGetProperty("ok", out var ok) && ok.GetBoolean()) + { + return json; + } + + var description = json is not null && json.RootElement.TryGetProperty("description", out var d) ? d.GetString() : null; + TimeSpan? after = json is not null && json.RootElement.TryGetProperty("parameters", out var p) && p.TryGetProperty("retry_after", out var r) + ? TimeSpan.FromSeconds(r.GetInt32()) + : null; + json?.Dispose(); + var status = (int)response.StatusCode; + throw new TelegramException($"Telegram ha risposto {status}: {Redactor.Redact(description ?? response.ReasonPhrase ?? "")}", + retryable: response.StatusCode == HttpStatusCode.TooManyRequests || status >= 500, after); + } + } +} diff --git a/src/Anubis/Supervision/ChildEngine.cs b/src/Anubis/Supervision/ChildEngine.cs new file mode 100644 index 0000000..647d0f4 --- /dev/null +++ b/src/Anubis/Supervision/ChildEngine.cs @@ -0,0 +1,158 @@ +using System.Diagnostics; +using System.IO.Pipes; +using System.Security.Cryptography; +using System.Text; + +namespace Anubis.Supervision; + +/// +/// The engine as a child process of the guard, with its channel: a named pipe open to this user only, created +/// before the process starts. The child's output goes where the guard's goes (the container log). +/// +public sealed class ChildEngine : IEngineProcess +{ + private readonly Process _process; + private readonly NamedPipeServerStream _pipe; + private readonly CancellationTokenSource _stop = new(); + private readonly SemaphoreSlim _write = new(1, 1); + private readonly Task _reading; + private readonly TaskCompletionSource _connected = new(TaskCreationOptions.RunContinuationsAsynchronously); + private int _disposed; + + private ChildEngine(Process process, NamedPipeServerStream pipe, Action onMessage) + { + _process = process; + _pipe = pipe; + Exited = WaitAsync(process); + _reading = Task.Run(() => ReadAsync(onMessage, _stop.Token)); + } + + public Task Exited { get; } + + /// + /// Starts with and the guard's environment, plus the pipe's + /// name; the drill's fault only when asks for it. + /// + public static ChildEngine Start(string file, IEnumerable arguments, IReadOnlyDictionary environment, EngineStart start) + { + ArgumentNullException.ThrowIfNull(arguments); + ArgumentNullException.ThrowIfNull(environment); + ArgumentNullException.ThrowIfNull(start); + var name = "anubis-" + Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(8)); + var pipe = new NamedPipeServerStream(name, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); + var info = new ProcessStartInfo(file) { UseShellExecute = false }; + foreach (var argument in arguments) + { + info.ArgumentList.Add(argument); + } + + info.Environment.Clear(); + foreach (var (key, value) in environment) + { + if (value is not null && key != GuardChannel.FaultVariable && key != GuardChannel.PipeVariable) + { + info.Environment[key] = value; + } + } + + info.Environment[GuardChannel.PipeVariable] = name; + if (start.Fault && environment.GetValueOrDefault(GuardChannel.FaultVariable) is { Length: > 0 } fault) + { + info.Environment[GuardChannel.FaultVariable] = fault; + } + + try + { + var process = Process.Start(info) ?? throw new InvalidOperationException("Il motore non è partito."); + return new ChildEngine(process, pipe, start.OnMessage); + } + catch + { + pipe.Dispose(); + throw; + } + } + + public async Task RequestStopAsync(CancellationToken cancellationToken) + { + await _connected.Task.WaitAsync(cancellationToken).ConfigureAwait(false); + await _write.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + var bytes = Encoding.UTF8.GetBytes(GuardChannel.Write(new GuardMessage(GuardMessageTypes.Stop)) + "\n"); + await _pipe.WriteAsync(bytes, cancellationToken).ConfigureAwait(false); + await _pipe.FlushAsync(cancellationToken).ConfigureAwait(false); + } + finally + { + _write.Release(); + } + } + + public void Kill() + { + try + { + if (!_process.HasExited) + { + _process.Kill(entireProcessTree: true); + } + } + catch (InvalidOperationException) + { + // Already gone. + } + } + + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) == 1) + { + return; + } + + _stop.Cancel(); + try + { + _reading.Wait(TimeSpan.FromSeconds(5)); + } + catch (AggregateException) + { + } + + _pipe.Dispose(); + _process.Dispose(); + _stop.Dispose(); + _write.Dispose(); + } + + private static async Task WaitAsync(Process process) + { + await process.WaitForExitAsync().ConfigureAwait(false); + return process.ExitCode; + } + + private async Task ReadAsync(Action onMessage, CancellationToken cancellationToken) + { + try + { + await _pipe.WaitForConnectionAsync(cancellationToken).ConfigureAwait(false); + _connected.TrySetResult(); + using var reader = new StreamReader(_pipe, Encoding.UTF8, leaveOpen: true); + while (await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false) is { } line) + { + if (GuardChannel.Read(line) is { } message) + { + onMessage(message); + } + } + } + catch (Exception ex) when (ex is OperationCanceledException or IOException or ObjectDisposedException) + { + } + finally + { + _connected.TrySetCanceled(CancellationToken.None); + } + } +} diff --git a/src/Anubis/Supervision/GuardBrokers.cs b/src/Anubis/Supervision/GuardBrokers.cs new file mode 100644 index 0000000..92f49c3 --- /dev/null +++ b/src/Anubis/Supervision/GuardBrokers.cs @@ -0,0 +1,53 @@ +using Anubis.Brokers; +using Anubis.Core; +using Anubis.Data; +using Anubis.Notifications; +using Anubis.Trading; +using Microsoft.Extensions.Logging; + +namespace Anubis.Supervision; + +/// The broker adapters and the warnings of the guard, from the keys the engine handed it in memory. +public static class GuardBrokers +{ + /// + /// The adapter of a demo account. Real accounts get none until the real-money phase gives the guard the startup + /// consent of its own (ADR 0012); the simulator needs none, the engine is its broker. + /// + public static IBrokerAccount? Create(HttpClient http, IClock clock, GuardAccount account, IReadOnlyList keys) + { + ArgumentNullException.ThrowIfNull(account); + ArgumentNullException.ThrowIfNull(keys); + if (account.Environment != TradingEnvironments.Demo || keys.FirstOrDefault(k => k.Service == account.Broker && k.Environment == account.Environment) is not { } key) + { + return null; + } + + return account.Broker switch + { + Venues.Alpaca when key.Values.Count >= 2 => new AlpacaTrading(http, clock, new AlpacaCredentials(key.Values[0], key.Values[1]), + new AlpacaTradingOptions { Environment = account.Environment }, TradingConsent.None), + Venues.Okx when key.Values.Count >= 3 => new OkxTrading(http, clock, new OkxCredentials(key.Values[0], key.Values[1], key.Values[2]), + new OkxTradingOptions { Environment = account.Environment }, TradingConsent.None), + _ => null, + }; + } + + /// The guard's warning: always in its log, and on Telegram when the engine handed it the bot's token and chat. + public static async Task AlertAsync(HttpClient http, ILogger logger, IReadOnlyList keys, string text, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(keys); + GuardLog.Alert(logger, text.ReplaceLineEndings(" ")); + if (keys.FirstOrDefault(k => k.Service == GuardKeys.Telegram) is { Values.Count: >= 2 } telegram) + { + await new TelegramClient(http, telegram.Values[0]).SendAsync(telegram.Values[1], "Anubis, guardia" + Environment.NewLine + text, cancellationToken) + .ConfigureAwait(false); + } + } +} + +internal static partial class GuardLog +{ + [LoggerMessage(Level = LogLevel.Warning, Message = "Guard alert: {Text}")] + public static partial void Alert(ILogger logger, string text); +} diff --git a/src/Anubis/Supervision/GuardDrill.cs b/src/Anubis/Supervision/GuardDrill.cs new file mode 100644 index 0000000..433ccbe --- /dev/null +++ b/src/Anubis/Supervision/GuardDrill.cs @@ -0,0 +1,419 @@ +using System.Globalization; +using System.Net; +using System.Net.Sockets; +using System.Security.Cryptography; +using System.Text; +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; +using Anubis.Platform; +using Anubis.Trading; +using Microsoft.Extensions.Logging; + +namespace Anubis.Supervision; + +/// The outcome of the guard drill, line by line in Italian. +public sealed record DrillResult(bool Passed, IReadOnlyList Lines); + +/// +/// The guard drill (issue #48, ADR 0012): the real guard and the real engine, as child process, in a folder of their +/// own with a SQLite database. A position of 0.01 BTC with its stop on the internal simulator and a sale already +/// decided; the engine starts with the fault that blocks its main loop right after the sale leaves, with the stop +/// removed. The drill passes when the guard intervened, the engine restarted, the sale left open was canceled, the +/// stop came back for the whole quantity and the guard's note reached the diary. Prices come from a small local +/// server that answers like OKX: nothing leaves the computer. Same drill in the tests and in the Docker image. +/// +public static class GuardDrill +{ + public const decimal Quantity = 0.01m; + public const decimal StopLevel = 45000m; + + /// Times short enough for a drill of about two minutes. + public static GuardOptions Options { get; } = new() + { + Silence = TimeSpan.FromSeconds(20), + StalledStart = TimeSpan.FromMinutes(3), + GracefulStop = TimeSpan.FromSeconds(30), + }; + + /// The drill in a new temporary folder, removed at the end. Exit code 0 when it passes. + public static async Task RunAsync(string serverDll, TextWriter output, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(output); + var folder = Path.Combine(Path.GetTempPath(), "anubis-drill-" + Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(6))); + try + { + var result = await RunInAsync(folder, serverDll, Options, line => output.WriteLine(line), cancellationToken).ConfigureAwait(false); + await output.WriteLineAsync(result.Passed ? "Esercitazione della guardia superata." : "Esercitazione della guardia NON superata.").ConfigureAwait(false); + return result.Passed ? 0 : 1; + } + finally + { + try + { + Directory.Delete(folder, recursive: true); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // A leftover temporary folder is harmless. + } + } + } + + public static async Task RunInAsync(string folder, string serverDll, GuardOptions options, Action say, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(say); + var lines = new List(); + void Say(string line) + { + lines.Add(line); + say(line); + } + + var data = new DataDirectory(folder); + data.Ensure(); + using var okx = FakeOkx.Start(); + var held = await SeedAsync(data, cancellationToken).ConfigureAwait(false); + Say($"Preparato: {Format.Quantity(held)} BTC con lo stop a {Format.Price(StopLevel)} e una vendita già decisa."); + + var environment = ChildEnvironment(okx.Address); + var clock = SystemClock.Instance; + var logger = new LineLogger(Say); + var guardian = new Guardian(new GuardPaths(folder), clock, options, + start => ChildEngine.Start(GuardLaunch.Dotnet(), [serverDll, "--platform", "docker", "--data-dir", folder], environment, start), + (_, _) => null, (text, _, _) => + { + Say("Avviso della guardia: " + text.ReplaceLineEndings(" ")); + return Task.CompletedTask; + }, logger); + guardian.Start(fault: true); + using var stop = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + var guarding = guardian.RunAsync(stop.Token); + + var intervened = await WaitAsync(() => guardian.Interventions > 0, options.Silence + TimeSpan.FromMinutes(3), cancellationToken).ConfigureAwait(false); + var restarted = intervened && await WaitAsync(() => guardian.EngineAlive && guardian.Stage == GuardStages.Running, TimeSpan.FromMinutes(3), cancellationToken) + .ConfigureAwait(false); + await stop.CancelAsync().ConfigureAwait(false); + var code = await guarding.ConfigureAwait(false); + Say($"Motore fermato in ordine alla fine dell'esercitazione (codice {code})."); + + var passed = Check(intervened, "La guardia è intervenuta dopo il silenzio del ciclo principale.", "La guardia non è intervenuta.", Say); + passed &= Check(restarted, "Il motore è ripartito e il suo ciclo batte di nuovo.", "Il motore non è ripartito.", Say); + var notes = guardian.Notes; + var at = notes.Count > 0 ? notes[0].At : DateTimeOffset.MaxValue; + await using (var db = Database.Open(new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = data.SqliteFile }, allowCreate: false)) + { + var hung = await db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM orders WHERE side = 'sell' AND purpose = 'exit' AND created_at < @t", ("t", at)), cancellationToken) + .ConfigureAwait(false); + var canceled = await db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM executions WHERE side = 'sell' AND purpose = 'exit' AND status = 'canceled' AND reason = @r", + ("r", LiveReasons.Restart)), cancellationToken).ConfigureAwait(false); + var stops = await db.ReadAsync(s => s.QueryAsync("SELECT quantity FROM orders WHERE purpose = 'stop' AND created_at > @t", r => r.Money("quantity"), ("t", at)), + cancellationToken).ConfigureAwait(false); + var noted = await db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM journal WHERE code = 'guard_intervention'"), cancellationToken).ConfigureAwait(false); + var again = await db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM planned_orders WHERE side = 'sell' AND created_at > @t", ("t", at)), cancellationToken) + .ConfigureAwait(false); + passed &= Check(hung > 0, "Prima dell'intervento la vendita era partita, senza più lo stop.", "La vendita non era partita prima dell'intervento.", Say); + passed &= Check(canceled > 0, "Alla ripartenza la vendita rimasta a metà è stata annullata.", "La vendita rimasta a metà non è stata annullata.", Say); + passed &= Check(stops.Any(q => q == held), $"Lo stop è tornato per tutti i {Format.Quantity(held)} BTC.", "Lo stop non è tornato per l'intera quantità.", Say); + passed &= Check(again > 0, "La vendita già decisa è ripartita con un ordine nuovo.", "La vendita già decisa non è ripartita.", Say); + passed &= Check(noted > 0, "La nota della guardia è nel diario.", "La nota della guardia non è nel diario.", Say); + } + + return new DrillResult(passed, lines); + } + + private static bool Check(bool ok, string yes, string no, Action say) + { + say((ok ? "OK " : "NO ") + (ok ? yes : no)); + return ok; + } + + private static async Task WaitAsync(Func condition, TimeSpan timeout, CancellationToken cancellationToken) + { + var until = SystemClock.Instance.UtcNow + timeout; + while (!condition()) + { + if (SystemClock.Instance.UtcNow > until) + { + return false; + } + + await Task.Delay(250, cancellationToken).ConfigureAwait(false); + } + + return true; + } + + private static Dictionary ChildEnvironment(Uri okx) + { + var environment = new Dictionary(StringComparer.Ordinal); + foreach (System.Collections.DictionaryEntry entry in Environment.GetEnvironmentVariables()) + { + var key = (string)entry.Key; + if (!key.StartsWith("ANUBIS_", StringComparison.Ordinal) && !key.StartsWith("ALPACA_", StringComparison.Ordinal) && + !key.StartsWith("OKX_", StringComparison.Ordinal) && !key.StartsWith("TELEGRAM_", StringComparison.Ordinal)) + { + environment[key] = entry.Value as string; + } + } + + environment["ANUBIS_PLATFORM"] = "docker"; + environment["ANUBIS_DB_ENGINE"] = "sqlite"; + environment["ANUBIS_SECRET_KEY"] = Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(24)); + environment["ANUBIS_ADMIN_PASSWORD"] = Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(12)); + environment["PORT"] = FreePort().ToString(CultureInfo.InvariantCulture); + environment["TZ"] = "Europe/Rome"; + environment[DrillOkxVariable] = okx.ToString(); + environment[GuardChannel.FaultVariable] = GuardChannel.HangMidSale; + return environment; + } + + /// + /// The address of the local server that answers like OKX in the drill. Honored only on this computer's own + /// addresses (loopback): it can never point the bot at a price source elsewhere. + /// + public const string DrillOkxVariable = "ANUBIS_DRILL_OKX_URL"; + + /// The OKX addresses of the drill, or null when the variable is missing or not a loopback address. + public static Brokers.OkxOptions? DrillOkx(IReadOnlyDictionary environment) + { + ArgumentNullException.ThrowIfNull(environment); + if (environment.GetValueOrDefault(DrillOkxVariable) is not { Length: > 0 } text || !Uri.TryCreate(text, UriKind.Absolute, out var url) || !url.IsLoopback) + { + return null; + } + + var socket = new UriBuilder(url) { Scheme = "ws" }; + return new Brokers.OkxOptions + { + RestUrl = url, + PublicStreamUrl = new Uri(socket.Uri, "/ws/v5/public"), + BusinessStreamUrl = new Uri(socket.Uri, "/ws/v5/business"), + }; + } + + // The database the engine will find: installation, accounts, BTC, the capital, a filled purchase with its stop on + // the simulator, and the sale decided for now. Built with the same order manager the engine uses. + private static async Task SeedAsync(DataDirectory data, CancellationToken cancellationToken) + { + var clock = SystemClock.Instance; + await using var db = Database.Open(new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = data.SqliteFile }, allowCreate: true); + await Migrations.MigrateAsync(db, clock, null, cancellationToken).ConfigureAwait(false); + var identity = await Installation.CheckAsync(db, data, clock, cancellationToken).ConfigureAwait(false); + var accounts = await AccountSetup.EnsureAsync(db, clock, alpacaDemo: false, okxDemo: false, cancellationToken).ConfigureAwait(false); + var account = accounts.First(a => a.Broker == Venues.Okx && a.Environment == TradingEnvironments.Simulation); + var btc = await new InstrumentCatalog(db, clock).EnsureAsync(new InstrumentSpec(Venues.Okx, "BTC-EUR", "BTC-EUR", AssetClasses.Crypto, "EUR") + { + BaseCurrency = "BTC", + TickSize = 0.1m, + LotSize = 0.00000001m, + MinSize = 0.00001m, + Status = "live", + }, cancellationToken).ConfigureAwait(false); + var ledger = new Ledger(db, clock); + await new Capital(db, clock, ledger, new FxStore(db, clock)).SetAsync(Venues.Okx, 1000m, "esercitazione", cancellationToken).ConfigureAwait(false); + + Task QuoteAsync(string symbol, CancellationToken _) => Task.FromResult(new Quote(symbol, FakeOkx.Bid, FakeOkx.Ask, clock.UtcNow)); + using var paper = new PaperBroker(PaperOptions.Okx() with { MinLatency = TimeSpan.Zero, MaxLatency = TimeSpan.Zero }, clock, QuoteAsync, + symbol => symbol == btc.Symbol ? btc.Spec : null, new PaperBookStore(db, clock, account.AccountId)); + await paper.DepositAsync(1000m, "EUR", cancellationToken).ConfigureAwait(false); + using var manager = new OrderManager(db, clock, ledger, paper, account, ClientOrderIds.InstallationCode(identity.File!.InstallationId), + (id, _) => Task.FromResult(id == btc.Id ? btc : null), QuoteAsync) + { + PassiveSteps = 0, + ConfirmPrice = QuoteAsync, + MarketOpen = (_, _) => Task.FromResult(true), + }; + var (_, refusal) = await manager.SubmitAsync(new TradeIntent(btc.Id, StrategyNames.CryptoTrend, OrderSide.Buy, Quantity, OrderPurpose.Entry, Ids.NewId(clock)) + { + StopLevel = StopLevel, + }, cancellationToken).ConfigureAwait(false); + if (refusal is not null) + { + throw new InvalidOperationException("Esercitazione: acquisto rifiutato (" + refusal + ")."); + } + + for (var i = 0; ; i++) + { + await paper.PumpAsync(cancellationToken).ConfigureAwait(false); + await manager.TickAsync(cancellationToken).ConfigureAwait(false); + var stops = await db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM orders WHERE purpose = 'stop' AND status = 'submitted'"), cancellationToken).ConfigureAwait(false); + if (stops > 0) + { + break; + } + + if (i > 100) + { + throw new InvalidOperationException("Esercitazione: la posizione non ha avuto il suo stop."); + } + + await Task.Delay(100, cancellationToken).ConfigureAwait(false); + } + + var held = (await ledger.PositionsAsync(account.AccountId, cancellationToken).ConfigureAwait(false)).Single().Quantity; + var now = clock.UtcNow; + await db.WriteAsync(s => s.ExecuteAsync( + "INSERT INTO planned_orders (id, decision_id, strategy, account_id, instrument_id, side, purpose, quantity, exit_all, stop_level, stop_offset, reference_price, reason, " + + "due_at, valid_until, status, outcome, execution_id, created_at, updated_at) VALUES (@id, @d, @s, @a, @i, 'sell', 'exit', @q, @x, NULL, NULL, @r, 'esercitazione', " + + "@now, NULL, 'pending', NULL, NULL, @now, @now)", cancellationToken, + ("id", Ids.NewId(clock)), ("d", Ids.NewId(clock)), ("s", StrategyNames.CryptoTrend), ("a", account.AccountId), ("i", btc.Id), ("q", held), ("x", true), + ("r", FakeOkx.Bid), ("now", now)), cancellationToken).ConfigureAwait(false); + return held; + } + + private static int FreePort() + { + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + return ((IPEndPoint)listener.LocalEndpoint).Port; + } + + /// + /// A local server that answers like OKX's REST interface with a fixed price for every ticker and nothing for the + /// rest; anything else (the streams) gets 404. Plain HTTP/1.1 on the loopback address, one request per connection. + /// + private sealed class FakeOkx : IDisposable + { + public const decimal Bid = 50000m; + public const decimal Ask = 50010m; + + private readonly TcpListener _listener; + private readonly CancellationTokenSource _stop = new(); + private readonly Task _loop; + + private FakeOkx() + { + _listener = new TcpListener(IPAddress.Loopback, 0); + _listener.Start(); + Address = new Uri($"http://127.0.0.1:{((IPEndPoint)_listener.LocalEndpoint).Port}/"); + _loop = Task.Run(() => AcceptAsync(_stop.Token)); + } + + public Uri Address { get; } + + public static FakeOkx Start() => new(); + + public void Dispose() + { + _stop.Cancel(); + _listener.Stop(); + try + { + _loop.Wait(TimeSpan.FromSeconds(5)); + } + catch (AggregateException) + { + } + + _stop.Dispose(); + } + + private async Task AcceptAsync(CancellationToken cancellationToken) + { + while (!cancellationToken.IsCancellationRequested) + { + TcpClient client; + try + { + client = await _listener.AcceptTcpClientAsync(cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is OperationCanceledException or SocketException or ObjectDisposedException) + { + return; + } + + _ = Task.Run(() => AnswerAsync(client, cancellationToken), CancellationToken.None); + } + } + + private static async Task AnswerAsync(TcpClient client, CancellationToken cancellationToken) + { + using (client) + { + try + { + var stream = client.GetStream(); + using var reader = new StreamReader(stream, Encoding.ASCII, leaveOpen: true); + var request = await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false) ?? ""; + while (await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false) is { Length: > 0 }) + { + } + + var target = request.Split(' ') is [_, var path, ..] ? path : "/"; + var (status, body) = Route(target); + var bytes = Encoding.UTF8.GetBytes(body); + var head = $"HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {bytes.Length}\r\nConnection: close\r\n\r\n"; + await stream.WriteAsync(Encoding.ASCII.GetBytes(head), cancellationToken).ConfigureAwait(false); + await stream.WriteAsync(bytes, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is IOException or OperationCanceledException or SocketException) + { + } + } + } + + private static (string Status, string Body) Route(string target) + { + if (target.StartsWith("/ws", StringComparison.Ordinal)) + { + return ("404 Not Found", "{}"); + } + + if (target.StartsWith("/api/v5/market/ticker?instId=", StringComparison.Ordinal)) + { + var symbol = Uri.UnescapeDataString(target["/api/v5/market/ticker?instId=".Length..]); + var ts = SystemClock.Instance.UtcNow.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture); + return ("200 OK", $"{{\"code\":\"0\",\"msg\":\"\",\"data\":[{{\"instId\":\"{symbol}\",\"bidPx\":\"{Bid.ToString(CultureInfo.InvariantCulture)}\"," + + $"\"askPx\":\"{Ask.ToString(CultureInfo.InvariantCulture)}\",\"bidSz\":\"1\",\"askSz\":\"1\",\"ts\":\"{ts}\"}}]}}"); + } + + // The list of instruments has the drill's one: an instrument missing from it is taken as delisted. + if (target.StartsWith("/api/v5/public/instruments", StringComparison.Ordinal)) + { + return ("200 OK", "{\"code\":\"0\",\"msg\":\"\",\"data\":[{\"instId\":\"BTC-EUR\",\"baseCcy\":\"BTC\",\"quoteCcy\":\"EUR\",\"tickSz\":\"0.1\",\"lotSz\":\"0.00000001\",\"minSz\":\"0.00001\",\"state\":\"live\"}]}"); + } + + return ("200 OK", "{\"code\":\"0\",\"msg\":\"\",\"data\":[]}"); + } + } +} + +/// How the guard finds the .NET host and the engine next to itself. +public static class GuardLaunch +{ + /// The dotnet host that runs the engine: the one running now when it is dotnet itself, otherwise the one the SDK names. + public static string Dotnet() + { + if (Environment.ProcessPath is { } current && Path.GetFileNameWithoutExtension(current).Equals("dotnet", StringComparison.OrdinalIgnoreCase)) + { + return current; + } + + return Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") is { Length: > 0 } host ? host : "dotnet"; + } + + /// The engine's program next to the guard's. + public static string Server() => Path.Combine(AppContext.BaseDirectory, "Anubis.Server.dll"); +} + +/// A logger that writes one line per message: the guard's log goes where the container's goes. +public sealed class LineLogger(Action write) : ILogger +{ + public IDisposable? BeginScope(TState state) + where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => logLevel >= LogLevel.Information; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) + { + ArgumentNullException.ThrowIfNull(formatter); + if (!IsEnabled(logLevel)) + { + return; + } + + var text = Redactor.Redact(formatter(state, exception) + (exception is null ? "" : " — " + exception.Message)); + write($"{SystemClock.Instance.UtcNow:yyyy-MM-dd HH:mm:ss} guardia {logLevel}: {text}"); + } +} diff --git a/src/Anubis/Supervision/GuardLink.cs b/src/Anubis/Supervision/GuardLink.cs new file mode 100644 index 0000000..365ad08 --- /dev/null +++ b/src/Anubis/Supervision/GuardLink.cs @@ -0,0 +1,170 @@ +using System.IO.Pipes; +using System.Text; +using System.Threading.Channels; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; + +namespace Anubis.Supervision; + +/// +/// The engine's end of the channel to the guard (SPEC 9.3): the beat of the main loop, the startup steps, the keys +/// and the stops it decides. Messages wait in a short queue and the oldest beats give way: a slow guard never slows +/// the engine. When the guard is gone the engine goes on by itself. +/// +public sealed partial class GuardLink : IAsyncDisposable +{ + private readonly Lock _gate = new(); + private readonly NamedPipeClientStream _pipe; + private readonly Channel _outgoing = Channel.CreateBounded(new BoundedChannelOptions(64) { FullMode = BoundedChannelFullMode.DropOldest }); + private readonly CancellationTokenSource _stop = new(); + private readonly ILogger _logger; + private readonly Task _loop; + private string _stage = GuardStages.Starting; + private string? _step; + + private GuardLink(string pipeName, ILogger logger) + { + _logger = logger; + _pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); + _loop = Task.Run(() => RunAsync(_stop.Token)); + } + + /// The link when a guard started this engine (); null otherwise. + public static GuardLink? FromEnvironment(IReadOnlyDictionary environment, ILogger? logger = null) + { + ArgumentNullException.ThrowIfNull(environment); + return environment.GetValueOrDefault(GuardChannel.PipeVariable) is { Length: > 0 } name ? new GuardLink(name, logger ?? NullLogger.Instance) : null; + } + + /// The guard asked for an orderly stop. + public Action? StopRequested { get; set; } + + public string Stage + { + get + { + lock (_gate) + { + return _stage; + } + } + } + + /// A new stage or startup step: told to the guard at once. + public void Set(string stage, string? step = null) + { + lock (_gate) + { + if (_stage == stage && _step == step) + { + return; + } + + _stage = stage; + _step = step; + } + + Beat(); + } + + /// A step of the startup of SPEC 9.4. + public void Step(string step) => Set(GuardStages.Starting, step); + + /// Alive, at the current stage. + public void Beat() + { + GuardMessage message; + lock (_gate) + { + message = GuardMessage.Beat(_stage, _step); + } + + _outgoing.Writer.TryWrite(message); + } + + public void SendKeys(IReadOnlyList keys) => _outgoing.Writer.TryWrite(new GuardMessage(GuardMessageTypes.Keys) { Keys = keys }); + + /// A stop decided by the engine: the guard will not restart it. Waits a moment for the message to leave. + public async Task AnnounceAsync(string reason) + { + _outgoing.Writer.TryWrite(new GuardMessage(GuardMessageTypes.Stopping) { Reason = reason }); + for (var i = 0; i < 20 && _outgoing.Reader.Count > 0; i++) + { + await Task.Delay(50).ConfigureAwait(false); + } + } + + public async ValueTask DisposeAsync() + { + await _stop.CancelAsync().ConfigureAwait(false); + try + { + await _loop.ConfigureAwait(false); + } + catch (OperationCanceledException) + { + } + + await _pipe.DisposeAsync().ConfigureAwait(false); + _stop.Dispose(); + } + + private async Task RunAsync(CancellationToken cancellationToken) + { + try + { + await _pipe.ConnectAsync(TimeSpan.FromSeconds(30), cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is TimeoutException or IOException or UnauthorizedAccessException) + { + LogNoGuard(_logger, ex.Message); + return; + } + + var reading = ReadAsync(cancellationToken); + var writer = new StreamWriter(_pipe, new UTF8Encoding(false), leaveOpen: true) { AutoFlush = true, NewLine = "\n" }; + await using (writer.ConfigureAwait(false)) + { + try + { + await foreach (var message in _outgoing.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false)) + { + await writer.WriteLineAsync(GuardChannel.Write(message).AsMemory(), cancellationToken).ConfigureAwait(false); + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + } + catch (IOException ex) + { + LogGuardLost(_logger, ex.Message); + } + } + + await reading.ConfigureAwait(false); + } + + private async Task ReadAsync(CancellationToken cancellationToken) + { + using var reader = new StreamReader(_pipe, Encoding.UTF8, leaveOpen: true); + try + { + while (await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false) is { } line) + { + if (GuardChannel.Read(line) is { Type: GuardMessageTypes.Stop }) + { + StopRequested?.Invoke(); + } + } + } + catch (Exception ex) when (ex is OperationCanceledException or IOException or ObjectDisposedException) + { + } + } + + [LoggerMessage(Level = LogLevel.Warning, Message = "Guard channel not reached: {Reason}. The engine runs without its guard.")] + private static partial void LogNoGuard(ILogger logger, string reason); + + [LoggerMessage(Level = LogLevel.Warning, Message = "Guard channel lost: {Reason}")] + private static partial void LogGuardLost(ILogger logger, string reason); +} diff --git a/src/Anubis/Supervision/GuardProtocol.cs b/src/Anubis/Supervision/GuardProtocol.cs new file mode 100644 index 0000000..3f3f4af --- /dev/null +++ b/src/Anubis/Supervision/GuardProtocol.cs @@ -0,0 +1,120 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Anubis.Supervision; + +/// +/// The channel between the guard and the engine (SPEC 9.3, ADR 0012): a local named pipe whose name the guard puts +/// in , one JSON message per line. The engine sends its beat, the startup steps, the broker +/// keys (in memory only) and the stops it decides; the guard sends only "stop". +/// +public static class GuardChannel +{ + /// The pipe the engine connects to. Without it the engine runs on its own (development, tests). + public const string PipeVariable = "ANUBIS_GUARD_PIPE"; + + /// + /// Fault injection for the guard drill (ADR 0012): blocks the main loop right after a sale + /// leaves. The guard never passes it to an engine it restarts. + /// + public const string FaultVariable = "ANUBIS_FAULT"; + + public const string HangMidSale = "hang-mid-sale"; + + public static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web) + { + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + Converters = { new JsonStringEnumConverter() }, + }; + + public static string Write(GuardMessage message) => JsonSerializer.Serialize(message, Json); + + /// A line of the channel; null when it is not a message (a broken line is ignored, never fatal). + public static GuardMessage? Read(string? line) + { + if (string.IsNullOrWhiteSpace(line)) + { + return null; + } + + try + { + return JsonSerializer.Deserialize(line, Json) is { Type.Length: > 0 } message ? message : null; + } + catch (JsonException) + { + return null; + } + } +} + +public static class GuardMessageTypes +{ + /// Engine to guard: alive, with its stage and the startup step it is on. + public const string Beat = "beat"; + + /// Engine to guard: the keys of the broker accounts and of Telegram, kept in memory only. + public const string Keys = "keys"; + + /// Engine to guard: a stop decided by the engine (exit, restore, import): not restarted. + public const string Stopping = "stopping"; + + /// Guard to engine: stop in an orderly way (the container is stopping). + public const string Stop = "stop"; +} + +/// Stages of the engine as the guard sees them. +public static class GuardStages +{ + /// The startup steps of SPEC 9.4: watched for 10 minutes without progress. + public const string Starting = "starting"; + + /// The main loop runs: watched for 2 minutes of silence. + public const string Running = "running"; + + /// Error page or first run: waiting for the user, never a reason to intervene. + public const string Waiting = "waiting"; +} + +/// One message of the channel. +public sealed record GuardMessage(string Type) +{ + public string? Stage { get; init; } + + public string? Step { get; init; } + + public string? Reason { get; init; } + + public IReadOnlyList? Keys { get; init; } + + public static GuardMessage Beat(string stage, string? step) => new(GuardMessageTypes.Beat) { Stage = stage, Step = step }; + + // Never prints the keys. + public override string ToString() => $"GuardMessage({Type}, {Stage}, {Step})"; +} + +/// +/// The keys of one account, as the engine has them: Alpaca key and secret, OKX key, secret and passphrase, Telegram +/// token and chat. Held only in the guard's memory, never written (SPEC 9.3). +/// +public sealed record GuardKeys(string Service, string Environment, IReadOnlyList Values) +{ + public const string Telegram = "telegram"; + + public override string ToString() => $"GuardKeys({Service}, {Environment}, ***)"; +} + +/// Where the guard and the engine meet in the data folder. +public sealed record GuardPaths(string DataRoot) +{ + public string Folder => Path.Combine(DataRoot, "guard"); + + /// Positions, stop levels and open orders, kept current by the engine for the guard. + public string StateFile => Path.Combine(Folder, "state.json"); + + /// The guard does not write in the database: it leaves notes here, which the engine puts in the diary. + public string NotesFolder => Path.Combine(Folder, "notes"); + + /// The "Ferma tutto" file (SPEC 9.3). + public string StopFile => Path.Combine(DataRoot, "STOP"); +} diff --git a/src/Anubis/Supervision/GuardRepair.cs b/src/Anubis/Supervision/GuardRepair.cs new file mode 100644 index 0000000..c0ed4f6 --- /dev/null +++ b/src/Anubis/Supervision/GuardRepair.cs @@ -0,0 +1,130 @@ +using Anubis.Core; +using Anubis.Trading; + +namespace Anubis.Supervision; + +/// What the guard did on one account. +public sealed record RepairOutcome(IReadOnlyList Lines, IReadOnlyList Placed, bool Complete); + +/// +/// The guard's work on a broker account while the engine is stopped (SPEC 9.3): reads positions and the outcome of the +/// orders in the state file, cancels the purchases and sales left open, and puts back only the stops that are +/// missing and were not executed, for the quantity still held. Protective sales and stops are never touched. +/// +public static class GuardRepair +{ + /// + /// The guard's stops take sequences this far above the engine's next one: if a note were lost, the engine's next + /// stops would still not reuse their ids. + /// + public const int SequenceGap = 500; + + public static async Task RunAsync(GuardState state, GuardAccount account, IBrokerAccount broker, IClock clock, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(state); + ArgumentNullException.ThrowIfNull(account); + ArgumentNullException.ThrowIfNull(broker); + ArgumentNullException.ThrowIfNull(clock); + var lines = new List(); + var placed = new List(); + var complete = true; + + // 1. Purchases and sales still waiting: the open ones the broker shows, and those the state lists. + var open = (await broker.GetOpenOrdersAsync(cancellationToken).ConfigureAwait(false)) + .Where(o => ClientOrderIds.IsOurs(o.ClientOrderId, state.Installation)).ToList(); + var waiting = open.Where(o => ClientOrderIds.Parse(o.ClientOrderId)?.Purpose is OrderPurpose.Entry or OrderPurpose.Exit) + .Select(o => (o.ClientOrderId, o.Symbol, o.Side)).ToList(); + foreach (var listed in account.Orders.Where(o => o.Purpose is OrderPurpose.Entry or OrderPurpose.Exit && waiting.All(w => w.ClientOrderId != o.ClientOrderId))) + { + if (await broker.GetOrderAsync(listed.ClientOrderId, listed.Symbol, cancellationToken).ConfigureAwait(false) is { IsOpen: true } remote) + { + waiting.Add((remote.ClientOrderId, remote.Symbol, remote.Side)); + } + } + + foreach (var (clientId, symbol, side) in waiting) + { + await broker.CancelOrderAsync(clientId, symbol, cancellationToken).ConfigureAwait(false); + lines.Add($"Ho annullato {(side == OrderSide.Buy ? "l'acquisto" : "la vendita")} di {Shown(symbol)} rimast{(side == OrderSide.Buy ? "o" : "a")} in attesa."); + } + + // 2. What the bot holds now: the state's quantity plus the fills of its own orders since then, never more than the account has. + var fills = (await broker.GetFillsAsync(state.WrittenAt, cancellationToken).ConfigureAwait(false)) + .Where(f => f.ExecutedAt > state.WrittenAt && ClientOrderIds.IsOurs(f.ClientOrderId, state.Installation)).ToList(); + var positions = await broker.GetPositionsAsync(cancellationToken).ConfigureAwait(false); + var stops = (await broker.GetOpenOrdersAsync(cancellationToken).ConfigureAwait(false)) + .Where(o => o.IsOpen && o.Side == OrderSide.Sell && ClientOrderIds.Parse(o.ClientOrderId) is { Purpose: OrderPurpose.Stop } parts && parts.Installation == state.Installation) + .ToList(); + foreach (var bySymbol in account.Positions.Where(p => p.StopLevel is not null).GroupBy(p => p.Symbol, StringComparer.Ordinal)) + { + var available = positions.Where(p => p.Symbol == bySymbol.Key).Sum(p => p.Quantity); + foreach (var position in bySymbol.OrderBy(p => p.Strategy, StringComparer.Ordinal)) + { + var code = ClientOrderIds.StrategyCodes.GetValueOrDefault(position.Strategy); + var moved = fills.Where(f => f.Symbol == position.Symbol && ClientOrderIds.Parse(f.ClientOrderId)?.Strategy == position.Strategy) + .Sum(f => f.Side == OrderSide.Buy ? f.Quantity : -f.Quantity); + var held = Math.Min(Math.Max(0m, position.Quantity + moved), available); + available -= held; + var covered = stops.Where(o => o.Symbol == position.Symbol && code is not null && ClientOrderIds.Parse(o.ClientOrderId)?.Strategy == position.Strategy) + .Sum(o => o.Remaining); + var missing = OrderRules.RoundDown(held - covered, position.Lot); + if (missing <= 0m || code is null) + { + continue; + } + + var sequence = Math.Min(position.NextStopSequence + SequenceGap, ClientOrderIds.MaxSequence - 2); + foreach (var (quantity, timeInForce) in Shapes(position, missing, account.FractionalStopsAreDayOnly)) + { + var clientId = ClientOrderIds.Build(state.Installation, account.Environment, position.Strategy, OrderPurpose.Stop, position.StopKey, sequence++); + var request = new OrderRequest(clientId, position.Symbol, OrderSide.Sell, OrderKind.Stop, quantity, timeInForce) { StopPrice = position.StopLevel }; + try + { + var remote = await broker.SubmitOrderAsync(request, cancellationToken).ConfigureAwait(false); + placed.Add(new PlacedStop(account.AccountId, position.InstrumentId, position.Symbol, position.Strategy, clientId, remote.BrokerOrderId, quantity, + position.StopLevel!.Value, timeInForce)); + lines.Add($"Ho rimesso lo stop di {Shown(position.Symbol)} a {Format.Price(position.StopLevel.Value)} per {Format.Quantity(quantity)}."); + } + catch (OrderRejectedException ex) + { + complete = false; + lines.Add($"{account.Name} ha rifiutato lo stop di {Shown(position.Symbol)} ({ex.Code}): la posizione resta senza stop finché il motore non riparte."); + } + } + } + } + + if (lines.Count == 0) + { + lines.Add($"Su {account.Name} non c'era nulla da annullare e ogni posizione aveva il suo stop."); + } + + return new RepairOutcome(lines, placed, complete); + } + + /// The stops a quantity needs on the venue, as the engine places them (SPEC 7.2): fractions of shares only as day orders. + public static IReadOnlyList<(decimal Quantity, TimeInForce TimeInForce)> Shapes(GuardPosition position, decimal quantity, bool fractionalDayOnly) + { + ArgumentNullException.ThrowIfNull(position); + if (!fractionalDayOnly || position.IsCrypto) + { + return [(quantity, TimeInForce.Gtc)]; + } + + var (whole, fraction) = OrderRules.SplitWhole(quantity); + var shapes = new List<(decimal, TimeInForce)>(); + if (whole > 0m) + { + shapes.Add((whole, TimeInForce.Gtc)); + } + + if (fraction > 0m) + { + shapes.Add((fraction, TimeInForce.Day)); + } + + return shapes; + } + + private static string Shown(string symbol) => DiaryText.Shown(symbol); +} diff --git a/src/Anubis/Supervision/GuardState.cs b/src/Anubis/Supervision/GuardState.cs new file mode 100644 index 0000000..6ecf457 --- /dev/null +++ b/src/Anubis/Supervision/GuardState.cs @@ -0,0 +1,116 @@ +using System.Globalization; +using System.Text.Json; +using Anubis.Trading; + +namespace Anubis.Supervision; + +/// +/// What the guard needs to protect the positions while the engine is stopped (SPEC 9.3): written by the engine every +/// few seconds, read by the guard only after it stopped the engine. +/// +public sealed record GuardState(DateTimeOffset WrittenAt, string Installation, IReadOnlyList Accounts); + +public sealed record GuardAccount(Guid AccountId, string Name, string Broker, string Environment, bool FractionalStopsAreDayOnly, + IReadOnlyList Positions, IReadOnlyList Orders); + +/// +/// A position of a strategy: quantity, stop level already on the tick, lot, and what the guard needs to name a stop +/// the engine will recognize as its own (the key of the position's stops and the next free sequence). +/// +public sealed record GuardPosition(Guid InstrumentId, string Symbol, string Strategy, decimal Quantity, decimal? StopLevel, decimal Lot, bool IsCrypto, + string StopKey, int NextStopSequence); + +/// An order the engine believes open. +public sealed record GuardOrder(string ClientOrderId, Guid InstrumentId, string Symbol, string Strategy, OrderSide Side, OrderPurpose Purpose, decimal Quantity, + decimal? StopPrice); + +/// A stop the guard placed while the engine was stopped: the engine adopts it at the restart. +public sealed record PlacedStop(Guid AccountId, Guid InstrumentId, string Symbol, string Strategy, string ClientOrderId, string? BrokerOrderId, decimal Quantity, + decimal StopPrice, TimeInForce TimeInForce); + +/// +/// The note of one intervention: when, why, what the guard did, in the words of the diary. The engine writes it in the +/// diary at the restart and adopts the stops it lists. +/// +public sealed record GuardNote(DateTimeOffset At, string Reason, IReadOnlyList Lines, IReadOnlyList Placed) +{ + /// The engine was silent for the 2 minutes of SPEC 9.3. + public const string Silence = "silence"; + + /// The startup steps did not move for 10 minutes. + public const string Stalled = "stalled"; + + /// The engine ended without announcing it. + public const string Crash = "crash"; + + /// The intervention made the bot restart in "Ferma tutto" (third forced restart within an hour). + public bool StopFileCreated { get; init; } +} + +/// Reading and writing the guard's files: each write goes to a temporary file first, so a reader never sees half of it. +public static class GuardFiles +{ + public static void WriteState(GuardPaths paths, GuardState state) + { + ArgumentNullException.ThrowIfNull(paths); + Write(paths.StateFile, JsonSerializer.Serialize(state, GuardChannel.Json)); + } + + /// The last state the engine wrote; null when there is none or it cannot be read. + public static GuardState? ReadState(GuardPaths paths) + { + ArgumentNullException.ThrowIfNull(paths); + return Read(paths.StateFile); + } + + public static string WriteNote(GuardPaths paths, GuardNote note) + { + ArgumentNullException.ThrowIfNull(paths); + ArgumentNullException.ThrowIfNull(note); + var path = Path.Combine(paths.NotesFolder, note.At.UtcDateTime.ToString("yyyyMMdd'T'HHmmssfff'Z'", CultureInfo.InvariantCulture) + ".json"); + Write(path, JsonSerializer.Serialize(note, GuardChannel.Json)); + return path; + } + + /// The notes not yet taken by the engine, oldest first, with their files. + public static IReadOnlyList<(string Path, GuardNote Note)> ReadNotes(GuardPaths paths) + { + ArgumentNullException.ThrowIfNull(paths); + if (!Directory.Exists(paths.NotesFolder)) + { + return []; + } + + var notes = new List<(string, GuardNote)>(); + foreach (var file in Directory.GetFiles(paths.NotesFolder, "*.json").Order(StringComparer.Ordinal)) + { + if (Read(file) is { } note) + { + notes.Add((file, note)); + } + } + + return notes; + } + + private static T? Read(string path) + where T : class + { + try + { + return File.Exists(path) ? JsonSerializer.Deserialize(File.ReadAllText(path), GuardChannel.Json) : null; + } + catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException) + { + return null; + } + } + + private static void Write(string path, string text) + { + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + var temporary = path + ".tmp"; + File.WriteAllText(temporary, text); + File.Move(temporary, path, overwrite: true); + } +} diff --git a/src/Anubis/Supervision/Guardian.cs b/src/Anubis/Supervision/Guardian.cs new file mode 100644 index 0000000..43fea09 --- /dev/null +++ b/src/Anubis/Supervision/Guardian.cs @@ -0,0 +1,499 @@ +using Anubis.Core; +using Anubis.Trading; +using Microsoft.Extensions.Logging; + +namespace Anubis.Supervision; + +/// The times of the guard (SPEC 9.3). The drill shortens them; the bot uses these. +public sealed record GuardOptions +{ + /// Silence of the main loop, after a successful start, that makes the guard intervene. + public TimeSpan Silence { get; init; } = TimeSpan.FromMinutes(2); + + /// Startup steps that do not move for this long make the guard intervene. + public TimeSpan StalledStart { get; init; } = TimeSpan.FromMinutes(10); + + public TimeSpan Poll { get; init; } = TimeSpan.FromSeconds(1); + + /// A round of the guard this late means its own clock jumped (the computer slept): the silence counts from now. + public TimeSpan ClockJump { get; init; } = TimeSpan.FromSeconds(30); + + /// How long an orderly stop may take before the engine is ended (the container waits 60 seconds). + public TimeSpan GracefulStop { get; init; } = TimeSpan.FromSeconds(55); + + public TimeSpan ForcedWindow { get; init; } = TimeSpan.FromHours(1); + + /// The forced restart, within , that restarts the engine in "Ferma tutto". + public int ForcedLimit { get; init; } = 3; + + public TimeSpan DownAlertEvery { get; init; } = TimeSpan.FromHours(1); + + /// Pauses before restarting an engine that keeps closing by itself: the first restart is immediate. + public IReadOnlyList CrashPauses { get; init; } = + [TimeSpan.Zero, TimeSpan.FromSeconds(10), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(15)]; +} + +/// How to start the engine: with the drill's fault or without, and where its messages go. +public sealed record EngineStart(bool Fault, Action OnMessage); + +/// The engine as a child process of the guard. +public interface IEngineProcess : IDisposable +{ + /// Completes with the exit code when the process ends. + Task Exited { get; } + + /// Asks for an orderly stop through the channel. + Task RequestStopAsync(CancellationToken cancellationToken); + + /// Ends the process at once, with everything it started. + void Kill(); +} + +/// +/// The guard (SPEC 9.3): parent of the engine, it listens to its beat and intervenes when the main loop is silent for +/// 2 minutes after a successful start, or the startup steps of 9.4 do not move for 10 minutes. Then, in this order: +/// ends the engine, reads positions and orders from the brokers, cancels the purchases and sales left open, puts back +/// the missing stops, leaves a note, warns, restarts the engine. Orderly stops are not reactions: they are passed on +/// and waited for, and the engine is not restarted. At the third forced restart within an hour the engine restarts in +/// "Ferma tutto". The guard never writes in the database. +/// +public sealed partial class Guardian(GuardPaths paths, IClock clock, GuardOptions options, Func start, + Func, IBrokerAccount?> brokers, Func, CancellationToken, Task> alert, ILogger logger) +{ + private readonly Lock _gate = new(); + private readonly List _forced = []; + private IEngineProcess? _engine; + private string _stage = GuardStages.Starting; + private string? _step; + private DateTimeOffset _lastBeat; + private DateTimeOffset _stepSince; + private bool _announced; + private IReadOnlyList _keys = []; + private DateTimeOffset _lastRound; + private DateTimeOffset? _downSince; + private DateTimeOffset? _nextDownAlert; + private DateTimeOffset? _restartAt; + private int _crashes; + + /// The stage the engine last declared. + public string Stage + { + get + { + lock (_gate) + { + return _stage; + } + } + } + + public int Interventions { get; private set; } + + /// The engine has a process now (not waiting for the pause after a crash). + public bool EngineAlive => _engine is { Exited.IsCompleted: false }; + + /// The notes written so far, for the drill and the tests. + public IReadOnlyList Notes => [.. _notes]; + + private readonly List _notes = []; + + /// Starts the engine; only for the drill. + public void Start(bool fault = false) => StartEngine(fault); + + /// A message from the engine. + public void Receive(GuardMessage message) + { + ArgumentNullException.ThrowIfNull(message); + var now = clock.UtcNow; + lock (_gate) + { + switch (message.Type) + { + case GuardMessageTypes.Beat: + var stage = message.Stage ?? _stage; + if (stage != _stage || message.Step != _step) + { + _stepSince = now; + } + + _stage = stage; + _step = message.Step; + _lastBeat = now; + if (stage is GuardStages.Running or GuardStages.Waiting) + { + // The engine is back: no more "it does not restart" alerts. + _downSince = null; + _nextDownAlert = null; + _crashes = 0; + } + + break; + case GuardMessageTypes.Keys: + _keys = message.Keys ?? []; + foreach (var value in _keys.SelectMany(k => k.Values)) + { + Redactor.Register(value); + } + + break; + case GuardMessageTypes.Stopping: + _announced = true; + LogAnnounced(logger, message.Reason ?? "-"); + break; + } + } + } + + /// Watches until the engine stops on purpose, or until asks the guard to stop it. + public async Task RunAsync(CancellationToken shutdown) + { + if (_engine is null && _restartAt is null) + { + StartEngine(fault: false); + } + + while (true) + { + var exited = _engine?.Exited ?? Task.FromResult(0); + try + { + await Task.WhenAny(Task.Delay(options.Poll, shutdown), _engine is null ? Task.Delay(Timeout.Infinite, shutdown) : exited).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + } + + if (shutdown.IsCancellationRequested) + { + return await StopAsync().ConfigureAwait(false); + } + + if (await RoundAsync(shutdown).ConfigureAwait(false) is { } code) + { + return code; + } + } + } + + /// One round of watching; the exit code when the engine stopped on purpose and the guard's work is over. + public async Task RoundAsync(CancellationToken cancellationToken) + { + var now = clock.UtcNow; + if (_lastRound != default && now - _lastRound > options.ClockJump) + { + // The guard's own clock jumped too (the computer slept): the engine's silence starts now, not then. + lock (_gate) + { + _lastBeat = now; + _stepSince = now; + } + } + + _lastRound = now; + if (_engine is null) + { + if (_restartAt is { } at && now >= at) + { + _restartAt = null; + StartEngine(fault: false); + } + + await DownAlertAsync(now, cancellationToken).ConfigureAwait(false); + return null; + } + + if (_engine.Exited.IsCompleted) + { + var code = await _engine.Exited.ConfigureAwait(false); + bool announced; + lock (_gate) + { + announced = _announced; + } + + if (announced) + { + LogEnded(logger, code); + return code; + } + + await InterveneAsync(GuardNote.Crash, cancellationToken).ConfigureAwait(false); + return null; + } + + string stage; + string? step; + DateTimeOffset beat; + DateTimeOffset since; + lock (_gate) + { + (stage, step, beat, since) = (_stage, _step, _lastBeat, _stepSince); + } + + if (stage == GuardStages.Running && now - beat > options.Silence) + { + await InterveneAsync(GuardNote.Silence, cancellationToken).ConfigureAwait(false); + } + else if (stage == GuardStages.Starting && now - since > options.StalledStart) + { + await InterveneAsync(GuardNote.Stalled, cancellationToken, step).ConfigureAwait(false); + } + + await DownAlertAsync(now, cancellationToken).ConfigureAwait(false); + return null; + } + + /// + /// The container is stopping: the engine gets "stop" and up to to close in + /// order, then it is ended. It is not restarted. + /// + public async Task StopAsync() + { + lock (_gate) + { + _announced = true; + } + + var engine = _engine; + if (engine is null) + { + return 0; + } + + try + { + using var asking = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + await engine.RequestStopAsync(asking.Token).ConfigureAwait(false); + } + catch (Exception ex) when (ex is IOException or OperationCanceledException or ObjectDisposedException or InvalidOperationException) + { + // The channel is gone: the wait below ends the engine anyway. + } + + if (await Task.WhenAny(engine.Exited, Task.Delay(options.GracefulStop)).ConfigureAwait(false) != engine.Exited) + { + LogKilledAtStop(logger); + engine.Kill(); + } + + return await engine.Exited.ConfigureAwait(false); + } + + private void StartEngine(bool fault) + { + _engine?.Dispose(); + var now = clock.UtcNow; + lock (_gate) + { + _stage = GuardStages.Starting; + _step = null; + _lastBeat = now; + _stepSince = now; + _announced = false; + } + + _lastRound = now; + _engine = start(new EngineStart(fault, Receive)); + LogStarted(logger, fault); + } + + private async Task InterveneAsync(string reason, CancellationToken cancellationToken, string? step = null) + { + var engine = _engine!; + var now = clock.UtcNow; + Interventions++; + LogIntervention(logger, reason); + + // 1. The engine stops first: the guard touches orders only while it is stopped. + engine.Kill(); + try + { + await engine.Exited.WaitAsync(TimeSpan.FromSeconds(30), CancellationToken.None).ConfigureAwait(false); + } + catch (TimeoutException) + { + LogStillAlive(logger); + } + + engine.Dispose(); + _engine = null; + + // 2-4. Each broker account: orders left waiting canceled, missing stops put back. + var lines = new List { Opening(reason, step) }; + var placed = new List(); + IReadOnlyList keys; + lock (_gate) + { + keys = _keys; + } + + var state = GuardFiles.ReadState(paths); + if (state is null) + { + lines.Add("Non ho trovato il file di stato del motore: posizioni e stop li rimette in ordine il motore alla ripartenza."); + } + else + { + foreach (var account in state.Accounts.Where(a => a.Positions.Count > 0 || a.Orders.Count > 0)) + { + lines.AddRange(await RepairAsync(state, account, keys, placed, cancellationToken).ConfigureAwait(false)); + } + } + + // The third forced restart within an hour: the engine restarts in "Ferma tutto" (SPEC 9.3). + _forced.RemoveAll(t => now - t >= options.ForcedWindow); + _forced.Add(now); + var stopAll = _forced.Count >= options.ForcedLimit; + if (stopAll) + { + WriteStopFile(now); + lines.Add("È il terzo riavvio forzato in un'ora: il motore riparte in \"Ferma tutto\". Per ripartire togli il file STOP e conferma dall'interfaccia."); + } + + // 5. The note for the diary, then the warning. + var note = new GuardNote(now, reason, lines, placed) { StopFileCreated = stopAll }; + try + { + GuardFiles.WriteNote(paths, note); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + LogNoteFailed(logger, ex); + } + + _notes.Add(note); + await AlertAsync(string.Join(Environment.NewLine, lines), cancellationToken).ConfigureAwait(false); + + // 6. The restart, never with the drill's fault. An engine that keeps closing by itself waits a little longer each time. + _downSince ??= now; + _nextDownAlert ??= now + options.DownAlertEvery; + var pause = TimeSpan.Zero; + if (reason == GuardNote.Crash) + { + _crashes++; + pause = options.CrashPauses[Math.Min(_crashes, options.CrashPauses.Count) - 1]; + } + + if (pause <= TimeSpan.Zero) + { + StartEngine(fault: false); + } + else + { + _restartAt = now + pause; + } + } + + private async Task> RepairAsync(GuardState state, GuardAccount account, IReadOnlyList keys, List placed, CancellationToken cancellationToken) + { + if (account.Environment == TradingEnvironments.Simulation) + { + return [$"{account.Name} è il simulatore interno: posizioni e stop li rimette in ordine il motore alla ripartenza."]; + } + + IBrokerAccount? broker; + try + { + broker = brokers(account, keys); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + return [$"{account.Name}: non riesco a collegarmi al conto ({Redactor.Redact(ex.Message)}): ci pensa il motore alla ripartenza."]; + } + + if (broker is null) + { + return [$"{account.Name}: non ho le chiavi del conto, quindi non posso intervenire: ci pensa il motore alla ripartenza."]; + } + + try + { + var outcome = await GuardRepair.RunAsync(state, account, broker, clock, cancellationToken).ConfigureAwait(false); + placed.AddRange(outcome.Placed); + return [.. outcome.Lines]; + } + catch (BrokerException ex) + { + return [$"{account.Name}: non raggiungo il conto ({Redactor.Redact(ex.Message)}): ci pensa il motore alla ripartenza."]; + } + finally + { + (broker as IDisposable)?.Dispose(); + } + } + + private async Task DownAlertAsync(DateTimeOffset now, CancellationToken cancellationToken) + { + if (_downSince is not { } since || _nextDownAlert is not { } next || now < next) + { + return; + } + + _nextDownAlert = next + options.DownAlertEvery; + await AlertAsync($"Il motore non riparte da {DiaryText.Duration(now - since)}. Le posizioni hanno gli stop che ho rimesso io; " + + "quelli giornalieri sulle frazioni di azione scadono a fine seduta e senza il motore nessuno li rimette domani.", cancellationToken).ConfigureAwait(false); + } + + private async Task AlertAsync(string text, CancellationToken cancellationToken) + { + IReadOnlyList keys; + lock (_gate) + { + keys = _keys; + } + + try + { + await alert(text, keys, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + LogAlertFailed(logger, ex); + } + } + + private void WriteStopFile(DateTimeOffset now) + { + try + { + Directory.CreateDirectory(paths.DataRoot); + File.WriteAllText(paths.StopFile, $"Creato dalla guardia il {now:yyyy-MM-dd HH:mm} UTC: terzo riavvio forzato in un'ora.{Environment.NewLine}"); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + LogNoteFailed(logger, ex); + } + } + + private string Opening(string reason, string? step) => reason switch + { + GuardNote.Silence => $"La guardia è intervenuta: il motore non dava segni di vita da {DiaryText.Duration(options.Silence)}. L'ho fermato, ho controllato i conti e l'ho riavviato.", + GuardNote.Stalled => $"La guardia è intervenuta: l'avvio del motore era fermo da {DiaryText.Duration(options.StalledStart)}" + + (step is null ? "" : $" al passo \"{step}\"") + ". L'ho fermato, ho controllato i conti e l'ho riavviato.", + _ => "La guardia è intervenuta: il motore si è chiuso senza avvisare. Ho controllato i conti e l'ho riavviato.", + }; + + [LoggerMessage(Level = LogLevel.Information, Message = "Engine started (drill fault: {Fault})")] + private static partial void LogStarted(ILogger logger, bool fault); + + [LoggerMessage(Level = LogLevel.Warning, Message = "Guard intervention: {Reason}")] + private static partial void LogIntervention(ILogger logger, string reason); + + [LoggerMessage(Level = LogLevel.Information, Message = "Engine announced its stop: {Reason}")] + private static partial void LogAnnounced(ILogger logger, string reason); + + [LoggerMessage(Level = LogLevel.Information, Message = "Engine ended with code {Code}")] + private static partial void LogEnded(ILogger logger, int code); + + [LoggerMessage(Level = LogLevel.Warning, Message = "Engine did not stop in time: ended")] + private static partial void LogKilledAtStop(ILogger logger); + + [LoggerMessage(Level = LogLevel.Error, Message = "Engine still alive after being ended")] + private static partial void LogStillAlive(ILogger logger); + + [LoggerMessage(Level = LogLevel.Error, Message = "Guard note or STOP file not written")] + private static partial void LogNoteFailed(ILogger logger, Exception exception); + + [LoggerMessage(Level = LogLevel.Error, Message = "Guard alert not sent")] + private static partial void LogAlertFailed(ILogger logger, Exception exception); +} diff --git a/src/Anubis/Trading/DiaryText.cs b/src/Anubis/Trading/DiaryText.cs index c1103e7..58cec0a 100644 --- a/src/Anubis/Trading/DiaryText.cs +++ b/src/Anubis/Trading/DiaryText.cs @@ -150,6 +150,11 @@ public static class DiaryText /// A missed job left out at the restart, with its reason (SPEC 5.6). public static string Skipped(string what, string reason) => $"Saltato: {what}. {reason}"; + /// A purchase or sale left open at a start (SPEC 9.4): canceled, and proposed again. + public static string RestartedOrder(bool sale, string symbol) => sale + ? $"Alla ripartenza ho annullato la vendita di {Shown(symbol)} rimasta aperta: la vendita già decisa riparte subito con un ordine nuovo." + : $"Alla ripartenza ho annullato l'acquisto di {Shown(symbol)} rimasto aperto: lo ripropongo con le regole del recupero."; + /// An entry left out because the price moved too far from the planned one (SPEC 5.6). public static string EntryDropped(string symbol, decimal movedPercent, decimal limitPercent) => $"Scartato l'acquisto di {Shown(symbol)}: il prezzo si è mosso del {Format.Percent(movedPercent, 1)} dall'orario previsto, oltre il limite del {Format.Percent(limitPercent, 0)}."; diff --git a/src/Anubis/Trading/LiveEngine.cs b/src/Anubis/Trading/LiveEngine.cs index 932aace..9f58aaf 100644 --- a/src/Anubis/Trading/LiveEngine.cs +++ b/src/Anubis/Trading/LiveEngine.cs @@ -22,6 +22,9 @@ public static class LiveReasons public const string OrderInProgress = "order_in_progress"; public const string NothingHeld = "nothing_held"; public const string Recovered = "recovered"; + + /// A purchase or sale left open at a start, canceled by the steps of SPEC 9.4. + public const string Restart = "restart"; } /// States of a planned order. @@ -911,6 +914,55 @@ public sealed partial class LiveEngine : IDisposable await CloseAsync(order, refusal is null ? PlannedStates.Submitted : PlannedStates.Refused, refusal, execution, recovered, cancellationToken).ConfigureAwait(false); } + /// + /// The step of SPEC 9.4 that comes after the reconciliation: the purchases and sales left open on the account are + /// canceled (their stops come back at once), the exits already decided restart now with a new order, and the + /// interrupted entries are proposed again with their time and reference price, so the rules of SPEC 5.6 apply. + /// The answer is how many were proposed again. + /// + public async Task ResumeAsync(OrderManager manager, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(manager); + var canceled = await manager.CancelWorkingAsync(LiveReasons.Restart, cancellationToken: cancellationToken).ConfigureAwait(false); + var again = 0; + foreach (var execution in canceled) + { + var row = await _db.ReadAsync(s => s.FirstOrDefaultAsync( + "SELECT p.id, p.decision_id, p.strategy, p.account_id, p.instrument_id, p.side, p.purpose, p.quantity, p.exit_all, p.stop_level, p.stop_offset, " + + "p.reference_price, p.reason, p.due_at, p.valid_until, e.filled FROM planned_orders p JOIN executions e ON e.id = p.execution_id WHERE p.execution_id = @e", + r => new Interrupted(new Planned(r.Id("id"), r.Id("decision_id"), r.Text("strategy"), r.Id("account_id"), r.Id("instrument_id"), Wire.Side(r.Text("side")), + Wire.Purpose(r.Text("purpose")), r.Money("quantity"), r.Bool("exit_all"), r.MoneyOrNull("stop_level"), r.MoneyOrNull("stop_offset"), r.Money("reference_price"), + r.Text("reason"), r.Moment("due_at"), r.MomentOrNull("valid_until")), r.Money("filled")), ("e", execution)), cancellationToken).ConfigureAwait(false); + if (row is not { } found || (found.Order.Quantity - found.Filled <= 0m && !found.Order.ExitAll)) + { + continue; + } + + var (order, filled) = found; + var symbol = (await _catalog.GetAsync(order.InstrumentId, cancellationToken).ConfigureAwait(false))?.Symbol ?? "?"; + var now = _clock.UtcNow; + var sale = order.Side == OrderSide.Sell; + await _db.WriteAsync(async s => + { + await s.ExecuteAsync( + "INSERT INTO planned_orders (id, decision_id, strategy, account_id, instrument_id, side, purpose, quantity, exit_all, stop_level, stop_offset, reference_price, " + + "reason, due_at, valid_until, status, outcome, execution_id, created_at, updated_at) VALUES (@id, @d, @s, @a, @i, @side, @p, @q, @x, @sl, @so, @r, @reason, " + + "@due, @until, @st, NULL, NULL, @now, @now)", cancellationToken, + ("id", Ids.NewId(_clock)), ("d", order.DecisionId), ("s", order.Strategy), ("a", order.AccountId), ("i", order.InstrumentId), ("side", Wire.Text(order.Side)), + ("p", Wire.Text(order.Purpose)), ("q", Math.Max(0m, order.Quantity - filled)), ("x", order.ExitAll), ("sl", order.StopLevel), ("so", order.StopOffset), + ("r", order.Reference), ("reason", order.Reason), ("due", sale ? now : order.Due), ("until", order.ValidUntil), ("st", PlannedStates.Pending), ("now", now)) + .ConfigureAwait(false); + await Diary.WriteAsync(s, _clock, DiaryKinds.Orders, LiveReasons.Restart, DiaryText.RestartedOrder(sale, symbol), new { planned = order.Id, execution }, + cancellationToken).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); + again++; + } + + return again; + } + + private sealed record Interrupted(Planned Order, decimal Filled); + private static string OrderWords(Planned order, string symbol) => (order.Side == OrderSide.Buy ? "l'acquisto di " : "la vendita di ") + DiaryText.Shown(symbol); diff --git a/src/Anubis/Trading/OrderManager.Guard.cs b/src/Anubis/Trading/OrderManager.Guard.cs new file mode 100644 index 0000000..5e38687 --- /dev/null +++ b/src/Anubis/Trading/OrderManager.Guard.cs @@ -0,0 +1,84 @@ +using Anubis.Core; +using Anubis.Supervision; + +namespace Anubis.Trading; + +/// What the order manager gives to the guard and takes back from it (SPEC 9.3). +public sealed partial class OrderManager +{ + /// + /// Called right after a sale leaves, before the turn ends. Only the guard drill sets it, to block the main loop + /// with a sale halfway (ADR 0012). + /// + public Func? AfterSale { get; init; } + + /// + /// The account as the guard needs it: every position with its stop level on the tick and the names its stops + /// take, and the orders believed open. + /// + public async Task GuardAccountAsync(CancellationToken cancellationToken) + { + var positions = new List(); + foreach (var position in await _ledger.PositionsAsync(_account.AccountId, cancellationToken).ConfigureAwait(false)) + { + if (position.Quantity <= 0m || await _instruments(position.InstrumentId, cancellationToken).ConfigureAwait(false) is not { } instrument) + { + continue; + } + + var level = position.StopPrice is { } stop ? OrderRules.StopPrice(stop, OrderRules.TickOf(instrument.Spec, stop)) : (decimal?)null; + var key = ClientOrderIds.Key(StopKey(position.InstrumentId, position.Strategy)); + var next = await NextStopSequenceAsync(position.InstrumentId, position.Strategy, key, cancellationToken).ConfigureAwait(false); + positions.Add(new GuardPosition(position.InstrumentId, instrument.Symbol, position.Strategy, position.Quantity, level, OrderRules.LotOf(instrument.Spec), + instrument.IsCrypto, key, next)); + } + + var orders = new List(); + var open = await _db.ReadAsync(s => s.QueryAsync(OrderSelect + " WHERE account_id = @a AND status IN ('created', 'submitted', 'partially_filled')", ReadOrder, + ("a", _account.AccountId)), cancellationToken).ConfigureAwait(false); + foreach (var row in open) + { + var symbol = (await _instruments(row.InstrumentId, cancellationToken).ConfigureAwait(false))?.Symbol ?? ""; + orders.Add(new GuardOrder(row.ClientOrderId, row.InstrumentId, symbol, row.Strategy, row.Side, row.Purpose, row.Quantity, row.Stop)); + } + + return new GuardAccount(_account.AccountId, _account.Name, _account.Broker, _account.Environment, _broker.Capabilities.FractionalStopsAreDayOnly, positions, orders); + } + + /// + /// A stop the guard placed while the engine was stopped becomes one of the engine's stops: recorded, then read + /// again from the broker (it may have triggered meanwhile). False when it was already known. + /// + public async Task AdoptStopAsync(PlacedStop placed, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(placed); + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + if (await OrderByClientIdAsync(placed.ClientOrderId, cancellationToken).ConfigureAwait(false) is not null) + { + return false; + } + + var row = new OrderRow(Ids.NewId(_clock), null, placed.InstrumentId, placed.Strategy, placed.ClientOrderId, OrderSide.Sell, OrderKind.Stop, OrderPurpose.Stop, + placed.Quantity, null, placed.StopPrice, OrderStatus.Created, 0m, null, placed.StopPrice, null, placed.TimeInForce, false, _clock.UtcNow); + await _db.WriteAsync(async s => + { + await InsertOrderAsync(s, row, cancellationToken).ConfigureAwait(false); + await s.ExecuteAsync("UPDATE orders SET broker_order_id = @b, submitted_at = @now, reason = 'placed by the guard' WHERE id = @id", cancellationToken, + ("b", placed.BrokerOrderId), ("now", _clock.UtcNow), ("id", row.Id)).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); + if (await _broker.GetOrderAsync(placed.ClientOrderId, placed.Symbol, cancellationToken).ConfigureAwait(false) is { } remote) + { + await ApplyRemoteAsync(row, remote, "placed by the guard", cancellationToken).ConfigureAwait(false); + await SyncFillsCoreAsync(cancellationToken).ConfigureAwait(false); + } + + return true; + } + finally + { + _gate.Release(); + } + } +} diff --git a/src/Anubis/Trading/OrderManager.cs b/src/Anubis/Trading/OrderManager.cs index 8c68e48..c8dbb5d 100644 --- a/src/Anubis/Trading/OrderManager.cs +++ b/src/Anubis/Trading/OrderManager.cs @@ -375,14 +375,15 @@ public sealed partial class OrderManager : IDisposable /// /// Cancels the executions under way, except protective sales (SPEC 9.3, "Ferma tutto"): the open order of each is - /// canceled with the broker, and the stops it had removed come back at once for the quantity held. + /// canceled with the broker, and the stops it had removed come back at once for the quantity held. The answer is + /// the executions canceled. /// - public async Task CancelWorkingAsync(string reason, Func? strategy = null, CancellationToken cancellationToken = default) + public async Task> CancelWorkingAsync(string reason, Func? strategy = null, CancellationToken cancellationToken = default) { await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); try { - var count = 0; + var canceled = new List(); foreach (var exec in await WorkingAsync(cancellationToken).ConfigureAwait(false)) { if (exec.Purpose == OrderPurpose.Protective || (strategy is not null && !strategy(exec.Strategy))) @@ -400,10 +401,10 @@ public sealed partial class OrderManager : IDisposable await SyncFillsCoreAsync(cancellationToken).ConfigureAwait(false); await FinishAsync(exec, ExecutionStates.Canceled, reason, instrument, cancellationToken).ConfigureAwait(false); - count++; + canceled.Add(exec.Id); } - return count; + return canceled; } finally { @@ -626,6 +627,10 @@ public sealed partial class OrderManager : IDisposable } }, cancellationToken).ConfigureAwait(false); await SendAsync(exec, row, instrument, cancellationToken).ConfigureAwait(false); + if (exec.Side == OrderSide.Sell && exec.Purpose == OrderPurpose.Exit && AfterSale is { } afterSale) + { + await afterSale(cancellationToken).ConfigureAwait(false); + } } private async Task SendAsync(ExecRow exec, OrderRow row, Instrument instrument, CancellationToken cancellationToken) diff --git a/src/Anubis/Trading/ReasonCatalog.cs b/src/Anubis/Trading/ReasonCatalog.cs index 7571e11..951a1eb 100644 --- a/src/Anubis/Trading/ReasonCatalog.cs +++ b/src/Anubis/Trading/ReasonCatalog.cs @@ -83,6 +83,7 @@ public static class ReasonCatalog ["superseded"] = "Sostituito da una decisione più recente.", ["order_in_progress"] = "Un ordine sullo stesso strumento era ancora in corso.", ["nothing_held"] = "Niente da vendere: la posizione era già chiusa.", + ["restart"] = "Annullato alla ripartenza del bot: se era ancora dovuto, è stato riproposto.", ["recovered"] = "Recuperato dopo un'assenza.", }; diff --git a/src/Anubis/Trading/TradingService.cs b/src/Anubis/Trading/TradingService.cs index 14a45bc..bd44a26 100644 --- a/src/Anubis/Trading/TradingService.cs +++ b/src/Anubis/Trading/TradingService.cs @@ -4,6 +4,7 @@ using Anubis.Core; using Anubis.Data; using Anubis.Db; using Anubis.Risk; +using Anubis.Supervision; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; @@ -192,6 +193,9 @@ public sealed partial class TradingService : IDisposable private volatile bool _started; + /// The startup steps of SPEC 9.4 are done and the loop runs. + public bool IsStarted => _started; + /// The live engine (SPEC 5.5, issue #47): the decisions at their times, the planned orders, the recovery. public LiveEngine Engine { get; } @@ -216,6 +220,23 @@ public sealed partial class TradingService : IDisposable public TimeSpan TickInterval { get; init; } = TimeSpan.FromSeconds(5); + /// The channel to the guard (SPEC 9.3): startup steps and the beat of the loop. Null without a guard. + public GuardLink? Guard { get; init; } + + /// Where the state file for the guard is written and its notes are read. Null without a guard. + public GuardPaths? GuardFiles { get; init; } + + /// The guard drill's fault (ADR 0012): or nothing. + public string? Fault { get; init; } + + /// How often the loop writes the state file for the guard. + public TimeSpan GuardStateEvery { get; init; } = TimeSpan.FromSeconds(10); + + /// A broker clock further than this from the computer's is reported at the start (SPEC 9.4). + public TimeSpan ClockTolerance { get; init; } = TimeSpan.FromSeconds(5); + + private DateTimeOffset _guardStateAt; + public IReadOnlyCollection Managers => [.. _managers.Values]; public OrderManager? ManagerOf(Guid accountId) => _managers.GetValueOrDefault(accountId); @@ -233,14 +254,21 @@ public sealed partial class TradingService : IDisposable return accounts; } - /// Accounts, brokers and order managers; then the simulator catches up, keys are checked and every account reconciled. + /// + /// The startup of SPEC 9.4 after the migrations: brokers, clock, corporate actions, then for every account the + /// complete reconciliation, the purchases and sales left open canceled (exits restart, entries are proposed again) + /// and every position checked for its stop. Each step is told to the guard. + /// public async Task StartAsync(CancellationToken cancellationToken) { + Guard?.Step("conti e strategie"); var accounts = await PrepareAsync(cancellationToken).ConfigureAwait(false); var alpaca = await AlpacaKeysAsync(cancellationToken).ConfigureAwait(false); var okx = await OkxKeysAsync(cancellationToken).ConfigureAwait(false); await RefreshSpecsAsync(cancellationToken).ConfigureAwait(false); await RefreshLimitsAsync(cancellationToken).ConfigureAwait(false); + Guard?.Step("connessione ai broker"); + var hang = Fault == GuardChannel.HangMidSale; foreach (var account in accounts) { var broker = Build(account, alpaca, okx); @@ -259,10 +287,16 @@ public sealed partial class TradingService : IDisposable Gate = Risk is null ? null : Risk.GateAsync, LivePermit = Stages.LiveRefusalAsync, PurchasePriceCheck = (limit, quote) => RiskRules.TechnicalRefusal(_clock.UtcNow, quote.At, quote.Mid, limit, null, _limits), + + // The guard drill only: the main loop stops here for good, with a sale halfway. + AfterSale = hang ? _ => Task.Delay(Timeout.Infinite, CancellationToken.None) : null, }; } await GuardAsync("simulatore", () => FundSimulatorsAsync(cancellationToken), cancellationToken).ConfigureAwait(false); + Guard?.Step("orologio"); + await GuardAsync("orologio", () => CheckClocksAsync(cancellationToken), cancellationToken).ConfigureAwait(false); + Guard?.Step("azioni societarie"); // SPEC 5.6: corporate actions come first, so the stops the reconciliation puts back already know about a split. if (_market is not null) @@ -271,6 +305,7 @@ public sealed partial class TradingService : IDisposable } await GuardAsync("azioni societarie nei registri", () => CorporateActionsAsync(cancellationToken), cancellationToken).ConfigureAwait(false); + var notes = GuardFiles is null ? [] : Supervision.GuardFiles.ReadNotes(GuardFiles); foreach (var manager in _managers.Values) { await GuardAsync("avvio " + manager.Account.Name, async () => @@ -284,12 +319,104 @@ public sealed partial class TradingService : IDisposable await Reconciler.CheckKeyAsync(manager, cancellationToken).ConfigureAwait(false); } + // The stops the guard put back while the engine was stopped become the engine's own, before anything compares. + foreach (var placed in notes.SelectMany(n => n.Note.Placed).Where(p => p.AccountId == manager.Account.AccountId)) + { + await manager.AdoptStopAsync(placed, cancellationToken).ConfigureAwait(false); + } + + Guard?.Step("riconciliazione " + manager.Account.Name); await Reconciler.ReconcileAsync(manager, cancellationToken).ConfigureAwait(false); + Guard?.Step("ordini rimasti aperti " + manager.Account.Name); + await Engine.ResumeAsync(manager, cancellationToken).ConfigureAwait(false); + Guard?.Step("stop " + manager.Account.Name); + await manager.AlignStopsAsync(cancellationToken).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false); } + await GuardAsync("note della guardia", () => TakeGuardNotesAsync(notes, cancellationToken), cancellationToken).ConfigureAwait(false); await GuardAsync("patrimonio", () => PhotographAsync(cancellationToken), cancellationToken).ConfigureAwait(false); + await GuardAsync("stato per la guardia", () => WriteGuardStateAsync(cancellationToken), cancellationToken).ConfigureAwait(false); + await GuardAsync("chiavi per la guardia", () => SendGuardKeysAsync(alpaca, okx, cancellationToken), cancellationToken).ConfigureAwait(false); _started = true; + Guard?.Set(GuardStages.Running); + } + + /// + /// What the guard needs if the engine stops answering (SPEC 9.3): positions, stop levels and open orders of every + /// account. Written to a temporary file first, so the guard never reads half of it. + /// + public async Task WriteGuardStateAsync(CancellationToken cancellationToken) + { + if (GuardFiles is null) + { + return; + } + + var accounts = new List(); + foreach (var manager in _managers.Values) + { + accounts.Add(await manager.GuardAccountAsync(cancellationToken).ConfigureAwait(false)); + } + + Supervision.GuardFiles.WriteState(GuardFiles, new GuardState(_clock.UtcNow, InstallationCode, accounts)); + _guardStateAt = _clock.UtcNow; + } + + // The guard's notes go in the diary once their stops are adopted; then they are gone. + private async Task TakeGuardNotesAsync(IReadOnlyList<(string Path, GuardNote Note)> notes, CancellationToken cancellationToken) + { + foreach (var (path, note) in notes) + { + await _db.WriteAsync(s => Diary.WriteAsync(s, _clock, DiaryKinds.System, "guard_intervention", string.Join(" ", note.Lines), + new { at = note.At, reason = note.Reason, stops = note.Placed.Count, stopFile = note.StopFileCreated }, cancellationToken), cancellationToken).ConfigureAwait(false); + File.Delete(path); + } + } + + // The keys reach the guard in memory only: it needs them to protect the positions while the engine is stopped. + private async Task SendGuardKeysAsync(AlpacaCredentials? alpaca, OkxCredentials? okx, CancellationToken cancellationToken) + { + if (Guard is null) + { + return; + } + + var keys = new List(); + if (alpaca is not null) + { + keys.Add(new GuardKeys(Venues.Alpaca, TradingEnvironments.Demo, [alpaca.KeyId, alpaca.Secret])); + } + + if (okx is not null) + { + keys.Add(new GuardKeys(Venues.Okx, TradingEnvironments.Demo, [okx.Key, okx.Secret, okx.Passphrase])); + } + + var token = await _secrets.RevealAsync("TELEGRAM_BOT_TOKEN", cancellationToken).ConfigureAwait(false); + var chat = await _secrets.RevealAsync("TELEGRAM_CHAT_ID", cancellationToken).ConfigureAwait(false); + if (!string.IsNullOrWhiteSpace(token) && !string.IsNullOrWhiteSpace(chat)) + { + keys.Add(new GuardKeys(GuardKeys.Telegram, "", [token, chat])); + } + + Guard.SendKeys(keys); + } + + // SPEC 9.4: the clock of each broker against the computer's. A large gap is said, not corrected: the computer's clock is the system's. + private async Task CheckClocksAsync(CancellationToken cancellationToken) + { + foreach (var manager in _managers.Values.Where(m => m.Broker is not PaperBroker)) + { + var remote = await manager.Broker.ServerTimeAsync(cancellationToken).ConfigureAwait(false); + var gap = (remote - _clock.UtcNow).Duration(); + if (gap > ClockTolerance) + { + await _db.WriteAsync(s => Diary.NotifyAsync(s, _clock, "clock_gap", + $"L'orologio di questo computer differisce di {Math.Round(gap.TotalSeconds)} secondi da quello di {manager.Account.Name}: controlla la sincronizzazione dell'ora.", + cancellationToken), cancellationToken).ConfigureAwait(false); + } + } } /// @@ -377,6 +504,12 @@ public sealed partial class TradingService : IDisposable } await TickAllAsync(cancellationToken).ConfigureAwait(false); + Guard?.Beat(); + if (GuardFiles is not null && _clock.UtcNow - _guardStateAt >= GuardStateEvery) + { + await GuardAsync("stato per la guardia", () => WriteGuardStateAsync(cancellationToken), cancellationToken).ConfigureAwait(false); + } + await Task.Delay(TickInterval, cancellationToken).ConfigureAwait(false); } } diff --git a/tests/Anubis.Tests/GuardTests.cs b/tests/Anubis.Tests/GuardTests.cs new file mode 100644 index 0000000..036cb29 --- /dev/null +++ b/tests/Anubis.Tests/GuardTests.cs @@ -0,0 +1,414 @@ +using Anubis.Core; +using Anubis.Data; +using Anubis.Supervision; +using Anubis.Trading; +using Microsoft.Extensions.Logging.Abstractions; + +namespace Anubis.Tests; + +/// The guard (issue #48, SPEC 9.3, 9.4): when it intervenes, what it does on the broker, and the restart. +[TestClass] +public sealed class GuardTests +{ + private static readonly CancellationToken _none = CancellationToken.None; + private static readonly TimeSpan _minute = TimeSpan.FromMinutes(1); + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task TwoMinutesOfSilenceAfterAStartMakeTheGuardInterveneAndRestartWithoutTheFault() + { + using var g = new GuardRig(fault: true); + g.Engine.Beat(GuardStages.Starting, "database"); + await g.PassAsync(TimeSpan.FromMinutes(5)).ConfigureAwait(false); + g.Engine.Beat(GuardStages.Running); + await g.PassAsync(TimeSpan.FromMinutes(10), () => g.Engine.Beat(GuardStages.Running)).ConfigureAwait(false); + await g.PassAsync(TimeSpan.FromSeconds(110)).ConfigureAwait(false); + Assert.AreEqual(0, g.Guardian.Interventions, "Five minutes of startup, a loop that beats, then 1:50 of silence: nothing yet."); + + await g.PassAsync(TimeSpan.FromSeconds(20)).ConfigureAwait(false); + Assert.AreEqual(1, g.Guardian.Interventions); + Assert.IsTrue(g.Engines[0].Killed); + Assert.HasCount(2, g.Engines); + Assert.IsTrue(g.Engines[0].Start.Fault, "The first engine had the drill's fault…"); + Assert.IsFalse(g.Engines[1].Start.Fault, "…the one the guard restarts never has it."); + Assert.Contains("non dava segni di vita da 2 minuti", g.Alerts.Single()); + var note = GuardFiles.ReadNotes(g.Paths).Single().Note; + Assert.AreEqual(GuardNote.Silence, note.Reason); + Assert.Contains("Non ho trovato il file di stato", string.Join(" ", note.Lines)); + Assert.IsFalse(File.Exists(g.Paths.StopFile)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task TheErrorPageIsNeverAReasonToIntervene() + { + using var g = new GuardRig(); + g.Engine.Beat(GuardStages.Waiting); + await g.PassAsync(TimeSpan.FromHours(1)).ConfigureAwait(false); + Assert.AreEqual(0, g.Guardian.Interventions); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task StartupStepsThatDoNotMoveForTenMinutesMakeTheGuardIntervene() + { + using var g = new GuardRig(); + g.Engine.Beat(GuardStages.Starting, "migrazioni e identità"); + await g.PassAsync(TimeSpan.FromMinutes(9)).ConfigureAwait(false); + g.Engine.Beat(GuardStages.Starting, "riconciliazione OKX demo"); + await g.PassAsync(TimeSpan.FromMinutes(9), () => g.Engine.Beat(GuardStages.Starting, "riconciliazione OKX demo")).ConfigureAwait(false); + Assert.AreEqual(0, g.Guardian.Interventions, "A step that moves resets the count; the same step repeated does not."); + + await g.PassAsync(TimeSpan.FromMinutes(2)).ConfigureAwait(false); + Assert.AreEqual(1, g.Guardian.Interventions); + Assert.Contains("al passo \"riconciliazione OKX demo\"", g.Alerts.Single()); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task AJumpOfTheGuardsOwnClockIsNotSilence() + { + using var g = new GuardRig(); + g.Engine.Beat(GuardStages.Running); + await g.PassAsync(TimeSpan.FromSeconds(30)).ConfigureAwait(false); + + // The computer slept for a quarter of an hour: guard and engine both stopped. + g.Clock.Advance(TimeSpan.FromMinutes(15)); + await g.Guardian.RoundAsync(_none).ConfigureAwait(false); + await g.PassAsync(TimeSpan.FromSeconds(110)).ConfigureAwait(false); + Assert.AreEqual(0, g.Guardian.Interventions); + + await g.PassAsync(TimeSpan.FromSeconds(20)).ConfigureAwait(false); + Assert.AreEqual(1, g.Guardian.Interventions, "After the jump the silence counts again from the wake-up."); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task TheContainersStopIsPassedOnAndNeverRestarted() + { + using var g = new GuardRig(); + g.Engine.Beat(GuardStages.Running); + Assert.AreEqual(0, await g.Guardian.StopAsync().ConfigureAwait(false)); + Assert.IsTrue(g.Engine.StopAsked); + Assert.IsFalse(g.Engine.Killed); + Assert.HasCount(1, g.Engines); + + // An engine that does not close in time is ended. + using var slow = new GuardRig(options: new GuardOptions { GracefulStop = TimeSpan.FromMilliseconds(200) }); + slow.Engine.ExitOnStop = false; + Assert.AreEqual(137, await slow.Guardian.StopAsync().ConfigureAwait(false)); + Assert.IsTrue(slow.Engine.Killed); + Assert.AreEqual(0, slow.Guardian.Interventions); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task AStopTheEngineAnnouncesEndsTheGuardWithoutARestart() + { + using var g = new GuardRig(); + g.Engine.Beat(GuardStages.Running); + g.Engine.Start.OnMessage(new GuardMessage(GuardMessageTypes.Stopping) { Reason = "uscita" }); + g.Engine.Exit(0); + Assert.AreEqual(0, await g.Guardian.RoundAsync(_none).ConfigureAwait(false)); + Assert.HasCount(1, g.Engines); + Assert.AreEqual(0, g.Guardian.Interventions); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task TheThirdForcedRestartWithinAnHourRestartsInStopEverything() + { + using var g = new GuardRig(); + for (var i = 1; i <= 3; i++) + { + g.Engine.Beat(GuardStages.Running); + await g.PassAsync(TimeSpan.FromMinutes(3)).ConfigureAwait(false); + Assert.AreEqual(i, g.Guardian.Interventions); + Assert.AreEqual(i == 3, File.Exists(g.Paths.StopFile), $"After intervention {i}."); + } + + var last = GuardFiles.ReadNotes(g.Paths)[^1].Note; + Assert.IsTrue(last.StopFileCreated); + Assert.Contains("\"Ferma tutto\"", g.Alerts[^1]); + + // Spread over more than an hour, three are not three within an hour. + using var spread = new GuardRig(); + for (var i = 0; i < 3; i++) + { + spread.Engine.Beat(GuardStages.Running); + await spread.PassAsync(TimeSpan.FromMinutes(3)).ConfigureAwait(false); + spread.Engine.Beat(GuardStages.Running); + await spread.PassAsync(TimeSpan.FromMinutes(30), () => spread.Engine.Beat(GuardStages.Running)).ConfigureAwait(false); + } + + Assert.AreEqual(3, spread.Guardian.Interventions); + Assert.IsFalse(File.Exists(spread.Paths.StopFile)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task AnEngineThatKeepsClosingIsRestartedWithPausesAndTheUserIsRemindedEveryHour() + { + using var g = new GuardRig(options: new GuardOptions { StalledStart = TimeSpan.FromHours(5) }); + g.Engine.Exit(1); + await g.Guardian.RoundAsync(_none).ConfigureAwait(false); + Assert.HasCount(2, g.Engines, "The first restart is immediate."); + Assert.Contains("si è chiuso senza avvisare", g.Alerts[0]); + + g.Engine.Exit(1); + await g.Guardian.RoundAsync(_none).ConfigureAwait(false); + Assert.HasCount(2, g.Engines, "The second waits ten seconds."); + await g.PassAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false); + Assert.HasCount(3, g.Engines); + + // It starts, but never gets to run: every hour a reminder about the stops on fractions of shares. + await g.PassAsync(TimeSpan.FromMinutes(61)).ConfigureAwait(false); + var reminder = g.Alerts.Single(a => a.Contains("non riparte", StringComparison.Ordinal)); + Assert.Contains("frazioni di azione scadono a fine seduta", reminder); + g.Engine.Beat(GuardStages.Running); + await g.PassAsync(TimeSpan.FromMinutes(70), () => g.Engine.Beat(GuardStages.Running)).ConfigureAwait(false); + Assert.AreEqual(1, g.Alerts.Count(a => a.Contains("non riparte", StringComparison.Ordinal)), "Once it runs, the reminders stop."); + } + + /// + /// The acceptance test of issue #48 on a broker account: the main loop blocks right after a sale leaves, with the + /// stop already removed. The guard stops the engine, cancels the sale, puts the stop back for the quantity held and + /// restarts the engine, which adopts the guard's stop and finds the account in order. + /// + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task ALoopBlockedWithASaleHalfwayGetsItsStopBackAndTheEngineRestarts() + { + await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); + var account = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Demo).ConfigureAwait(false); + var btc = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false); + var paper = rig.Paper(PaperOptions.Okx(), account.AccountId); + await paper.DepositAsync(100_000m, "EUR", _none).ConfigureAwait(false); + await rig.Ledger.RecordCapitalAsync(account.AccountId, StrategyNames.CryptoTrend, 100_000m, "EUR", "test", _none).ConfigureAwait(false); + rig.Quote(btc.Symbol, 60000m, 60010m); + + // The demo account at the broker, which the guard reaches on its own. + var remote = new FaultyBroker(paper, TradingEnvironments.Demo); + using var hang = new CancellationTokenSource(); + var sold = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + OrderManager Engine(Func? afterSale) => new(rig.Db, rig.Clock, rig.Ledger, remote, account, TradingRig.Installation, rig.FindAsync, rig.QuoteAsync) + { + ConfirmPrice = rig.QuoteAsync, + MarketOpen = (_, _) => Task.FromResult(true), + AfterSale = afterSale, + }; + + using var first = Engine(async _ => + { + sold.TrySetResult(); + await Task.Delay(Timeout.Infinite, hang.Token).ConfigureAwait(false); + }); + await first.SubmitAsync(new TradeIntent(btc.Id, StrategyNames.CryptoTrend, OrderSide.Buy, 0.01m, OrderPurpose.Entry, Ids.NewId(rig.Clock)) + { + StopLevel = 57000m, + StartAggressive = true, + }, _none).ConfigureAwait(false); + await rig.TurnsAsync(first, 3, _minute).ConfigureAwait(false); + var held = (await rig.Ledger.PositionAsync(account.AccountId, btc.Id, StrategyNames.CryptoTrend, _none).ConfigureAwait(false))!.Quantity; + Assert.AreEqual(held, (await OpenAsync(remote, OrderPurpose.Stop).ConfigureAwait(false)).Sum(o => o.Quantity)); + + var folder = Directory.CreateTempSubdirectory("anubis-guard-").FullName; + try + { + var paths = new GuardPaths(folder); + GuardFiles.WriteState(paths, new GuardState(rig.Clock.UtcNow, TradingRig.Installation, [await first.GuardAccountAsync(_none).ConfigureAwait(false)])); + + // The sale: the stop goes, the order leaves, and the loop never comes back. + await first.SubmitAsync(new TradeIntent(btc.Id, StrategyNames.CryptoTrend, OrderSide.Sell, held, OrderPurpose.Exit, Ids.NewId(rig.Clock)), _none).ConfigureAwait(false); + var blocked = Task.Run(() => first.TickAsync(hang.Token)); + await sold.Task.WaitAsync(TimeSpan.FromSeconds(30)).ConfigureAwait(false); + Assert.IsEmpty(await OpenAsync(remote, OrderPurpose.Stop).ConfigureAwait(false), "Halfway: the stop is gone…"); + Assert.HasCount(1, await OpenAsync(remote, OrderPurpose.Exit).ConfigureAwait(false), "…and the sale waits on the book."); + + // The guard: two minutes of silence, then it works on the account with the keys it was given. + var engines = new List(); + var guardian = new Guardian(paths, rig.Clock, new GuardOptions(), s => + { + var engine = new FakeEngine(s); + engines.Add(engine); + return engine; + }, (a, keys) => a.AccountId == account.AccountId && keys.Count > 0 ? remote : null, (_, _, _) => Task.CompletedTask, NullLogger.Instance); + guardian.Start(); + engines[0].Start.OnMessage(new GuardMessage(GuardMessageTypes.Keys) { Keys = [new GuardKeys(Venues.Okx, TradingEnvironments.Demo, ["k", "s", "p"])] }); + engines[0].Beat(GuardStages.Running); + for (var i = 0; i < 13 && guardian.Interventions == 0; i++) + { + rig.Clock.Advance(TimeSpan.FromSeconds(10)); + await guardian.RoundAsync(_none).ConfigureAwait(false); + } + + Assert.AreEqual(1, guardian.Interventions); + Assert.IsTrue(engines[0].Killed); + Assert.HasCount(2, engines, "The guard restarted the engine."); + Assert.IsEmpty(await OpenAsync(remote, OrderPurpose.Exit).ConfigureAwait(false), "The sale left waiting is canceled."); + var stops = await OpenAsync(remote, OrderPurpose.Stop).ConfigureAwait(false); + Assert.AreEqual((held, 57000m), (stops.Sum(o => o.Quantity), stops.Single().StopPrice), "The stop is back for the whole quantity."); + var note = GuardFiles.ReadNotes(paths).Single().Note; + Assert.AreEqual(stops.Single().ClientOrderId, note.Placed.Single().ClientOrderId); + Assert.IsTrue(note.Lines.Any(l => l.Contains("Ho annullato la vendita di BTC", StringComparison.Ordinal)), string.Join(" | ", note.Lines)); + + // The engine starts again (SPEC 9.4): it adopts the guard's stop, reconciles, cancels what it had left open. + using var second = Engine(null); + using var live = new LiveEngine(rig.Db, rig.Clock, rig.Ledger, new StageBook(rig.Db, rig.Clock, TradingConsent.None, (_, _, _) => Task.FromResult(false)), + _ => second, rig.QuoteAsync); + Assert.IsTrue(await second.AdoptStopAsync(note.Placed.Single(), _none).ConfigureAwait(false)); + var report = await new Reconciler(rig.Db, rig.Clock, rig.Ledger).ReconcileAsync(second, _none).ConfigureAwait(false); + await live.ResumeAsync(second, _none).ConfigureAwait(false); + await second.AlignStopsAsync(_none).ConfigureAwait(false); + engines[1].Beat(GuardStages.Running); + await rig.TurnsAsync(second, 2, _minute).ConfigureAwait(false); + + // The only thing the engine finds changed is the sale the guard canceled; nothing is left different. + Assert.IsEmpty(report.Differences, string.Join(" | ", report.Differences.Select(d => d.Message))); + Assert.AreEqual(OrderPurpose.Exit, ClientOrderIds.Parse(report.Healed.Single().Split(':')[1])?.Purpose, report.Healed.Single()); + Assert.AreEqual(GuardStages.Running, guardian.Stage); + var after = await OpenAsync(remote, OrderPurpose.Stop).ConfigureAwait(false); + Assert.AreEqual(stops.Single().ClientOrderId, after.Single().ClientOrderId, "The guard's stop stays: no second stop on the same quantity."); + var sale = await rig.QueryAsync("SELECT status, reason FROM executions WHERE side = 'sell'", r => r.Text("status") + "/" + r.TextOrNull("reason")).ConfigureAwait(false); + Assert.AreEqual("canceled/" + LiveReasons.Restart, sale.Single()); + var adopted = await rig.QueryAsync("SELECT status, reason FROM orders WHERE client_order_id = @c", r => r.Text("status") + "/" + r.TextOrNull("reason"), + ("c", after.Single().ClientOrderId)).ConfigureAwait(false); + Assert.AreEqual("submitted/placed by the guard", adopted.Single()); + Assert.AreEqual((held, 57000m), await rig.Ledger.PositionAsync(account.AccountId, btc.Id, StrategyNames.CryptoTrend, _none).ConfigureAwait(false) is { } p + ? (p.Quantity, p.StopPrice!.Value) : default); + + await hang.CancelAsync().ConfigureAwait(false); + await Assert.ThrowsAsync(() => blocked).ConfigureAwait(false); + } + finally + { + Directory.Delete(folder, recursive: true); + } + } + + /// + /// The same proof with real processes (the drill that also runs in the Docker image): the real guard, the real + /// engine as its child, a sale blocked halfway on the internal simulator, then the restart by SPEC 9.4. + /// + [TestMethod] + [TestCategory(Category.Integration)] + [Timeout(600_000, CooperativeCancellation = true)] + public async Task TheGuardDrillPassesWithTheRealEngineAsChildProcess() + { + if (TestDatabase.Engine == "postgres") + { + Assert.Inconclusive("The drill has its own SQLite database: it runs in the SQLite pass."); + } + + var folder = Directory.CreateTempSubdirectory("anubis-drill-").FullName; + try + { + var result = await GuardDrill.RunInAsync(folder, Path.Combine(AppContext.BaseDirectory, "Anubis.Server.dll"), GuardDrill.Options, + line => Console.WriteLine(line), _none).ConfigureAwait(false); + Assert.IsTrue(result.Passed, string.Join(Environment.NewLine, result.Lines)); + } + finally + { + try + { + Directory.Delete(folder, recursive: true); + } + catch (IOException) + { + } + } + } + + private static async Task> OpenAsync(FaultyBroker broker, OrderPurpose purpose) => + [.. (await broker.GetOpenOrdersAsync(_none).ConfigureAwait(false)).Where(o => ClientOrderIds.Parse(o.ClientOrderId)?.Purpose == purpose)]; + + /// The engine process as the guard sees it, driven by the test. + private sealed class FakeEngine(EngineStart start) : IEngineProcess + { + private readonly TaskCompletionSource _exit = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public EngineStart Start { get; } = start; + + public Task Exited => _exit.Task; + + public bool StopAsked { get; private set; } + + public bool Killed { get; private set; } + + public bool ExitOnStop { get; set; } = true; + + public Task RequestStopAsync(CancellationToken cancellationToken) + { + StopAsked = true; + if (ExitOnStop) + { + Start.OnMessage(new GuardMessage(GuardMessageTypes.Stopping) { Reason = "uscita" }); + _exit.TrySetResult(0); + } + + return Task.CompletedTask; + } + + public void Kill() + { + Killed = true; + _exit.TrySetResult(137); + } + + public void Exit(int code) => _exit.TrySetResult(code); + + public void Beat(string stage, string? step = null) => Start.OnMessage(GuardMessage.Beat(stage, step)); + + public void Dispose() + { + } + } + + /// A guard on a manual clock with fake engines, a data folder of its own and the alerts it sends. + private sealed class GuardRig : IDisposable + { + public GuardRig(bool fault = false, GuardOptions? options = null) + { + Folder = Directory.CreateTempSubdirectory("anubis-guard-").FullName; + Paths = new GuardPaths(Folder); + Guardian = new Guardian(Paths, Clock, options ?? new GuardOptions(), s => + { + var engine = new FakeEngine(s); + Engines.Add(engine); + return engine; + }, (_, _) => null, (text, _, _) => + { + Alerts.Add(text); + return Task.CompletedTask; + }, NullLogger.Instance); + Guardian.Start(fault); + } + + public ManualClock Clock { get; } = new(new DateTimeOffset(2026, 11, 11, 9, 0, 0, TimeSpan.Zero)); + + public string Folder { get; } + + public GuardPaths Paths { get; } + + public Guardian Guardian { get; } + + public List Engines { get; } = []; + + public List Alerts { get; } = []; + + public FakeEngine Engine => Engines[^1]; + + /// Time passes in rounds of ten seconds; runs before every round. + public async Task PassAsync(TimeSpan span, Action? each = null) + { + for (var t = TimeSpan.Zero; t < span; t += TimeSpan.FromSeconds(10)) + { + Clock.Advance(TimeSpan.FromSeconds(10)); + each?.Invoke(); + await Guardian.RoundAsync(_none).ConfigureAwait(false); + } + } + + public void Dispose() => Directory.Delete(Folder, recursive: true); + } +} diff --git a/tools/Anubis.Tasks/Program.cs b/tools/Anubis.Tasks/Program.cs index 2393bb6..e981ce2 100644 --- a/tools/Anubis.Tasks/Program.cs +++ b/tools/Anubis.Tasks/Program.cs @@ -39,7 +39,7 @@ int Test(string engine, string[] extra) ["test", "Anubis.slnx", "--filter", "TestCategory!=LiveDemo", "--logger", "console;verbosity=normal", .. extra], env) ?? 0; } -// What the remote CI does, run locally: check on SQLite, tests on PostgreSQL, image build. +// What the remote CI does, run locally: check on SQLite, tests on PostgreSQL, image build, the guard drill in the image. int Ci() { var failed = Check(); @@ -70,9 +70,14 @@ int Ci() } } - return failed != 0 ? failed : BuildImage("ci"); + failed = failed != 0 ? failed : BuildImage("ci"); + return failed != 0 ? failed : GuardDrill("ci"); } +// The guard drill inside the image (issue #48): the real guard and the real engine, a sale blocked halfway, the restart. +int GuardDrill(string tag) => + Step("Esercitazione della guardia nell'immagine", "docker", ["run", "--rm", $"gitea.encke-hake.ts.net/balbosoft/anubis:{tag}", "drill"]) ?? 0; + int BuildImage(string tag) => Step("Costruzione dell'immagine Docker", "docker", ["build", "-f", "deploy/docker/Dockerfile", "-t", $"gitea.encke-hake.ts.net/balbosoft/anubis:{tag}", "."]) ?? 0; From 84c540786c30a69ae841c4caab92b82fdc478eb4 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 11 Nov 2026 19:53:55 +0100 Subject: [PATCH 05/12] Send Telegram notices, answer phone commands and call the heartbeat (refs #52) Every notice is written to the queue in the same transaction as what it tells, then sent every ten seconds. Each has a state: pending, sent, or failed with its error. Network failures and 429s are retried with growing pauses (Telegram's own wait when it gives one). Refusals are final. A notice that could not leave within a day is given up instead of arriving late. Every fill now also reaches the phone, and so do pause, resume and restart. Commands are read by long polling and obeyed only from the configured chat and only when fresh, so yesterday's /pausa never pauses today. They are /stato, /posizioni, /oggi, /pausa, /riprendi, /ferma (confirmed with /conferma within two minutes) and /aiuto. Restarting after "Ferma tutto", real money, limits and keys stay in the interface. Also added: - the heartbeat call every minute when an address is configured; - the morning summary at 08:00, caught up within four hours; - an optional hourly or evening status; - a Telegram section in Impostazioni: test-before-save, a test button, the queue's state and the last successful heartbeat; - on desktop, the first-run page recommends the heartbeat. Tests run against a fake Telegram server, including the commands through the real server. Co-Authored-By: Claude Opus 5.5 --- src/Anubis.Server/AnubisHost.cs | 36 +- .../Components/Pages/Impostazioni.razor | 110 +++++- .../Components/Pages/PrimoAvvio.razor | 6 +- src/Anubis.Server/Endpoints.cs | 21 +- src/Anubis.Server/Forms.cs | 109 +++++- src/Anubis.Server/ServerOptions.cs | 3 + src/Anubis.Server/TelegramDesk.cs | 176 +++++++++ src/Anubis.Server/TelegramServices.cs | 159 ++++++++ src/Anubis/Core/Settings.cs | 5 +- src/Anubis/Notifications/Notifications.cs | 133 +++++++ src/Anubis/Notifications/TelegramBot.cs | 258 +++++++++++++ src/Anubis/Notifications/TelegramClient.cs | 39 ++ src/Anubis/Trading/Diary.cs | 5 +- src/Anubis/Trading/OrderManager.cs | 7 +- tests/Anubis.Tests/ServerHarness.cs | 3 +- tests/Anubis.Tests/TelegramTests.cs | 363 ++++++++++++++++++ 16 files changed, 1416 insertions(+), 17 deletions(-) create mode 100644 src/Anubis.Server/TelegramDesk.cs create mode 100644 src/Anubis.Server/TelegramServices.cs create mode 100644 src/Anubis/Notifications/Notifications.cs create mode 100644 src/Anubis/Notifications/TelegramBot.cs create mode 100644 tests/Anubis.Tests/TelegramTests.cs diff --git a/src/Anubis.Server/AnubisHost.cs b/src/Anubis.Server/AnubisHost.cs index 88144f8..703aaaa 100644 --- a/src/Anubis.Server/AnubisHost.cs +++ b/src/Anubis.Server/AnubisHost.cs @@ -39,7 +39,7 @@ internal sealed record HostChanged(HostMode Mode); /// Everything that needs the database, built once it is reachable and the installation checks out. internal sealed record AppServices(Database Db, SettingsStore Settings, SecretStore Secrets, AccessStore Access, Backups Backups, Scheduler Scheduler, - MarketDataService? MarketData = null, TradingService? Trading = null, Laboratory? Lab = null); + MarketDataService? MarketData = null, TradingService? Trading = null, Laboratory? Lab = null, TelegramServices? Telegram = null); /// /// The startup state machine of the server (SPEC 15.1, 15.6): reads the startup configuration, opens the configured @@ -67,6 +67,7 @@ internal sealed partial class AnubisHost( private CancellationTokenSource? _schedulerStop; private MarketDataService? _market; private TradingService? _trading; + private TelegramServices? _telegram; private Laboratory? _lab; private volatile HostStatus _status = new(HostMode.Starting, null, null, clock.UtcNow, 0); private volatile AppServices? _services; @@ -80,6 +81,8 @@ internal sealed partial class AnubisHost( public HostStatus Status => _status; + public IClock Clock => clock; + /// The running services; null until the first successful start. public AppServices? Services => _status.Mode == HostMode.Ready ? _services : null; @@ -333,7 +336,11 @@ internal sealed partial class AnubisHost( // The laboratory computes on its own thread and reads only local data; the demo shows appendix F and runs none. _lab = options.Demo ? null : new Laboratory(_db, clock, Config.Data.Research, logger); - _services = new AppServices(_db, settings, secrets, access, backups, scheduler, _market, _trading, _lab); + // Telegram and the sign of life (SPEC 14): not in the demo, and in tests only with their fake network. + _telegram = options.Demo || (overrides is not null && overrides.TelegramHttp is null) + ? null + : new TelegramServices(this, _db, clock, settings, secrets, Config.HeartbeatUrl, overrides?.TelegramHttp, logger); + _services = new AppServices(_db, settings, secrets, access, backups, scheduler, _market, _trading, _lab, _telegram); // Before the scheduler writes its first run: how long the bot was away, and which runs it missed (SPEC 5.6). var lastDues = new Dictionary(StringComparer.Ordinal); @@ -480,7 +487,7 @@ internal sealed partial class AnubisHost( var backup = new ScheduledJob("backup", "Salvataggio del database", Schedule.Daily(new TimeOnly(3, 30), Config.TimeZone), async ct => await backups.TakeAsync(_db!, "notturno", ct).ConfigureAwait(false)) { MaxLateness = TimeSpan.FromHours(2), CatchUpWithin = TimeSpan.FromDays(3650) }; - foreach (var job in new[] { backup }.Concat(_market?.Jobs() ?? []).Concat(_trading?.Jobs() ?? [])) + foreach (var job in new[] { backup }.Concat(_market?.Jobs() ?? []).Concat(_trading?.Jobs() ?? []).Concat(_telegram?.Jobs() ?? [])) { scheduler.Add(job, lastDues.TryGetValue(job.Name, out var due) ? due : null); } @@ -490,6 +497,7 @@ internal sealed partial class AnubisHost( var market = _market; var trading = _trading; var lab = _lab; + var telegram = _telegram; _schedulerLoop = Task.Run(async () => { using var runs = bus.Subscribe(); @@ -497,6 +505,7 @@ internal sealed partial class AnubisHost( var collecting = market is null ? Task.CompletedTask : RunMarketDataAsync(market, token); var dealing = trading is null ? Task.CompletedTask : RunTradingAsync(trading, token); var testing = lab is null ? Task.CompletedTask : RunLabAsync(lab, token); + var writing = telegram is null ? Task.CompletedTask : RunTelegramAsync(telegram, token); try { await scheduler.RunAsync(token).ConfigureAwait(false); @@ -508,6 +517,7 @@ internal sealed partial class AnubisHost( await collecting.ConfigureAwait(false); await dealing.ConfigureAwait(false); await testing.ConfigureAwait(false); + await writing.ConfigureAwait(false); await recorder.ConfigureAwait(false); }, CancellationToken.None); } @@ -542,6 +552,21 @@ internal sealed partial class AnubisHost( } } + private async Task RunTelegramAsync(TelegramServices telegram, CancellationToken cancellationToken) + { + try + { + await telegram.RunAsync(cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + } + catch (Exception ex) + { + LogTelegramFailed(logger, ex); + } + } + private async Task RunTradingAsync(TradingService trading, CancellationToken cancellationToken) { try @@ -621,6 +646,8 @@ internal sealed partial class AnubisHost( _trading = null; _lab?.Dispose(); _lab = null; + _telegram?.Dispose(); + _telegram = null; } // Values of the startup configuration that also exist as settings are read-only in the interface (SPEC 13.5). @@ -673,6 +700,9 @@ internal sealed partial class AnubisHost( [LoggerMessage(Level = LogLevel.Error, Message = "Market data stopped")] private static partial void LogMarketDataFailed(ILogger logger, Exception exception); + [LoggerMessage(Level = LogLevel.Error, Message = "Telegram stopped")] + private static partial void LogTelegramFailed(ILogger logger, Exception exception); + [LoggerMessage(Level = LogLevel.Error, Message = "Laboratory stopped")] private static partial void LogLabFailed(ILogger logger, Exception exception); diff --git a/src/Anubis.Server/Components/Pages/Impostazioni.razor b/src/Anubis.Server/Components/Pages/Impostazioni.razor index 55c1aaa..1b7b094 100644 --- a/src/Anubis.Server/Components/Pages/Impostazioni.razor +++ b/src/Anubis.Server/Components/Pages/Impostazioni.razor @@ -23,6 +23,11 @@ "capitale" => "Capitale affidato aggiornato e diviso tra le strategie.", "limiti" => "Limiti di rischio salvati.", "rischio" => "Impostazione del rischio salvata.", + "telegram" => "Telegram funziona: ti ho mandato un messaggio di prova e ho salvato token e chat.", + "telegram-prova" => "Messaggio di prova partito: controlla il telefono.", + "telegram-tolto" => "Telegram tolto: non ti scrivo più finché non lo rimetti.", + "segnale" => "Segnale di vita salvato: la prima chiamata è andata bene, da adesso lo chiamo ogni minuto.", + "segnale-tolto" => "Segnale di vita tolto.", _ => "Fatto.", })

@@ -33,7 +38,7 @@ }
@@ -186,6 +191,93 @@ }
+
+

Telegram e segnale di vita

+

Su Telegram ti scrivo il riepilogo del mattino, ogni acquisto e vendita con il risultato, gli avvisi di rischio, i blocchi e gli errori. Dalla stessa chat accetto /stato, /posizioni, /oggi, /pausa, /riprendi, /ferma (con conferma) e /aiuto; da altre chat nessun comando. Soldi veri, limiti e chiavi non si cambiano da Telegram.

+
+
Token del bot
@KeyState(_telegramToken)
+
Chat
@KeyState(_telegramChat)
+
Ultimo messaggio partito
@(_queue?.LastSentAt is { } sent ? Format.ShortDate(sent, Shell.Now, Shell.Zone) : "Nessuno")
+ @if (_queue is { } q && (q.Pending > 0 || q.Retrying > 0 || q.GaveUp > 0)) + { +
In attesa
@q.Pending in coda@(q.Retrying > 0 ? $", {q.Retrying} da ritentare" : "")@(q.GaveUp > 0 ? $", {q.GaveUp} non partiti" : "")
+ } + @if (_queue?.LastError is { } lastError) + { +
Ultimo errore
@lastError
+ } +
+ @if (Shell.IsDemo) + { +

Nella modalità dimostrativa Telegram non si usa.

+ } + else if (_telegramToken.FromEnvironment || _telegramChat.FromEnvironment) + { +

Token e chat arrivano dalle variabili d'ambiente: si cambiano nella configurazione del container.

+ } + else + { +
+ + + + + + + +

Prima di salvarli mando un messaggio di prova: se non parte, non salvo nulla. Il token non lo rimostro mai.

+ } + @if (!Shell.IsDemo && _telegramToken.IsSet && _telegramChat.IsSet) + { +
+ @if (!_telegramToken.FromEnvironment && !_telegramChat.FromEnvironment) + { +
+ } + } + +

Stato periodico

+
+ + + + + + + +

Segnale di vita

+

Facoltativo. Se metti l'indirizzo di un servizio di controllo esterno (per esempio healthchecks.io), lo chiamo ogni minuto. Quando le chiamate si fermano è quel servizio ad avvisarti: è l'unico modo per sapere che il bot è spento quando è spento.

+
+
Indirizzo
@(Host.Services!.Telegram?.ConfiguredHeartbeat is not null ? "Dalla configurazione d'avvio (ANUBIS_HEARTBEAT_URL)" : KeyState(_heartbeat))
+ @if (Host.Services.Telegram is { } tg) + { +
Ultima chiamata riuscita
@(tg.Heartbeat.LastOk is { } beat ? Format.ShortDate(beat, Shell.Now, Shell.Zone) : "Nessuna da quando il bot è partito")
+ @if (tg.Heartbeat.LastError is { } beatError) + { +
Ultimo errore
@beatError
+ } + } +
+ @if (!Shell.IsDemo && Host.Services.Telegram is { ConfiguredHeartbeat: null }) + { +
+ + + + + + @if (_heartbeat.IsSet) + { +
+ } + } +
+

Dati

@@ -365,6 +457,11 @@ private List _history = []; private IReadOnlyList _backups = []; private bool _hasSecondFactor; + private SecretStatus _telegramToken = new(Anubis.Notifications.TelegramSettings.TokenSecret, false, false, null); + private SecretStatus _telegramChat = new(Anubis.Notifications.TelegramSettings.ChatSecret, false, false, null); + private SecretStatus _heartbeat = new(TelegramServices.HeartbeatSecret, false, false, null); + private SettingValue _telegramStatus = new(SettingsStore.TelegramStatus.Key, "never", false, null); + private Anubis.Notifications.NotificationSummary? _queue; private string? _draft; private string? _draftUri; @@ -397,6 +494,11 @@ _anyLive = await (services.Trading?.Stages ?? new StageBook(services.Db, Clock, TradingConsent.None, (_, _, _) => Task.FromResult(false))).AnyLiveAsync(null, ct); _backups = services.Backups.List(); + _telegramToken = await services.Secrets.StatusAsync(Anubis.Notifications.TelegramSettings.TokenSecret, ct); + _telegramChat = await services.Secrets.StatusAsync(Anubis.Notifications.TelegramSettings.ChatSecret, ct); + _heartbeat = await services.Secrets.StatusAsync(TelegramServices.HeartbeatSecret, ct); + _telegramStatus = await services.Settings.GetAsync(SettingsStore.TelegramStatus.Key, ct); + _queue = services.Telegram is { } telegram ? await telegram.Sender.SummaryAsync(ct) : null; var ledger = new Ledger(services.Db, Clock); var capital = new Capital(services.Db, Clock, ledger, new FxStore(services.Db, Clock)); var reconciler = new Reconciler(services.Db, Clock, ledger); @@ -445,6 +547,12 @@ "frase-rischio" => $"Una strategia usa soldi veri: per aggiungere rischio scrivi la frase «{StageBook.RaisePhrase}». Non ho cambiato nulla.", "password-rischio" => "Password o codice non corretti. Dopo cinque tentativi sbagliati devi aspettare 15 minuti. Non ho cambiato nulla.", "retrocessione-rischio" => "Una strategia con soldi veri ha una condizione di retrocessione in corso: finché dura non si aggiunge rischio. Non ho cambiato nulla.", + "telegram-rifiutato" => "Telegram non ha accettato token o chat, o non ha risposto: il messaggio di prova non è partito e non ho salvato nulla. Controlla il token di @BotFather e il numero della chat.", + "telegram-prova" => "Il messaggio di prova non è partito: controlla token e chat, o riprova tra poco.", + "telegram-vuoto" => "Servono il token del bot e il numero della chat.", + "telegram-ambiente" => "Token e chat arrivano dalle variabili d'ambiente: si cambiano nella configurazione del container.", + "segnale" => "L'indirizzo non va bene: serve https:// (http solo nella rete di casa).", + "segnale-fallito" => "Il servizio di controllo non ha risposto bene alla prova: non ho salvato l'indirizzo.", "scenari" => "Gli scenari non sono validi: una riga ciascuno, con descrizione e tre percentuali separate da punto e virgola.", _ => PasswordMessages.For(Errore), diff --git a/src/Anubis.Server/Components/Pages/PrimoAvvio.razor b/src/Anubis.Server/Components/Pages/PrimoAvvio.razor index 7e94b7a..ab05f99 100644 --- a/src/Anubis.Server/Components/Pages/PrimoAvvio.razor +++ b/src/Anubis.Server/Components/Pages/PrimoAvvio.razor @@ -12,7 +12,11 @@ } else { -

Due passi: dove tenere i dati e la password per entrare. Conti, capitale e Telegram si aggiungono dopo, dalle Impostazioni.

+

Due passi: dove tenere i dati e la password per entrare. Conti, capitale, Telegram e segnale di vita si aggiungono dopo, dalle Impostazioni: Telegram ha un pulsante che manda un messaggio di prova.

+ @if (Host.Config.Platform == Anubis.Platform.PlatformKind.Desktop) + { +

Su un computer di casa ti consiglio il segnale di vita (Impostazioni, sezione Telegram): un servizio esterno che ti avvisa quando il bot smette di chiamarlo. È l'unico modo per sapere che il bot è spento quando il computer è spento.

+ } @if (Message is { } message) { diff --git a/src/Anubis.Server/Endpoints.cs b/src/Anubis.Server/Endpoints.cs index 6d32a75..f880161 100644 --- a/src/Anubis.Server/Endpoints.cs +++ b/src/Anubis.Server/Endpoints.cs @@ -195,7 +195,7 @@ internal static partial class Endpoints api.MapPost("/bot/{command}", async (string command, AnubisHost host, HttpContext context, CancellationToken ct) => { - var (ok, message) = await BotCommandAsync(host, command, context, ct).ConfigureAwait(false); + var (ok, message) = await BotCommandAsync(host, command, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false); return ok ? Results.Json(new { state = message }, _json) : Error(StatusCodes.Status409Conflict, "comando_non_ammesso", message); }); @@ -255,7 +255,7 @@ internal static partial class Endpoints /// Pause blocks new entries and keeps stops and exits; "Ferma tutto" is the switch of SPEC 9.3 (its full effect /// arrives with the engine). Resume works only from a pause, never after "Ferma tutto" (SPEC 14). ///
- internal static async Task<(bool Ok, string Message)> BotCommandAsync(AnubisHost host, string command, HttpContext context, CancellationToken ct) + internal static async Task<(bool Ok, string Message)> BotCommandAsync(AnubisHost host, string command, string by, CancellationToken ct) { var settings = host.Services!.Settings; var current = (await settings.GetAsync(SettingsStore.BotState.Key, ct).ConfigureAwait(false)).Value; @@ -280,7 +280,6 @@ internal static partial class Endpoints : "Comando non ammesso nello stato attuale del bot."); } - var by = context.User.Identity?.Name ?? "utente"; if (host.Services.Trading is { Risk: { } risk } trading) { // The switch of SPEC 9.3 goes through the risk engine: it cancels the orders under way and keeps the stops. @@ -297,6 +296,7 @@ internal static partial class Endpoints try { await risk.RestartAsync(by, ct).ConfigureAwait(false); + await NotifyBotAsync(host, "bot_restarted", $"Il bot è ripartito dopo «Ferma tutto» (da {by}).", ct).ConfigureAwait(false); return (true, target); } catch (InvalidOperationException ex) @@ -307,9 +307,24 @@ internal static partial class Endpoints } await settings.SetAsync(SettingsStore.BotState.Key, target, by, ct).ConfigureAwait(false); + if (target != current) + { + // Blocks and unblocks reach the phone (SPEC 14), whoever gave the command. + await NotifyBotAsync(host, "bot_" + target, target switch + { + "paused" => $"Bot in pausa (da {by}): niente nuovi acquisti, stop e uscite proseguono.", + "active" => $"Bot ripartito dalla pausa (da {by}).", + "stopped" => $"«Ferma tutto» (da {by}): niente nuove posizioni, gli stop restano. Si riparte solo dall'interfaccia.", + _ => $"Stato del bot: {target} (da {by}).", + }, ct).ConfigureAwait(false); + } + return (true, target); } + private static Task NotifyBotAsync(AnubisHost host, string code, string message, CancellationToken ct) => + host.Services!.Db.WriteAsync(s => Anubis.Trading.Diary.NotifyAsync(s, host.Clock, code, message, ct), ct); + // Live status (SPEC 13.4): one message on connect, one at every change and a heartbeat every few seconds, so the // page can tell how old its data are and warn when the link drops. private static async Task StatusSocketAsync(HttpContext context, AnubisHost host, ShellData shell, EventBus bus) diff --git a/src/Anubis.Server/Forms.cs b/src/Anubis.Server/Forms.cs index d54feb9..1da97e2 100644 --- a/src/Anubis.Server/Forms.cs +++ b/src/Anubis.Server/Forms.cs @@ -34,6 +34,11 @@ internal static partial class Forms signed.MapPost("/chiavi/{broker}", SaveKeysAsync); signed.MapPost("/chiavi/{broker}/togli", RemoveKeysAsync); signed.MapPost("/capitale/{broker}", SetCapitalAsync); + signed.MapPost("/telegram", SaveTelegramAsync); + signed.MapPost("/telegram/prova", TestTelegramAsync); + signed.MapPost("/telegram/togli", RemoveTelegramAsync); + signed.MapPost("/segnale-di-vita", SaveHeartbeatAsync); + signed.MapPost("/segnale-di-vita/togli", RemoveHeartbeatAsync); signed.MapPost("/laboratorio", PlanTrialAsync); signed.MapPost("/strategie/{strategy}/{choice}", StrategyStageAsync); signed.MapPost("/rischio/limiti", SetLimitsAsync); @@ -159,7 +164,7 @@ internal static partial class Forms private static async Task SetSettingAsync(string key, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) { var back = Back(form, "/impostazioni"); - if (key != SettingsStore.Theme.Key && key != SettingsStore.Currency.Key && key != SettingsStore.CentralBankMeetings.Key) + if (key != SettingsStore.Theme.Key && key != SettingsStore.Currency.Key && key != SettingsStore.CentralBankMeetings.Key && key != SettingsStore.TelegramStatus.Key) { return Results.Redirect(With(back, "errore", "impostazione")); } @@ -176,7 +181,7 @@ internal static partial class Forms private static async Task BotAsync(string command, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) { var back = Back(form, "/"); - var (ok, message) = await Endpoints.BotCommandAsync(host, command, context, ct).ConfigureAwait(false); + var (ok, message) = await Endpoints.BotCommandAsync(host, command, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false); return Results.Redirect(ok ? back : With(back, "errore", message.Contains("STOP", StringComparison.Ordinal) ? "file-stop" : "bot")); } @@ -274,6 +279,106 @@ internal static partial class Forms return Results.Redirect(back + "?ok=chiavi#conti"); } + /// + /// The bot's Telegram (SPEC 14): a test message first, sent at once; token and chat are saved only when it left. + /// + private static async Task SaveTelegramAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) + { + const string back = "/impostazioni"; + if (host.IsDemo || host.Services is not { Telegram: { } telegram } services) + { + return Results.Redirect(back + "?errore=motore#telegram"); + } + + if ((await services.Secrets.StatusAsync(Anubis.Notifications.TelegramSettings.TokenSecret, ct).ConfigureAwait(false)).FromEnvironment + || (await services.Secrets.StatusAsync(Anubis.Notifications.TelegramSettings.ChatSecret, ct).ConfigureAwait(false)).FromEnvironment) + { + return Results.Redirect(back + "?errore=telegram-ambiente#telegram"); + } + + var token = form["token"].ToString().Trim(); + var chat = form["chat"].ToString().Trim(); + if (token.Length is 0 or > 200 || chat.Length is 0 or > 40) + { + return Results.Redirect(back + "?errore=telegram-vuoto#telegram"); + } + + if (await telegram.TestAsync(new Anubis.Notifications.TelegramSettings(token, chat), ct).ConfigureAwait(false) is not null) + { + return Results.Redirect(back + "?errore=telegram-rifiutato#telegram"); + } + + var who = context.User.Identity?.Name ?? "utente"; + await services.Secrets.SetAsync(Anubis.Notifications.TelegramSettings.TokenSecret, token, who, ct).ConfigureAwait(false); + await services.Secrets.SetAsync(Anubis.Notifications.TelegramSettings.ChatSecret, chat, who, ct).ConfigureAwait(false); + return Results.Redirect(back + "?ok=telegram#telegram"); + } + + // The form is bound even when unused: binding it is what makes the antiforgery check run on the route. + private static async Task TestTelegramAsync(IFormCollection form, AnubisHost host, CancellationToken ct) + { + const string back = "/impostazioni"; + if (host.IsDemo || host.Services is not { Telegram: { } telegram } + || await telegram.ReadAsync(ct).ConfigureAwait(false) is not { } settings) + { + return Results.Redirect(back + "?errore=telegram-vuoto#telegram"); + } + + return Results.Redirect(await telegram.TestAsync(settings, ct).ConfigureAwait(false) is null ? back + "?ok=telegram-prova#telegram" : back + "?errore=telegram-prova#telegram"); + } + + private static async Task RemoveTelegramAsync(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#telegram"); + } + + var who = context.User.Identity?.Name ?? "utente"; + await services.Secrets.RemoveAsync(Anubis.Notifications.TelegramSettings.TokenSecret, who, ct).ConfigureAwait(false); + await services.Secrets.RemoveAsync(Anubis.Notifications.TelegramSettings.ChatSecret, who, ct).ConfigureAwait(false); + return Results.Redirect(back + "?ok=telegram-tolto#telegram"); + } + + /// The address of the checking service (SPEC 14): called once as a test, saved encrypted only when it answered. + private static async Task SaveHeartbeatAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) + { + const string back = "/impostazioni"; + if (host.IsDemo || host.Services is not { Telegram: { ConfiguredHeartbeat: null } telegram } services) + { + return Results.Redirect(back + "?errore=motore#telegram"); + } + + var address = form["indirizzo"].ToString().Trim(); + if (address.Length is 0 or > 500 || Anubis.Notifications.Heartbeat.Check(address) is not null) + { + return Results.Redirect(back + "?errore=segnale#telegram"); + } + + var probe = new Anubis.Notifications.Heartbeat(telegram.Http, host.Clock, _ => Task.FromResult(new Uri(address)), Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance); + if (!await probe.BeatAsync(ct).ConfigureAwait(false)) + { + return Results.Redirect(back + "?errore=segnale-fallito#telegram"); + } + + await services.Secrets.SetAsync(TelegramServices.HeartbeatSecret, address, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false); + await telegram.Heartbeat.BeatAsync(ct).ConfigureAwait(false); + return Results.Redirect(back + "?ok=segnale#telegram"); + } + + private static async Task RemoveHeartbeatAsync(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#telegram"); + } + + await services.Secrets.RemoveAsync(TelegramServices.HeartbeatSecret, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false); + return Results.Redirect(back + "?ok=segnale-tolto#telegram"); + } + private static async Task RemoveKeysAsync(string broker, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) { const string back = "/impostazioni"; diff --git a/src/Anubis.Server/ServerOptions.cs b/src/Anubis.Server/ServerOptions.cs index 668fc75..a7f3473 100644 --- a/src/Anubis.Server/ServerOptions.cs +++ b/src/Anubis.Server/ServerOptions.cs @@ -76,6 +76,9 @@ internal sealed record ServerOverrides public Func? MarketSockets { get; init; } + /// Answers the Telegram calls and the sign of life instead of the network; tests without it have no Telegram. + public HttpMessageHandler? TelegramHttp { get; init; } + /// True starts the accounts and the order managers in a test; off by default in tests. public bool? Trading { get; init; } } diff --git a/src/Anubis.Server/TelegramDesk.cs b/src/Anubis.Server/TelegramDesk.cs new file mode 100644 index 0000000..e223d08 --- /dev/null +++ b/src/Anubis.Server/TelegramDesk.cs @@ -0,0 +1,176 @@ +using System.Text; +using Anubis.Core; +using Anubis.Data; +using Anubis.Notifications; +using Anubis.Trading; + +namespace Anubis.Server; + +/// +/// The answers of the Telegram commands and the messages the bot writes by itself (SPEC 14), from the same data as +/// the Panoramica: one world, the simulated one until there is a real account. +/// +internal sealed class TelegramDesk(AnubisHost host) : ITelegramDesk +{ + private const string By = "Telegram"; + + private AppServices Services => host.Services ?? throw new InvalidOperationException("Il bot sta ancora partendo: riprova tra poco."); + + private TimeZoneInfo Zone => host.Config.TimeZone; + + public async Task StatusAsync(CancellationToken cancellationToken) + { + var services = Services; + var now = host.Clock.UtcNow; + var bot = (await services.Settings.GetAsync(SettingsStore.BotState.Key, cancellationToken).ConfigureAwait(false)).Value; + var overview = await Overview.LoadAsync(services, "oggi", now, Zone, cancellationToken).ConfigureAwait(false); + var text = new StringBuilder(); + text.Append(bot switch { "paused" => "Bot in pausa", "stopped" => "Bot fermo («Ferma tutto»)", _ => "Bot attivo" }) + .Append(" · solo denaro finto").AppendLine("."); + if (overview.HasData) + { + var today = overview.Cells[0]; + text.Append("Patrimonio ").Append(Format.Money(overview.Points[^1].Equity)).Append(", oggi ").Append(Format.Money(today.Amount, withSign: true)) + .Append(" (").Append(Format.Percent(today.Percent, 2, withSign: true)).AppendLine(")."); + } + + text.Append(Positions(overview.Positions, overview.PositionsWithoutStop)); + if (overview.OpenOrders > 0) + { + text.Append(' ').Append(overview.OpenOrders == 1 ? "1 ordine in corso." : $"{overview.OpenOrders} ordini in corso."); + } + + text.AppendLine(); + if (overview.Next.Count > 0 && overview.Next[0] is var next) + { + text.Append("Prossima mossa: ").Append(next.Time).Append(' ').Append(next.Text).AppendLine("."); + } + + return text.ToString().TrimEnd(); + } + + public async Task PositionsAsync(CancellationToken cancellationToken) + { + var services = Services; + var rows = await services.Db.ReadAsync(s => s.QueryAsync( + "SELECT a.name, a.environment, a.base_currency, i.symbol, p.strategy, p.quantity, p.average_price, p.last_price, p.stop_price FROM positions p " + + "JOIN accounts a ON a.id = p.account_id JOIN instruments i ON i.id = p.instrument_id WHERE p.quantity > 0 ORDER BY a.name, i.symbol", + r => (Account: r.Text("name"), Environment: r.Text("environment"), Currency: r.Text("base_currency"), Symbol: r.Text("symbol"), Strategy: r.Text("strategy"), + Quantity: r.Money("quantity"), Average: r.Money("average_price"), Last: r.MoneyOrNull("last_price"), Stop: r.MoneyOrNull("stop_price"))), cancellationToken) + .ConfigureAwait(false); + var world = rows.Any(r => TradingEnvironments.World(r.Environment) == Worlds.Real) ? Worlds.Real : Worlds.Simulated; + rows = [.. rows.Where(r => TradingEnvironments.World(r.Environment) == world)]; + if (rows.Count == 0) + { + return "Nessuna posizione aperta."; + } + + var text = new StringBuilder(); + foreach (var r in rows) + { + var last = r.Last ?? r.Average; + var gain = (last - r.Average) * r.Quantity; + text.Append(DiaryText.Shown(r.Symbol)).Append(": ").Append(Format.Quantity(r.Quantity)).Append(" a ").Append(Format.Money(r.Average, r.Currency)) + .Append(", ora ").Append(Format.Money(last, r.Currency)).Append(" (").Append(Format.Money(gain, r.Currency, withSign: true)).Append("), ") + .Append(r.Stop is { } stop ? "stop a " + Format.Money(stop, r.Currency) : "SENZA STOP") + .Append(" · ").Append(StrategyNames.Label(r.Strategy)).Append(", ").Append(r.Account).AppendLine(); + } + + return text.ToString().TrimEnd(); + } + + public async Task TodayAsync(CancellationToken cancellationToken) + { + var services = Services; + var now = host.Clock.UtcNow; + var local = TimeZoneInfo.ConvertTime(now, Zone); + var midnight = new DateTimeOffset(local.Date, local.Offset).ToUniversalTime(); + var entries = await services.Db.ReadAsync(s => s.QueryAsync( + "SELECT occurred_at, message FROM journal WHERE kind = @k AND occurred_at >= @from ORDER BY occurred_at", + r => (At: r.Moment("occurred_at"), Text: r.Text("message")), ("k", DiaryKinds.Orders), ("from", midnight)), cancellationToken).ConfigureAwait(false); + var overview = await Overview.LoadAsync(services, "oggi", now, Zone, cancellationToken).ConfigureAwait(false); + var text = new StringBuilder(); + if (overview.HasData) + { + text.Append("Oggi ").Append(Format.Money(overview.Cells[0].Amount, withSign: true)).Append(" (").Append(Format.Percent(overview.Cells[0].Percent, 2, withSign: true)) + .AppendLine(")."); + } + + if (entries.Count == 0) + { + text.Append("Nessun ordine oggi."); + return text.ToString(); + } + + const int Shown = 15; + foreach (var e in entries.TakeLast(Shown)) + { + text.Append(TimeZoneInfo.ConvertTime(e.At, Zone).ToString("HH:mm", System.Globalization.CultureInfo.InvariantCulture)).Append(' ').AppendLine(e.Text); + } + + if (entries.Count > Shown) + { + text.Append("…e altre ").Append(entries.Count - Shown).Append(" righe nel Diario."); + } + + return text.ToString().TrimEnd(); + } + + public Task PauseAsync(CancellationToken cancellationToken) => + CommandAsync("pausa", "In pausa: niente nuovi acquisti; stop e uscite proseguono. /riprendi per ripartire.", cancellationToken); + + public Task ResumeAsync(CancellationToken cancellationToken) => CommandAsync("riprendi", "Ripartito dalla pausa.", cancellationToken); + + public Task StopAllAsync(CancellationToken cancellationToken) => + CommandAsync("ferma", "«Ferma tutto» fatto: ordini in attesa annullati, niente nuove posizioni, gli stop restano. Si riparte solo dall'interfaccia, pagina Rischio.", + cancellationToken); + + /// The morning summary (SPEC 14): the night, the positions, what comes today. + public async Task MorningAsync(CancellationToken cancellationToken) + { + var services = Services; + var now = host.Clock.UtcNow; + var overview = await Overview.LoadAsync(services, "oggi", now, Zone, cancellationToken).ConfigureAwait(false); + var text = new StringBuilder("Buongiorno.").AppendLine(); + if (overview.HasData) + { + text.Append("Patrimonio ").Append(Format.Money(overview.Points[^1].Equity)).Append("; ultimi 7 giorni ").Append(Format.Money(overview.Cells[1].Amount, withSign: true)) + .AppendLine("."); + } + + text.AppendLine(Positions(overview.Positions, overview.PositionsWithoutStop)); + var local = TimeZoneInfo.ConvertTime(now, Zone).Date; + var today = overview.Next.Count == 0 ? [] : services.Scheduler.Upcoming(20) + .Where(u => TimeZoneInfo.ConvertTime(u.DueUtc, Zone).Date == local) + .Select(u => TimeZoneInfo.ConvertTime(u.DueUtc, Zone).ToString("HH:mm", System.Globalization.CultureInfo.InvariantCulture) + " " + u.Description) + .ToList(); + if (today.Count > 0) + { + text.AppendLine("Oggi:"); + foreach (var line in today) + { + text.AppendLine(line); + } + } + + return text.ToString().TrimEnd(); + } + + private static string Positions(int count, int withoutStop) => count switch + { + 0 => "Nessuna posizione aperta.", + 1 => withoutStop == 0 ? "1 posizione, con il suo stop." : "1 posizione, SENZA STOP.", + _ => withoutStop == 0 ? $"{count} posizioni, tutte con lo stop." : $"{count} posizioni, {withoutStop} SENZA STOP.", + }; + + private async Task CommandAsync(string command, string done, CancellationToken cancellationToken) + { + if (host.IsDemo) + { + return "Nella modalità dimostrativa il bot non si comanda."; + } + + var (ok, message) = await Endpoints.BotCommandAsync(host, command, By, cancellationToken).ConfigureAwait(false); + return ok ? done : message; + } +} diff --git a/src/Anubis.Server/TelegramServices.cs b/src/Anubis.Server/TelegramServices.cs new file mode 100644 index 0000000..51b11f1 --- /dev/null +++ b/src/Anubis.Server/TelegramServices.cs @@ -0,0 +1,159 @@ +using Anubis.Core; +using Anubis.Db; +using Anubis.Notifications; + +namespace Anubis.Server; + +/// +/// Telegram and the sign of life (SPEC 14): the queue sent every few seconds, the commands read as they arrive, the +/// call to the checking service every minute, the morning summary and the optional periodic status. +/// +internal sealed class TelegramServices : IDisposable +{ + /// The secret that keeps the address of the checking service when the configuration does not give one. + public const string HeartbeatSecret = "HEARTBEAT_URL"; + + public static readonly TimeOnly MorningAt = new(8, 0); + public static readonly TimeOnly EveningAt = new(20, 0); + + private readonly HttpClient _http; + private readonly Database _db; + private readonly IClock _clock; + private readonly SettingsStore _settings; + private readonly SecretStore _secrets; + private readonly TimeZoneInfo _zone; + + public TelegramServices(AnubisHost host, Database db, IClock clock, SettingsStore settings, SecretStore secrets, string? configuredHeartbeat, HttpMessageHandler? handler, + Microsoft.Extensions.Logging.ILogger logger) + { + ArgumentNullException.ThrowIfNull(host); + _db = db; + _clock = clock; + _settings = settings; + _secrets = secrets; + _zone = host.Config.TimeZone; + _http = handler is null ? new HttpClient() : new HttpClient(handler, disposeHandler: false); + + // Longer than the wait of the commands' long polling. + _http.Timeout = TimeSpan.FromSeconds(60); + Desk = new TelegramDesk(host); + Sender = new NotificationSender(db, clock, ReadAsync, Client); + Bot = new TelegramBot(clock, ReadAsync, Client, new TelegramCommands(Desk, clock), logger); + ConfiguredHeartbeat = configuredHeartbeat; + Heartbeat = new Heartbeat(_http, clock, HeartbeatAddressAsync, logger); + } + + public TelegramDesk Desk { get; } + + public NotificationSender Sender { get; } + + public TelegramBot Bot { get; } + + public Heartbeat Heartbeat { get; } + + /// The address from the startup configuration (ANUBIS_HEARTBEAT_URL): it wins over the one saved here. + public string? ConfiguredHeartbeat { get; } + + /// How often the queue is looked at. + public TimeSpan SendEvery { get; init; } = TimeSpan.FromSeconds(10); + + /// The client of Telegram and of the checking service. + public HttpClient Http => _http; + + public TelegramClient Client(string token) => new(_http, token); + + public Task ReadAsync(CancellationToken cancellationToken) => TelegramSettings.ReadAsync(_secrets, cancellationToken); + + public async Task HeartbeatAddressAsync(CancellationToken cancellationToken) + { + var text = ConfiguredHeartbeat ?? await _secrets.RevealAsync(HeartbeatSecret, cancellationToken).ConfigureAwait(false); + return string.IsNullOrWhiteSpace(text) || Heartbeat.Check(text) is not null ? null : new Uri(text.Trim()); + } + + public IReadOnlyList Jobs() => + [ + new("segnale-di-vita", "Segnale di vita al servizio di controllo", Schedule.Every(TimeSpan.FromMinutes(1)), async ct => await Heartbeat.BeatAsync(ct).ConfigureAwait(false)) + { + MaxLateness = TimeSpan.FromMinutes(2), + }, + + // The summary is still useful a little late; after four hours the day has moved on (SPEC 5.6). + new("riepilogo-mattino", "Riepilogo del mattino su Telegram", Schedule.Daily(MorningAt, _zone), MorningAsync) + { + MaxLateness = TimeSpan.FromHours(4), + CatchUpWithin = TimeSpan.FromHours(4), + }, + new("stato-ogni-ora", "Stato periodico su Telegram, se scelto ogni ora", Schedule.Every(TimeSpan.FromHours(1)), ct => PeriodicAsync("hourly", ct)), + new("stato-ogni-giorno", "Stato periodico su Telegram, se scelto ogni giorno", Schedule.Daily(EveningAt, _zone), ct => PeriodicAsync("daily", ct)), + ]; + + /// Sends the queue and reads the commands until the services stop. + public async Task RunAsync(CancellationToken cancellationToken) + { + var commands = Bot.RunAsync(cancellationToken); + try + { + while (!cancellationToken.IsCancellationRequested) + { + await Sender.SendDueAsync(cancellationToken).ConfigureAwait(false); + await Task.Delay(SendEvery, cancellationToken).ConfigureAwait(false); + } + } + finally + { + try + { + await commands.ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + } + } + } + + /// + /// The test of Impostazioni: a message to the chat, sent at once and not through the queue, so the answer says + /// whether Telegram took it. Null when it went; otherwise the reason, in the user's words. + /// + public async Task TestAsync(TelegramSettings telegram, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(telegram); + try + { + var client = Client(telegram.Token); + var name = await client.GetMeAsync(cancellationToken).ConfigureAwait(false); + await client.SendAsync(telegram.ChatId, $"Anubis: messaggio di prova. Da qui ti scrivo{(name.Length > 0 ? " come @" + name : "")}; scrivi /aiuto per i comandi.", + cancellationToken).ConfigureAwait(false); + return null; + } + catch (TelegramException ex) + { + return ex.Message; + } + } + + public void Dispose() => _http.Dispose(); + + private async Task MorningAsync(CancellationToken cancellationToken) + { + if (await ReadAsync(cancellationToken).ConfigureAwait(false) is null) + { + return; + } + + var text = await Desk.MorningAsync(cancellationToken).ConfigureAwait(false); + await _db.WriteAsync(s => NotificationSender.EnqueueAsync(s, _clock, "morning_summary", text, cancellationToken), cancellationToken).ConfigureAwait(false); + } + + private async Task PeriodicAsync(string every, CancellationToken cancellationToken) + { + if ((await _settings.GetAsync(SettingsStore.TelegramStatus.Key, cancellationToken).ConfigureAwait(false)).Value != every + || await ReadAsync(cancellationToken).ConfigureAwait(false) is null) + { + return; + } + + var text = await Desk.StatusAsync(cancellationToken).ConfigureAwait(false); + await _db.WriteAsync(s => NotificationSender.EnqueueAsync(s, _clock, "periodic_status", text, cancellationToken), cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/Anubis/Core/Settings.cs b/src/Anubis/Core/Settings.cs index 47ddac9..6c9a2cb 100644 --- a/src/Anubis/Core/Settings.cs +++ b/src/Anubis/Core/Settings.cs @@ -41,8 +41,11 @@ public sealed class SettingsStore(Database db, IClock clock, EventBus bus, IRead public static readonly SettingDefinition CentralBankMeetings = new("calendar.central_banks", "Riunioni di Fed e BCE", Data.CentralBanks.DefaultList, Check: Data.CentralBanks.Check); + /// The optional periodic status on Telegram (SPEC 14): never, every hour or every evening. + public static readonly SettingDefinition TelegramStatus = new("telegram.status", "Stato periodico su Telegram", "never", ["never", "hourly", "daily"]); + public static readonly IReadOnlyList All = - [Theme, Currency, BotState, CentralBankMeetings, .. Risk.RiskSettings.All, Risk.Scenarios.Setting]; + [Theme, Currency, BotState, CentralBankMeetings, TelegramStatus, .. Risk.RiskSettings.All, Risk.Scenarios.Setting]; private readonly IReadOnlyDictionary _overrides = overrides ?? new Dictionary(); diff --git a/src/Anubis/Notifications/Notifications.cs b/src/Anubis/Notifications/Notifications.cs new file mode 100644 index 0000000..b6a6364 --- /dev/null +++ b/src/Anubis/Notifications/Notifications.cs @@ -0,0 +1,133 @@ +using Anubis.Core; +using Anubis.Db; + +namespace Anubis.Notifications; + +/// The state of a notification (SPEC 14): never "sent" before Telegram said ok. +public static class NotificationStates +{ + /// In the queue: not tried yet, or Telegram is not configured. + public const string Pending = "pending"; + + public const string Sent = "sent"; + + /// Tried and refused; tried again at next_attempt_at, or never again when that is empty. + public const string Failed = "failed"; +} + +/// The bot's Telegram: the token and the one chat it writes to and takes commands from. +public sealed record TelegramSettings(string Token, string ChatId) +{ + public const string TokenSecret = "TELEGRAM_BOT_TOKEN"; + public const string ChatSecret = "TELEGRAM_CHAT_ID"; + + /// Both secrets, or null while either is missing. + public static async Task ReadAsync(SecretStore secrets, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(secrets); + var token = await secrets.RevealAsync(TokenSecret, cancellationToken).ConfigureAwait(false); + var chat = await secrets.RevealAsync(ChatSecret, cancellationToken).ConfigureAwait(false); + return string.IsNullOrWhiteSpace(token) || string.IsNullOrWhiteSpace(chat) ? null : new TelegramSettings(token.Trim(), chat.Trim()); + } +} + +/// What Impostazioni shows of the queue: the last message that left, what waits, what failed and why. +public sealed record NotificationSummary(DateTimeOffset? LastSentAt, int Pending, int Retrying, int GaveUp, string? LastError); + +/// +/// The Telegram queue (SPEC 14). Every message is written first, then sent: a refusal or a network failure is +/// recorded and tried again with growing pauses; a message that could not leave within a day is given up, with the +/// reason, rather than arriving late as if it were news. +/// +public sealed class NotificationSender(Database db, IClock clock, Func> settings, Func client) +{ + /// Older than this, a message is no longer worth sending. + public static readonly TimeSpan MaxAge = TimeSpan.FromHours(24); + + public const int MaxAttempts = 8; + + /// At most this many messages per pass: Telegram limits the messages to one chat. + public const int Batch = 20; + + /// Writes a message in the queue, in the same transaction as what it tells. + public static Task EnqueueAsync(DbSession s, IClock clock, string kind, string message, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(s); + ArgumentNullException.ThrowIfNull(clock); + return s.ExecuteAsync( + "INSERT INTO notifications (id, channel, kind, message, status, attempts, created_at) VALUES (@id, 'telegram', @k, @m, @st, 0, @at)", cancellationToken, + ("id", Ids.NewId(clock)), ("k", kind), ("m", message), ("st", NotificationStates.Pending), ("at", clock.UtcNow)); + } + + /// The pause before attempt + 1: 1, 2, 4, 8, 16, 32, then 60 minutes. + public static TimeSpan Pause(int attempts) => TimeSpan.FromMinutes(Math.Min(60, 1 << Math.Clamp(attempts - 1, 0, 6))); + + /// Sends what is due; the answer is how many left. Without Telegram configured everything stays in the queue. + public async Task SendDueAsync(CancellationToken cancellationToken) + { + if (await settings(cancellationToken).ConfigureAwait(false) is not { } telegram) + { + return 0; + } + + var now = clock.UtcNow; + var due = await db.ReadAsync(s => s.QueryAsync( + "SELECT id, message, attempts, created_at FROM notifications WHERE channel = 'telegram' AND (status = @p OR (status = @f AND next_attempt_at IS NOT NULL AND next_attempt_at <= @now)) " + + "ORDER BY created_at, id LIMIT " + Batch.ToString(System.Globalization.CultureInfo.InvariantCulture), + r => (Id: r.Id("id"), Message: r.Text("message"), Attempts: r.IsNull("attempts") ? 0 : (int)r.Number("attempts"), Created: r.Moment("created_at")), + ("p", NotificationStates.Pending), ("f", NotificationStates.Failed), ("now", now)), cancellationToken).ConfigureAwait(false); + var bot = client(telegram.Token); + var sent = 0; + foreach (var item in due) + { + if (now - item.Created > MaxAge) + { + await MarkAsync(item.Id, NotificationStates.Failed, item.Attempts, null, "Non partito entro un giorno: non lo mando più.", cancellationToken).ConfigureAwait(false); + continue; + } + + try + { + await bot.SendAsync(telegram.ChatId, item.Message, cancellationToken).ConfigureAwait(false); + await MarkAsync(item.Id, NotificationStates.Sent, item.Attempts + 1, null, null, cancellationToken).ConfigureAwait(false); + sent++; + } + catch (TelegramException ex) + { + var attempts = item.Attempts + 1; + DateTimeOffset? next = ex.Retryable && attempts < MaxAttempts + ? clock.UtcNow + (ex.RetryAfter is { } wait && wait > Pause(attempts) ? wait : Pause(attempts)) + : null; + await MarkAsync(item.Id, NotificationStates.Failed, attempts, next, ex.Message, cancellationToken).ConfigureAwait(false); + if (ex.Retryable) + { + // Telegram unreachable or asking to slow down: the others wait for the next pass. + break; + } + } + } + + return sent; + } + + public Task SummaryAsync(CancellationToken cancellationToken) => + db.ReadAsync(async s => + { + var last = await s.FirstOrDefaultAsync("SELECT MAX(sent_at) AS at FROM notifications WHERE channel = 'telegram' AND status = @s", + r => r.MomentOrNull("at"), ("s", NotificationStates.Sent)).ConfigureAwait(false); + var pending = await s.CountAsync("SELECT COUNT(*) FROM notifications WHERE channel = 'telegram' AND status = @p", ("p", NotificationStates.Pending)).ConfigureAwait(false); + var retrying = await s.CountAsync("SELECT COUNT(*) FROM notifications WHERE channel = 'telegram' AND status = @f AND next_attempt_at IS NOT NULL", + ("f", NotificationStates.Failed)).ConfigureAwait(false); + var gaveUp = await s.CountAsync("SELECT COUNT(*) FROM notifications WHERE channel = 'telegram' AND status = @f AND next_attempt_at IS NULL", + ("f", NotificationStates.Failed)).ConfigureAwait(false); + var error = await s.FirstOrDefaultAsync( + "SELECT last_error FROM notifications WHERE channel = 'telegram' AND status = @f ORDER BY created_at DESC, id DESC LIMIT 1", + r => r.TextOrNull("last_error"), ("f", NotificationStates.Failed)).ConfigureAwait(false); + return new NotificationSummary(last, (int)pending, (int)retrying, (int)gaveUp, error); + }, cancellationToken); + + private Task MarkAsync(Guid id, string status, int attempts, DateTimeOffset? next, string? error, CancellationToken cancellationToken) => + db.WriteAsync(s => s.ExecuteAsync( + "UPDATE notifications SET status = @s, attempts = @a, next_attempt_at = @n, last_error = @e, sent_at = @sent WHERE id = @id", cancellationToken, + ("s", status), ("a", attempts), ("n", next), ("e", error), ("sent", status == NotificationStates.Sent ? clock.UtcNow : (DateTimeOffset?)null), ("id", id)), cancellationToken); +} diff --git a/src/Anubis/Notifications/TelegramBot.cs b/src/Anubis/Notifications/TelegramBot.cs new file mode 100644 index 0000000..8533aef --- /dev/null +++ b/src/Anubis/Notifications/TelegramBot.cs @@ -0,0 +1,258 @@ +using Anubis.Core; +using Microsoft.Extensions.Logging; + +namespace Anubis.Notifications; + +/// +/// What the Telegram commands read and do (SPEC 14), answered in plain Italian. Nothing here turns on real money, +/// changes a limit or shows a secret: the interface does those, never the phone. +/// +public interface ITelegramDesk +{ + Task StatusAsync(CancellationToken cancellationToken); + + Task PositionsAsync(CancellationToken cancellationToken); + + Task TodayAsync(CancellationToken cancellationToken); + + Task PauseAsync(CancellationToken cancellationToken); + + /// Only from a pause, never after "Ferma tutto" (SPEC 9.3, 14). + Task ResumeAsync(CancellationToken cancellationToken); + + /// "Ferma tutto", already confirmed. + Task StopAllAsync(CancellationToken cancellationToken); +} + +/// The commands of SPEC 14 and the confirmation of /ferma: two minutes to send /conferma. +public sealed class TelegramCommands(ITelegramDesk desk, IClock clock) +{ + public static readonly TimeSpan ConfirmWithin = TimeSpan.FromMinutes(2); + + public const string Help = + "Comandi:\n" + + "/stato – come sta il bot\n" + + "/posizioni – cosa ho in mano, con gli stop\n" + + "/oggi – cosa ho fatto oggi\n" + + "/pausa – niente nuovi acquisti, stop e uscite proseguono\n" + + "/riprendi – riparto dalla pausa\n" + + "/ferma – «Ferma tutto», con conferma\n" + + "/aiuto – questo elenco\n" + + "Soldi veri, limiti e chiavi si cambiano solo dall'interfaccia."; + + private DateTimeOffset? _stopAskedAt; + + /// The answer to one message; null for a message that is not a command. + public async Task AnswerAsync(string text, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(text); + var word = text.Trim().Split((char[])[' ', '\n', '\t'], 2)[0]; + if (!word.StartsWith('/')) + { + return null; + } + + // In a group Telegram adds the bot's name: "/stato@AnubisBot". + var command = word[1..].Split('@')[0].ToLowerInvariant(); + if (command != "conferma") + { + _stopAskedAt = null; + } + + switch (command) + { + case "start" or "aiuto" or "help": + return Help; + case "stato": + return await desk.StatusAsync(cancellationToken).ConfigureAwait(false); + case "posizioni": + return await desk.PositionsAsync(cancellationToken).ConfigureAwait(false); + case "oggi": + return await desk.TodayAsync(cancellationToken).ConfigureAwait(false); + case "pausa": + return await desk.PauseAsync(cancellationToken).ConfigureAwait(false); + case "riprendi": + return await desk.ResumeAsync(cancellationToken).ConfigureAwait(false); + case "ferma": + _stopAskedAt = clock.UtcNow; + return "Vuoi davvero «Ferma tutto»? Annullo gli ordini in attesa e non apro nuove posizioni; gli stop restano. " + + "Da qui non si riparte: si riparte solo dall'interfaccia, pagina Rischio.\nPer confermare scrivi /conferma entro 2 minuti."; + case "conferma": + if (_stopAskedAt is { } asked && clock.UtcNow - asked <= ConfirmWithin) + { + _stopAskedAt = null; + return await desk.StopAllAsync(cancellationToken).ConfigureAwait(false); + } + + _stopAskedAt = null; + return "Non c'è niente da confermare: scrivi prima /ferma."; + default: + return "Non conosco questo comando.\n" + Help; + } + } +} + +/// +/// Reads the messages sent to the bot and answers the commands (SPEC 14). Only the chat of the settings is obeyed; +/// the others get no answer at all. A message older than five minutes, found after a stop of the bot, is not +/// obeyed: a /pausa of yesterday must not pause today. +/// +public sealed partial class TelegramBot(IClock clock, Func> settings, Func client, + TelegramCommands commands, ILogger logger) +{ + public static readonly TimeSpan StaleAfter = TimeSpan.FromMinutes(5); + + /// How long one call waits for a message on Telegram's side. + public int WaitSeconds { get; init; } = 25; + + /// The pause after a failure, or while Telegram is not configured. + public TimeSpan Retry { get; init; } = TimeSpan.FromSeconds(30); + + private long _offset; + + /// One read of the messages; the answer is how many commands were obeyed. + public async Task PollOnceAsync(CancellationToken cancellationToken) + { + if (await settings(cancellationToken).ConfigureAwait(false) is not { } telegram) + { + return -1; + } + + var bot = client(telegram.Token); + var updates = await bot.GetUpdatesAsync(_offset, WaitSeconds, cancellationToken).ConfigureAwait(false); + var obeyed = 0; + foreach (var update in updates) + { + _offset = Math.Max(_offset, update.UpdateId + 1); + if (update.ChatId != telegram.ChatId) + { + LogStranger(logger, update.ChatId ?? "?"); + continue; + } + + if (update.Text is not { } text || update.Date is not { } date || clock.UtcNow - date > StaleAfter) + { + continue; + } + + string? answer; + try + { + answer = await commands.AnswerAsync(text, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + LogCommandFailed(logger, ex); + answer = "Non ci sono riuscito: " + Redactor.Redact(ex.Message); + } + + if (answer is not null) + { + obeyed++; + await bot.SendAsync(telegram.ChatId, answer, cancellationToken).ConfigureAwait(false); + } + } + + return obeyed; + } + + /// The loop: reads, answers, and after a failure waits and tries again. + public async Task RunAsync(CancellationToken cancellationToken) + { + while (!cancellationToken.IsCancellationRequested) + { + TimeSpan? pause = null; + try + { + if (await PollOnceAsync(cancellationToken).ConfigureAwait(false) < 0) + { + pause = Retry; + } + } + catch (TelegramException ex) + { + LogPollFailed(logger, ex.Message); + pause = ex.RetryAfter is { } after && after > Retry ? after : Retry; + } + + if (pause is { } wait) + { + await Task.Delay(wait, cancellationToken).ConfigureAwait(false); + } + } + } + + [LoggerMessage(Level = LogLevel.Warning, Message = "Telegram message from another chat ignored: {Chat}")] + private static partial void LogStranger(ILogger logger, string chat); + + [LoggerMessage(Level = LogLevel.Warning, Message = "Telegram read failed: {Error}")] + private static partial void LogPollFailed(ILogger logger, string error); + + [LoggerMessage(Level = LogLevel.Error, Message = "Telegram command failed")] + private static partial void LogCommandFailed(ILogger logger, Exception ex); +} + +/// +/// The sign of life (SPEC 14): a call to an outside checking service every minute. When the calls stop, that +/// service warns the user: the only way to know the bot is off while it is off. +/// +public sealed partial class Heartbeat(HttpClient http, IClock clock, Func> address, ILogger logger) +{ + public DateTimeOffset? LastOk { get; private set; } + + public string? LastError { get; private set; } + + /// True when the call went through; false when there is no address or it failed. + public async Task BeatAsync(CancellationToken cancellationToken) + { + if (await address(cancellationToken).ConfigureAwait(false) is not { } url) + { + return false; + } + + try + { + using var response = await http.GetAsync(url, cancellationToken).ConfigureAwait(false); + if (response.IsSuccessStatusCode) + { + LastOk = clock.UtcNow; + LastError = null; + return true; + } + + LastError = $"Il servizio ha risposto {(int)response.StatusCode}."; + } + catch (HttpRequestException ex) + { + LastError = "Il servizio non risponde: " + Redactor.Redact(ex.Message); + } + catch (TaskCanceledException) when (!cancellationToken.IsCancellationRequested) + { + LastError = "Il servizio non ha risposto in tempo."; + } + + LogFailed(logger, LastError); + return false; + } + + /// An address the interface accepts: https, or http only on this computer or the local network. + public static string? Check(string value) + { + if (string.IsNullOrWhiteSpace(value)) + { + return null; + } + + if (!Uri.TryCreate(value.Trim(), UriKind.Absolute, out var uri) || uri.Scheme is not ("https" or "http")) + { + return "Serve un indirizzo che inizi con https://."; + } + + return uri.Scheme == "http" && !(uri.IsLoopback || uri.Host.EndsWith(".local", StringComparison.OrdinalIgnoreCase) || System.Net.IPAddress.TryParse(uri.Host, out _)) + ? "Fuori dalla rete di casa serve https://." + : null; + } + + [LoggerMessage(Level = LogLevel.Warning, Message = "Heartbeat failed: {Error}")] + private static partial void LogFailed(ILogger logger, string error); +} diff --git a/src/Anubis/Notifications/TelegramClient.cs b/src/Anubis/Notifications/TelegramClient.cs index 469d859..5635b76 100644 --- a/src/Anubis/Notifications/TelegramClient.cs +++ b/src/Anubis/Notifications/TelegramClient.cs @@ -35,6 +35,9 @@ public sealed class TelegramException : Exception public TimeSpan? RetryAfter { get; } } +/// A message to the bot: who wrote it (the chat), what and when. +public sealed record TelegramUpdate(long UpdateId, string? ChatId, string? Text, DateTimeOffset? Date); + /// /// The Telegram Bot API (SPEC 14): plain text messages to the user's chat. The token is part of the address, so the /// address is never logged; errors carry only Telegram's own description. @@ -43,6 +46,8 @@ public sealed class TelegramClient { public static readonly Uri DefaultBase = new("https://api.telegram.org/"); + private static readonly string[] MessagesOnly = ["message"]; + private readonly HttpClient _http; private readonly string _token; private readonly Uri _base; @@ -70,6 +75,40 @@ public sealed class TelegramClient cancellationToken).ConfigureAwait(false); } + /// + /// The messages sent to the bot after , waiting up to for + /// one (long polling). The next call passes the last update's id plus one, which tells Telegram they were read. + /// + public async Task> GetUpdatesAsync(long offset, int waitSeconds, CancellationToken cancellationToken) + { + using var answer = await CallAsync("getUpdates", new Dictionary { ["offset"] = offset, ["timeout"] = waitSeconds, ["allowed_updates"] = MessagesOnly }, + cancellationToken).ConfigureAwait(false); + var updates = new List(); + foreach (var item in answer.RootElement.GetProperty("result").EnumerateArray()) + { + string? chat = null; + string? text = null; + DateTimeOffset? date = null; + if (item.TryGetProperty("message", out var message)) + { + chat = message.TryGetProperty("chat", out var c) && c.TryGetProperty("id", out var id) ? id.GetRawText().Trim('"') : null; + text = message.TryGetProperty("text", out var t) && t.ValueKind == JsonValueKind.String ? t.GetString() : null; + date = message.TryGetProperty("date", out var d) && d.TryGetInt64(out var seconds) ? DateTimeOffset.FromUnixTimeSeconds(seconds) : null; + } + + updates.Add(new TelegramUpdate(item.GetProperty("update_id").GetInt64(), chat, text, date)); + } + + return updates; + } + + /// The bot's own name: the test of Impostazioni, which proves the token works without writing to anyone. + public async Task GetMeAsync(CancellationToken cancellationToken) + { + using var answer = await CallAsync("getMe", new Dictionary(), cancellationToken).ConfigureAwait(false); + return answer.RootElement.GetProperty("result").TryGetProperty("username", out var name) ? name.GetString() ?? "" : ""; + } + /// One call of the Bot API; the answer's result when Telegram says ok. public async Task CallAsync(string method, object body, CancellationToken cancellationToken) { diff --git a/src/Anubis/Trading/Diary.cs b/src/Anubis/Trading/Diary.cs index 39e9f7c..d812944 100644 --- a/src/Anubis/Trading/Diary.cs +++ b/src/Anubis/Trading/Diary.cs @@ -18,7 +18,7 @@ public static class DiaryKinds /// /// The bot's diary and its notices (SPEC 13.6): short sentences in Italian, in the first person. A notice is also -/// queued for Telegram; the sender arrives with Phase 6, the queue is kept from now. +/// queued for Telegram (SPEC 14), in the same transaction. /// public static class Diary { @@ -36,7 +36,6 @@ public static class Diary ArgumentNullException.ThrowIfNull(s); ArgumentNullException.ThrowIfNull(clock); await WriteAsync(s, clock, DiaryKinds.System, code, message, null, cancellationToken).ConfigureAwait(false); - await s.ExecuteAsync("INSERT INTO notifications (id, channel, kind, message, status, created_at) VALUES (@id, 'telegram', @k, @m, 'pending', @at)", cancellationToken, - ("id", Ids.NewId(clock)), ("k", code), ("m", message), ("at", clock.UtcNow)).ConfigureAwait(false); + await Notifications.NotificationSender.EnqueueAsync(s, clock, code, message, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Anubis/Trading/OrderManager.cs b/src/Anubis/Trading/OrderManager.cs index c8dbb5d..7e2412f 100644 --- a/src/Anubis/Trading/OrderManager.cs +++ b/src/Anubis/Trading/OrderManager.cs @@ -786,9 +786,12 @@ public sealed partial class OrderManager : IDisposable } var reason = fill.Side == OrderSide.Sell && row.Purpose is OrderPurpose.Stop or OrderPurpose.Protective ? ReasonCatalog.Text("stop") : null; - await Diary.WriteAsync(s, _clock, DiaryKinds.Orders, "fill", - DiaryText.Fill(fill.Side, fill.Quantity, instrument?.Symbol ?? "?", instrument?.IsCrypto ?? false, fill.Price, _account.Currency, reason, closed), + var text = DiaryText.Fill(fill.Side, fill.Quantity, instrument?.Symbol ?? "?", instrument?.IsCrypto ?? false, fill.Price, _account.Currency, reason, closed); + await Diary.WriteAsync(s, _clock, DiaryKinds.Orders, "fill", text, new { fill.ExecutionId, row.ClientOrderId, outcome.SlippageBp, outcome.TradeId, Account = _account.Name }, cancellationToken).ConfigureAwait(false); + + // Every purchase and sale reaches the phone, with the result when it closes a trade (SPEC 14). + await Notifications.NotificationSender.EnqueueAsync(s, _clock, "fill", _account.Name + ": " + text, cancellationToken).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false); if (row.Purpose == OrderPurpose.Stop && outcome.Quantity > 0m && instrument is not null) { diff --git a/tests/Anubis.Tests/ServerHarness.cs b/tests/Anubis.Tests/ServerHarness.cs index 065a83a..376366a 100644 --- a/tests/Anubis.Tests/ServerHarness.cs +++ b/tests/Anubis.Tests/ServerHarness.cs @@ -76,7 +76,7 @@ internal sealed partial class ServerHarness : IAsyncDisposable } public static async Task StartAsync(string platform, IReadOnlyDictionary environment, string? dataDir = null, - string[]? extraArgs = null, bool waitReady = true, HttpMessageHandler? marketHttp = null, bool trading = false) + string[]? extraArgs = null, bool waitReady = true, HttpMessageHandler? marketHttp = null, bool trading = false, HttpMessageHandler? telegramHttp = null) { var owns = dataDir is null; dataDir ??= TempFolder.Create("server"); @@ -90,6 +90,7 @@ internal sealed partial class ServerHarness : IAsyncDisposable MarketHttp = marketHttp, MarketSockets = marketHttp is null ? null : () => new FakeSocket(), Trading = trading, + TelegramHttp = telegramHttp, }); await app.StartAsync().ConfigureAwait(false); var cookies = new CookieContainer(); diff --git a/tests/Anubis.Tests/TelegramTests.cs b/tests/Anubis.Tests/TelegramTests.cs new file mode 100644 index 0000000..cb55257 --- /dev/null +++ b/tests/Anubis.Tests/TelegramTests.cs @@ -0,0 +1,363 @@ +using System.Collections.Concurrent; +using System.Net; +using System.Text; +using System.Text.Json; +using Anubis.Core; +using Anubis.Notifications; +using Anubis.Server; +using Microsoft.Extensions.Logging.Abstractions; + +namespace Anubis.Tests; + +/// Telegram and the sign of life (issue #52, SPEC 14), against a fake Telegram server. +[TestClass] +public sealed class TelegramTests +{ + private const string Token = "123456:fake-token-for-tests_abcdefghijklmnop"; + private const string Chat = "424242"; + private static readonly CancellationToken _none = CancellationToken.None; + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task EveryMessageHasItsStateAndAFailureIsTriedAgainLater() + { + await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); + var telegram = new FakeTelegram(); + TelegramSettings? configured = null; + using var http = new HttpClient(telegram); + var sender = new NotificationSender(rig.Db, rig.Clock, _ => Task.FromResult(configured), token => new TelegramClient(http, token)); + await EnqueueAsync(rig, "uno", "due").ConfigureAwait(false); + + // Without Telegram the messages wait in the queue: never "sent". + Assert.AreEqual(0, await sender.SendDueAsync(_none).ConfigureAwait(false)); + Assert.AreEqual(new NotificationSummary(null, 2, 0, 0, null), await sender.SummaryAsync(_none).ConfigureAwait(false)); + + // Telegram slows us down: the first fails, the second waits for the next pass. + configured = new TelegramSettings(Token, Chat); + telegram.Refuse = "sendMessage"; + telegram.RefusalStatus = HttpStatusCode.TooManyRequests; + Assert.AreEqual(0, await sender.SendDueAsync(_none).ConfigureAwait(false)); + var states = await StatesAsync(rig).ConfigureAwait(false); + Assert.AreEqual("failed/1/Telegram ha risposto 429: Too Many Requests: retry after 90", states["uno"].Text); + Assert.AreEqual(rig.Clock.UtcNow.AddSeconds(90), states["uno"].Next, "Telegram's own wait, longer than the first pause of a minute."); + Assert.AreEqual("pending/0/", states["due"].Text); + + // Back up: what is due leaves, the failed one when its time comes. + telegram.Refuse = null; + Assert.AreEqual(1, await sender.SendDueAsync(_none).ConfigureAwait(false)); + rig.Clock.Advance(TimeSpan.FromSeconds(90)); + Assert.AreEqual(1, await sender.SendDueAsync(_none).ConfigureAwait(false)); + states = await StatesAsync(rig).ConfigureAwait(false); + Assert.AreEqual(("sent/2/", "sent/1/"), (states["uno"].Text, states["due"].Text)); + Assert.AreEqual(2, telegram.Sent.Count(m => m.Chat == Chat)); + Assert.AreEqual(new NotificationSummary(rig.Clock.UtcNow, 0, 0, 0, null), await sender.SummaryAsync(_none).ConfigureAwait(false)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task ARefusalIsNotTriedAgainAndAMessageOlderThanADayIsGivenUp() + { + await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); + var telegram = new FakeTelegram { Refuse = "sendMessage", RefusalStatus = HttpStatusCode.BadRequest }; + using var http = new HttpClient(telegram); + var sender = new NotificationSender(rig.Db, rig.Clock, _ => Task.FromResult(new TelegramSettings(Token, Chat)), + token => new TelegramClient(http, token)); + await EnqueueAsync(rig, "rifiutato").ConfigureAwait(false); + await sender.SendDueAsync(_none).ConfigureAwait(false); + var states = await StatesAsync(rig).ConfigureAwait(false); + Assert.AreEqual("failed/1/Telegram ha risposto 400: Bad Request: chat not found", states["rifiutato"].Text); + Assert.IsNull(states["rifiutato"].Next, "A refusal is final: the same message would be refused again."); + + telegram.Refuse = null; + await EnqueueAsync(rig, "vecchio").ConfigureAwait(false); + rig.Clock.Advance(TimeSpan.FromHours(25)); + Assert.AreEqual(0, await sender.SendDueAsync(_none).ConfigureAwait(false)); + states = await StatesAsync(rig).ConfigureAwait(false); + Assert.AreEqual("failed/0/Non partito entro un giorno: non lo mando più.", states["vecchio"].Text); + Assert.IsEmpty(telegram.Sent); + var summary = await sender.SummaryAsync(_none).ConfigureAwait(false); + Assert.AreEqual((0, 0, 2), (summary.Pending, summary.Retrying, summary.GaveUp)); + + // The pauses between attempts grow up to an hour. + Assert.AreEqual("1 2 4 8 16 32 60 60", string.Join(" ", Enumerable.Range(1, 8).Select(a => NotificationSender.Pause(a).TotalMinutes))); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task FermaWantsAConfirmationWithinTwoMinutes() + { + var clock = new ManualClock(new DateTimeOffset(2026, 11, 11, 9, 0, 0, TimeSpan.Zero)); + var desk = new FakeDesk(); + var commands = new TelegramCommands(desk, clock); + + Assert.Contains("/conferma entro 2 minuti", (await commands.AnswerAsync("/ferma", _none).ConfigureAwait(false))!); + Assert.AreEqual(0, desk.Stops); + clock.Advance(TimeSpan.FromSeconds(100)); + Assert.AreEqual("fermato", await commands.AnswerAsync("/conferma", _none).ConfigureAwait(false)); + Assert.AreEqual(1, desk.Stops); + + // Too late, or another command in between: nothing to confirm. + await commands.AnswerAsync("/ferma", _none).ConfigureAwait(false); + clock.Advance(TimeSpan.FromMinutes(3)); + Assert.Contains("niente da confermare", (await commands.AnswerAsync("/conferma", _none).ConfigureAwait(false))!); + await commands.AnswerAsync("/ferma", _none).ConfigureAwait(false); + await commands.AnswerAsync("/stato", _none).ConfigureAwait(false); + Assert.Contains("niente da confermare", (await commands.AnswerAsync("/conferma", _none).ConfigureAwait(false))!); + Assert.AreEqual(1, desk.Stops); + + // The other commands, the bot's name of a group, help, and plain text that is no command. + Assert.AreEqual("stato", await commands.AnswerAsync("/stato@AnubisBot", _none).ConfigureAwait(false)); + Assert.AreEqual("posizioni", await commands.AnswerAsync("/POSIZIONI", _none).ConfigureAwait(false)); + Assert.AreEqual("oggi", await commands.AnswerAsync(" /oggi grazie", _none).ConfigureAwait(false)); + Assert.AreEqual("pausa", await commands.AnswerAsync("/pausa", _none).ConfigureAwait(false)); + Assert.AreEqual("riprendi", await commands.AnswerAsync("/riprendi", _none).ConfigureAwait(false)); + Assert.AreEqual(TelegramCommands.Help, await commands.AnswerAsync("/aiuto", _none).ConfigureAwait(false)); + Assert.StartsWith("Non conosco questo comando.", (await commands.AnswerAsync("/compra BTC", _none).ConfigureAwait(false))!); + Assert.IsNull(await commands.AnswerAsync("ciao", _none).ConfigureAwait(false)); + Assert.DoesNotContain("limiti", TelegramCommands.Help.Split('\n')[0]); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task OnlyTheChatOfTheSettingsIsObeyedAndOldMessagesAreNot() + { + var clock = new ManualClock(new DateTimeOffset(2026, 11, 11, 9, 0, 0, TimeSpan.Zero)); + var telegram = new FakeTelegram(); + using var http = new HttpClient(telegram); + var desk = new FakeDesk(); + var bot = new TelegramBot(clock, _ => Task.FromResult(new TelegramSettings(Token, Chat)), token => new TelegramClient(http, token), + new TelegramCommands(desk, clock), NullLogger.Instance); + + telegram.Write("999", "/pausa", clock.UtcNow); + telegram.Write(Chat, "/pausa", clock.UtcNow - TimeSpan.FromHours(20)); + telegram.Write(Chat, "/stato", clock.UtcNow); + Assert.AreEqual(1, await bot.PollOnceAsync(_none).ConfigureAwait(false)); + Assert.AreEqual((Chat, "stato"), telegram.Sent.Single()); + Assert.AreEqual(0, desk.Pauses, "Neither the stranger's /pausa nor yesterday's."); + + // The next read tells Telegram the first three were read. + Assert.AreEqual(0, await bot.PollOnceAsync(_none).ConfigureAwait(false)); + Assert.AreEqual(4, telegram.LastOffset); + + // Without Telegram configured the loop only waits. + var idle = new TelegramBot(clock, _ => Task.FromResult(null), token => new TelegramClient(http, token), new TelegramCommands(desk, clock), + NullLogger.Instance); + Assert.AreEqual(-1, await idle.PollOnceAsync(_none).ConfigureAwait(false)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public async Task TheSignOfLifeCallsTheServiceAndSaysWhenItFails() + { + var clock = new ManualClock(new DateTimeOffset(2026, 11, 11, 9, 0, 0, TimeSpan.Zero)); + var calls = 0; + var fake = new FakeHttp().On(u => u.Host == "hc.example", _ => FakeHttp.Respond("OK", ++calls == 2 ? HttpStatusCode.ServiceUnavailable : HttpStatusCode.OK)); + using var http = fake.Client(); + Uri? address = null; + var beat = new Heartbeat(http, clock, _ => Task.FromResult(address), NullLogger.Instance); + Assert.IsFalse(await beat.BeatAsync(_none).ConfigureAwait(false), "No address, no call."); + Assert.IsEmpty(fake.Requests); + + address = new Uri("https://hc.example/ping/abc"); + Assert.IsTrue(await beat.BeatAsync(_none).ConfigureAwait(false)); + Assert.AreEqual(clock.UtcNow, beat.LastOk); + clock.Advance(TimeSpan.FromMinutes(1)); + Assert.IsFalse(await beat.BeatAsync(_none).ConfigureAwait(false)); + Assert.AreEqual(("Il servizio ha risposto 503.", clock.UtcNow - TimeSpan.FromMinutes(1)), (beat.LastError, beat.LastOk)); + + Assert.IsNull(Heartbeat.Check("https://hc-ping.com/uuid")); + Assert.IsNull(Heartbeat.Check("http://192.168.30.23:8000/ping/x")); + Assert.IsNotNull(Heartbeat.Check("http://hc-ping.com/uuid")); + Assert.IsNotNull(Heartbeat.Check("ftp://example.com")); + Assert.IsNotNull(Heartbeat.Check("non è un indirizzo")); + } + + /// + /// The acceptance criterion of SPEC 14 with the real server: commands from the phone change the bot's state, the + /// changes reach the phone, a stranger is ignored, and after "Ferma tutto" the phone cannot restart the bot. + /// + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheCommandsWorkFromThePhoneThroughTheRealServer() + { + var telegram = new FakeTelegram(); + var env = ServerHarness.DockerSqlite(); + env["TELEGRAM_BOT_TOKEN"] = Token; + env["TELEGRAM_CHAT_ID"] = Chat; + await using var server = await ServerHarness.StartAsync("docker", env, telegramHttp: telegram).ConfigureAwait(false); + var services = server.Host.Services!; + async Task AskAsync(string text, string chat = Chat) + { + var before = telegram.Sent.Count; + telegram.Write(chat, text, DateTimeOffset.UtcNow); + var until = DateTimeOffset.UtcNow.AddSeconds(20); + while (DateTimeOffset.UtcNow < until) + { + if (telegram.Sent.Skip(before).FirstOrDefault(m => m.Chat == chat && !m.Text.Contains("(da Telegram)", StringComparison.Ordinal)) is { Text: { } answer }) + { + return answer; + } + + await Task.Delay(50).ConfigureAwait(false); + } + + return "(nessuna risposta)"; + } + + async Task StateAsync() => (await services.Settings.GetAsync(SettingsStore.BotState.Key, _none).ConfigureAwait(false)).Value; + + Assert.StartsWith("Bot attivo", await AskAsync("/stato").ConfigureAwait(false)); + Assert.AreEqual("Nessuna posizione aperta.", await AskAsync("/posizioni").ConfigureAwait(false)); + Assert.AreEqual("Nessun ordine oggi.", await AskAsync("/oggi").ConfigureAwait(false)); + + Assert.StartsWith("In pausa", await AskAsync("/pausa").ConfigureAwait(false)); + Assert.AreEqual("paused", await StateAsync().ConfigureAwait(false)); + await WaitForAsync(() => telegram.Sent.Any(m => m.Text.StartsWith("Bot in pausa (da Telegram)", StringComparison.Ordinal))).ConfigureAwait(false); + + Assert.AreEqual("(nessuna risposta)", await AskAsync("/riprendi", "777").ConfigureAwait(false), "Another chat gets nothing."); + Assert.AreEqual("paused", await StateAsync().ConfigureAwait(false)); + Assert.AreEqual("Ripartito dalla pausa.", await AskAsync("/riprendi").ConfigureAwait(false)); + Assert.AreEqual("active", await StateAsync().ConfigureAwait(false)); + + Assert.Contains("/conferma", await AskAsync("/ferma").ConfigureAwait(false)); + Assert.AreEqual("active", await StateAsync().ConfigureAwait(false)); + Assert.StartsWith("«Ferma tutto» fatto", await AskAsync("/conferma").ConfigureAwait(false)); + Assert.AreEqual("stopped", await StateAsync().ConfigureAwait(false)); + Assert.Contains("riattivalo dalla pagina Rischio", await AskAsync("/riprendi").ConfigureAwait(false)); + Assert.AreEqual("stopped", await StateAsync().ConfigureAwait(false)); + + // Every notice has its state, and the Impostazioni page shows the last message that left. + await WaitForAsync(() => telegram.Sent.Any(m => m.Text.StartsWith("«Ferma tutto» (da Telegram)", StringComparison.Ordinal))).ConfigureAwait(false); + var notices = await services.Db.ReadAsync(s => s.QueryAsync("SELECT kind, status FROM notifications", r => r.Text("kind") + "/" + r.Text("status")), _none) + .ConfigureAwait(false); + Assert.Contains("bot_paused/sent", notices); + Assert.Contains("bot_active/sent", notices); + Assert.IsFalse(telegram.Sent.Any(m => m.Text.Contains(Token, StringComparison.Ordinal))); + await server.SignInFirstTimeAsync().ConfigureAwait(false); + var page = await server.TextAsync("/impostazioni").ConfigureAwait(false); + Assert.Contains("Telegram e segnale di vita", page); + Assert.Contains("Token e chat arrivano dalle variabili", page); + Assert.DoesNotContain(Token, page); + } + + private static async Task WaitForAsync(Func condition) + { + var until = DateTimeOffset.UtcNow.AddSeconds(20); + while (!condition()) + { + Assert.IsLessThan(until, DateTimeOffset.UtcNow, "Timed out."); + await Task.Delay(50).ConfigureAwait(false); + } + } + + private static Task EnqueueAsync(TradingRig rig, params string[] messages) => + rig.Db.WriteAsync(async s => + { + foreach (var message in messages) + { + await NotificationSender.EnqueueAsync(s, rig.Clock, "test", message, _none).ConfigureAwait(false); + rig.Clock.Advance(TimeSpan.FromMilliseconds(1)); + } + }, _none); + + private static async Task> StatesAsync(TradingRig rig) => + (await rig.QueryAsync("SELECT message, status, attempts, last_error, next_attempt_at FROM notifications", + r => (Message: r.Text("message"), Text: r.Text("status") + "/" + r.Number("attempts") + "/" + r.TextOrNull("last_error"), Next: r.MomentOrNull("next_attempt_at"))) + .ConfigureAwait(false)).ToDictionary(x => x.Message, x => (x.Text, x.Next)); + + private sealed class FakeDesk : ITelegramDesk + { + public int Stops { get; private set; } + + public int Pauses { get; private set; } + + public Task StatusAsync(CancellationToken cancellationToken) => Task.FromResult("stato"); + + public Task PositionsAsync(CancellationToken cancellationToken) => Task.FromResult("posizioni"); + + public Task TodayAsync(CancellationToken cancellationToken) => Task.FromResult("oggi"); + + public Task PauseAsync(CancellationToken cancellationToken) + { + Pauses++; + return Task.FromResult("pausa"); + } + + public Task ResumeAsync(CancellationToken cancellationToken) => Task.FromResult("riprendi"); + + public Task StopAllAsync(CancellationToken cancellationToken) + { + Stops++; + return Task.FromResult("fermato"); + } + } +} + +/// +/// A Telegram Bot API on the test's side: messages written by the test come back from getUpdates, sendMessage is +/// recorded, and one method can be made to refuse. getUpdates answers at once (no long wait) after a short pause. +/// +internal sealed class FakeTelegram : HttpMessageHandler +{ + private readonly ConcurrentQueue<(long Id, string Chat, string Text, DateTimeOffset Date)> _updates = new(); + private long _nextId = 1; + + public List<(string Chat, string Text)> Sent { get; } = []; + + public long LastOffset { get; private set; } + + /// The method that fails, with . + public string? Refuse { get; set; } + + public HttpStatusCode RefusalStatus { get; set; } = HttpStatusCode.BadRequest; + + public void Write(string chat, string text, DateTimeOffset at) => _updates.Enqueue((Interlocked.Increment(ref _nextId) - 1, chat, text, at)); + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var method = request.RequestUri!.AbsolutePath.Split('/')[^1]; + using var body = JsonDocument.Parse(request.Content is null ? "{}" : await request.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false)); + if (method == Refuse) + { + return RefusalStatus == HttpStatusCode.TooManyRequests + ? Json(RefusalStatus, """{"ok":false,"error_code":429,"description":"Too Many Requests: retry after 90","parameters":{"retry_after":90}}""") + : Json(RefusalStatus, """{"ok":false,"error_code":400,"description":"Bad Request: chat not found"}"""); + } + + switch (method) + { + case "getMe": + return Json(HttpStatusCode.OK, """{"ok":true,"result":{"id":1,"is_bot":true,"username":"AnubisProvaBot"}}"""); + case "sendMessage": + lock (Sent) + { + Sent.Add((body.RootElement.GetProperty("chat_id").GetString()!, body.RootElement.GetProperty("text").GetString()!)); + } + + return Json(HttpStatusCode.OK, """{"ok":true,"result":{"message_id":1}}"""); + case "getUpdates": + var offset = body.RootElement.TryGetProperty("offset", out var o) ? o.GetInt64() : 0; + LastOffset = offset; + while (_updates.TryPeek(out var first) && first.Id < offset) + { + _updates.TryDequeue(out _); + } + + if (_updates.IsEmpty) + { + await Task.Delay(30, cancellationToken).ConfigureAwait(false); + } + + var items = _updates.ToArray().Where(u => u.Id >= offset).Select(u => new + { + update_id = u.Id, + message = new { message_id = u.Id, date = u.Date.ToUnixTimeSeconds(), chat = new { id = long.Parse(u.Chat, System.Globalization.CultureInfo.InvariantCulture) }, text = u.Text }, + }); + return Json(HttpStatusCode.OK, JsonSerializer.Serialize(new { ok = true, result = items })); + default: + return Json(HttpStatusCode.NotFound, """{"ok":false,"description":"Not Found"}"""); + } + } + + private static HttpResponseMessage Json(HttpStatusCode status, string json) => new(status) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; +} From e96ca70a1a854bbce441cf9101ca8eec7455bbfb Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 11 Nov 2026 20:32:19 +0100 Subject: [PATCH 06/12] Build the Panoramica and Diario e sistema screens as in the mockups (refs #51) Panoramica now follows mockup 01. Below "Finora" and "Adesso e dopo" it shows: - the two account cards with the invested/cash bar and a 30-day trend; - the four risk limits; - the open positions by value; - the strategies; - the news, learning and system tiles. On the phone it follows mockup 09: Conti as a list, four positions with "Vedi le altre", and two limits. Outside the demo, news and learning say they are not active yet (Phases 7 and 8). The next moves are the scheduler's moves only, no longer every interval job. Diario e sistema follows mockup 08: - the diary grouped by day, with search and filter chips (plain links, no JavaScript) and older days on request; - how each component is doing; - the scheduled jobs; - the host's processor, memory and disk; - the technical logs as a zip, for signed-in users only. In demo mode the screens show the values of appendix F.10. Tests cover the demo figures, the filters and search, and the logs download. Co-Authored-By: Claude Opus 5.5 --- src/Anubis.Server/Assets/app.css | 136 +++++++ .../Components/Pages/Diario.razor | 191 ++++++--- .../Components/Pages/Panoramica.razor | 370 +++++++++++++++++- src/Anubis.Server/DiaryView.cs | 243 ++++++++++++ src/Anubis.Server/Endpoints.cs | 35 ++ src/Anubis.Server/Overview.cs | 22 +- src/Anubis.Server/PanoramaView.cs | 214 ++++++++++ src/Anubis.Server/SystemView.cs | 332 ++++++++++++++++ src/Anubis/Core/Scheduling.cs | 5 +- src/Anubis/Demo/Data/aggregates.json | 41 +- tests/Anubis.Tests/OverviewScreenTests.cs | 162 ++++++++ 11 files changed, 1666 insertions(+), 85 deletions(-) create mode 100644 src/Anubis.Server/DiaryView.cs create mode 100644 src/Anubis.Server/PanoramaView.cs create mode 100644 src/Anubis.Server/SystemView.cs create mode 100644 tests/Anubis.Tests/OverviewScreenTests.cs diff --git a/src/Anubis.Server/Assets/app.css b/src/Anubis.Server/Assets/app.css index d9ca913..08d3c9f 100644 --- a/src/Anubis.Server/Assets/app.css +++ b/src/Anubis.Server/Assets/app.css @@ -522,6 +522,123 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we .events dt { color: var(--text-3); } .limits-form { max-width: none; margin-bottom: 8px; } +/* ---- Panoramica, under the top block (mockup 01) ---- */ +.phone-only { display: none !important; } +.next-decision { display: flex; align-items: flex-start; gap: 10px; color: var(--text-2); font-size: 14px; } +.next-decision .icon { margin-top: 2px; color: var(--text-3); } +.overview-row { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 20px; align-items: stretch; } +.overview-row-wide { grid-template-columns: minmax(0, 1.85fr) minmax(0, 1fr); align-items: start; } +.overview-empty { grid-column: span 2; display: flex; flex-direction: column; gap: 8px; color: var(--text-2); } +.overview-account { display: flex; flex-direction: column; } +.overview-account h2 { font-size: 15px; line-height: 22px; } +.overview-account .account-value { margin: 12px 0 0; gap: 12px; } +.overview-account .account-equity { font-size: 28px; line-height: 34px; } +.split-bar.thin { height: 8px; margin-top: 16px; } +.split-key { display: flex; justify-content: space-between; gap: 12px; flex-wrap: wrap; margin-top: 10px; color: var(--text-2); font-size: 13px; } +.split-key > span { display: inline-flex; align-items: center; } +.split-key .swatch { width: 9px; height: 9px; margin-right: 4px; } +.split-key .swatch:last-of-type { margin-right: 8px; } +.split-key strong { color: var(--text); font-weight: 600; margin-left: 6px; font-variant-numeric: tabular-nums; } +.month { display: flex; align-items: flex-end; justify-content: space-between; gap: 12px; margin-top: 16px; padding-top: 14px; border-top: 1px solid var(--rule-inner); } +.month > div { display: flex; flex-direction: column; } +.month strong { font-weight: 650; font-variant-numeric: tabular-nums; } +.spark-mini { width: 120px; height: 36px; flex: none; overflow: visible; } +.spark-mini polyline { fill: none; stroke: var(--text-2); stroke-width: 1.5; stroke-linejoin: round; } +.spark-mini circle { fill: var(--text); } +.overview-account > .note { margin-top: 14px; } +.status-pill { display: inline-flex; align-items: center; gap: 6px; font-size: 13.5px; font-weight: 600; } +.status-pill.attention { color: var(--attention); } +.overview-risk { display: flex; flex-direction: column; } +.overview-risk .panel-head { margin-bottom: 10px; } +.overview-risk > .note { margin-top: 14px; } +.overview-risk .more { margin-top: 10px; align-self: flex-start; } +.limit-list { display: flex; flex-direction: column; gap: 12px; } +.limit { display: flex; flex-direction: column; gap: 6px; } +.limit-line { display: flex; justify-content: space-between; gap: 12px; color: var(--text-2); font-size: 13.5px; font-variant-numeric: tabular-nums; } +.limit-line strong { color: var(--text); font-weight: 650; } +.usage.notched { overflow: visible; } +.notch { position: absolute; top: -4px; width: 2px; height: 14px; margin-left: -1px; background: var(--text); border-radius: 1px; } +.panel-head h2 .note { margin-left: 8px; } +.overview-positions { padding-bottom: 6px; } +.strategy-list { list-style: none; margin: 0; padding: 0; } +.strategy-list li { display: flex; flex-direction: column; gap: 4px; padding: 14px 0; border-bottom: 1px solid var(--rule-inner); } +.strategy-list li:first-child { padding-top: 4px; } +.strategy-line { display: flex; justify-content: space-between; gap: 12px; font-variant-numeric: tabular-nums; } +.strategy-line strong { display: inline-flex; align-items: center; font-weight: 650; } +.strategy-bar { display: block; height: 8px; margin: 4px 0 6px; } +.strategy-bar span { display: block; height: 100%; border-radius: 4px; } +.info-note { margin-top: 18px; padding: 12px 16px; border-radius: 10px; background: var(--info-bg); color: var(--link); font-size: 13.5px; } +.overview-tiles { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 28px; align-items: start; } +.tile .panel-head { margin-bottom: 8px; } +.tile h2 { font-size: 15px; } +.news-list { list-style: none; margin: 0; padding: 0; } +.news-list li { display: flex; flex-direction: column; gap: 4px; padding: 12px 0; border-bottom: 1px solid var(--rule-inner); } +.news-list li:first-child { padding-top: 4px; } +.news-list li:last-child { border-bottom: 0; } +.news-list strong { font-weight: 600; } +.news-list .attention { align-items: flex-start; font-size: 13.5px; } +.news-list .attention .icon { margin-top: 2px; } +.news-list .muted { font-size: 13.5px; } +.tile > p + .limit { margin-top: 14px; } +.tile-facts { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 8px 12px; margin: 16px 0 0; padding-top: 12px; border-top: 1px solid var(--rule-inner); font-size: 13.5px; } +.tile-facts dt { color: var(--text-2); } +.tile-facts dd { margin: 0; text-align: right; font-weight: 600; } +.system-tiles { list-style: none; margin: 0; padding: 0; } +.system-tiles li { display: grid; grid-template-columns: 16px auto minmax(0, 1fr); gap: 10px; align-items: center; padding: 8px 0; border-bottom: 1px solid var(--rule-inner); font-size: 13.5px; } +.system-tiles li:last-child { border-bottom: 0; } +.system-tiles .muted { text-align: right; } +.ok > .icon { color: var(--gain); } +.warn > .icon { color: var(--attention); } +.off > .icon { color: var(--text-3); } +.phone-list { list-style: none; margin: 0; padding: 0; } +.phone-list li { display: flex; justify-content: space-between; gap: 12px; padding: 14px 0; border-top: 1px solid var(--rule-inner); } +.phone-list li > span { display: flex; flex-direction: column; gap: 4px; min-width: 0; } +.phone-list .num { align-items: flex-end; text-align: right; font-variant-numeric: tabular-nums; } +.phone-list .sub { display: inline-flex; align-items: center; gap: 6px; color: var(--text-2); font-size: 14px; } +.phone-list .sub.gain, .phone-list strong.gain { color: var(--gain); } +.phone-list .sub.loss, .phone-list strong.loss { color: var(--loss); } +.phone-list .swatch { margin-right: 0; } +.phone-list .dot.down { background: var(--loss); } + +/* ---- Diario e sistema (mockup 08) ---- */ +.journal-columns { display: grid; grid-template-columns: minmax(0, 1.75fr) minmax(0, 1fr); gap: 24px; align-items: start; } +.journal { padding: 24px 26px; } +.journal-head { display: flex; align-items: center; justify-content: space-between; gap: 12px 16px; flex-wrap: wrap; } +.journal-search { flex: 0 1 330px; } +.chips { display: flex; flex-wrap: wrap; gap: 8px; margin: 16px 0 8px; } +.chip { display: inline-flex; align-items: center; min-height: 32px; padding: 0 14px; border: 1px solid var(--control); border-radius: 999px; color: var(--text); text-decoration: none; font-size: 14px; } +.chip:hover { background: var(--surface-2); } +.chip.on { background: var(--text); border-color: var(--text); color: var(--surface); font-weight: 550; } +.journal-found { margin-top: 12px; } +.panel h3.journal-day { margin: 28px 0 0; padding-bottom: 10px; border-bottom: 2px solid var(--text); font-size: 14.5px; } +.journal-list { list-style: none; margin: 0; padding: 0; } +.journal-list li { display: grid; grid-template-columns: 44px 22px minmax(0, 1fr) auto; gap: 12px; align-items: start; padding: 12px 0; border-bottom: 1px solid var(--rule-inner); } +.journal-list time { color: var(--text-3); font-variant-numeric: tabular-nums; } +.journal-icon { color: var(--text-2); margin-top: 1px; } +.attention-entry .journal-icon { color: var(--attention); } +.journal-text { min-width: 0; display: flex; flex-direction: column; gap: 4px; overflow-wrap: anywhere; } +.journal-text strong { font-weight: 650; } +.journal-rest { color: var(--text-2); } +.journal-kind { color: var(--text-3); font-size: 13.5px; text-align: right; } +.journal-more { display: flex; justify-content: center; margin-top: 18px; } +.journal-side { display: flex; flex-direction: column; gap: 24px; min-width: 0; } +.journal-side .panel-head { margin-bottom: 4px; } +.system-parts { list-style: none; margin: 0; padding: 0; } +.system-parts li { display: flex; align-items: flex-start; gap: 12px; padding: 12px 0; border-top: 1px solid var(--rule-inner); } +.system-parts li > .icon { margin-top: 2px; } +.system-parts li > span { display: flex; flex-direction: column; min-width: 0; } +.system-parts strong { font-weight: 600; } +.system-parts li > span > span { color: var(--text-2); } +.job-list li { grid-template-columns: 96px minmax(0, 1fr); } +.job-list li:last-child { border-bottom: 0; } +.host { display: flex; flex-direction: column; gap: 12px; } +.host > h2 { margin-bottom: 0; } +.host .btn { align-self: flex-start; } +@media (max-width: 1180px) { + .overview-row { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .overview-row-wide, .journal-columns { grid-template-columns: minmax(0, 1fr); } +} + /* ---- Service pages ---- */ .service { min-height: 100vh; display: flex; justify-content: center; padding: 48px 16px; } .service-box { width: 100%; max-width: 720px; display: flex; flex-direction: column; gap: 16px; } @@ -601,3 +718,22 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we .bottom-item.active { background: var(--surface-2); color: var(--text); font-weight: 650; } .nav-item, .btn, .more-list a { min-height: 44px; } } + +/* Panoramica and Diario on the phone: mockup 09, and mockup 08 stacked in one column */ +@media (max-width: 760px) { + .desk-only { display: none !important; } + .cells > .cell-extra { display: none; } + section.phone-only, div.phone-only, ul.phone-only { display: block !important; } + a.phone-only { display: inline-block !important; } + span.phone-only { display: inline !important; } + .overview-row, .overview-row-wide, .overview-tiles { grid-template-columns: minmax(0, 1fr); gap: 14px; } + .half-next .moves { margin-top: 4px; border-top: 1px solid var(--rule); } + .phone-list li:last-child { padding-bottom: 4px; } + .journal { padding: 18px; } + .journal-search { flex: 1 1 100%; } + .journal-list li { grid-template-columns: 40px 18px minmax(0, 1fr); gap: 4px 10px; } + .journal-kind { grid-column: 3; text-align: left; font-size: 12.5px; line-height: 16px; } + .chip { min-height: 40px; } + .journal-side { gap: 14px; } + .job-list li { grid-template-columns: 84px minmax(0, 1fr); } +} diff --git a/src/Anubis.Server/Components/Pages/Diario.razor b/src/Anubis.Server/Components/Pages/Diario.razor index 280efa1..c03aaa0 100644 --- a/src/Anubis.Server/Components/Pages/Diario.razor +++ b/src/Anubis.Server/Components/Pages/Diario.razor @@ -5,86 +5,157 @@ Diario e sistema · Anubis -
-
-

Diario

- @if (_entries.Count == 0) +@{ + var d = _diary; + var s = _system; +} +
+
+
+

Diario

+
+ + @if (d.Search is { } search) { -

Ancora nessuna voce.

+

+ @(d.Days.Sum(x => x.Entries.Count) switch { 0 => "Nessuna voce", 1 => "Una voce", var n => $"{n} voci" }) con «@search»@(d.Truncated ? $", le {DiaryView.MaxSearchResults} più recenti" : ""). + Togli la ricerca +

} - else + @if (d.IsEmpty && d.Search is null) { -
- - - - @foreach (var e in _entries) - { - - } - -
QuandoTipoVoce
@Format.ShortDate(e.At, Shell.Now, Shell.Zone)@e.Kind@e.Text
-
+

@(d.Filter == "tutto" ? "Ancora nessuna voce. Qui il bot scrive ogni decisione, ordine e controllo, in parole semplici, appena succede." : "Nessuna voce di questo tipo finora.")

+ } + @foreach (var day in d.Days) + { +

@day.Heading

+
    + @foreach (var e in day.Entries) + { +
  1. + + +
    +

    @if (e.Lead is { } lead) {@lead}@foreach (var piece in e.Main) {if (piece.Class is { } css) {@piece.Text} else {@piece.Text}}

    + @if (e.Rest is { } rest) + { +

    @rest

    + } + @if (e.Trade is { } trade) + { + Perché l'ho comprata e venduta + } +
    + @e.Kind +
  2. + } +
+ } + @if (d.HasOlder) + { + }
-
-

Sistema

-
-
Versione
@AnubisInfo.Version
-
Piattaforma
@(Host.Config.Platform == PlatformKind.Docker ? "Docker" : "Desktop")
-
Database
@(Host.Config.Db?.Engine == DbEngine.Postgres ? "PostgreSQL" : "SQLite") · risponde
-
In funzione da
@Format.Ago(Shell.Now - _since).Replace(" fa", "", StringComparison.Ordinal)
-
-

Lavori in programma

-
    - @foreach (var job in _upcoming) - { -
  • @Format.ShortDate(job.DueUtc, Shell.Now, Shell.Zone)@job.Description
  • - } -
- @if (_jobs.Count > 0) - { -

Ultimi lavori

-
    - @foreach (var job in _jobs) + +
    +
    +
    +

    Come sta il sistema

    + @(s.AllWell ? "Tutto regolare" : "Qualcosa da controllare") +
    +
      + @foreach (var part in s.Parts) { -
    • @(job.Finished is { } f ? Format.ShortDate(f, Shell.Now, Shell.Zone) : "—")@job.Description: @Outcome(job.Outcome)
    • +
    • + + @part.Name@part.Detail +
    • }
    - } -
    +
+ +
+

Lavori in programma

+ @if (s.Jobs.Count == 0) + { +

Nessun lavoro in programma: il pianificatore parte con il motore.

+ } + else + { +
    + @foreach (var job in s.Jobs) + { +
  • @job.Time@job.Text
  • + } +
+ } +
+ +
+

Il computer che lo ospita

+ @foreach (var r in s.Resources) + { +
+
@r.Label@r.Value@if (r.Of is { } of) { su @of}
+ +
+ } +

@s.Running

+ Scarica i registri tecnici +
+
@code { - private List<(DateTimeOffset At, string Kind, string Text)> _entries = []; - private List<(string Description, DateTimeOffset? Finished, string? Outcome)> _jobs = []; - private IReadOnlyList _upcoming = []; - private DateTimeOffset _since; + private DiaryView _diary = null!; + private SystemView _system = null!; [CascadingParameter] public HttpContext? HttpContext { get; set; } + [SupplyParameterFromQuery(Name = "tipo")] + public string? Tipo { get; set; } + + [SupplyParameterFromQuery(Name = "cerca")] + public string? Cerca { get; set; } + + [SupplyParameterFromQuery(Name = "giorni")] + public string? Giorni { get; set; } + protected override async Task LoadAsync() { var ct = HttpContext?.RequestAborted ?? CancellationToken.None; - var services = Host.Services!; - (_entries, _jobs) = await services.Db.ReadAsync(async s => - { - var entries = await s.QueryAsync("SELECT occurred_at, kind, message FROM journal ORDER BY occurred_at DESC LIMIT 200", - r => (r.Moment("occurred_at"), r.Text("kind"), r.Text("message"))); - var jobs = await s.QueryAsync("SELECT description, last_finished_at, last_outcome FROM jobs ORDER BY last_finished_at DESC", - r => (r.Text("description"), r.MomentOrNull("last_finished_at"), r.TextOrNull("last_outcome"))); - return (entries, jobs); - }, ct); - _upcoming = services.Scheduler.Upcoming(10); - _since = Host.Status.Since; + _diary = await DiaryView.LoadAsync(Host.Services!.Db, Tipo, Cerca, Giorni, Shell.Now, Shell.Zone, ct); + _system = await SystemView.LoadAsync(Host, Shell, ct); } - private static string Outcome(string? outcome) => outcome switch + private static string PartClass(PartState state) => state switch { - "succeeded" => "fatto", - "failed" => "non riuscito", - "skipped" => "saltato, orario superato", - _ => "in attesa", + PartState.Ok => "ok", + PartState.Warn => "warn", + _ => "off", }; + + private static string PartIcon(PartState state) => state switch + { + PartState.Ok => "tick", + PartState.Warn => "alert", + _ => "clock", + }; + + private static string Css(decimal value) => Math.Round(value, 3).ToString("0.###", CultureInfo.InvariantCulture); } diff --git a/src/Anubis.Server/Components/Pages/Panoramica.razor b/src/Anubis.Server/Components/Pages/Panoramica.razor index 65f86ae..643c148 100644 --- a/src/Anubis.Server/Components/Pages/Panoramica.razor +++ b/src/Anubis.Server/Components/Pages/Panoramica.razor @@ -2,12 +2,20 @@ @page "/" @inject AnubisHost Host @inject ShellData Shell +@using Anubis.Trading +@using Anubis.Data Panoramica · Anubis @{ var o = _overview; + var p = _panorama; var c = _currency; + var moves = p.DemoMoves ?? o.Next; + var last = p.DemoLast ?? o.Last; + // On the phone only the first two moves of the bot, without the calendar's events (SPEC 13.4). + var phoneMoves = moves.Select((m, i) => (m, i)).Where(x => !x.m.Calendar).Take(2).Select(x => x.i).ToHashSet(); + var v = p.Accounts; } @if (!o.CapitalSet && !Shell.IsDemo) { @@ -42,7 +50,9 @@ @Shell.Money(o.Result.Amount, c, withSign: true) @Format.Percent(o.Result.Percent, 2, withSign: true) -

Dal @Format.LongDate(o.From), partendo da @Shell.Money(o.FromEquity, c). Commissioni già tolte.

+ var from = Format.LongDate(o.From); + var year = from.LastIndexOf(' '); +

Dal @from[..year]@from[year..], partendo da @Shell.Money(o.FromEquity, c). Commissioni già tolte.

@foreach (var (cell, i) in o.Cells.Select((x, i) => (x, i))) { @@ -63,47 +73,321 @@

Adesso e dopo

@if (_runningDays is { } days) { - Attivo da @days giorni senza interruzioni + Attivo da @days giorni senza interruzioni }

@Statement(o)

-

Prossime mosse

- @if (o.Next.Count == 0) + @if (p.NextDecision is { } decision) { -

Niente in programma.

+

@decision

+ } +

Prossime mosse

+ @if (moves.Count == 0) + { +

Niente in programma: le mosse compaiono quando il motore di trading lavora con almeno una strategia.

} else {
    - @foreach (var move in o.Next) + @for (var i = 0; i < moves.Count; i++) { -
  • @move.Time@move.Text
  • + var move = moves[i]; +
  • @move.Time@move.Text@if (move.Where is { } where) { (@where)}
  • }
} -

Ultime azioni

- @if (o.Last.Count == 0) +
+

Ultime azioni

+ @if (last.Count == 0) + { +

Ancora nessuna voce nel diario.

+ } + else + { +
    + @foreach (var action in last) + { +
  • @action.When@action.Text
  • + } +
+ } + Apri il diario completo +
+ Tutte le mosse e il diario + + + +@* Accounts and the four limits (mockup 01); on the phone a compact list of the accounts (mockup 09). *@ +
+ @if (!v.HasAccounts) + { +
+

Nessun conto ancora.

+

Il bot crea da solo i due simulatori interni, OKX e Alpaca, al primo avvio del motore di trading. I conti di prova compaiono quando ne aggiungi le chiavi in Impostazioni.

+
+ } + @foreach (var a in v.Accounts) + { + var up = a.Result >= 0; + var held = v.Positions.Where(x => x.AccountId == a.Id).ToList(); + var slices = held.GroupBy(x => x.Strategy).OrderBy(g => StrategyNames.Base.ToList().FindIndex(b => b.Name == g.Key)) + .Select(g => (Strategy: g.Key, Eur: g.Sum(x => x.ValueEur))).ToList(); + var shares = Format.Shares([.. slices.Select(s => s.Eur), a.Eur(a.Cash)]); + var trend = p.Trends.GetValueOrDefault(a.Id); + + } +
+
+

Rischio

+ @(p.LimitsKept ? "Tutti i limiti rispettati" : "Un limite chiede attenzione") +
+
+ @foreach (var l in p.Limits) + { +
+
@l.Label@l.Value su @l.Threshold
+ = 0.8m ? "high" : null)"> + + @if (l.Worst is { } w) + { + + } + +
+ } +
+ @if (p.Limits[1].Worst is not null && _worst is { } worst) { -

Ancora nessuna voce nel diario.

+

La tacca segna il calo peggiore finora: @Format.Percent(worst * 100m, 2).

+ } + Vedi tutti i limiti +
+
+ +@if (v.HasAccounts) +{ +
+

Conti

+
    + @foreach (var a in v.Accounts) + { + var up = a.Result >= 0; +
  • + @a.Name@a.Kind, @(Down(a) ? "non risponde" : "connesso") + @Shell.Money(a.Eur(a.Equity), c)@Shell.Money(a.Eur(a.Result), c, withSign: true) +
  • + } +
+
+} + +@* Positions by value and the strategies (mockup 01); on the phone the first four positions (mockup 09). *@ +
+
+
+

Posizioni aperte + @if (v.Positions.Count > 0) + { + @v.Positions.Count, per @Shell.Money(v.InvestedEur, c). Risultato aperto @Shell.Money(v.OpenResultEur, c, withSign: true) + } +

+ @if (v.Positions.Count > 0) + { + @v.Positions.Count, risultato @Shell.Money(v.OpenResultEur, c, withSign: true) + } + Dettaglio +
+ @if (v.Positions.Count == 0) + { +

Nessuna posizione aperta. Quando una strategia compra, qui vedi ogni posizione con il suo valore, il risultato e lo stop che la protegge.

} else { -
    - @foreach (var action in o.Last) +
    + + + + + + @foreach (var x in v.Positions) + { + var gain = x.ResultEur >= 0; + + + + + + + + } + +
    StrumentoStrategiaValoreRisultatoStop
    @x.Symbol @x.Name@StrategyNames.Label(x.Strategy)@Shell.Money(x.ValueEur, c)@Shell.Money(x.ResultEur, c, withSign: true) (@Format.Percent(x.Percent, 2, withSign: true))@if (x.Stop is { } stop) {@Format.Money(stop, x.Currency, decimals: AccountsView.StopDecimals(stop)) (@Format.Percent(x.Last == 0 ? 0 : (stop / x.Last - 1m) * 100m, 1))} else {nessuno}
    +
    +
      + @foreach (var x in v.Positions.Take(4)) { -
    • @action.When@action.Text
    • + var gain = x.ResultEur >= 0; +
    • + @x.Symbol@StrategyNames.Label(x.Strategy) + @Shell.Money(x.ValueEur, c)@Shell.Money(x.ResultEur, c, withSign: true) +
    • }
    - Tutto il diario + @(v.Positions.Count > 4 ? $"Vedi le altre {v.Positions.Count - 4}" : "Vedi i conti") + } +
+
+
+

Strategie

+ Dettaglio +
+ @if (p.Strategies.Count == 0) + { +

Le strategie compaiono quando parte il motore di trading.

+ } + else + { +
    + @foreach (var s in p.Strategies) + { +
  • +
    @s.Name@Shell.Money(s.Result, c, withSign: true)
    + + @s.Stage + @s.Trades +
  • + } +
+ } + @if (!p.AnyLive) + { +

Nessuna strategia usa soldi veri. Passano al conto reale solo dopo aver superato tutti i requisiti, e solo se lo confermi tu.

+ } +
+
+ +
+
+

Rischio

+ @(p.LimitsKept ? "Limiti rispettati" : "Da controllare") +
+
+ @foreach (var l in new[] { p.Limits[2], p.Limits[1] }) + { +
+
@l.Label@l.Value su @l.Threshold.Replace(",00%", "%", StringComparison.Ordinal)
+ + + @if (l.Worst is { } w) + { + + } + +
}
+@* News, model and system (mockup 01): sections without a frame, under a dark rule (SPEC 13.2). *@ +
+
+

Notizie che contano

Tutte
+ @if (p.News is null) + { +

La lettura delle notizie non è ancora attiva. Quando lo sarà, qui vedrai le tre che contano di più per le tue posizioni e cosa ne ho fatto.

+ } + else + { +
    + @foreach (var n in p.News) + { +
  • + @n.When, @n.About + @n.Title + @if (n.Active) {}@n.Effect +
  • + } +
+ } +
+
+

Apprendimento

Dettaglio
+ @if (p.Learning is not { } m) + { +

L'apprendimento non è ancora attivo. Quando lo sarà, il modello osserverà i segnali delle strategie e qui vedrai quanto ci azzecca, prima che possa decidere qualcosa.

+ } + else + { +

Il modello osserva e impara, ma non decide ancora.

+
+
Segnali già valutati@m.Signals su @m.Needed necessari
+ +
+
+
Previsioni azzeccate
@m.Precision% su dati mai visti
+
Ultimo addestramento
@m.Trained
+
Prossima verifica
@m.NextCheck
+
+ } +
+
+

Sistema

Dettaglio
+
    + @foreach (var part in p.System.Tiles) + { +
  • @part.Name@part.Detail
  • + } +
+
+
+ @code { private Overview _overview = null!; + private PanoramaView _panorama = null!; private string _currency = "EUR"; private string _period = "avvio"; private int? _runningDays; + private decimal? _worst; [CascadingParameter] public HttpContext? HttpContext { get; set; } @@ -118,6 +402,8 @@ var services = Host.Services!; _currency = Shell.Effective((await services.Settings.GetAsync(SettingsStore.Currency.Key, ct)).Value); _overview = await Overview.LoadAsync(services, _period, Shell.Now, Shell.Zone, ct); + _panorama = await PanoramaView.LoadAsync(Host, Shell, _overview, ct); + _worst = _panorama.Limits[1].Worst is { } share ? -share * (await Anubis.Risk.RiskSettings.LoadAsync(services.Settings, ct)).DrawdownStop : null; using var aggregates = Shell.Aggregates(); _runningDays = aggregates?.RootElement.GetProperty("giorno").GetInt32(); } @@ -135,4 +421,60 @@ : $"{o.PositionsWithoutStop} senza stop"; return o.Positions == 1 ? $"Sorveglio una posizione, {stops}. {orders}" : $"Sorveglio {o.Positions} posizioni, {stops}. {orders}"; } + + private static bool Down(AccountCard a) => a.State.LastOutcome == ReconcileOutcomes.Unreachable; + + private string AccountNote(AccountCard a, IReadOnlyList held) + { + var count = held.Count == 1 ? "1 posizione" : $"{held.Count} posizioni"; + if (held.Count == 0) + { + count = "Nessuna posizione aperta"; + } + + if (a.Broker != Venues.Alpaca) + { + var stops = held.Count(x => x.Stop is not null); + var stopText = held.Count == 0 ? "" : stops == 1 ? ", 1 stop attivo" : $", {stops} stop attivi"; + return $"{count}{stopText}. Commissioni pagate finora: {Shell.Money(a.Eur(a.Fees), _currency)}."; + } + + var fractions = held.Any(x => x.Quantity != decimal.Truncate(x.Quantity)); + var stopsText = held.Count == 0 ? "" + : " Stop permanenti sulle azioni intere" + (!fractions ? "." : _panorama.FractionStops is { } back + ? $"; sulle frazioni tornano alle {TimeZoneInfo.ConvertTime(back, Shell.Zone).ToString("HH:mm", CultureInfo.InvariantCulture)}." + : "; sulle frazioni valgono fino alla chiusura."); + var dollars = a.Currency == "USD" && a.Rate > 0m ? $" Conto in dollari: {Format.Money(a.Equity, "USD")} al cambio {Format.Quantity(a.Rate)}." : ""; + return count + "." + stopsText + dollars; + } + + private static string PartClass(PartState state) => state switch + { + PartState.Ok => "ok", + PartState.Warn => "warn", + _ => "off", + }; + + private static string PartIcon(PartState state) => state switch + { + PartState.Ok => "tick", + PartState.Warn => "alert", + _ => "clock", + }; + + private static string Css(decimal value) => Math.Round(value, 3).ToString("0.###", CultureInfo.InvariantCulture); + + private static string Spark(IReadOnlyList points) + { + var (min, max) = (points.Min(), points.Max()); + var range = Math.Max(0.01m, max - min); + return string.Join(' ', points.Select((x, i) => Css(i * 116m / (points.Count - 1) + 2m) + "," + Css(32m - (x - min) / range * 28m))); + } + + private static (string X, string Y) SparkEnd(IReadOnlyList points) + { + var (min, max) = (points.Min(), points.Max()); + var range = Math.Max(0.01m, max - min); + return ("118", Css(32m - (points[^1] - min) / range * 28m)); + } } diff --git a/src/Anubis.Server/DiaryView.cs b/src/Anubis.Server/DiaryView.cs new file mode 100644 index 0000000..5e622cb --- /dev/null +++ b/src/Anubis.Server/DiaryView.cs @@ -0,0 +1,243 @@ +using System.Globalization; +using System.Text.RegularExpressions; +using Anubis.Core; +using Anubis.Db; +using Anubis.Trading; + +namespace Anubis.Server; + +/// A piece of a diary line: plain text, or an amount coloured as a gain or a loss (always with its sign). +internal sealed record DiaryPiece(string Text, string? Class = null); + +/// +/// A diary entry as the page draws it (mockup 08): the first sentence as the main line, the rest underneath; a rule +/// the bot changed shows its lead in bold; a sale that closed a trade links to its "why". +/// +internal sealed record DiaryEntry(DateTimeOffset At, string Kind, string Icon, string? Lead, IReadOnlyList Main, string? Rest, bool Attention, string? Trade); + +internal sealed record DiaryDay(DateOnly Day, string Heading, IReadOnlyList Entries); + +/// +/// The diary of "Diario e sistema" (SPEC 13.6): in order of time, grouped by local day, with filters by kind and a +/// search. Static pages: the filters and "Mostra i giorni precedenti" are links with query values. +/// +internal sealed partial record DiaryView(IReadOnlyList Days, string Filter, string? Search, int Range, bool HasOlder, bool Truncated) +{ + /// The risk kind of the filters: not a kind of its own in the journal, but the codes of the risk engine and its relatives. + public const string RiskKind = "Rischio"; + + public const int DefaultRange = 2; + public const int MaxSearchResults = 200; + + /// The filter chips, in the order of the mockup: query value, label, kind. + public static readonly IReadOnlyList<(string Key, string Label, string? Kind)> Filters = + [ + ("tutto", "Tutto", null), + ("decisioni", "Decisioni", DiaryKinds.Decisions), + ("ordini", "Ordini", DiaryKinds.Orders), + ("notizie", "Notizie", DiaryKinds.News), + ("rischio", "Rischio", RiskKind), + ("apprendimento", "Apprendimento", DiaryKinds.Learning), + ("sistema", "Sistema", DiaryKinds.System), + ]; + + /// Journal codes that speak of risk without passing through risk_events: refused orders, keys, prudent accounts, the guard. + private static readonly string[] _riskCodes = ["order_rejected", "stop_rejected", "key_can_withdraw", "account_prudent", "guard_intervention", "clock_gap", "sell_not_filled"]; + + private const string RiskCondition = "(code IN (SELECT kind FROM risk_events) OR code IN ('order_rejected', 'stop_rejected', 'key_can_withdraw', 'account_prudent', 'guard_intervention', 'clock_gap', 'sell_not_filled'))"; + + private static readonly string[] _daysLong = ["domenica", "lunedì", "martedì", "mercoledì", "giovedì", "venerdì", "sabato"]; + private static readonly string[] _monthsLong = ["gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre"]; + private static readonly CompareInfo _compare = CultureInfo.GetCultureInfo("it-IT").CompareInfo; + + public bool IsEmpty => Days.Count == 0; + + /// The query string of this view with one value changed, for the links of the page. + public string Link(string? filter = null, int? range = null) + { + var parts = new List(); + var f = filter ?? Filter; + if (f != "tutto") + { + parts.Add("tipo=" + Uri.EscapeDataString(f)); + } + + if (!string.IsNullOrEmpty(Search)) + { + parts.Add("cerca=" + Uri.EscapeDataString(Search)); + } + + var r = range ?? Range; + if (r != DefaultRange) + { + parts.Add("giorni=" + r.ToString(CultureInfo.InvariantCulture)); + } + + return "/diario" + (parts.Count == 0 ? "" : "?" + string.Join('&', parts)); + } + + public static async Task LoadAsync(Database db, string? filter, string? search, string? days, DateTimeOffset now, TimeZoneInfo zone, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(db); + var key = Filters.Any(f => f.Key == filter) ? filter! : "tutto"; + var kind = Filters.First(f => f.Key == key).Kind; + var text = string.IsNullOrWhiteSpace(search) ? null : search.Trim(); + if (text is { Length: > 100 }) + { + text = text[..100]; + } + + var range = int.TryParse(days, NumberStyles.None, CultureInfo.InvariantCulture, out var n) ? Math.Clamp(n, 1, 3650) : DefaultRange; + var (where, parameters) = kind switch + { + null => ("1 = 1", Array.Empty<(string, object?)>()), + RiskKind => (RiskCondition, []), + _ => ("kind = @k AND NOT " + RiskCondition, new (string, object?)[] { ("k", kind) }), + }; + + var (rows, older, truncated) = await db.ReadAsync(async s => + { + const string columns = "SELECT occurred_at, kind, code, message FROM journal WHERE "; + if (text is not null) + { + // The search reads the whole diary, newest first; the comparison is done here, the same on both engines, + // ignoring case and accents. + var all = await s.QueryAsync(columns + where + " ORDER BY occurred_at DESC LIMIT 5000", Row, parameters).ConfigureAwait(false); + var found = all.Where(r => _compare.IndexOf(r.Message, text, CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace) >= 0).ToList(); + return (found.Take(MaxSearchResults).ToList(), false, found.Count > MaxSearchResults); + } + + // The range ends on the newest day that has an entry, so a quiet bot never shows an empty page. + var latest = await s.FirstOrDefaultAsync("SELECT MAX(occurred_at) AS at FROM journal WHERE " + where, r => r.MomentOrNull("at"), parameters).ConfigureAwait(false); + if (latest is null) + { + return ([], false, false); + } + + var today = LocalDay(now, zone); + var anchor = LocalDay(latest.Value, zone) is var last && last < today ? last : today; + var from = Start(anchor.AddDays(1 - range), zone); + var withFrom = parameters.Append(("from", from)).ToArray(); + var list = await s.QueryAsync(columns + where + " AND occurred_at >= @from ORDER BY occurred_at DESC LIMIT 2000", Row, withFrom).ConfigureAwait(false); + var before = await s.CountAsync("SELECT COUNT(*) FROM journal WHERE " + where + " AND occurred_at < @from", withFrom).ConfigureAwait(false); + return (list.ToList(), before > 0, list.Count >= 2000); + }, cancellationToken).ConfigureAwait(false); + + var risky = rows.Count == 0 ? new HashSet(StringComparer.Ordinal) + : (await db.ReadAsync(s => s.QueryAsync("SELECT DISTINCT kind FROM risk_events", r => r.Text("kind")), cancellationToken).ConfigureAwait(false)) + .Concat(_riskCodes).ToHashSet(StringComparer.Ordinal); + var day0 = LocalDay(now, zone); + var grouped = rows + .GroupBy(r => LocalDay(r.At, zone)) + .Select(g => new DiaryDay(g.Key, Heading(g.Key, day0), [.. g.Select(r => Entry(r.At, risky.Contains(r.Code) ? RiskKind : r.Kind, r.Code, r.Message))])) + .ToList(); + return new DiaryView(grouped, key, text, range, older, truncated); + + static (DateTimeOffset At, string Kind, string Code, string Message) Row(DbRow r) => (r.Moment("occurred_at"), r.Text("kind"), r.Text("code"), r.Text("message")); + } + + /// "Oggi, venerdì 9 ottobre", "Ieri, giovedì 8 ottobre", "Mercoledì 7 ottobre"; the year when it is not this one. + public static string Heading(DateOnly day, DateOnly today) + { + var name = $"{_daysLong[(int)day.DayOfWeek]} {day.Day.ToString(CultureInfo.InvariantCulture)} {_monthsLong[day.Month - 1]}" + + (day.Year == today.Year ? "" : " " + day.Year.ToString(CultureInfo.InvariantCulture)); + return day == today ? "Oggi, " + name : day == today.AddDays(-1) ? "Ieri, " + name : char.ToUpperInvariant(name[0]) + name[1..]; + } + + /// Splits a diary sentence the way the mockup draws it. + public static DiaryEntry Entry(DateTimeOffset at, string kind, string code, string message) + { + ArgumentNullException.ThrowIfNull(message); + // The demo's row of appendix F says in words where the link goes; the link is drawn, the words are not. + var text = DemoLink().Replace(message, "").Trim(); + string main; + string? rest = null; + string? lead = null; + var reason = text.IndexOf(" Motivo: ", StringComparison.Ordinal); + var attention = reason > 0; + if (attention) + { + // A rule changed by the bot: what it decided, in bold up to the colon, then why. + main = text[..reason]; + rest = text[(reason + 1)..]; + var colon = main.IndexOf(':', StringComparison.Ordinal); + if (colon > 0) + { + lead = main[..(colon + 1)]; + main = main[(colon + 1)..]; + } + } + else if (text.Length > 80 && SentenceEnd().Match(text) is { Success: true } end) + { + // Long entries: the first sentence on the main line, the explanation underneath. Short ones stay on one line. + main = text[..end.Index]; + rest = text[(end.Index + end.Length)..]; + } + else + { + main = text; + } + + string? trade = null; + if (kind == DiaryKinds.Orders && Sale().Match(text) is { Success: true } sale) + { + // A sale that closed a trade: its "why" is on the Operazioni page, found by the instrument. + trade = sale.Groups["symbol"].Value.Split('/')[0]; + } + + return new DiaryEntry(at, kind, IconOf(kind), lead, Pieces(main), rest, attention, trade); + } + + private static List Pieces(string text) + { + var pieces = new List(); + var position = 0; + foreach (Match m in SignedAmount().Matches(text)) + { + if (m.Index > position) + { + pieces.Add(new DiaryPiece(text[position..m.Index])); + } + + pieces.Add(new DiaryPiece(m.Value, m.Value[0] == '+' ? "gain" : "loss")); + position = m.Index + m.Length; + } + + if (position < text.Length) + { + pieces.Add(new DiaryPiece(text[position..])); + } + + return pieces; + } + + private static string IconOf(string kind) => kind switch + { + DiaryKinds.Orders => "arrows", + DiaryKinds.Decisions => "layers", + DiaryKinds.News => "news", + DiaryKinds.Learning => "network", + RiskKind => "shield", + _ => "sliders", + }; + + private static DateOnly LocalDay(DateTimeOffset moment, TimeZoneInfo zone) => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(moment, zone).DateTime); + + private static DateTimeOffset Start(DateOnly day, TimeZoneInfo zone) + { + var local = day.ToDateTime(TimeOnly.MinValue); + return new DateTimeOffset(local, zone.GetUtcOffset(local)).ToUniversalTime(); + } + + [GeneratedRegex(@"\s*\(con il collegamento ""[^""]*""\)")] + private static partial Regex DemoLink(); + + [GeneratedRegex(@"(?<=[.!?])\s+(?=[A-ZÀ-Ý0-9])")] + private static partial Regex SentenceEnd(); + + [GeneratedRegex(@"^Vendut[oaie] \S+ (?\S+) a [^:]+: [+−]")] + private static partial Regex Sale(); + + [GeneratedRegex(@"(? + { + var folder = host.Config.Data.Logs; + var day = TimeZoneInfo.ConvertTime(clock.UtcNow, shell.Zone).ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture); + return Results.File(LogArchive(folder), "application/zip", $"anubis-registri-{day}.zip"); + }); + // The external sources and the live feed: what is on, what is off and why (SPEC 4.4). api.MapGet("/data/sources", async (AnubisHost host, IClock clock, CancellationToken ct) => { @@ -219,6 +228,32 @@ internal static partial class Endpoints internal static IResult Error(int status, string code, string message) => Results.Json(new ApiError(code, message), _json, statusCode: status); + /// The daily log files (anubis-*.log) of a folder in a zip, newest first; an empty zip when there are none yet. + internal static byte[] LogArchive(string folder) + { + using var buffer = new MemoryStream(); + using (var zip = new System.IO.Compression.ZipArchive(buffer, System.IO.Compression.ZipArchiveMode.Create, leaveOpen: true)) + { + var files = Directory.Exists(folder) ? Directory.EnumerateFiles(folder, "anubis-*.log").OrderDescending(StringComparer.Ordinal).ToList() : []; + foreach (var file in files) + { + try + { + using var source = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + var entry = zip.CreateEntry(Path.GetFileName(file), System.IO.Compression.CompressionLevel.Optimal); + using var target = entry.Open(); + source.CopyTo(target); + } + catch (IOException) + { + // A file removed by the rotation in the meantime: the others still go. + } + } + } + + return buffer.ToArray(); + } + private static async ValueTask CsrfFilterAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next) { var http = context.HttpContext; diff --git a/src/Anubis.Server/Overview.cs b/src/Anubis.Server/Overview.cs index d0943f3..dbb18fc 100644 --- a/src/Anubis.Server/Overview.cs +++ b/src/Anubis.Server/Overview.cs @@ -9,7 +9,8 @@ public sealed record EquityPoint(DateTimeOffset At, DateOnly Day, decimal Equity internal sealed record PeriodResult(string Label, decimal Amount, decimal Percent); -internal sealed record NextMove(string Time, string Text); +/// A move of the bot with its time; is the account, marks an economic event. +internal sealed record NextMove(string Time, string Text, string? Where = null, bool Calendar = false); internal sealed record LastAction(string When, string Text); @@ -30,7 +31,8 @@ internal sealed record Overview( int OpenOrders, IReadOnlyList Next, IReadOnlyList Last, - bool CapitalSet = true) + bool CapitalSet = true, + DateTimeOffset? NextDecision = null) { public static readonly IReadOnlyList<(string Key, string Label)> Periods = [("avvio", "Dall'avvio"), ("30", "30 giorni"), ("7", "7 giorni"), ("oggi", "Oggi")]; @@ -52,7 +54,7 @@ internal sealed record Overview( var open = await s.CountAsync( $"SELECT COUNT(*) FROM orders o JOIN accounts a ON a.id = o.account_id WHERE a.environment IN ({mine}) " + "AND o.status IN ('created', 'submitted', 'partially_filled') AND (o.purpose IS NULL OR o.purpose <> 'stop')").ConfigureAwait(false); - var j = await s.QueryAsync("SELECT occurred_at, message FROM journal ORDER BY occurred_at DESC LIMIT 4", + var j = await s.QueryAsync("SELECT occurred_at, message FROM journal ORDER BY occurred_at DESC LIMIT 3", r => (At: r.Moment("occurred_at"), Text: r.Text("message"))).ConfigureAwait(false); var capital = await s.CountAsync("SELECT COUNT(*) FROM capital_changes").ConfigureAwait(false); return (p, held.Count, held.Count(x => x.Stop is null), open, j, capital > 0); @@ -65,14 +67,18 @@ internal sealed record Overview( .Select(g => g.Last()) .ToList(); - var next = services.Scheduler.Upcoming(5) + // The moves are the jobs that decide or send orders (SPEC 13.2), not the background work that runs every minute. + var moves = services.Scheduler.Upcoming(200).Where(u => u.IsMove).Take(5).ToList(); + var next = moves .Select(u => new NextMove(TimeZoneInfo.ConvertTime(u.DueUtc, zone).ToString("HH:mm", System.Globalization.CultureInfo.InvariantCulture), u.Description)) .ToList(); - var last = journal.Select(j => new LastAction(Format.ShortDate(j.At, now, zone), j.Text)).ToList(); + DateTimeOffset? decision = moves.Count > 0 ? moves[0].DueUtc : null; + // Today's actions show the time alone, as in the mockup: "02:06", "Ieri 21:58". + var last = journal.Select(j => new LastAction(Today(Format.ShortDate(j.At, now, zone)), j.Text)).ToList(); if (daily.Count == 0) { - return new Overview([], [], new PeriodResult("", 0, 0), default, 0, [], (int)positions, (int)withoutStop, (int)orders, next, last, capitalSet); + return new Overview([], [], new PeriodResult("", 0, 0), default, 0, [], (int)positions, (int)withoutStop, (int)orders, next, last, capitalSet, decision); } var latest = daily[^1]; @@ -104,6 +110,8 @@ internal sealed record Overview( cells.Add(new PeriodResult("Senza bot", amount, basis == 0m ? 0m : amount / basis * 100m)); } - return new Overview(daily, series, Between("", start), start.Day, start.Equity, cells, (int)positions, (int)withoutStop, (int)orders, next, last, capitalSet); + return new Overview(daily, series, Between("", start), start.Day, start.Equity, cells, (int)positions, (int)withoutStop, (int)orders, next, last, capitalSet, decision); } + + private static string Today(string shortDate) => shortDate.StartsWith("Oggi ", StringComparison.Ordinal) ? shortDate["Oggi ".Length..] : shortDate; } diff --git a/src/Anubis.Server/PanoramaView.cs b/src/Anubis.Server/PanoramaView.cs new file mode 100644 index 0000000..61b4b93 --- /dev/null +++ b/src/Anubis.Server/PanoramaView.cs @@ -0,0 +1,214 @@ +using System.Globalization; +using System.Text.Json; +using Anubis.Core; +using Anubis.Data; +using Anubis.Risk; +using Anubis.Trading; + +namespace Anubis.Server; + +/// The last 30 days of an account: the result net of flows and the daily values in euro for the small line. +internal sealed record AccountTrend(decimal Month, IReadOnlyList Points); + +/// A news item of the "Notizie che contano" tile; when its effect is still on. +internal sealed record PanoramaNews(string When, string About, string Title, string Effect, bool Active); + +/// The model at a glance: signals counted toward the 300, precision on unseen cases, training and next check. +internal sealed record PanoramaLearning(int Signals, int Needed, int Precision, string Trained, string NextCheck); + +/// One of the four limits of the Panoramica (SPEC 13.6): value, threshold, share used and, for the fall, the worst so far. +internal sealed record PanoramaLimit(string Label, string Value, string Threshold, decimal Share, decimal? Worst = null); + +/// A strategy at a glance: result, the bar against the best one, its stage in words and its trades. +internal sealed record PanoramaStrategy(string Name, string Color, decimal Result, decimal Bar, string Stage, string Trades); + +/// +/// Everything under the top block of the Panoramica (SPEC 13.6, mockup 01): accounts with their last 30 days, the +/// four main limits, positions, strategies, news, model and system. In demo mode the values of appendix F that +/// exist only as totals come from the aggregates (SPEC 13.1); outside it news and the model are not active yet. +/// +internal sealed record PanoramaView( + AccountsView Accounts, + IReadOnlyDictionary Trends, + IReadOnlyList Limits, + bool LimitsKept, + IReadOnlyList Strategies, + bool AnyLive, + SystemView System, + IReadOnlyList? DemoMoves, + IReadOnlyList? DemoLast, + string? NextDecision, + IReadOnlyList? News, + PanoramaLearning? Learning, + DateTimeOffset? FractionStops) +{ + private static readonly CultureInfo _it = CultureInfo.InvariantCulture; + + public static async Task LoadAsync(AnubisHost host, ShellData shell, Overview overview, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(host); + ArgumentNullException.ThrowIfNull(shell); + ArgumentNullException.ThrowIfNull(overview); + var services = host.Services!; + var clock = host.Clock; + var risk = await RiskView.LoadAsync(services, clock, shell.Zone, cancellationToken).ConfigureAwait(false); + var accounts = await AccountsView.LoadAsync(services, clock, shell.Zone, cancellationToken).ConfigureAwait(false); + var strategies = await StrategiesView.LoadAsync(services, clock, false, cancellationToken).ConfigureAwait(false); + var system = await SystemView.LoadAsync(host, shell, cancellationToken).ConfigureAwait(false); + var trends = await TrendsAsync(services, accounts, shell.Now, shell.Zone, cancellationToken).ConfigureAwait(false); + + // The four limits of the Panoramica, read from the same rows as the Rischio page. + var rows = risk.Rows.ToDictionary(r => r.Key); + var day = rows[RiskSettings.DailyLoss.Key]; + var invested = rows[RiskSettings.MaxInvested.Key]; + var biggest = rows[RiskSettings.MaxPosition.Key]; + var fall = risk.Risk.Measures.Drawdown; + decimal? worst = risk.Drawdown.Count > 0 ? risk.Drawdown.Min(d => d.Drawdown) : null; + var stop = risk.Limits.DrawdownStop; + var limits = new List + { + new("Perdita di oggi", day.Now, day.Threshold, day.Usage ?? 0m), + new("Calo dal massimo", Format.Percent(fall * 100m, 2), Format.Percent(-stop * 100m, 2), stop <= 0m ? 0m : Math.Clamp(-fall / stop, 0m, 1m), + worst is { } w && stop > 0m ? Math.Clamp(-w / stop, 0m, 1m) : null), + new("Capitale investito", invested.Now, invested.Threshold, invested.Usage ?? 0m), + new("Posizione più grande" + (biggest.Detail is { } symbol ? $" ({symbol.Split('/')[0]})" : ""), biggest.Now, biggest.Threshold, biggest.Usage ?? 0m), + }; + var kept = !risk.AnyBlock && risk.Rows.All(r => r.Usage is null or < 1m); + + // Strategies: the bar compares each result with the best one; the stage says what is still missing. + var best = strategies.Cards.Select(c => Math.Abs(c.ResultEur)).DefaultIfEmpty(0m).Max(); + var cards = strategies.Cards.Select(c => new PanoramaStrategy(c.Name, c.Color, c.ResultEur, best == 0m ? 0m : Math.Abs(c.ResultEur) / best, Stage(c), Trades(c))).ToList(); + var anyLive = strategies.Cards.Any(c => StrategyStages.IsLive(c.Stage.Stage)); + + // The daily stops of the fractions come back with the orders after the open (SPEC 7.2). + DateTimeOffset? fractions = accounts.MarketOpen ? null : accounts.MarketNext + (services.Trading?.Engine.Options.OrdersAfterOpen ?? new LiveEngineOptions().OrdersAfterOpen); + + using var aggregates = shell.Aggregates(); + if (aggregates is null) + { + return new PanoramaView(accounts, trends, limits, kept, cards, anyLive, system, null, null, Decision(overview.NextDecision, shell.Now, shell.Zone), null, null, fractions); + } + + var root = aggregates.RootElement; + var demo = root.GetProperty("panoramica"); + var moves = demo.GetProperty("mosse").EnumerateArray().Select(m => new NextMove(m.GetProperty("ora").GetString()!, m.GetProperty("testo").GetString()!, + m.TryGetProperty("dove", out var where) ? where.GetString() : null, m.GetProperty("calendario").GetBoolean())).ToList(); + var last = demo.GetProperty("ultime_azioni").EnumerateArray().Select(a => new LastAction(a.GetProperty("quando").GetString()!, a.GetProperty("testo").GetString()!)).ToList(); + var news = root.GetProperty("notizie").GetProperty("panoramica").EnumerateArray().Select(n => new PanoramaNews(n.GetProperty("quando").GetString()!, + n.GetProperty("riguarda").GetString()!, n.GetProperty("titolo").GetString()!, n.GetProperty("effetto").GetString()!, n.GetProperty("in_corso").GetBoolean())).ToList(); + var model = root.GetProperty("apprendimento"); + var learning = new PanoramaLearning(model.GetProperty("segnali").GetInt32(), model.GetProperty("necessari").GetInt32(), model.GetProperty("precisione_pct").GetInt32(), + model.GetProperty("ultimo_addestramento").GetString()!, model.GetProperty("prossima_verifica").GetString()!); + + // The 30-day results of appendix F.2: the generated daily series of each account only ends on its total. + var month = root.GetProperty("conti").EnumerateArray().ToDictionary(c => c.GetProperty("nome").GetString()!, + c => decimal.Parse(c.GetProperty("trenta_giorni").GetString()!, _it), StringComparer.Ordinal); + var demoTrends = accounts.Accounts.ToDictionary(a => a.Id, + a => new AccountTrend(month.GetValueOrDefault(a.Name, trends.GetValueOrDefault(a.Id)?.Month ?? 0m), trends.GetValueOrDefault(a.Id)?.Points ?? [])); + return new PanoramaView(accounts, demoTrends, limits, kept, cards, anyLive, system, moves, last, demo.GetProperty("prossima_decisione").GetString(), news, learning, fractions); + } + + private static async Task> TrendsAsync(AppServices services, AccountsView accounts, DateTimeOffset now, TimeZoneInfo zone, + CancellationToken cancellationToken) + { + var shown = accounts.Accounts.ToDictionary(a => a.Id); + var world = accounts.Accounts.Any(a => TradingEnvironments.World(a.Environment) == Worlds.Real) ? Worlds.Real : Worlds.Simulated; + var rows = await services.Db.ReadAsync(s => s.QueryAsync( + "SELECT taken_at, account_id, currency, equity, flows FROM equity_snapshots WHERE scope = 'account' AND world = @w AND taken_at >= @f ORDER BY taken_at, id", + r => (At: r.Moment("taken_at"), Account: r.IdOrNull("account_id"), Currency: r.TextOrNull("currency"), Equity: r.Money("equity"), Flows: r.MoneyOrNull("flows") ?? 0m), + ("w", world), ("f", now.AddDays(-32))), cancellationToken).ConfigureAwait(false); + var result = new Dictionary(); + foreach (var group in rows.Where(r => r.Account is { } id && shown.ContainsKey(id)).GroupBy(r => r.Account!.Value)) + { + var account = shown[group.Key]; + decimal Eur(decimal amount, string? currency) => currency == "USD" ? account.Eur(amount) : amount; + var daily = group.GroupBy(r => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(r.At, zone).DateTime)).Select(g => g.Last()).ToList(); + var latest = daily[^1]; + var latestDay = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(latest.At, zone).DateTime); + var start = daily.LastOrDefault(p => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(p.At, zone).DateTime) <= latestDay.AddDays(-30)); + start = start == default ? daily[0] : start; + var month = Eur(latest.Equity, latest.Currency) - Eur(start.Equity, start.Currency) - (Eur(latest.Flows, latest.Currency) - Eur(start.Flows, start.Currency)); + var points = daily.Where(p => p.At >= start.At).Select(p => Eur(p.Equity - p.Flows, p.Currency)).ToList(); + result[group.Key] = new AccountTrend(month, points); + } + + return result; + } + + /// Where a strategy is on its path, with the requirement that is furthest away: "In simulazione, giorno 58 di 60". + private static string Stage(StrategyCard card) + { + var stage = card.Stage.Stage; + if (stage == StrategyStages.Observation) + { + return "In osservazione"; + } + + if (stage == StrategyStages.Real) + { + return "Con soldi veri"; + } + + var where = stage == StrategyStages.Reduced ? "In reale ridotto" : "In simulazione"; + var missing = card.Requirements + .Where(r => !r.Met && r.Key is "days" or "trades") + .Select(r => (r.Key, Value: Whole(r.Value), Target: Whole(r.Target))) + .Where(r => r.Value is not null && r.Target is > 0) + .OrderBy(r => (decimal)r.Value!.Value / r.Target!.Value) + .FirstOrDefault(); + return missing.Key switch + { + "days" => $"{where}, giorno {missing.Value} di {missing.Target}", + "trades" => $"{where}, {missing.Value} operazioni su {missing.Target}", + _ => where, + }; + + static int? Whole(string text) + { + var digits = new string(text.Where(char.IsAsciiDigit).ToArray()); + return int.TryParse(digits, NumberStyles.None, _it, out var n) ? n : null; + } + } + + private static string Trades(StrategyCard card) + { + var open = card.Open.Distinct().Count(); + var positions = open switch + { + 0 => "Nessuna posizione aperta", + 1 => "1 posizione aperta", + _ => $"{open} posizioni aperte", + }; + var closed = card.Closed switch + { + 0 => "nessuna operazione chiusa", + 1 => $"1 operazione chiusa ({(card.Winners == 1 ? "in guadagno" : "in perdita")})", + _ => $"{card.Closed} operazioni chiuse ({card.Winners} in guadagno)", + }; + return positions + ", " + closed; + } + + /// "Prossima decisione tra 7 ore e 14 minuti, alle 15:35." + private static string? Decision(DateTimeOffset? due, DateTimeOffset now, TimeZoneInfo zone) + { + if (due is not { } at || at <= now) + { + return null; + } + + var wait = at - now; + var hours = (int)wait.TotalHours; + var minutes = wait.Minutes; + var span = (hours, minutes) switch + { + (0, <= 1) => "un minuto", + (0, _) => $"{minutes} minuti", + (1, 0) => "un'ora", + (_, 0) => $"{hours} ore", + (1, _) => $"un'ora e {minutes} minuti", + _ => $"{hours} ore e {minutes} minuti", + }; + var time = TimeZoneInfo.ConvertTime(at, zone).ToString("HH:mm", _it); + return wait < TimeSpan.FromHours(24) ? $"Prossima decisione tra {span}, alle {time}." : $"Prossima decisione {Format.ShortDate(at, now, zone).ToLowerInvariant()}."; + } +} diff --git a/src/Anubis.Server/SystemView.cs b/src/Anubis.Server/SystemView.cs new file mode 100644 index 0000000..01f4e81 --- /dev/null +++ b/src/Anubis.Server/SystemView.cs @@ -0,0 +1,332 @@ +using System.Diagnostics; +using System.Globalization; +using System.Text.Json; +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; +using Anubis.Platform; + +namespace Anubis.Server; + +/// How a component is doing: working, off by choice or not there yet, or in need of a look. +internal enum PartState +{ + Ok, + Off, + Warn, +} + +/// A component of the system with a line on how it is doing. +internal sealed record SystemPart(string Name, string Detail, PartState State); + +/// A resource of the computer: what is used, out of how much, as a share for the bar. +internal sealed record HostResource(string Label, string Value, string? Of, decimal Share); + +/// A job in the scheduler, with its time as people say it ("15:35", "Dom 03:00"). +internal sealed record PlannedJob(string Time, string Text); + +/// +/// The "Diario e sistema" right column and the Sistema tile of the Panoramica (SPEC 13.6, mockups 01 and 08): the +/// components with their state, the jobs in the scheduler, the resources of the computer, version and platform. +/// In demo mode the values of appendix F.10 (SPEC 13.1); otherwise the real services, process and disk. +/// +internal sealed record SystemView( + IReadOnlyList Parts, + IReadOnlyList Tiles, + IReadOnlyList Jobs, + IReadOnlyList Resources, + string Running) +{ + private static readonly CultureInfo _it = CultureInfo.InvariantCulture; + private static readonly string[] _days = ["Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab"]; + private static readonly string[] _months = ["gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre"]; + + /// Nothing needs a look; components that are off by choice or not active yet do not count. + public bool AllWell => Parts.All(p => p.State != PartState.Warn); + + public static async Task LoadAsync(AnubisHost host, ShellData shell, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(host); + ArgumentNullException.ThrowIfNull(shell); + using var aggregates = shell.Aggregates(); + return aggregates is not null ? Demo(aggregates.RootElement, shell) : await RealAsync(host, shell, cancellationToken).ConfigureAwait(false); + } + + private static SystemView Demo(JsonElement root, ShellData shell) + { + var system = root.GetProperty("sistema"); + var accounts = root.GetProperty("conti").EnumerateArray().ToList(); + var okxMs = accounts[0].GetProperty("risposta_ms").GetInt32(); + var alpacaMs = accounts[1].GetProperty("risposta_ms").GetInt32(); + var database = root.GetProperty("database").GetString()!; + var size = Format.Number(Dec(system, "database_gb"), 1) + " GB"; + var telegram = system.GetProperty("telegram_ultimo").GetString(); + var parts = new List + { + new("Motore di trading", $"attivo, un controllo ogni {system.GetProperty("controllo_secondi").GetInt32()} secondi", PartState.Ok), + new("Prezzi da OKX Europe", $"in diretta, risposta in {okxMs} ms", PartState.Ok), + new("Prezzi da Alpaca", "collegato, " + Market(shell), PartState.Ok), + new("Lettura delle notizie", $"{system.GetProperty("notizie_fonti").GetInt32()} fonti, ultima lettura alle {system.GetProperty("notizie_ultima").GetString()}", PartState.Ok), + new("Database " + database, $"{size}, ultimo salvataggio alle {system.GetProperty("ultimo_salvataggio").GetString()}", PartState.Ok), + new("Telegram", $"collegato, ultimo messaggio alle {telegram}", PartState.Ok), + }; + var tiles = new List + { + new("OKX Europe", $"connesso, {okxMs} ms", PartState.Ok), + new("Alpaca", $"connesso, {alpacaMs} ms", PartState.Ok), + new("Prezzi di mercato", $"aggiornati {root.GetProperty("dati_aggiornati_secondi").GetInt32()} s fa", PartState.Ok), + new("Notizie", $"{root.GetProperty("notizie").GetProperty("lette_24h").GetInt32()} lette in 24 ore", PartState.Ok), + new("Database", $"{database}, {size}", PartState.Ok), + new("Telegram", $"ultimo messaggio alle {telegram}", PartState.Ok), + }; + var jobs = system.GetProperty("lavori").EnumerateArray() + .Select(j => new PlannedJob(j.GetProperty("ora").GetString()!, j.GetProperty("testo").GetString()!)).ToList(); + var memory = Dec(system, "memoria_gb"); + var memoryTotal = system.GetProperty("memoria_totale_gb").GetDecimal(); + var disk = Dec(system, "disco_gb"); + var diskTotal = system.GetProperty("disco_totale_gb").GetDecimal(); + var resources = new List + { + new("Processore", system.GetProperty("cpu_pct").GetInt32().ToString(_it) + "%", null, system.GetProperty("cpu_pct").GetDecimal() / 100m), + new("Memoria", Format.Number(memory, 1) + " GB", Format.Number(memoryTotal), memory / memoryTotal), + new("Spazio per i dati", Format.Number(disk, 1) + " GB", Format.Number(diskTotal), disk / diskTotal), + }; + var started = DateOnly.ParseExact(root.GetProperty("avvio").GetString()!, "yyyy-MM-dd", _it); + var running = $"Anubis {root.GetProperty("versione").GetString()} in {root.GetProperty("piattaforma").GetString()}, acceso dal {started.Day} {_months[started.Month - 1]}: " + + $"{root.GetProperty("giorno").GetInt32()} giorni senza interruzioni."; + return new SystemView(parts, tiles, jobs, resources, running); + } + + private static async Task RealAsync(AnubisHost host, ShellData shell, CancellationToken cancellationToken) + { + var services = host.Services!; + var now = shell.Now; + var zone = shell.Zone; + var parts = new List(); + var tiles = new List(); + + // The trading engine, and the state the user chose for the bot. + var bot = (await services.Settings.GetAsync(SettingsStore.BotState.Key, cancellationToken).ConfigureAwait(false)).Value; + var trading = services.Trading; + parts.Add(trading switch + { + null => new SystemPart("Motore di trading", "spento: le strategie non lavorano", PartState.Off), + { IsStarted: false } => new SystemPart("Motore di trading", "non è ancora partito: se non parte entro qualche minuto, guarda i registri tecnici", PartState.Warn), + _ when bot == "stopped" => new SystemPart("Motore di trading", "fermo con Ferma tutto: riparte solo con la tua conferma, dalla pagina Rischio", PartState.Warn), + _ => new SystemPart("Motore di trading", + $"{(bot == "paused" ? "in pausa" : "attivo")}, un controllo ogni {(int)trading.TickInterval.TotalSeconds} secondi", PartState.Ok), + }); + + // The two price feeds: the live OKX connection, the state of the Alpaca source. + var market = services.MarketData; + var sources = market is null ? [] : await new SourceStateStore(services.Db, host.Clock).ListAsync(cancellationToken).ConfigureAwait(false); + var okx = sources.FirstOrDefault(s => s.Source == MarketDataService.OkxSource); + var (okxPart, okxTile) = market switch + { + null => (new SystemPart("Prezzi da OKX Europe", "spenti", PartState.Off), new SystemPart("OKX Europe", "spento", PartState.Off)), + { LiveConnected: true } => (new SystemPart("Prezzi da OKX Europe", "in diretta", PartState.Ok), new SystemPart("OKX Europe", "connesso", PartState.Ok)), + _ when Failing(okx) => (new SystemPart("Prezzi da OKX Europe", "non rispondono: riprovo da solo", PartState.Warn), new SystemPart("OKX Europe", "non risponde", PartState.Warn)), + _ => (new SystemPart("Prezzi da OKX Europe", "in collegamento", PartState.Off), new SystemPart("OKX Europe", "in collegamento", PartState.Off)), + }; + parts.Add(okxPart); + var alpaca = sources.FirstOrDefault(s => s.Source == MarketDataService.AlpacaSource); + var (alpacaPart, alpacaTile) = (market, alpaca) switch + { + (null, _) => (new SystemPart("Prezzi da Alpaca", "spenti", PartState.Off), new SystemPart("Alpaca", "spento", PartState.Off)), + (_, null) => (new SystemPart("Prezzi da Alpaca", "in attesa del primo collegamento", PartState.Off), new SystemPart("Alpaca", "in attesa", PartState.Off)), + (_, { Enabled: false }) => (new SystemPart("Prezzi da Alpaca", "spenti: mancano le chiavi del conto di prova, in Impostazioni", PartState.Off), + new SystemPart("Alpaca", "senza chiavi", PartState.Off)), + _ when Failing(alpaca) => (new SystemPart("Prezzi da Alpaca", "non rispondono: riprovo da solo", PartState.Warn), new SystemPart("Alpaca", "non risponde", PartState.Warn)), + _ => (new SystemPart("Prezzi da Alpaca", "collegato, " + Market(shell, market.UsCalendar), PartState.Ok), new SystemPart("Alpaca", "connesso", PartState.Ok)), + }; + parts.Add(alpacaPart); + tiles.Add(okxTile); + tiles.Add(alpacaTile); + var newest = market?.Freshness.Snapshot().Select(s => s.LastDataAt).Max(); + tiles.Add(newest is { } at + ? new SystemPart("Prezzi di mercato", "aggiornati " + Ago(now - at), now - at > TimeSpan.FromMinutes(5) ? PartState.Warn : PartState.Ok) + : new SystemPart("Prezzi di mercato", "in attesa dei primi prezzi", PartState.Off)); + + // News arrive with phase 7 (SPEC 10). + parts.Add(new SystemPart("Lettura delle notizie", "non ancora attiva", PartState.Off)); + tiles.Add(new SystemPart("Notizie", "non ancora attive", PartState.Off)); + + // The database: engine, size, last backup. + var engine = services.Db.Engine == DbEngine.Postgres ? "PostgreSQL" : "SQLite"; + var bytes = await SizeAsync(services.Db, host.Config.Db, cancellationToken).ConfigureAwait(false); + var backups = services.Backups.List(); + var lastBackup = backups.Count == 0 ? null : (DateTimeOffset?)backups.Max(b => b.TakenAt); + var size = bytes is { } b ? Bytes(b) : null; + var saved = lastBackup is { } l ? "ultimo salvataggio " + When(l, now, zone) : "nessun salvataggio ancora"; + parts.Add(new SystemPart("Database " + engine, (size is null ? "" : size + ", ") + saved, PartState.Ok)); + tiles.Add(new SystemPart("Database", engine + (size is null ? "" : ", " + size), PartState.Ok)); + + // Telegram: the last message that really left (SPEC 14), never one only queued. + var telegram = services.Telegram; + var settings = telegram is null ? null : await telegram.ReadAsync(cancellationToken).ConfigureAwait(false); + if (telegram is null || settings is null) + { + parts.Add(new SystemPart("Telegram", "non configurato: si imposta in Impostazioni", PartState.Off)); + tiles.Add(new SystemPart("Telegram", "non configurato", PartState.Off)); + } + else + { + var summary = await telegram.Sender.SummaryAsync(cancellationToken).ConfigureAwait(false); + var last = summary.LastSentAt is { } sent ? "ultimo messaggio " + When(sent, now, zone) : "nessun messaggio inviato ancora"; + var stuck = summary.Retrying + summary.GaveUp > 0; + parts.Add(new SystemPart("Telegram", stuck ? "alcuni messaggi non sono partiti: riprovo da solo; " + last : "collegato, " + last, stuck ? PartState.Warn : PartState.Ok)); + tiles.Add(new SystemPart("Telegram", last, stuck ? PartState.Warn : PartState.Ok)); + } + + // Appointments only: the jobs that run every minute or every hour are background work. + var jobs = services.Scheduler.Upcoming(200).Where(u => !u.Periodic).Take(7) + .Select(u => new PlannedJob(JobTime(u.DueUtc, now, zone), u.Description)).ToList(); + + var since = host.Status.Since; + var platform = host.Config.Platform == PlatformKind.Docker ? "in Docker" : "come applicazione desktop"; + var localSince = TimeZoneInfo.ConvertTime(since, zone); + var days = (int)Math.Floor((now - since).TotalDays); + var running = days >= 1 + ? $"Anubis {AnubisInfo.Version} {platform}, acceso dal {localSince.Day} {_months[localSince.Month - 1]}: {days} {(days == 1 ? "giorno" : "giorni")} senza interruzioni." + : $"Anubis {AnubisInfo.Version} {platform}, acceso oggi alle {localSince.ToString("HH:mm", _it)}."; + return new SystemView(parts, tiles, jobs, MeasureHost(host.Config.Data), running); + } + + private static bool Failing(SourceState? state) => + state is { LastError: not null } && (state.LastSuccessAt is null || state.LastRequestAt > state.LastSuccessAt); + + private static string Market(ShellData shell, IMarketCalendar? calendar = null) + { + var (open, next) = AccountsView.MarketState(calendar, shell.Now); + var time = TimeZoneInfo.ConvertTime(next, shell.Zone).ToString("HH:mm", _it); + return open ? "mercato aperto fino alle " + time : "mercato chiuso fino alle " + time; + } + + private static async Task SizeAsync(Database db, DbSettings? settings, CancellationToken cancellationToken) + { + try + { + if (db.Engine == DbEngine.Postgres) + { + return await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT pg_database_size(current_database()) AS n", r => (long?)r.Number("n")), cancellationToken) + .ConfigureAwait(false); + } + + if (settings?.SqlitePath is { } path && File.Exists(path)) + { + var wal = path + "-wal"; + return new FileInfo(path).Length + (File.Exists(wal) ? new FileInfo(wal).Length : 0); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.Data.Common.DbException) + { + // The size is a detail: without it the line still says engine and backups. + } + + return null; + } + + /// + /// Processor of this process (share of all cores since the last look, or since it started), its memory against + /// what the container or computer gives it, and the disk that holds the data folder. + /// + private static List MeasureHost(DataDirectory data) + { + var list = new List(); + var cpu = CpuSampler.Share(); + list.Add(new HostResource("Processore", Format.Number(cpu * 100m) + "%", null, cpu)); + + using var process = Process.GetCurrentProcess(); + var used = process.WorkingSet64; + var total = GC.GetGCMemoryInfo().TotalAvailableMemoryBytes; + if (total > 0) + { + list.Add(new HostResource("Memoria", Bytes(used), Bytes(total, unit: false), Math.Clamp((decimal)used / total, 0m, 1m))); + } + + try + { + var drive = new DriveInfo(Path.GetPathRoot(Path.GetFullPath(data.Root))!); + if (drive.IsReady && drive.TotalSize > 0) + { + var taken = drive.TotalSize - drive.AvailableFreeSpace; + list.Add(new HostResource("Spazio per i dati", Bytes(taken), Bytes(drive.TotalSize, unit: false), Math.Clamp((decimal)taken / drive.TotalSize, 0m, 1m))); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException) + { + // A disk that cannot be measured is left out rather than shown wrong. + } + + return list; + } + + /// A size as people read it: "780 MB", "1,8 GB"; without the unit for the "su 50" after the value. + public static string Bytes(long bytes, bool unit = true) + { + const decimal giga = 1024m * 1024m * 1024m; + var gb = bytes / giga; + if (!unit) + { + return Format.Number(gb, gb >= 10m ? 0 : 1); + } + + return gb >= 1m ? Format.Number(gb, 1) + " GB" : Format.Number(Math.Max(1m, bytes / (1024m * 1024m))) + " MB"; + } + + private static string When(DateTimeOffset moment, DateTimeOffset now, TimeZoneInfo zone) + { + var text = Format.ShortDate(moment, now, zone); + return text.StartsWith("Oggi ", StringComparison.Ordinal) ? "alle " + text["Oggi ".Length..] : text.StartsWith("Ieri ", StringComparison.Ordinal) ? "ieri alle " + text["Ieri ".Length..] : "del " + text; + } + + private static string Ago(TimeSpan elapsed) => elapsed.TotalSeconds < 60 ? $"{Math.Max(0, (int)elapsed.TotalSeconds)} s fa" : Format.Ago(elapsed); + + /// The time alone within a day, otherwise the day too: "15:35", "Dom 03:00". + public static string JobTime(DateTimeOffset due, DateTimeOffset now, TimeZoneInfo zone) + { + var local = TimeZoneInfo.ConvertTime(due, zone); + var time = local.ToString("HH:mm", _it); + return due - now < TimeSpan.FromHours(24) ? time : _days[(int)local.DayOfWeek] + " " + time; + } + + private static decimal Dec(JsonElement element, string name) => decimal.Parse(element.GetProperty(name).GetString()!, _it); + + /// The processor used by this process between two looks, as a share of all cores. + private static class CpuSampler + { + private static readonly Lock _gate = new(); + private static (long Ticks, TimeSpan Cpu)? _last; + + public static decimal Share() + { + using var process = Process.GetCurrentProcess(); + var cpu = process.TotalProcessorTime; + var ticks = Stopwatch.GetTimestamp(); + lock (_gate) + { + TimeSpan wall; + TimeSpan used; + if (_last is { } last && Stopwatch.GetElapsedTime(last.Ticks, ticks) >= TimeSpan.FromSeconds(1)) + { + wall = Stopwatch.GetElapsedTime(last.Ticks, ticks); + used = cpu - last.Cpu; + } + else + { + // First look, or two looks too close together: the average since the process started. + wall = Uptime(process); + used = cpu; + } + + _last = (ticks, cpu); + var share = wall <= TimeSpan.Zero ? 0d : used.TotalMilliseconds / (wall.TotalMilliseconds * Environment.ProcessorCount); + return Math.Clamp((decimal)share, 0m, 1m); + } + } + + // A measure of the process, not a business time: the system clock against the process's own start, since the + // injected clock may stand still (demo) or run in another world (tests). + private static TimeSpan Uptime(Process process) => DateTime.UtcNow - process.StartTime.ToUniversalTime(); + } +} diff --git a/src/Anubis/Core/Scheduling.cs b/src/Anubis/Core/Scheduling.cs index c927fb9..1c8bdcb 100644 --- a/src/Anubis/Core/Scheduling.cs +++ b/src/Anubis/Core/Scheduling.cs @@ -149,6 +149,9 @@ public sealed record JobRun(string Name, DateTimeOffset DueUtc, DateTimeOffset S public sealed record UpcomingRun(string Name, string Description, DateTimeOffset DueUtc) { public bool IsMove { get; init; } + + /// A job that comes back at a fixed interval (every minute, every hour): background work, not an appointment. + public bool Periodic { get; init; } } /// @@ -221,7 +224,7 @@ public sealed partial class Scheduler(IClock clock, EventBus bus, ILogger j.Due is not null) .OrderBy(j => j.Due) .Take(count) - .Select(j => new UpcomingRun(j.Job.Name, j.Job.Description, j.Due!.Value) { IsMove = j.Job.IsMove }) + .Select(j => new UpcomingRun(j.Job.Name, j.Job.Description, j.Due!.Value) { IsMove = j.Job.IsMove, Periodic = j.Job.Schedule is IntervalSchedule }) .ToList(); } } diff --git a/src/Anubis/Demo/Data/aggregates.json b/src/Anubis/Demo/Data/aggregates.json index 9e0650b..e7b2527 100644 --- a/src/Anubis/Demo/Data/aggregates.json +++ b/src/Anubis/Demo/Data/aggregates.json @@ -50,10 +50,45 @@ { "nome": "equity_meanrev", "etichetta": "Mean reversion azioni USA", "conto": "Alpaca", "giorno": 58, "di": 60, "quota_pct": 15, "capitale": "1500", "risultato": "11.36", "risultato_pct": "0.76", "calo_peggiore_pct": "-1.1", "chiuse": 21, "in_guadagno": 10 } ], "operazioni": { "chiuse": 41, "in_guadagno": 22, "guadagno_medio": "28.42", "perdita_media": "-20.31", "rapporto": "1.62", "incassati": "239.28", "commissioni": "14.82" }, - "notizie": { "lette_24h": 312, "sulle_posizioni": 9, "con_effetto": 2, "spesa_oggi": "0.04", "tetto": "0.50" }, - "apprendimento": { "stato": "observation", "segnali": 212, "necessari": 300, "precisione_pct": 56 }, + "notizie": { + "lette_24h": 312, "sulle_posizioni": 9, "con_effetto": 2, "spesa_oggi": "0.04", "tetto": "0.50", + "panoramica": [ + { "quando": "06:10", "riguarda": "su SOL", "titolo": "Rinviato di una settimana l'aggiornamento della rete Solana", "effetto": "Negativa: per 24 ore non aumento SOL", "in_corso": true }, + { "quando": "Ieri 22:41", "riguarda": "su JPM", "titolo": "JPMorgan pubblica i conti martedì prima dell'apertura", "effetto": "Evento in arrivo: niente mean reversion su JPM fino a martedì", "in_corso": true }, + { "quando": "07:52", "riguarda": "sul mercato in generale", "titolo": "I verbali della banca centrale USA non cambiano le attese sui tassi", "effetto": "Nessun effetto: non cambio nulla", "in_corso": false } + ] + }, + "panoramica": { + "prossima_decisione": "Prossima decisione tra 7 ore e 14 minuti, all'apertura di Wall Street.", + "mosse": [ + { "ora": "15:35", "testo": "Rimetto gli stop del giorno sulle frazioni di 6 azioni", "dove": "Alpaca", "calendario": false }, + { "ora": "16:00", "testo": "Esce la fiducia dei consumatori USA: impatto medio, non blocco gli ingressi", "calendario": true }, + { "ora": "21:55", "testo": "Controllo AAPL: vendo se è sopra la media a 5 giorni", "calendario": false }, + { "ora": "22:20", "testo": "Wall Street ha chiuso: calcolo i segnali sulle azioni", "calendario": false }, + { "ora": "02:05", "testo": "Chiusura giornaliera crypto: ricalcolo i trend di 10 monete", "calendario": false } + ], + "ultime_azioni": [ + { "quando": "02:06", "testo": "Alzato lo stop di BTC a 66.180 € (era 65.400 €)" }, + { "quando": "Ieri 21:58", "testo": "Venduto MSFT: +9,84 $ in 3 giorni" }, + { "quando": "Ieri 15:36", "testo": "Comprate 2 AAPL a 259,80 $" } + ] + }, + "apprendimento": { + "stato": "observation", "segnali": 212, "necessari": 300, "precisione_pct": 56, + "ultimo_addestramento": "domenica 4 ottobre", "prossima_verifica": "domenica 11 ottobre, 03:00" + }, "sistema": { "controllo_secondi": 5, "notizie_fonti": 16, "database_gb": "1.8", "ultimo_salvataggio": "03:30", "telegram_ultimo": "08:00", - "cpu_pct": 6, "memoria_gb": "1.1", "memoria_totale_gb": 4, "disco_gb": "2.3", "disco_totale_gb": 50 + "cpu_pct": 6, "memoria_gb": "1.1", "memoria_totale_gb": 4, "disco_gb": "2.3", "disco_totale_gb": 50, + "notizie_ultima": "08:20", + "lavori": [ + { "ora": "15:35", "testo": "Stop del giorno sulle azioni" }, + { "ora": "21:55", "testo": "Uscite della mean reversion" }, + { "ora": "22:20", "testo": "Segnali sulle azioni" }, + { "ora": "02:05", "testo": "Segnali sulle crypto" }, + { "ora": "03:00", "testo": "Controllo del modello" }, + { "ora": "03:30", "testo": "Salvataggio del database" }, + { "ora": "Dom 03:00", "testo": "Verifica settimanale del modello" } + ] } } diff --git a/tests/Anubis.Tests/OverviewScreenTests.cs b/tests/Anubis.Tests/OverviewScreenTests.cs new file mode 100644 index 0000000..035fb36 --- /dev/null +++ b/tests/Anubis.Tests/OverviewScreenTests.cs @@ -0,0 +1,162 @@ +using System.IO.Compression; +using System.Net; +using Anubis.Server; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// The Panoramica and "Diario e sistema" screens (issue #51, mockups 01, 08 and 09). +[TestClass] +public sealed class OverviewScreenTests +{ + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheDemoPanoramicaShowsAccountsPositionsAndLimits() + { + var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]); + var demoRoot = server.Host.Config.Data.Root; + try + { + var page = await server.TextAsync("/"); + foreach (var text in new[] + { + // Adesso e dopo (F.10). + "Prossima decisione tra 7 ore e 14 minuti, all'apertura di Wall Street.", "Rimetto gli stop del giorno sulle frazioni di 6 azioni", + "Alzato lo stop di BTC a 66.180", "Apri il diario completo", "Tutte le mosse e il diario", + // The two accounts with their last 30 days (F.2). + "4.231,60", "+231,60", "2.326,50", "1.905,10", "+158,20", "3 posizioni, 3 stop attivi.", + "6.180,86", "4.344,63", "1.836,23", "+93,50", "sulle frazioni tornano alle 15:35", + // The four limits (F.10). + "Tutti i limiti rispettati", "Perdita di oggi", "nessuna", "−2,00%", "Calo dal massimo", "−15,00%", "Capitale investito", "64,1%", + "Posizione più grande (BTC)", "12,5%", "La tacca segna il calo peggiore finora: −2,82%.", "Vedi tutti i limiti", + // Positions by value, strategies, news, model, system. + "BTC/EUR", "1.299,84", "66.180", "(−7,3%)", "Vedi le altre 6", + "In simulazione, giorno 58 di 60", "In simulazione, 21 operazioni su 30", "1 posizione aperta, 21 operazioni chiuse (10 in guadagno)", + "Nessuna strategia usa soldi veri.", + "Rinviato di una settimana l'aggiornamento della rete Solana", "Negativa: per 24 ore non aumento SOL", + "Il modello osserva e impara, ma non decide ancora.", "domenica 11 ottobre, 03:00", + "connesso, 84 ms", "PostgreSQL, 1,8 GB", "ultimo messaggio alle 08:00", + }) + { + StringAssert.Contains(page, text, $"Missing «{text}» on the Panoramica."); + } + + Assert.IsLessThan(page.IndexOf("ETH/EUR", StringComparison.Ordinal), page.IndexOf("BTC/EUR", StringComparison.Ordinal), "Positions in order of value."); + } + finally + { + await server.DisposeAsync(); + TempFolder.Delete(demoRoot); + } + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheDiaryFiltersAndSearches() + { + var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]); + var demoRoot = server.Host.Config.Data.Root; + try + { + var all = await server.TextAsync("/diario"); + StringAssert.Contains(all, "Oggi, venerdì 9 ottobre"); + StringAssert.Contains(all, "Ieri, giovedì 8 ottobre"); + StringAssert.Contains(all, "Ho cambiato una regola per 24 ore:"); + StringAssert.Contains(all, "Motivo: l'aggiornamento della rete Solana è stato rinviato di una settimana."); + StringAssert.Contains(all, "href=\"/operazioni?cerca=MSFT\""); + StringAssert.Contains(all, "Perché l'ho comprata e venduta"); + Assert.IsFalse(all.Contains("(con il collegamento", StringComparison.Ordinal), "The demo's note on the link is not shown."); + StringAssert.Contains(all, "Tutto regolare"); + StringAssert.Contains(all, "collegato, mercato chiuso fino alle 15:30"); + StringAssert.Contains(all, "Dom 03:00"); + StringAssert.Contains(all, "Anubis 0.9.2 in Docker, acceso dal 12 agosto: 58 giorni senza interruzioni."); + + // A kind at a time. + var orders = await server.TextAsync("/diario?tipo=ordini"); + StringAssert.Contains(orders, "Alzato lo stop di BTC/EUR"); + Assert.IsFalse(orders.Contains("Inviato il riepilogo del mattino", StringComparison.Ordinal)); + Assert.IsFalse(orders.Contains("Controllo del modello: nessuna anomalia.", StringComparison.Ordinal)); + StringAssert.Contains(await server.TextAsync("/diario?tipo=rischio"), "Nessuna voce di questo tipo finora."); + + // The search ignores case and accents, and keeps the kind chosen. + var search = await server.TextAsync("/diario?cerca=MARTEDI"); + StringAssert.Contains(search, "Ho messo una restrizione fino a martedì:"); + Assert.IsFalse(search.Contains("Alzato lo stop", StringComparison.Ordinal)); + StringAssert.Contains(search, "Una voce con «MARTEDI»"); + var none = await server.TextAsync("/diario?tipo=ordini&cerca=solana"); + StringAssert.Contains(none, "Nessuna voce con «solana»"); + } + finally + { + await server.DisposeAsync(); + TempFolder.Delete(demoRoot); + } + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheLogsDownloadNeedsASessionAndIsAZip() + { + await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite()); + var logs = server.Host.Config.Data.Logs; + Directory.CreateDirectory(logs); + await File.WriteAllTextAsync(Path.Combine(logs, "anubis-2099-01-01.log"), "{\"message\":\"una riga\"}\n"); + await File.WriteAllTextAsync(Path.Combine(logs, "altro.txt"), "non è un registro"); + + using (var anonymous = await server.GetAsync("/api/registri.zip")) + { + Assert.AreEqual(HttpStatusCode.Unauthorized, anonymous.StatusCode); + } + + await server.SignInFirstTimeAsync(); + using (var zip = await server.GetAsync("/api/registri.zip")) + { + Assert.AreEqual(HttpStatusCode.OK, zip.StatusCode); + Assert.AreEqual("application/zip", zip.Content.Headers.ContentType?.MediaType); + await using var stream = await zip.Content.ReadAsStreamAsync(); + using var archive = new ZipArchive(stream, ZipArchiveMode.Read); + var names = archive.Entries.Select(e => e.Name).ToList(); + Assert.Contains("anubis-2099-01-01.log", names); + Assert.DoesNotContain("altro.txt", names); + using var reader = new StreamReader(archive.GetEntry("anubis-2099-01-01.log")!.Open()); + StringAssert.Contains(await reader.ReadToEndAsync(), "una riga"); + } + + // A new installation: the screens say what is missing instead of showing numbers. + var home = await server.TextAsync("/"); + StringAssert.Contains(home, "La lettura delle notizie non è ancora attiva."); + StringAssert.Contains(home, "L'apprendimento non è ancora attivo."); + var diary = await server.TextAsync("/diario"); + StringAssert.Contains(diary, "Come sta il sistema"); + StringAssert.Contains(diary, "non configurato"); + StringAssert.Contains(diary, "Il computer che lo ospita"); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void DiaryEntriesAreSplitAsTheMockupDraws() + { + var at = DateTimeOffset.UnixEpoch; + var rule = DiaryView.Entry(at, DiaryKinds.News, "demo", "Ho cambiato una regola per 24 ore: non aumento la posizione su SOL. Motivo: la rete è ferma."); + Assert.AreEqual("Ho cambiato una regola per 24 ore:", rule.Lead); + Assert.AreEqual("Motivo: la rete è ferma.", rule.Rest); + Assert.IsTrue(rule.Attention); + + var long1 = DiaryView.Entry(at, DiaryKinds.Orders, "stop_moved", "Alzato lo stop di BTC/EUR da 65.400 € a 66.180 €. Lo stop segue il prezzo quando sale."); + Assert.AreEqual("Alzato lo stop di BTC/EUR da 65.400 € a 66.180 €.", string.Concat(long1.Main.Select(p => p.Text))); + Assert.AreEqual("Lo stop segue il prezzo quando sale.", long1.Rest); + Assert.IsNull(long1.Trade); + + var shortOne = DiaryView.Entry(at, DiaryKinds.News, "demo", "Voce non confermata su un exchange. Nessuna azione: ricontrollo tra 2 ore."); + Assert.IsNull(shortOne.Rest, "A short entry stays on one line."); + + var sale = DiaryView.Entry(at, DiaryKinds.Orders, "fill", "Venduta 1 MSFT a 522,14 $: +9,84 $ in 3 giorni."); + Assert.AreEqual("MSFT", sale.Trade); + Assert.AreEqual("gain", sale.Main.Single(p => p.Class is not null).Class); + Assert.AreEqual("ETH", DiaryView.Entry(at, DiaryKinds.Orders, "fill", "Venduto 0,1 ETH/EUR a 2.500 €: −12,00 € in 4 giorni.").Trade); + Assert.IsNull(DiaryView.Entry(at, DiaryKinds.Orders, "fill", "Comprate 2 AAPL a 259,80 $.").Trade, "A purchase has no closed trade to explain."); + + Assert.AreEqual("Oggi, venerdì 9 ottobre", DiaryView.Heading(new DateOnly(2026, 10, 9), new DateOnly(2026, 10, 9))); + Assert.AreEqual("Mercoledì 7 ottobre", DiaryView.Heading(new DateOnly(2026, 10, 7), new DateOnly(2026, 10, 9))); + } +} From 9ae107000bb670d9d45d33a77e34bd6f312198f8 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 11 Nov 2026 20:34:25 +0100 Subject: [PATCH 07/12] Ignore late messages from a replaced engine; list only moves in the morning summary (refs #48 #52) The guard drill failed once under load. The pipe of the killed engine delivered a late "running" beat after the restart. The drill took the new engine as ready and stopped it before it had cancelled the half-done sale and put the stop back. The same late message could have made a crash of the new engine look like a planned stop, which the guard never restarts. Each engine the guard starts now has a number, and messages from a replaced one are ignored. The drill also waits until the restart's work is in the database before it checks. The morning Telegram summary listed every job due today, including the background ones that run every minute. It now lists only the bot's moves. Co-Authored-By: Claude Opus 5.5 --- src/Anubis.Server/TelegramDesk.cs | 4 ++-- src/Anubis/Supervision/GuardDrill.cs | 31 ++++++++++++++++++++++++++++ src/Anubis/Supervision/Guardian.cs | 29 ++++++++++++++++++++++++-- tests/Anubis.Tests/GuardTests.cs | 11 ++++++++++ 4 files changed, 71 insertions(+), 4 deletions(-) diff --git a/src/Anubis.Server/TelegramDesk.cs b/src/Anubis.Server/TelegramDesk.cs index e223d08..36bfbfd 100644 --- a/src/Anubis.Server/TelegramDesk.cs +++ b/src/Anubis.Server/TelegramDesk.cs @@ -140,8 +140,8 @@ internal sealed class TelegramDesk(AnubisHost host) : ITelegramDesk text.AppendLine(Positions(overview.Positions, overview.PositionsWithoutStop)); var local = TimeZoneInfo.ConvertTime(now, Zone).Date; - var today = overview.Next.Count == 0 ? [] : services.Scheduler.Upcoming(20) - .Where(u => TimeZoneInfo.ConvertTime(u.DueUtc, Zone).Date == local) + var today = overview.Next.Count == 0 ? [] : services.Scheduler.Upcoming(200) + .Where(u => u.IsMove && TimeZoneInfo.ConvertTime(u.DueUtc, Zone).Date == local) .Select(u => TimeZoneInfo.ConvertTime(u.DueUtc, Zone).ToString("HH:mm", System.Globalization.CultureInfo.InvariantCulture) + " " + u.Description) .ToList(); if (today.Count > 0) diff --git a/src/Anubis/Supervision/GuardDrill.cs b/src/Anubis/Supervision/GuardDrill.cs index 433ccbe..33fd486 100644 --- a/src/Anubis/Supervision/GuardDrill.cs +++ b/src/Anubis/Supervision/GuardDrill.cs @@ -93,6 +93,15 @@ public static class GuardDrill var intervened = await WaitAsync(() => guardian.Interventions > 0, options.Silence + TimeSpan.FromMinutes(3), cancellationToken).ConfigureAwait(false); var restarted = intervened && await WaitAsync(() => guardian.EngineAlive && guardian.Stage == GuardStages.Running, TimeSpan.FromMinutes(3), cancellationToken) .ConfigureAwait(false); + + // "Running" comes as soon as the scheduler starts: the restart's own work (adopting the stop, cancelling the sale + // left halfway, planning it again) may take a few more seconds on a busy machine. + if (restarted) + { + var noted = guardian.Notes; + await WaitForRepairAsync(data, noted.Count > 0 ? noted[0].At : DateTimeOffset.MinValue, TimeSpan.FromMinutes(2), cancellationToken).ConfigureAwait(false); + } + await stop.CancelAsync().ConfigureAwait(false); var code = await guarding.ConfigureAwait(false); Say($"Motore fermato in ordine alla fine dell'esercitazione (codice {code})."); @@ -122,6 +131,28 @@ public static class GuardDrill return new DrillResult(passed, lines); } + private static async Task WaitForRepairAsync(DataDirectory data, DateTimeOffset intervention, TimeSpan timeout, CancellationToken cancellationToken) + { + var until = SystemClock.Instance.UtcNow + timeout; + await using var db = Database.Open(new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = data.SqliteFile }, allowCreate: false); + while (SystemClock.Instance.UtcNow < until) + { + var done = await db.ReadAsync(async s => + await s.CountAsync("SELECT COUNT(*) FROM executions WHERE side = 'sell' AND purpose = 'exit' AND status = 'canceled' AND reason = @r", + ("r", LiveReasons.Restart)).ConfigureAwait(false) > 0 + && await s.CountAsync("SELECT COUNT(*) FROM planned_orders WHERE side = 'sell'").ConfigureAwait(false) > 1 + && await s.CountAsync("SELECT COUNT(*) FROM journal WHERE code = 'guard_intervention'").ConfigureAwait(false) > 0 + && await s.CountAsync("SELECT COUNT(*) FROM orders WHERE purpose = 'stop' AND created_at > @t", ("t", intervention)).ConfigureAwait(false) > 0, + cancellationToken).ConfigureAwait(false); + if (done) + { + return; + } + + await Task.Delay(TimeSpan.FromMilliseconds(500), cancellationToken).ConfigureAwait(false); + } + } + private static bool Check(bool ok, string yes, string no, Action say) { say((ok ? "OK " : "NO ") + (ok ? yes : no)); diff --git a/src/Anubis/Supervision/Guardian.cs b/src/Anubis/Supervision/Guardian.cs index 43fea09..47b4710 100644 --- a/src/Anubis/Supervision/Guardian.cs +++ b/src/Anubis/Supervision/Guardian.cs @@ -68,6 +68,9 @@ public sealed partial class Guardian(GuardPaths paths, IClock clock, GuardOption private DateTimeOffset _lastBeat; private DateTimeOffset _stepSince; private bool _announced; + + /// Which engine is the current one: a late message from an engine already replaced is ignored. + private int _generation; private IReadOnlyList _keys = []; private DateTimeOffset _lastRound; private DateTimeOffset? _downSince; @@ -100,13 +103,33 @@ public sealed partial class Guardian(GuardPaths paths, IClock clock, GuardOption /// Starts the engine; only for the drill. public void Start(bool fault = false) => StartEngine(fault); - /// A message from the engine. + /// A message from the current engine. public void Receive(GuardMessage message) + { + int current; + lock (_gate) + { + current = _generation; + } + + Receive(current, message); + } + + /// + /// A message from engine number . The pipe of a stopped engine can still deliver what it + /// had sent: a "running" beat would make the new engine look ready, a "stopping" would make its crash look planned. + /// + private void Receive(int generation, GuardMessage message) { ArgumentNullException.ThrowIfNull(message); var now = clock.UtcNow; lock (_gate) { + if (generation != _generation) + { + return; + } + switch (message.Type) { case GuardMessageTypes.Beat: @@ -283,8 +306,10 @@ public sealed partial class Guardian(GuardPaths paths, IClock clock, GuardOption { _engine?.Dispose(); var now = clock.UtcNow; + int generation; lock (_gate) { + generation = ++_generation; _stage = GuardStages.Starting; _step = null; _lastBeat = now; @@ -293,7 +318,7 @@ public sealed partial class Guardian(GuardPaths paths, IClock clock, GuardOption } _lastRound = now; - _engine = start(new EngineStart(fault, Receive)); + _engine = start(new EngineStart(fault, message => Receive(generation, message))); LogStarted(logger, fault); } diff --git a/tests/Anubis.Tests/GuardTests.cs b/tests/Anubis.Tests/GuardTests.cs index 036cb29..f7ecb2c 100644 --- a/tests/Anubis.Tests/GuardTests.cs +++ b/tests/Anubis.Tests/GuardTests.cs @@ -36,6 +36,17 @@ public sealed class GuardTests Assert.AreEqual(GuardNote.Silence, note.Reason); Assert.Contains("Non ho trovato il file di stato", string.Join(" ", note.Lines)); Assert.IsFalse(File.Exists(g.Paths.StopFile)); + + // What the stopped engine's pipe still delivers is not about the new one: it is not "running", and its crash + // is not a planned stop. + g.Engines[0].Beat(GuardStages.Running); + g.Engines[0].Start.OnMessage(new GuardMessage(GuardMessageTypes.Stopping) { Reason = "uscita" }); + Assert.AreEqual(GuardStages.Starting, g.Guardian.Stage); + g.Engine.Beat(GuardStages.Running); + Assert.AreEqual(GuardStages.Running, g.Guardian.Stage); + g.Engine.Exit(1); + await g.PassAsync(TimeSpan.FromSeconds(30)).ConfigureAwait(false); + Assert.HasCount(3, g.Engines, "An exit without notice is restarted, whatever the old engine said."); } [TestMethod] From 3d174931e9535e8ec7ffa93ad1a6f4cb67ff79b5 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 11 Nov 2026 20:36:22 +0100 Subject: [PATCH 08/12] Add the endurance run report and record the Phase 6 choices (refs #53 #54) "anubis soak" reads the bot's records over a time window and says whether the run kept control. It changes nothing, so it can run beside the working bot with docker exec. It exits with 4 when something needs a look. It checks: - the hours covered and silences longer than 15 minutes; - orders or decisions made twice; - unexplained reconciliation differences and each account's last outcome; - absences and guard interventions; - one crypto decision per daily close. ADR 0012 records what the specification leaves open in this phase: the live engine shares the backtest's decision call, run keys, recovery after an absence, the guard and its drill seams, the diary templates, the "senza bot" comparison, Telegram and the heartbeat, the screens and the endurance run. ROADMAP ticks the Phase 6 items and criteria with the tests that prove them, STATE moves on to Phase 7, and SVILUPPO explains the guard and the report. Co-Authored-By: Claude Opus 5.5 --- docs/ROADMAP.md | 26 ++-- docs/STATE.md | 24 ++- docs/SVILUPPO.md | 11 ++ docs/adr/0012-scelte-fase-6.md | 130 ++++++++++++++++ src/Anubis.Server/Program.cs | 6 + src/Anubis.Server/SoakCommand.cs | 77 ++++++++++ src/Anubis/Supervision/SoakReport.cs | 209 ++++++++++++++++++++++++++ tests/Anubis.Tests/SoakReportTests.cs | 85 +++++++++++ 8 files changed, 549 insertions(+), 19 deletions(-) create mode 100644 docs/adr/0012-scelte-fase-6.md create mode 100644 src/Anubis.Server/SoakCommand.cs create mode 100644 src/Anubis/Supervision/SoakReport.cs create mode 100644 tests/Anubis.Tests/SoakReportTests.cs diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index f43a54c..a05974e 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -13,9 +13,9 @@ aperta la fase. Se questo file e Gitea divergono, vale Gitea e si corregge quest | 1 | [Fondamenta](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/28) | Completata | | 2 | [Dati di mercato](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/29) | Completata (azioni in attesa delle chiavi Alpaca) | | 3 | [Conti, ordini, contabilità](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/30) | Completata (conti di prova in attesa delle chiavi) | -| 4 | [Backtest e laboratorio](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/31) | Da fare | -| 5 | [Strategie, portafoglio, rischio](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/32) | Da fare | -| 6 | [Motore dal vivo in simulazione](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/33) | Da fare | +| 4 | [Backtest e laboratorio](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/31) | Completata | +| 5 | [Strategie, portafoglio, rischio](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/32) | Completata (`crypto_trend` non superato, azionarie in attesa delle chiavi Alpaca) | +| 6 | [Motore dal vivo in simulazione](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/33) | Completata (prova di 48 ore in corso) | | 7 | [Notizie](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/34) | Da fare | | 8 | [Apprendimento](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/35) | Da fare | | 9 | [Rifinitura e consegna in Docker](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/36) | Da fare | @@ -184,25 +184,25 @@ Il bot che lavora da solo, in simulazione, giorno e notte, e lo racconta. **Lavori** -- [ ] [#47](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/47) Orchestrazione della giornata (5.5) e motore dal vivo in simulazione -- [ ] [#48](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/48) Processo di guardia, avvio e ripartenza sicuri -- [ ] [#49](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/49) Recupero dopo un'assenza (5.6) -- [ ] [#50](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/50) Diario con frasi in italiano dai codici motivo e confronto "senza bot" +- [x] [#47](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/47) Orchestrazione della giornata (5.5) e motore dal vivo in simulazione +- [x] [#48](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/48) Processo di guardia, avvio e ripartenza sicuri +- [x] [#49](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/49) Recupero dopo un'assenza (5.6) +- [x] [#50](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/50) Diario con frasi in italiano dai codici motivo e confronto "senza bot" - [ ] [#51](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/51) Schermate Panoramica e Diario e sistema -- [ ] [#52](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/52) Telegram e segnale di vita +- [x] [#52](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/52) Telegram e segnale di vita - [ ] [#53](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/53) Prova di durata di 48 ore in tempo reale - [ ] [#54](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/54) Chiusura della fase, revisione indipendente e tag `fase-6` **Criteri di accettazione** -- [ ] Il test di parità tra backtest e motore in simulazione passa, con correttivi e rischio attivi -- [ ] Una prova accelerata con orologio simulato copre almeno 10 giorni di mercato con guasti iniettati e termina con registro e conti riconciliati e senza ordini duplicati -- [ ] Un test blocca il ciclo principale con una vendita a metà e verifica che dopo la guardia la posizione abbia di nuovo i suoi stop e il motore sia ripartito; la stessa prova passa dentro l'immagine Docker -- [ ] Un test con orologio simulato spegne il bot per 3 ore, 20 ore e 3 giorni e verifica le righe di 5.6 i cui lavori esistono +- [x] Il test di parità tra backtest e motore in simulazione passa, con correttivi e rischio attivi (`TheLiveEngineMakesTheSameTradesAsTheBacktest` su 40 giorni di `crypto_trend`, `TheStockSideMakesTheSameTradesAsTheBacktest` su 6 settimane di `equity_meanrev`) +- [x] Una prova accelerata con orologio simulato copre almeno 10 giorni di mercato con guasti iniettati e termina con registro e conti riconciliati e senza ordini duplicati (`TenDaysWithFaultsEndReconciledWithoutDuplicateOrders`: 14 giorni con rete giù, risposta persa, ripartenza con un ordine a metà e database irraggiungibile, su SQLite e PostgreSQL) +- [x] Un test blocca il ciclo principale con una vendita a metà e verifica che dopo la guardia la posizione abbia di nuovo i suoi stop e il motore sia ripartito; la stessa prova passa dentro l'immagine Docker (`ALoopBlockedWithASaleHalfwayGetsItsStopBackAndTheEngineRestarts`, `TheGuardDrillPassesWithTheRealEngineAsChildProcess`; `docker run --rm drill` in `tasks ci` e nella CI: 7 controlli su 7) +- [x] Un test con orologio simulato spegne il bot per 3 ore, 20 ore e 3 giorni e verifica le righe di 5.6 i cui lavori esistono (`ThreeHoursOffRecoverTheCryptoDecisionAndDropAnEntryThatMovedTooFar`, `TwentyHoursOffLetTheLateDecisionsUpdateOnlyExitsAndDropExpiredEntries`, `ThreeDaysOffAreDeclaredUntilSeenAndMissedRunsAreMadeOnce`) - [ ] A fine fase parte una prova di durata in tempo reale di almeno 48 ore a cavallo di due sedute USA (solo crypto senza chiavi Alpaca) - [ ] In modalità dimostrativa la Panoramica corrisponde agli screen 01 (1440 px) e 09 (390 px) - [ ] Il Diario corrisponde allo screen 08 a 1440 px e a 390 px non scorre in orizzontale -- [ ] I comandi Telegram funzionano (o, senza token, superano i test con un finto server) +- [x] I comandi Telegram funzionano (o, senza token, superano i test con un finto server) — senza token, con un finto server: `TheCommandsWorkFromThePhoneThroughTheRealServer`, `FermaWantsAConfirmationWithinTwoMinutes`, `OnlyTheChatOfTheSettingsIsObeyedAndOldMessagesAreNot` e gli altri di `TelegramTests` ## Fase 7 — Notizie diff --git a/docs/STATE.md b/docs/STATE.md index 97e78b9..e9db65a 100644 --- a/docs/STATE.md +++ b/docs/STATE.md @@ -4,7 +4,7 @@ Aggiornato: 2026-11-11 ## Fase corrente -**Fase 5 — Strategie, portafoglio, rischio: completata.** La prossima è la Fase 6 (Motore dal vivo in simulazione), da iniziare con il via dell'utente. Nessuna delle tre strategie è ancora in simulazione: `crypto_trend` non ha superato il backtest e le due azionarie aspettano le chiavi di Alpaca. Restano in attesa delle chiavi demo di OKX e di Alpaca anche le prove sui conti di prova (Fase 3) e lo storico azionario (Fase 2). +**Fase 6 — Motore dal vivo in simulazione: completata.** La prova di durata di 48 ore è partita a fine fase sull'immagine Docker di questo PC (solo crypto, senza chiavi); il suo rapporto si controlla come primo passo della Fase 7 (Notizie), da iniziare con il via dell'utente. Nessuna strategia manda ordini: `crypto_trend` non ha superato il backtest e decide solo in osservazione, le due azionarie aspettano le chiavi di Alpaca. ## Fatto @@ -77,6 +77,14 @@ Aggiornato: 2026-11-11 - Stadi verso i soldi veri: osservazione, simulazione, reale ridotto, reale. Senza la procedura di 12.4 nessun ordine raggiunge un conto reale; una strategia retrocessa gestisce le uscite delle posizioni reali fino a zero; il gemello simulato resta fuori dai totali. In simulazione entra solo una strategia che ha superato il backtest. - Backtest onesti in `docs/backtests/` con `anubis backtest base`: storico Binance convertito in euro con il cambio BCE, monete tolte dal listino comprese, due universi, costi doppi e tripli, comprare e tenere accanto. **`crypto_trend` non supera** (calo massimo del 32,8% contro il 25% ammesso; probabilità di sovra-adattamento 0,84 su BTC, ETH e SOL) e resta in osservazione. Le due azionarie aspettano le chiavi di Alpaca. Gli esiti sono inclusi nell'applicazione e letti a ogni avvio. - Schermate Operazioni (con la scheda "perché" e l'esportazione CSV), Strategie e Rischio come i mockup 03, 04 e 07; in Impostazioni limiti, protezione per le operazioni in giornata e scenari. Fermare, chiudere e ripartire passano dal motore del rischio; alzare un limite mentre una strategia usa soldi veri chiede frase e password. +- **Fase 6** (scelte nell'ADR 0012): + - Motore dal vivo: ogni decisione passa dalla stessa chiamata del backtest (`DecideOnce`), agli orari di 5.5. Ogni decisione ha una chiave scritta nella stessa transazione dei suoi ordini pianificati e delle righe del diario, quindi una ripartenza non decide né manda niente due volte. Parità con il backtest provata su 40 giorni di `crypto_trend` e 6 settimane di `equity_meanrev`; 14 giorni con guasti iniettati finiscono riconciliati e senza ordini doppi. + - Recupero dopo un'assenza (5.6): l'assenza si misura dall'ultimo lavoro finito. I lavori persi si rifanno una volta o si saltano con il motivo. Le decisioni in ritardo aggiornano solo le uscite. Un'assenza di più di un giorno resta in Panoramica finché non la vedi. + - Processo di guardia: in Docker è il processo principale e il genitore del motore. Interviene dopo due minuti di silenzio, un avvio fermo dieci minuti o un'uscita senza preavviso. Annulla gli ordini a metà, rimette gli stop, avvisa e fa ripartire il motore. La terza ripartenza forzata in un'ora scrive il file STOP. La prova (`drill`) gira anche dentro l'immagine, in `tasks ci` e nella CI. + - Diario con le frasi fisse dell'appendice B e confronto "senza bot" (40% BTC, 60% SPY, ogni versamento investito nel suo giorno). + - Telegram: coda con stato, nuovi tentativi e abbandono dopo un giorno; comandi dal telefono solo dalla chat configurata e solo se recenti, `/ferma` con `/conferma`; riepilogo del mattino, stato facoltativo, segnale di vita ogni minuto. Sezione in Impostazioni. + - Schermate Panoramica e Diario e sistema come i mockup 01, 08 e 09. + - `anubis soak`: il rapporto di una prova di durata, letto dai registri del bot mentre lavora. ## In corso @@ -84,12 +92,15 @@ Nulla. ## Prossimo passo -Fase 6, motore dal vivo in simulazione: l'orchestrazione della giornata, il processo di guardia, il recupero dopo un'assenza, il Diario, Panoramica, Telegram e la prova di durata di 48 ore. Con le chiavi del conto paper di Alpaca si possono fare i backtest azionari (`anubis backtest base`) e chiudere i criteri in attesa delle Fasi 2 e 3. +1. Controllare il rapporto della prova di durata. Il container è `anubis-prova`; il comando è in `docs/SVILUPPO.md`, sezione "Guardia e prova di durata". +2. Poi la Fase 7, notizie. Con le chiavi del conto paper di Alpaca si possono anche fare i backtest azionari (`anubis backtest base`) e chiudere i criteri delle Fasi 2 e 3 in attesa. ## Da sapere - Le immagini .NET 10 sono su Ubuntu 24.04, non Debian (ADR 0006). -- La modalità dimostrativa mostra solo le parti già costruite: strategie e notizie della Panoramica arrivano con le loro fasi. Nella demo il motore di trading è spento. +- La modalità dimostrativa mostra le schermate costruite fin qui. Notizie e apprendimento appaiono solo con i dati dell'appendice F: fuori dalla demo arrivano con le Fasi 7 e 8. Nella demo il motore di trading e Telegram sono spenti. +- In Docker il processo principale è la guardia; fuori da Docker (`tasks dev`, VS Code) il server gira da solo. +- La guardia oggi apre solo i conti di prova: avrà i conti reali con la fase dei soldi veri (ADR 0012, punto 4). - Le chiavi dei conti di prova si inseriscono da Impostazioni → Conti e chiavi oppure nel file `.env`; quelle nelle variabili d'ambiente valgono di più. Una chiave OKX che permette i prelievi viene rifiutata. - Il capitale affidato si decide in euro in Impostazioni → Conti e chiavi. Finché non c'è, le strategie osservano soltanto. - `tasks dev` fuori da Docker usa la cartella dei dati vera dell'utente: per prove usa `tasks seed-demo`. @@ -97,7 +108,7 @@ Fase 6, motore dal vivo in simulazione: l'orchestrazione della giornata, il proc - OKX: WebSocket sulla porta 443, la 8443 è chiusa (API-NOTES O3). - Le coppie in EUR di OKX esistono da novembre 2023: prima di allora la storia crypto viene dagli archivi Binance in USDT. Il Laboratorio li usa nella loro valuta (ADR 0010, punto 13); i backtest delle strategie di base li convertono in euro con il cambio BCE del giorno (ADR 0011, punto 10). - `crypto_trend` resta in osservazione perché il suo backtest non è superato. Non ho ritoccato regole o soglie dopo aver visto il risultato: una nuova versione della strategia è una nuova prova, che il DSR conterà insieme alle precedenti. -- Il motore dal vivo (Fase 6) deve far girare una strategia con i parametri scritti nel suo file dell'esito (`parameters`), non con quelli predefiniti: sono quelli che si sono qualificati. +- Il motore dal vivo fa girare ogni strategia con i parametri scritti nel suo file dell'esito (`parameters`), non con quelli predefiniti: sono quelli che si sono qualificati. - Per rifare i backtest di base: `anubis backtest base --to AAAA-MM-GG --out docs/backtests` (con `--offline` usa gli archivi già scaricati). - Nella modalità dimostrativa il Laboratorio è spento: mostra l'elenco ma non esegue prove. - I dati di mercato si spengono con `ANUBIS_MARKET_DATA=off`; nella modalità dimostrativa sono sempre spenti. @@ -109,11 +120,12 @@ Fase 6, motore dal vivo in simulazione: l'orchestrazione della giornata, il proc | Cosa | Da quando serve | Senza | |---|---|---| -| Via libera per la Fase 6 | Subito | Non si parte | +| Via libera per la Fase 7 | Subito | Non si parte | | Chiavi del conto paper di Alpaca (`ALPACA_API_KEY_DEMO`, `ALPACA_API_SECRET_DEMO`) | Già dalla Fase 2 (dati azionari) | Parte azionaria spenta; storico azionario dal 2016 e backtest delle due strategie azionarie in attesa | | Chiavi demo di OKX Europe, senza permesso di prelievo | Fase 3 (ordini sui conti di prova) | Batteria di conformità su risposte d'esempio; criterio della Fase 3 in attesa | | Un token Gitea con permesso `write:package` come segreto `REGISTRY_TOKEN` | Fase 9 (pubblicazione dell'immagine) | Pubblicazione a mano | -| Token del bot Telegram e chat autorizzata (facoltativi) | Fase 6 | Test con un finto server | +| Token del bot Telegram e chat autorizzata (facoltativi), da Impostazioni → Telegram | Fase 6 | Nessun avviso sul telefono; comandi provati con un finto server | +| Un indirizzo per il segnale di vita (facoltativo, per esempio un controllo gratuito di Healthchecks.io) | Fase 6 | Nessuno avvisa se bot e guardia si spengono insieme | | Chiavi FRED e Finnhub (facoltative, gratuite) | Già dalla Fase 2 | Calendario limitato alla settimana corrente; filtro trimestrali spento | | Chiave di un modello linguistico (facoltativa) | Fase 7 | Solo classificatore locale | | Prova del template su Unraid | Fase 9 | Criterio in attesa | diff --git a/docs/SVILUPPO.md b/docs/SVILUPPO.md index 38f922a..aedd9ed 100644 --- a/docs/SVILUPPO.md +++ b/docs/SVILUPPO.md @@ -90,6 +90,17 @@ Apri la radice del repository in VS Code con l'estensione C# (`ms-dotnettools.cs Le attività `check`, `test` e `dev` sono anche in Terminale → Esegui attività. L'estensione è dell'editor, non del progetto: non entra nell'elenco dell'ADR 0004. +## Guardia e prova di durata + +- In Docker il processo principale è la guardia (`Anubis.Guard.dll`), che avvia il server come processo figlio (ADR 0012). Fuori da Docker, con `tasks dev` o da VS Code, il server gira da solo, senza guardia. +- La prova della guardia blocca davvero il motore con una vendita a metà e controlla che tutto torni a posto: + - `dotnet run --project src/Anubis.Guard -- drill` sul computer; + - `docker run --rm drill` dentro l'immagine. + + La fanno anche `tasks ci` e la CI. +- Il rapporto di una prova di durata si legge mentre il bot lavora: `docker exec -u 99:100 -e HOME=/tmp dotnet /app/Anubis.Server.dll soak --hours 48 --platform docker`, con l'utente del bot (`PUID:PGID`) perché i file del database restino suoi. Esce con 0 se tutto è regolare e con 4 se qualcosa va guardato. +- Gli appigli per le prove (`ANUBIS_FAULT`, `ANUBIS_DRILL_OKX_URL`) non si usano mai su un'installazione vera. + ## Pacchetti e consegne - **Docker**: immagine `gitea.encke-hake.ts.net/balbosoft/anubis`, pubblicata dalla CI sui tag `v*` nella sezione Packages del repository (ADR 0002). I tag `fase-N` non pubblicano nulla. diff --git a/docs/adr/0012-scelte-fase-6.md b/docs/adr/0012-scelte-fase-6.md new file mode 100644 index 0000000..e61b176 --- /dev/null +++ b/docs/adr/0012-scelte-fase-6.md @@ -0,0 +1,130 @@ +# 0012 — Scelte della Fase 6: motore dal vivo in simulazione + +Data: 2026-11-11 · Stato: accettata · Precisa la specifica (sezioni 5.5, 5.6, 7.4, 7.5, 9.3, 9.4, 13, 14) e gli ADR 0009–0011, senza aggiungere componenti esterni + +## Contesto + +La Fase 6 porta il bot che lavora da solo in simulazione: la giornata di 5.5, il recupero dopo un'assenza, il processo di guardia, il diario con le frasi dell'appendice B, Telegram con il segnale di vita, le schermate Panoramica e Diario e sistema, e la prova di durata in tempo reale. Alcune scelte non sono scritte nella specifica, o la precisano. Le raccolgo qui. + +## Decisione + +**1. Il motore dal vivo decide con la stessa chiamata del backtest.** +- Ogni decisione passa da `DecideOnce`, la stessa funzione che usa il motore di backtest, così prova e simulazione non possono divergere. Il test di parità lo controlla su 40 giorni di `crypto_trend` e su 6 settimane di `equity_meanrev`, con correttivi e rischio attivi. +- Gli orari sono quelli di 5.5: + - chiusura crypto alle 00:05 UTC; + - segnali azionari 20 minuti dopo la chiusura di Wall Street; + - uscite di `equity_meanrev` 5 minuti prima della chiusura; + - ordini azionari e stop del giorno all'apertura. +- Una strategia gira con i parametri scritti nel suo file dell'esito (`parameters`), cioè quelli che si sono qualificati, non con quelli predefiniti. +- Il motore parte dal pianificatore solo dopo che i conti sono stati riconciliati. + +**2. Ogni decisione si prende una volta sola, anche attraverso le ripartenze.** +- La decisione ha una chiave (`run_key`: strategia e chiusura su cui decide). Questa chiave viene scritta nella stessa transazione delle righe di decisione, degli ordini pianificati e delle righe del diario: o c'è tutto o non c'è niente. +- L'id di ogni ordine pianificato è l'id della decisione dell'intenzione, e da lì viene la chiave dell'ordine. Una ripartenza che trova l'esecuzione già presente non la manda una seconda volta. +- Gli ordini azionari decisi dopo la chiusura aspettano l'apertura nella tabella `planned_orders`. Ognuno ha una scadenza e un prezzo di riferimento. +- La prova accelerata copre 14 giorni con un guasto diverso nei giorni indicati: rete giù, una risposta persa, una ripartenza con un ordine a metà e il database irraggiungibile. Su SQLite e PostgreSQL termina riconciliata e senza ordini doppi. + +**3. Il recupero dopo un'assenza (5.6).** +- L'assenza si misura all'avvio dall'ultimo lavoro finito (`jobs.last_finished_at`). Sotto i 5 minuti è una ripartenza, non un'assenza. +- Ogni assenza va nel diario. Una più lunga di un giorno resta in cima alla Panoramica finché l'utente non l'ha vista. +- Ogni lavoro dichiara cosa fare con le esecuzioni perse: + - salvataggio, cambi, calendario di borsa e pulizia girano una volta alla ripartenza, comunque in ritardo; + - un lavoro con una scadenza si salta dopo quella scadenza, e il diario lo dice. +- Le azioni societarie si leggono prima che la riconciliazione rimetta gli stop. +- Una decisione presa in ritardo per l'assenza va nel diario come recuperata. Un'entrata il cui prezzo si è mosso troppo o che è scaduta si lascia cadere, con il suo motivo. + +**4. La guardia è il processo principale e il genitore del motore (9.3, 9.4).** +- In Docker il punto d'ingresso è `Anubis.Guard.dll`, che avvia `Anubis.Server.dll` come processo figlio con gli stessi argomenti. +- I due processi parlano su una pipe locale con nome (`ANUBIS_GUARD_PIPE`), un messaggio JSON per riga: + - il motore manda il battito, i passi dell'avvio, le chiavi dei conti (tenute solo in memoria) e gli stop che decide; + - la guardia manda solo "stop". +- La guardia interviene in tre casi: + - due minuti senza battito; + - un avvio fermo sullo stesso passo per dieci minuti; + - un'uscita del motore senza preavviso. +- Un salto dell'orologio oltre 30 secondi (computer sospeso) non conta come silenzio. +- Quando interviene, la guardia: + 1. ferma il motore; + 2. annulla i nostri acquisti e le nostre vendite rimasti aperti sui conti di prova; + 3. rimette gli stop che le posizioni richiedono, leggendoli dal file di stato che il motore scrive ogni dieci secondi; + 4. scrive una nota e avvisa l'utente; + 5. fa ripartire il motore. +- La terza ripartenza forzata in un'ora scrive il file STOP. +- Gli stop rimessi dalla guardia saltano 500 numeri di sequenza (`GuardRepair.SequenceGap`), così il loro id non si scontra mai con uno che il motore stava per mandare. +- Alla ripartenza il motore, prima di riconciliare: + - adotta gli stop della guardia; + - annulla gli ordini che aveva lasciato aperti (motivo `restart`); + - pianifica di nuovo le uscite già decise, che seguono così le regole di 5.6. +- Lo stop del container (SIGTERM) passa al motore, che chiude in ordine e non viene fatto ripartire. Il compose e il template Unraid concedono 60 secondi; la guardia ne aspetta 55. +- **I conti reali per ora sono fuori dalla guardia.** La guardia apre solo conti di prova. Avrà i conti reali con la fase dei soldi veri, quando riceverà anche la procedura di avvio di 12.4. Oggi nessuna strategia usa soldi veri. +- La guardia usa il runtime condiviso di ASP.NET (`FrameworkReference`): server e guardia stanno così nella stessa cartella `/app` dell'immagine, con le stesse librerie. + +**5. La prova della guardia ha due appigli, solo per la prova.** +- `ANUBIS_FAULT=hang-mid-sale` blocca il ciclo principale subito dopo l'invio di una vendita. La guardia non lo passa mai al motore che fa ripartire. +- `ANUBIS_DRILL_OKX_URL` indirizza il conto OKX della prova a un finto OKX. Funziona solo con indirizzi locali (loopback). +- La prova (`Anubis.Guard drill`) gira con processi veri in una cartella temporanea, anche dentro l'immagine Docker: lo fanno `tasks ci` e la CI. Fa sette controlli: + - la guardia è intervenuta; + - il motore è ripartito; + - la vendita era partita; + - la vendita rimasta a metà è stata annullata; + - lo stop è tornato per l'intera quantità; + - la vendita già decisa è ripartita con un ordine nuovo; + - la nota è nel diario. + +**6. Il diario si scrive con frasi fisse.** +- Le frasi nel tono dell'appendice B vengono da modelli (`DiaryText`) riempiti solo con ciò che è successo: esecuzioni con il risultato dell'operazione che chiudono, stop alzati, chiusura crypto, segnali azionari, segnali in osservazione, recupero e assenza. +- Le frasi dei codici motivo stanno nella libreria (`ReasonCatalog`), condivise da motore e schermate. Un test controlla che ogni codice abbia la sua frase. +- I generi del diario sono quelli della schermata: Ordini, Decisioni, Sistema, Notizie, Apprendimento. + +**7. Il confronto "senza bot" (7.5).** +- Ogni movimento di capitale viene investito nel suo giorno: 40% in BTC/EUR e 60% in SPY rettificato, convertito con il cambio BCE. Poi non si tocca più. +- Un prelievo vende i due nella proporzione che hanno raggiunto. +- I prezzi sono le chiusure del giorno prima, così un versamento non sembra mai un guadagno. +- Senza lo storico di SPY (niente chiavi Alpaca) la fotografia lascia vuoto il confronto, invece di mostrarne metà. + +**8. Telegram (14).** +- Ogni avviso va prima in coda (`notifications`), nella stessa transazione di ciò che racconta, e poi si spedisce. Il passo di spedizione gira ogni dieci secondi e manda al massimo 20 messaggi. +- Ogni messaggio ha uno stato: in attesa, spedito, oppure non riuscito con il suo errore. + - Rete giù e 429 si riprovano dopo 1, 2, 4… fino a 60 minuti, o dopo l'attesa indicata da Telegram se è più lunga; al massimo 8 tentativi. + - Un rifiuto di Telegram è definitivo. + - Un messaggio che non è partito entro un giorno si abbandona con il motivo, invece di arrivare tardi come se fosse una notizia. +- I comandi si leggono con il long polling. Valgono solo: + - dalla chat configurata (le altre si ignorano in silenzio); + - se hanno meno di 5 minuti, così un /pausa di ieri non mette in pausa oggi. +- `/ferma` chiede `/conferma` entro due minuti; qualsiasi altro comando nel frattempo la annulla. +- Ripartire dopo "Ferma tutto", i soldi veri, i limiti e le chiavi restano nell'interfaccia. +- Lavori in programma: + - riepilogo del mattino alle 08:00, recuperabile entro quattro ore; + - stato ogni ora o alle 20:00, solo se l'impostazione `telegram.status` lo chiede. +- Nella modalità dimostrativa Telegram è spento. +- Il passo Telegram del primo avvio resta in Impostazioni → Telegram: la pagina del primo avvio non ha ancora un database dove tenere i segreti. Quella pagina lo dice, e sul desktop raccomanda il segnale di vita. + +**9. Il segnale di vita.** Ogni minuto, se c'è un indirizzo, il bot chiama un servizio esterno (per esempio un controllo di Healthchecks.io). +- L'indirizzo viene da `ANUBIS_HEARTBEAT_URL`, oppure dal segreto `HEARTBEAT_URL` impostato da Impostazioni. +- È il servizio esterno ad avvisare se le chiamate smettono: copre il caso in cui bot e guardia sono spenti insieme. + +**10. Panoramica e Diario e sistema (13.6).** +- Le prossime mosse vengono dai lavori del pianificatore che sono mosse del bot; i lavori a intervallo (ogni minuto, ogni 5 minuti) non compaiono. Gli eventi del calendario economico tra le mosse ci sono solo nella demo, che usa i valori dell'appendice F.10; fuori dalla demo la riga "Prossima decisione" dice "tra X, alle HH:MM". +- Notizie e Apprendimento, fuori dalla demo, dicono "non ancora attivo" fino alle Fasi 7 e 8. +- Il Diario filtra per genere con semplici collegamenti, senza JavaScript. Il filtro Rischio raccoglie i codici del motore del rischio e quelli di ordini o stop rifiutati, chiavi con prelievo, conto prudente, intervento della guardia e salto dell'orologio. La ricerca ignora maiuscole e accenti, guarda le ultime 5.000 righe e ne mostra al massimo 200. "Mostra i giorni precedenti" aggiunge 7 giorni e compare solo se ci sono righe più vecchie. +- Non esiste ancora una pagina per una singola operazione: "Perché l'ho comprata e venduta" porta a Operazioni filtrata su quel titolo, dove la scheda "perché" si apre. +- Il computer che lo ospita: il processore è la quota di questo processo dall'ultima lettura; la memoria è quella del processo sul limite che .NET vede (nel container, il limite del container); lo spazio è quello del disco della cartella dei dati. +- "Scarica i registri tecnici" (`/api/registri.zip`) chiede l'accesso e mette nello zip solo i file `anubis-*.log` della cartella dei registri, già oscurati quando sono stati scritti. + +**11. La prova di durata.** +- `anubis soak` legge i registri del bot su una finestra di tempo e scrive un rapporto, senza cambiare niente. Può girare mentre il bot lavora, in Docker con `docker exec`. I suoi controlli: + - durata coperta; + - nessun silenzio oltre 15 minuti (la riconciliazione scrive una riga ogni 5); + - nessun ordine né decisione doppia; + - nessuna differenza inspiegata e ultima riconciliazione in regola per ogni conto; + - nessuno spegnimento; + - nessun intervento della guardia; + - una decisione `crypto_trend` per ogni chiusura giornaliera. +- La prova gira sull'immagine Docker di questo PC, con un volume suo, senza chiavi: conto crypto sul simulatore interno con prezzi veri di OKX, nessuna parte azionaria. +- `crypto_trend` non ha superato il backtest (ADR 0011, punto 13), quindi resta in osservazione: decide ogni notte, ma non manda ordini. Non la porto in simulazione per far vedere ordini: sarebbe aggirare il suo esito. Gli ordini, le ripartenze e i guasti sono coperti dalla prova accelerata (punto 2) e dalla prova della guardia (punto 5). + +## Conseguenze + +- Un riavvio, un crash o un'assenza non producono decisioni né ordini doppi: le chiavi e le transazioni lo garantiscono, e i test lo provano su entrambi i motori. +- I conti reali, quando arriveranno, avranno bisogno che anche la guardia sappia aprirli: è scritto qui per non dimenticarlo. +- Il rapporto della prova di durata si controlla come primo passo della Fase 7. diff --git a/src/Anubis.Server/Program.cs b/src/Anubis.Server/Program.cs index c145661..b14d60b 100644 --- a/src/Anubis.Server/Program.cs +++ b/src/Anubis.Server/Program.cs @@ -18,6 +18,12 @@ if (args.Length >= 1 && args[0] == "backtest") return await BacktestCommand.RunAsync(args[1..]).ConfigureAwait(false); } +// "anubis soak": the report of the endurance run in real time, read from the bot's records while it works (Phase 6). +if (args.Length >= 1 && args[0] == "soak") +{ + return await SoakCommand.RunAsync(args[1..]).ConfigureAwait(false); +} + var app = ServerApp.Build(args); await app.RunAsync().ConfigureAwait(false); return 0; diff --git a/src/Anubis.Server/SoakCommand.cs b/src/Anubis.Server/SoakCommand.cs new file mode 100644 index 0000000..1a1bc6b --- /dev/null +++ b/src/Anubis.Server/SoakCommand.cs @@ -0,0 +1,77 @@ +using System.Collections; +using System.Globalization; +using Anubis.Core; +using Anubis.Db; +using Anubis.Supervision; + +namespace Anubis.Server; + +/// +/// "anubis soak": the report of an endurance run in real time (SPEC 17, phase 6) from the bot's own records. It only +/// reads, so it can run while the bot works: in Docker with docker exec, on desktop from a second terminal. +/// +internal static class SoakCommand +{ + private const string Usage = + "Uso: anubis soak [--from AAAA-MM-GGTHH:MMZ] [--to AAAA-MM-GGTHH:MMZ] [--hours 48] [--out file.md]\n" + + " senza --from la prova è delle ultime --hours ore fino a --to (o adesso).\n" + + "Opzioni comuni: [--platform docker|desktop] [--data-dir ]"; + + /// 0 when the run is in order, 4 when something must be looked at, 1 when the report could not be made. + public static async Task RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary? environment = null, IClock? clock = null) + { + output ??= Console.Out; + clock ??= new SystemClock(); + var own = new Dictionary(StringComparer.Ordinal); + var rest = new List(); + for (var i = 0; i < args.Length; i++) + { + if (args[i] is "--from" or "--to" or "--hours" or "--out" && i + 1 < args.Length) + { + own[args[i]] = args[++i]; + } + else if (args[i] is "--help" or "-h") + { + await output.WriteLineAsync(Usage).ConfigureAwait(false); + return 2; + } + else + { + rest.Add(args[i]); + } + } + + environment ??= Environment.GetEnvironmentVariables().Cast().ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal); + try + { + var hours = own.TryGetValue("--hours", out var h) ? double.Parse(h, CultureInfo.InvariantCulture) : 48; + var to = own.TryGetValue("--to", out var t) ? DateTimeOffset.Parse(t, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) : clock.UtcNow; + var from = own.TryGetValue("--from", out var f) ? DateTimeOffset.Parse(f, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) : to - TimeSpan.FromHours(hours); + var options = ServerOptions.Parse([.. rest], environment); + var config = options.LoadConfig(environment); + if (!config.IsComplete) + { + await output.WriteLineAsync("La configurazione d'avvio non è completa: avvia prima il server una volta.").ConfigureAwait(false); + return 1; + } + + Redactor.Register(config.Db!.Password); + await using var db = Database.Open(config.Db!, allowCreate: false); + var report = await SoakReporter.BuildAsync(db, from, to, TimeSpan.FromHours(hours), config.TimeZone, CancellationToken.None).ConfigureAwait(false); + var text = report.Markdown(config.TimeZone); + if (own.TryGetValue("--out", out var file)) + { + await File.WriteAllTextAsync(Path.GetFullPath(file), text).ConfigureAwait(false); + } + + await output.WriteAsync(text).ConfigureAwait(false); + return report.Passed ? 0 : 4; + } + catch (Exception ex) when (ex is IOException or FormatException or ArgumentException or InvalidOperationException or SchemaException + or System.Data.Common.DbException or UnauthorizedAccessException or TimeZoneNotFoundException) + { + await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false); + return 1; + } + } +} diff --git a/src/Anubis/Supervision/SoakReport.cs b/src/Anubis/Supervision/SoakReport.cs new file mode 100644 index 0000000..d0c0957 --- /dev/null +++ b/src/Anubis/Supervision/SoakReport.cs @@ -0,0 +1,209 @@ +using System.Globalization; +using System.Text; +using Anubis.Core; +using Anubis.Db; +using Anubis.Trading; + +namespace Anubis.Supervision; + +/// One check of the endurance run: what was looked at and whether it is in order. +public sealed record SoakCheck(string Text, bool Ok); + +/// +/// The report of an endurance run in real time (SPEC 17, phase 6): over a window of the bot's own records, whether it +/// kept working without losing control. It reads only what the bot wrote; it changes nothing. +/// +public sealed record SoakReport(DateTimeOffset From, DateTimeOffset To, IReadOnlyList Checks, IReadOnlyList Facts) +{ + public bool Passed => Checks.All(c => c.Ok); + + public string Markdown(TimeZoneInfo zone) + { + ArgumentNullException.ThrowIfNull(zone); + var text = new StringBuilder(); + text.AppendLine("# Prova di durata") + .AppendLine() + .AppendLine(CultureInfo.InvariantCulture, $"Dal {Moment(From, zone)} al {Moment(To, zone)} ({Hours(To - From)}).") + .AppendLine() + .AppendLine(Passed ? "**Esito: regolare.**" : "**Esito: da guardare.** Le righe segnate con ✗ dicono cosa.") + .AppendLine() + .AppendLine("## Controlli") + .AppendLine(); + foreach (var check in Checks) + { + text.AppendLine(CultureInfo.InvariantCulture, $"- {(check.Ok ? "✓" : "✗")} {check.Text}"); + } + + text.AppendLine().AppendLine("## Che cosa è successo").AppendLine(); + foreach (var fact in Facts) + { + text.AppendLine("- " + fact); + } + + return text.ToString(); + } + + internal static string Moment(DateTimeOffset moment, TimeZoneInfo zone) => + TimeZoneInfo.ConvertTime(moment, zone).ToString("dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture); + + internal static string Hours(TimeSpan span) => + Format.Number((decimal)Math.Round(span.TotalHours, 1), span.TotalHours % 1 == 0 ? 0 : 1) + " ore"; +} + +/// Builds the from the database. +public static class SoakReporter +{ + /// The reconciliation runs every 5 minutes: a longer silence than this means the bot stopped working. + public static readonly TimeSpan MaxSilence = TimeSpan.FromMinutes(15); + + public static async Task BuildAsync(Database db, DateTimeOffset from, DateTimeOffset to, TimeSpan minimum, TimeZoneInfo zone, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(db); + ArgumentNullException.ThrowIfNull(zone); + if (to <= from) + { + throw new ArgumentException("La fine della prova deve venire dopo l'inizio.", nameof(to)); + } + + return await db.ReadAsync(async s => + { + var checks = new List(); + var facts = new List(); + (string Name, object? Value)[] window = [("from", from), ("to", to)]; + + // Continuity: the reconciliation writes a row every 5 minutes, whatever it finds. + var beats = await s.QueryAsync("SELECT occurred_at FROM reconciliations WHERE occurred_at >= @from AND occurred_at <= @to ORDER BY occurred_at", + r => r.Moment("occurred_at"), window).ConfigureAwait(false); + var covered = beats.Count == 0 ? TimeSpan.Zero : beats[^1] - beats[0]; + checks.Add(new SoakCheck($"Durata coperta dal lavoro del bot: {SoakReport.Hours(covered)} (servono almeno {SoakReport.Hours(minimum)}).", covered >= minimum)); + var silences = new List<(DateTimeOffset Start, TimeSpan Length)>(); + var edges = new List { from }; + edges.AddRange(beats); + edges.Add(to); + for (var i = 1; i < edges.Count; i++) + { + if (edges[i] - edges[i - 1] > MaxSilence) + { + silences.Add((edges[i - 1], edges[i] - edges[i - 1])); + } + } + + checks.Add(new SoakCheck(silences.Count == 0 + ? $"Nessun silenzio più lungo di {Minutes(MaxSilence)} ({beats.Count} riconciliazioni)." + : $"Silenzi più lunghi di {Minutes(MaxSilence)}: " + + string.Join(", ", silences.Select(g => $"dal {SoakReport.Moment(g.Start, zone)} per {Minutes(g.Length)}")) + ".", silences.Count == 0)); + + // No order twice: one order per client id, one execution per order key, one decision per run key. + var doubled = await s.CountAsync("SELECT COUNT(*) FROM (SELECT client_order_id FROM orders GROUP BY client_order_id HAVING COUNT(*) > 1) d").ConfigureAwait(false) + + await s.CountAsync("SELECT COUNT(*) FROM (SELECT order_key FROM executions GROUP BY order_key HAVING COUNT(*) > 1) d").ConfigureAwait(false) + + await s.CountAsync("SELECT COUNT(*) FROM (SELECT run_key FROM engine_runs GROUP BY run_key HAVING COUNT(*) > 1) d").ConfigureAwait(false); + checks.Add(new SoakCheck(doubled == 0 ? "Nessun ordine né decisione doppia." : $"Ordini o decisioni doppie: {doubled}.", doubled == 0)); + + // Reconciliations: never an unexplained difference, and every account ends in agreement. + var outcomes = await s.QueryAsync( + "SELECT a.name AS account, r.outcome AS outcome, COUNT(*) AS n FROM reconciliations r JOIN accounts a ON a.id = r.account_id " + + "WHERE r.occurred_at >= @from AND r.occurred_at <= @to GROUP BY a.name, r.outcome ORDER BY a.name, r.outcome", + r => (Account: r.Text("account"), Outcome: r.Text("outcome"), Count: r.Number("n")), window).ConfigureAwait(false); + var different = outcomes.Where(o => o.Outcome == ReconcileOutcomes.Different).Sum(o => o.Count); + checks.Add(new SoakCheck(different == 0 ? "Nessuna differenza inspiegata tra registro e conti." : $"Riconciliazioni con differenze inspiegate: {different}.", different == 0)); + var last = await s.QueryAsync( + "SELECT a.name AS account, r.outcome AS outcome FROM reconciliations r JOIN accounts a ON a.id = r.account_id " + + "WHERE r.occurred_at = (SELECT MAX(x.occurred_at) FROM reconciliations x WHERE x.account_id = r.account_id AND x.occurred_at <= @to) ORDER BY a.name", + r => (Account: r.Text("account"), Outcome: r.Text("outcome")), ("to", to)).ConfigureAwait(false); + var agreed = last.All(l => l.Outcome is ReconcileOutcomes.Clean or ReconcileOutcomes.Healed); + checks.Add(new SoakCheck(last.Count == 0 + ? "Nessun conto riconciliato." + : "Ultima riconciliazione: " + string.Join(", ", last.Select(l => $"{l.Account} {Outcome(l.Outcome)}")) + ".", last.Count > 0 && agreed)); + foreach (var group in outcomes.GroupBy(o => o.Account, StringComparer.Ordinal)) + { + facts.Add($"Riconciliazioni di {group.Key}: " + string.Join(", ", group.Select(o => $"{o.Count} {Outcome(o.Outcome)}")) + "."); + } + + // The bot was never away and the guard never had to step in. + var absences = await s.QueryAsync("SELECT started_at, ended_at FROM absences WHERE ended_at >= @from AND started_at <= @to ORDER BY started_at", + r => (Start: r.Moment("started_at"), End: r.Moment("ended_at")), window).ConfigureAwait(false); + checks.Add(new SoakCheck(absences.Count == 0 + ? "Il bot non si è mai spento." + : "Spento: " + string.Join(", ", absences.Select(a => $"dal {SoakReport.Moment(a.Start, zone)} per {Minutes(a.End - a.Start)}")) + ".", absences.Count == 0)); + var interventions = await s.CountAsync("SELECT COUNT(*) FROM journal WHERE code = 'guard_intervention' AND occurred_at >= @from AND occurred_at <= @to", window) + .ConfigureAwait(false); + checks.Add(new SoakCheck(interventions == 0 ? "La guardia non è mai dovuta intervenire." : $"Interventi della guardia: {interventions}.", interventions == 0)); + + // A crypto decision at every daily close in the window (00:05 UTC), whatever the stage of the strategy. + var closes = DailyCloses(from, to); + var runs = await s.QueryAsync("SELECT strategy, mode, COUNT(*) AS n FROM engine_runs WHERE created_at >= @from AND created_at <= @to GROUP BY strategy, mode ORDER BY strategy, mode", + r => (Strategy: r.Text("strategy"), Mode: r.Text("mode"), Count: r.Number("n")), window).ConfigureAwait(false); + var crypto = runs.Where(r => r.Strategy == StrategyNames.CryptoTrend).Sum(r => r.Count); + checks.Add(new SoakCheck($"Decisioni di {StrategyNames.CryptoTrend}: {crypto} su {closes} chiusure giornaliere.", crypto >= closes)); + facts.Add(runs.Count == 0 + ? "Nessuna decisione del motore." + : "Decisioni del motore: " + string.Join(", ", runs.Select(r => $"{r.Strategy} {r.Count} ({Mode(r.Mode)})")) + "."); + + // What the bot did and wrote, for the record. + facts.Add(Counted("Ordini", await GroupAsync(s, "SELECT status AS k, COUNT(*) AS n FROM orders WHERE created_at >= @from AND created_at <= @to GROUP BY status", window) + .ConfigureAwait(false))); + facts.Add(Counted("Esecuzioni", await GroupAsync(s, "SELECT status AS k, COUNT(*) AS n FROM executions WHERE created_at >= @from AND created_at <= @to GROUP BY status", window) + .ConfigureAwait(false))); + facts.Add(Counted("Ordini pianificati", await GroupAsync(s, + "SELECT status AS k, COUNT(*) AS n FROM planned_orders WHERE created_at >= @from AND created_at <= @to GROUP BY status", window).ConfigureAwait(false))); + facts.Add(Counted("Righe del diario", await GroupAsync(s, "SELECT kind AS k, COUNT(*) AS n FROM journal WHERE occurred_at >= @from AND occurred_at <= @to GROUP BY kind", window) + .ConfigureAwait(false))); + facts.Add(Counted("Messaggi Telegram", await GroupAsync(s, + "SELECT status AS k, COUNT(*) AS n FROM notifications WHERE created_at >= @from AND created_at <= @to GROUP BY status", window).ConfigureAwait(false))); + facts.Add(Counted("Eventi di rischio", await GroupAsync(s, "SELECT kind AS k, COUNT(*) AS n FROM risk_events WHERE occurred_at >= @from AND occurred_at <= @to GROUP BY kind", window) + .ConfigureAwait(false))); + facts.Add(Counted("Problemi nei dati", await GroupAsync(s, + "SELECT kind || ' ' || status AS k, COUNT(*) AS n FROM data_issues WHERE created_at >= @from AND created_at <= @to GROUP BY kind, status", window).ConfigureAwait(false))); + var failing = await s.QueryAsync("SELECT name, last_error FROM jobs WHERE last_error IS NOT NULL AND last_finished_at >= @from ORDER BY name", + r => r.Text("name") + " (" + Redactor.Redact(r.Text("last_error")) + ")", ("from", from)).ConfigureAwait(false); + facts.Add(failing.Count == 0 ? "Nessun lavoro in programma è finito con un errore all'ultima esecuzione." : "Lavori con un errore all'ultima esecuzione: " + string.Join("; ", failing) + "."); + return new SoakReport(from, to, checks, facts); + }, cancellationToken).ConfigureAwait(false); + } + + /// How many crypto daily decisions (00:05 UTC) fall in the window. + public static int DailyCloses(DateTimeOffset from, DateTimeOffset to) + { + var count = 0; + for (var day = DateOnly.FromDateTime(from.UtcDateTime); ; day = day.AddDays(1)) + { + var close = new DateTimeOffset(day.ToDateTime(new TimeOnly(0, 5)), TimeSpan.Zero); + if (close > to) + { + return count; + } + + if (close >= from) + { + count++; + } + } + } + + private static Task> GroupAsync(DbSession s, string sql, (string Name, object? Value)[] window) => + s.QueryAsync(sql, r => (Key: r.TextOrNull("k") ?? "?", Count: r.Number("n")), window); + + private static string Counted(string what, List<(string Key, long Count)> groups) => + groups.Count == 0 ? what + ": nessuno." : $"{what}: {groups.Sum(g => g.Count)} (" + string.Join(", ", groups.Select(g => $"{g.Key} {g.Count}")) + ")."; + + private static string Minutes(TimeSpan span) => + span.TotalMinutes < 120 ? Format.Number((decimal)Math.Round(span.TotalMinutes)) + " minuti" : SoakReport.Hours(span); + + private static string Outcome(string outcome) => outcome switch + { + ReconcileOutcomes.Clean => "in regola", + ReconcileOutcomes.Healed => "sistemate da sole", + ReconcileOutcomes.Different => "con differenze", + ReconcileOutcomes.Unreachable => "conto non raggiungibile", + _ => outcome, + }; + + private static string Mode(string mode) => mode switch + { + DecisionModes.Observation => "in osservazione", + DecisionModes.ExitsOnly => "solo uscite", + DecisionModes.Full => "complete", + _ => mode, + }; +} diff --git a/tests/Anubis.Tests/SoakReportTests.cs b/tests/Anubis.Tests/SoakReportTests.cs new file mode 100644 index 0000000..b8c0e75 --- /dev/null +++ b/tests/Anubis.Tests/SoakReportTests.cs @@ -0,0 +1,85 @@ +using Anubis.Core; +using Anubis.Data; +using Anubis.Supervision; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// The report of the endurance run (SPEC 17, phase 6): regular when the bot kept working, and it says what was not. +[TestClass] +public sealed class SoakReportTests +{ + private static readonly DateTimeOffset From = new(2026, 11, 11, 18, 0, 0, TimeSpan.Zero); + private static readonly DateTimeOffset To = From.AddHours(49); + + [TestMethod] + public void TheDailyCryptoClosesAreCountedInTheWindow() + { + Assert.AreEqual(2, SoakReporter.DailyCloses(From, To)); // 12 and 13 November at 00:05 UTC + var close = new DateTimeOffset(2026, 11, 11, 0, 5, 0, TimeSpan.Zero); + Assert.AreEqual(1, SoakReporter.DailyCloses(close, close)); + Assert.AreEqual(3, SoakReporter.DailyCloses(close, To)); + Assert.AreEqual(0, SoakReporter.DailyCloses(From, From.AddHours(5))); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task AQuietRunIsRegularAndTroublesAreNamed() + { + await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); + var okx = await rig.AccountAsync("okx", "demo").ConfigureAwait(false); + var reconciliations = new List(); + for (var at = From.AddMinutes(1); at <= To; at += TimeSpan.FromMinutes(5)) + { + reconciliations.Add(await ReconciledAsync(rig, okx.AccountId, at, ReconcileOutcomes.Clean).ConfigureAwait(false)); + } + + foreach (var day in new[] { 12, 13 }) + { + var at = new DateTimeOffset(2026, 11, day, 0, 5, 0, TimeSpan.Zero); + await rig.Db.WriteAsync(s => s.ExecuteAsync( + "INSERT INTO engine_runs (id, strategy, run_key, decision_day, decision_id, mode, state, proposed, created_at) VALUES (@id, @s, @k, @d, @dec, @m, NULL, NULL, @at)", + CancellationToken.None, ("id", Guid.NewGuid()), ("s", StrategyNames.CryptoTrend), ("k", $"{StrategyNames.CryptoTrend}:2026-11-{day - 1}"), + ("d", $"2026-11-{day - 1}"), ("dec", Guid.NewGuid()), ("m", DecisionModes.Observation), ("at", at))).ConfigureAwait(false); + } + + var report = await SoakReporter.BuildAsync(rig.Db, From, To, TimeSpan.FromHours(48), Zones.Rome).ConfigureAwait(false); + Assert.IsTrue(report.Passed, report.Markdown(Zones.Rome)); + var text = report.Markdown(Zones.Rome); + Assert.Contains("**Esito: regolare.**", text); + Assert.Contains("Decisioni di crypto_trend: 2 su 2 chiusure giornaliere.", text); + Assert.Contains("crypto_trend 2 (in osservazione)", text); + Assert.Contains("Ordini: nessuno.", text); + + // Half an hour of silence, an unexplained difference at the end and a guard intervention: each one is named. + await rig.Db.WriteAsync(async s => + { + foreach (var id in reconciliations.Skip(100).Take(6)) + { + await s.ExecuteAsync("DELETE FROM reconciliations WHERE id = @id", CancellationToken.None, ("id", id)).ConfigureAwait(false); + } + + rig.Clock.Set(From.AddHours(20)); + await Diary.WriteAsync(s, rig.Clock, DiaryKinds.System, "guard_intervention", "La guardia è intervenuta.", null, CancellationToken.None).ConfigureAwait(false); + }).ConfigureAwait(false); + await ReconciledAsync(rig, okx.AccountId, To, ReconcileOutcomes.Different).ConfigureAwait(false); + + report = await SoakReporter.BuildAsync(rig.Db, From, To, TimeSpan.FromHours(48), Zones.Rome).ConfigureAwait(false); + Assert.IsFalse(report.Passed); + var failed = report.Checks.Where(c => !c.Ok).Select(c => c.Text).ToList(); + Assert.HasCount(4, failed, string.Join(" | ", failed)); + Assert.IsTrue(failed.Any(f => f.StartsWith("Silenzi più lunghi di 15 minuti: dal 12/11/2026 03:16 per 35 minuti", StringComparison.Ordinal)), string.Join(" | ", failed)); + Assert.Contains("Riconciliazioni con differenze inspiegate: 1.", failed); + Assert.Contains("Interventi della guardia: 1.", failed); + Assert.IsTrue(failed.Any(f => f.Contains("con differenze", StringComparison.Ordinal))); + Assert.Contains("**Esito: da guardare.**", report.Markdown(Zones.Rome)); + } + + private static async Task ReconciledAsync(TradingRig rig, Guid account, DateTimeOffset at, string outcome) + { + var id = Guid.NewGuid(); + await rig.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO reconciliations (id, account_id, outcome, details, occurred_at, created_at) VALUES (@id, @a, @o, @d, @at, @at)", + CancellationToken.None, ("id", id), ("a", account), ("o", outcome), ("d", new Anubis.Db.DbJson("{}")), ("at", at))).ConfigureAwait(false); + return id; + } +} From 2185a0b36b04b2bf89bfd9b991f6fc89d0be6ff8 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 11 Nov 2026 21:10:28 +0100 Subject: [PATCH 09/12] Fix the defects found by the Phase 6 review (refs #47 #48 #49 #51 #52 #54) An independent review of the phase found nine defects. The ones that could lose money or orders: - Exits at the close of equity_meanrev are now planned orders written in the same transaction that claims the decision, so a restart can neither lose them nor send them twice. A sell with a deadline starts aggressive. - Resume also finds a planned order not yet linked to its execution (restart between sending and linking) and closes it before re-planning. - An account is "ready" only after adopting the guard's stops, checking the key, reconciling, resuming and aligning stops. Until then nothing is decided on it or sent to it, and the loop retries its startup each minute. The guard's note is deleted only when every stop it placed is in the ledger. - Each account's turn is cut after 45 s (60 s for a retried startup), so a slow broker no longer silences the heartbeat until the guard kills a healthy engine; the beat is also withheld when the scheduler has been silent for 30 minutes. Smaller ones: a stock decision made after the open is marked late; the Telegram loops survive unexpected errors; a long absence is shown on the Panoramica until "Ho visto" (SPEC 5.6); plain-http heartbeats are only accepted to home-network addresses; the soak report gives a daily close 30 minutes to be decided before expecting it. ADR 0012 point 12 records these choices; #51 and the two screen criteria are ticked in the roadmap. Co-Authored-By: Claude Opus 5.5 --- docs/ROADMAP.md | 6 +- docs/adr/0012-scelte-fase-6.md | 12 ++ src/Anubis.Server/AnubisHost.cs | 7 + .../Components/Pages/Panoramica.razor | 12 ++ src/Anubis.Server/Forms.cs | 12 ++ src/Anubis.Server/TelegramServices.cs | 18 +- src/Anubis/Notifications/TelegramBot.cs | 33 +++- src/Anubis/Supervision/SoakReport.cs | 9 +- src/Anubis/Trading/LiveEngine.cs | 124 ++++++++++--- src/Anubis/Trading/TradingService.cs | 173 ++++++++++++++---- tests/Anubis.Tests/LiveEngineTests.cs | 22 +++ tests/Anubis.Tests/LiveSupport.cs | 8 +- tests/Anubis.Tests/OverviewScreenTests.cs | 13 ++ tests/Anubis.Tests/ServerTests.cs | 32 ++-- tests/Anubis.Tests/SoakReportTests.cs | 3 +- tests/Anubis.Tests/TelegramTests.cs | 3 + 16 files changed, 397 insertions(+), 90 deletions(-) diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index a05974e..c69b63b 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -188,7 +188,7 @@ Il bot che lavora da solo, in simulazione, giorno e notte, e lo racconta. - [x] [#48](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/48) Processo di guardia, avvio e ripartenza sicuri - [x] [#49](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/49) Recupero dopo un'assenza (5.6) - [x] [#50](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/50) Diario con frasi in italiano dai codici motivo e confronto "senza bot" -- [ ] [#51](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/51) Schermate Panoramica e Diario e sistema +- [x] [#51](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/51) Schermate Panoramica e Diario e sistema - [x] [#52](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/52) Telegram e segnale di vita - [ ] [#53](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/53) Prova di durata di 48 ore in tempo reale - [ ] [#54](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/54) Chiusura della fase, revisione indipendente e tag `fase-6` @@ -200,8 +200,8 @@ Il bot che lavora da solo, in simulazione, giorno e notte, e lo racconta. - [x] Un test blocca il ciclo principale con una vendita a metà e verifica che dopo la guardia la posizione abbia di nuovo i suoi stop e il motore sia ripartito; la stessa prova passa dentro l'immagine Docker (`ALoopBlockedWithASaleHalfwayGetsItsStopBackAndTheEngineRestarts`, `TheGuardDrillPassesWithTheRealEngineAsChildProcess`; `docker run --rm drill` in `tasks ci` e nella CI: 7 controlli su 7) - [x] Un test con orologio simulato spegne il bot per 3 ore, 20 ore e 3 giorni e verifica le righe di 5.6 i cui lavori esistono (`ThreeHoursOffRecoverTheCryptoDecisionAndDropAnEntryThatMovedTooFar`, `TwentyHoursOffLetTheLateDecisionsUpdateOnlyExitsAndDropExpiredEntries`, `ThreeDaysOffAreDeclaredUntilSeenAndMissedRunsAreMadeOnce`) - [ ] A fine fase parte una prova di durata in tempo reale di almeno 48 ore a cavallo di due sedute USA (solo crypto senza chiavi Alpaca) -- [ ] In modalità dimostrativa la Panoramica corrisponde agli screen 01 (1440 px) e 09 (390 px) -- [ ] Il Diario corrisponde allo screen 08 a 1440 px e a 390 px non scorre in orizzontale +- [x] In modalità dimostrativa la Panoramica corrisponde agli screen 01 (1440 px) e 09 (390 px) (`TheDemoPanoramicaShowsAccountsPositionsAndLimits`; fotografie di `tasks screenshots`, confronto nella prova di #51) +- [x] Il Diario corrisponde allo screen 08 a 1440 px e a 390 px non scorre in orizzontale (`TheDiaryFiltersAndSearches`; a 390 px `scrollWidth` uguale alla larghezza su `/`, `/diario` e `/diario?cerca=…`) - [x] I comandi Telegram funzionano (o, senza token, superano i test con un finto server) — senza token, con un finto server: `TheCommandsWorkFromThePhoneThroughTheRealServer`, `FermaWantsAConfirmationWithinTwoMinutes`, `OnlyTheChatOfTheSettingsIsObeyedAndOldMessagesAreNot` e gli altri di `TelegramTests` ## Fase 7 — Notizie diff --git a/docs/adr/0012-scelte-fase-6.md b/docs/adr/0012-scelte-fase-6.md index e61b176..73e2859 100644 --- a/docs/adr/0012-scelte-fase-6.md +++ b/docs/adr/0012-scelte-fase-6.md @@ -123,6 +123,18 @@ La Fase 6 porta il bot che lavora da solo in simulazione: la giornata di 5.5, il - La prova gira sull'immagine Docker di questo PC, con un volume suo, senza chiavi: conto crypto sul simulatore interno con prezzi veri di OKX, nessuna parte azionaria. - `crypto_trend` non ha superato il backtest (ADR 0011, punto 13), quindi resta in osservazione: decide ogni notte, ma non manda ordini. Non la porto in simulazione per far vedere ordini: sarebbe aggirare il suo esito. Gli ordini, le ripartenze e i guasti sono coperti dalla prova accelerata (punto 2) e dalla prova della guardia (punto 5). +**12. Correzioni dopo la revisione indipendente.** Una revisione del codice della fase ha trovato nove difetti; le correzioni scelte sono queste. +- **Un conto parte solo quando è in ordine.** All'avvio ogni conto prima adotta gli stop messi dalla guardia, poi controlla la chiave, si riconcilia, riprende o annulla ciò che era rimasto a metà e allinea gli stop. Solo se tutto riesce il conto è "pronto". Finché non lo è, il motore non decide su di lui e non gli manda ordini pianificati; il ciclo riprova l'avvio ogni minuto. Prima, un broker che non rispondeva all'avvio lasciava il conto lavorare su un registro non riconciliato. +- **Gli stop della guardia si adottano prima di tutto il resto.** La nota della guardia si cancella solo quando ogni stop che ha messo risulta nel registro degli ordini; se l'adozione si interrompe, la nota resta e si riprova. +- **Un turno di conto ha un tempo massimo**: 45 secondi per il giro degli ordini, 60 per un nuovo avvio. Un broker lento non tiene più fermo il segnale di vita per i due minuti dopo i quali la guardia interviene: il turno si interrompe, si scrive nel registro e si riprova al giro dopo. Un motore davvero bloccato resta in silenzio e la guardia lo sente. +- **Il segnale di vita guarda anche il pianificatore.** Se il pianificatore, dove girano le decisioni, tace da 30 minuti (i suoi lavori più lunghi durano pochi minuti), il ciclo degli ordini smette di battere e la guardia interviene. +- **Le uscite alla chiusura di `equity_meanrev` sono ordini pianificati**, scritti nella stessa transazione che prende la chiave della decisione, con scadenza alla chiusura della sessione. Il rilascio li manda subito; una vendita con scadenza parte già aggressiva (limite vicino al prezzo opposto). Prima venivano mandate direttamente: un riavvio a metà poteva perderle o mandarle due volte. +- **La ripresa trova anche l'ordine pianificato non ancora collegato** alla sua esecuzione (riavvio tra l'invio e la scrittura del collegamento), dalla chiave dell'ordine, e lo chiude prima di ripianificare il resto. +- **Una decisione azionaria fatta dopo l'apertura** (per esempio dopo un'assenza) è segnata in ritardo e segue le regole del recupero. +- **I cicli di Telegram non si fermano per un errore inatteso** (database occupato, rete): scrivono nel registro e riprovano. +- **Lo spegnimento lungo si vede in Panoramica** (SPEC 5.6): un avviso in cima dice per quanto il bot è rimasto spento e rimanda al diario, finché l'utente non preme "Ho visto". +- Il segnale di vita in `http://` è accettato solo verso indirizzi della rete di casa (10.x, 172.16-31.x, 192.168.x, locali e i loro equivalenti IPv6); il rapporto della prova di durata non conta una chiusura giornaliera avvenuta meno di 30 minuti prima della fine della finestra. + ## Conseguenze - Un riavvio, un crash o un'assenza non producono decisioni né ordini doppi: le chiavi e le transazioni lo garantiscono, e i test lo provano su entrambi i motori. diff --git a/src/Anubis.Server/AnubisHost.cs b/src/Anubis.Server/AnubisHost.cs index 703aaaa..9a9df48 100644 --- a/src/Anubis.Server/AnubisHost.cs +++ b/src/Anubis.Server/AnubisHost.cs @@ -56,6 +56,9 @@ internal sealed partial class AnubisHost( ILogger logger, ServerOverrides? overrides = null) : BackgroundService { + /// A scheduler silent this long is stuck: the engine stops beating, so the guard steps in. + public static readonly TimeSpan SchedulerSilence = TimeSpan.FromMinutes(30); + private readonly TimeSpan _interval = overrides?.DatabaseCheckInterval ?? TimeSpan.FromSeconds(5); private readonly Lock _gate = new(); @@ -318,6 +321,10 @@ internal sealed partial class AnubisHost( // The drill's fault is honored only under a guard, which never passes it to an engine it restarts. Fault = Guard is null ? null : environment.GetValueOrDefault(GuardChannel.FaultVariable), + + // The decisions run in the scheduler: a scheduler silent for half an hour is stuck (its longest jobs take + // minutes), and the guard must hear it (SPEC 9.3). + OthersAlive = () => scheduler.LastBeatUtc is not { } beat || clock.UtcNow - beat < SchedulerSilence, } : null; if (_trading is not null) diff --git a/src/Anubis.Server/Components/Pages/Panoramica.razor b/src/Anubis.Server/Components/Pages/Panoramica.razor index 643c148..120500f 100644 --- a/src/Anubis.Server/Components/Pages/Panoramica.razor +++ b/src/Anubis.Server/Components/Pages/Panoramica.razor @@ -17,6 +17,14 @@ var phoneMoves = moves.Select((m, i) => (m, i)).Where(x => !x.m.Calendar).Take(2).Select(x => x.i).ToHashSet(); var v = p.Accounts; } +@if (_absence is { } away) +{ +
+ + Sono stato spento per @Anubis.Trading.DiaryText.Duration(away.Length), fino a @Format.ShortDate(away.EndedAt, Shell.Now, Shell.Zone, withTime: false).ToLowerInvariant() alle @TimeZoneInfo.ConvertTime(away.EndedAt, Shell.Zone).ToString("HH:mm", System.Globalization.CultureInfo.InvariantCulture). Ho ripreso i lavori saltati con le regole del recupero: cosa ho fatto e cosa ho lasciato perdere è nel diario. +
+
+} @if (!o.CapitalSet && !Shell.IsDemo) {

Primo passo: decidi quanto capitale affidare al bot in Impostazioni, Conti e chiavi. Lì puoi anche inserire le chiavi dei conti di prova. Finché non c'è capitale, le strategie osservano soltanto.

@@ -388,6 +396,7 @@ private string _period = "avvio"; private int? _runningDays; private decimal? _worst; + private Anubis.Trading.Absence? _absence; [CascadingParameter] public HttpContext? HttpContext { get; set; } @@ -406,6 +415,9 @@ _worst = _panorama.Limits[1].Worst is { } share ? -share * (await Anubis.Risk.RiskSettings.LoadAsync(services.Settings, ct)).DrawdownStop : null; using var aggregates = Shell.Aggregates(); _runningDays = aggregates?.RootElement.GetProperty("giorno").GetInt32(); + + // SPEC 5.6: an absence longer than a day stays at the top until the user says they have seen it. + _absence = Shell.IsDemo ? null : await new Anubis.Trading.AbsenceBook(services.Db, Host.Clock).DeclaredAsync(ct); } private static string Statement(Overview o) diff --git a/src/Anubis.Server/Forms.cs b/src/Anubis.Server/Forms.cs index 1da97e2..107a395 100644 --- a/src/Anubis.Server/Forms.cs +++ b/src/Anubis.Server/Forms.cs @@ -39,12 +39,24 @@ internal static partial class Forms signed.MapPost("/telegram/togli", RemoveTelegramAsync); signed.MapPost("/segnale-di-vita", SaveHeartbeatAsync); signed.MapPost("/segnale-di-vita/togli", RemoveHeartbeatAsync); + signed.MapPost("/assenza/{id:guid}/vista", AbsenceSeenAsync); signed.MapPost("/laboratorio", PlanTrialAsync); signed.MapPost("/strategie/{strategy}/{choice}", StrategyStageAsync); signed.MapPost("/rischio/limiti", SetLimitsAsync); signed.MapPost("/rischio/{key}", SetRiskSettingAsync); } + /// The notice of a long absence (SPEC 5.6) goes away once the user has seen it. + private static async Task AbsenceSeenAsync(Guid id, AnubisHost host, CancellationToken ct) + { + if (!host.IsDemo && host.Services is { } services) + { + await new Anubis.Trading.AbsenceBook(services.Db, host.Clock).AcknowledgeAsync(id, ct).ConfigureAwait(false); + } + + return Results.Redirect("/"); + } + private static string Back(IFormCollection form, string fallback) { var back = form["ritorno"].ToString(); diff --git a/src/Anubis.Server/TelegramServices.cs b/src/Anubis.Server/TelegramServices.cs index 51b11f1..aa8005e 100644 --- a/src/Anubis.Server/TelegramServices.cs +++ b/src/Anubis.Server/TelegramServices.cs @@ -8,7 +8,7 @@ namespace Anubis.Server; /// Telegram and the sign of life (SPEC 14): the queue sent every few seconds, the commands read as they arrive, the /// call to the checking service every minute, the morning summary and the optional periodic status. ///
-internal sealed class TelegramServices : IDisposable +internal sealed partial class TelegramServices : IDisposable { /// The secret that keeps the address of the checking service when the configuration does not give one. public const string HeartbeatSecret = "HEARTBEAT_URL"; @@ -22,6 +22,7 @@ internal sealed class TelegramServices : IDisposable private readonly SettingsStore _settings; private readonly SecretStore _secrets; private readonly TimeZoneInfo _zone; + private readonly Microsoft.Extensions.Logging.ILogger _logger; public TelegramServices(AnubisHost host, Database db, IClock clock, SettingsStore settings, SecretStore secrets, string? configuredHeartbeat, HttpMessageHandler? handler, Microsoft.Extensions.Logging.ILogger logger) @@ -32,6 +33,7 @@ internal sealed class TelegramServices : IDisposable _settings = settings; _secrets = secrets; _zone = host.Config.TimeZone; + _logger = logger; _http = handler is null ? new HttpClient() : new HttpClient(handler, disposeHandler: false); // Longer than the wait of the commands' long polling. @@ -95,7 +97,16 @@ internal sealed class TelegramServices : IDisposable { while (!cancellationToken.IsCancellationRequested) { - await Sender.SendDueAsync(cancellationToken).ConfigureAwait(false); + try + { + await Sender.SendDueAsync(cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (!cancellationToken.IsCancellationRequested) + { + // A busy or unreachable database, or anything else: the queue keeps its messages for the next pass. + LogSendFailed(_logger, ex); + } + await Task.Delay(SendEvery, cancellationToken).ConfigureAwait(false); } } @@ -156,4 +167,7 @@ internal sealed class TelegramServices : IDisposable var text = await Desk.StatusAsync(cancellationToken).ConfigureAwait(false); await _db.WriteAsync(s => NotificationSender.EnqueueAsync(s, _clock, "periodic_status", text, cancellationToken), cancellationToken).ConfigureAwait(false); } + + [Microsoft.Extensions.Logging.LoggerMessage(Level = Microsoft.Extensions.Logging.LogLevel.Error, Message = "Sending the Telegram queue failed")] + private static partial void LogSendFailed(Microsoft.Extensions.Logging.ILogger logger, Exception exception); } diff --git a/src/Anubis/Notifications/TelegramBot.cs b/src/Anubis/Notifications/TelegramBot.cs index 8533aef..d272857 100644 --- a/src/Anubis/Notifications/TelegramBot.cs +++ b/src/Anubis/Notifications/TelegramBot.cs @@ -174,6 +174,12 @@ public sealed partial class TelegramBot(IClock clock, Func Retry ? after : Retry; } + catch (Exception ex) when (!cancellationToken.IsCancellationRequested) + { + // The database or the network failed in a way Telegram did not report: the loop goes on after a pause. + LogLoopFailed(logger, ex); + pause = Retry; + } if (pause is { } wait) { @@ -188,6 +194,9 @@ public sealed partial class TelegramBot(IClock clock, FuncAn address of a home network: 10.x, 172.16-31.x, 192.168.x, link-local, or their IPv6 equivalents.
+ private static bool IsPrivate(string host) + { + if (!System.Net.IPAddress.TryParse(host.Trim('[', ']'), out var ip)) + { + return false; + } + + if (ip.IsIPv4MappedToIPv6) + { + ip = ip.MapToIPv4(); + } + + if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) + { + return System.Net.IPAddress.IsLoopback(ip) || ip.IsIPv6LinkLocal || ip.IsIPv6SiteLocal || ip.IsIPv6UniqueLocal; + } + + var b = ip.GetAddressBytes(); + return b[0] == 10 || b[0] == 127 || (b[0] == 172 && b[1] is >= 16 and <= 31) || (b[0] == 192 && b[1] == 168) || (b[0] == 169 && b[1] == 254); + } + [LoggerMessage(Level = LogLevel.Warning, Message = "Heartbeat failed: {Error}")] private static partial void LogFailed(ILogger logger, string error); } diff --git a/src/Anubis/Supervision/SoakReport.cs b/src/Anubis/Supervision/SoakReport.cs index d0c0957..aedbc97 100644 --- a/src/Anubis/Supervision/SoakReport.cs +++ b/src/Anubis/Supervision/SoakReport.cs @@ -162,9 +162,16 @@ public static class SoakReporter }, cancellationToken).ConfigureAwait(false); } - /// How many crypto daily decisions (00:05 UTC) fall in the window. + /// The time a daily decision is given to run and be written before the report expects it. + public static readonly TimeSpan DecisionTime = TimeSpan.FromMinutes(30); + + /// + /// How many crypto daily decisions (00:05 UTC) fall in the window. A close too near the end of the window is not + /// counted: its decision may still be running when the report is made. + /// public static int DailyCloses(DateTimeOffset from, DateTimeOffset to) { + to -= DecisionTime; var count = 0; for (var day = DateOnly.FromDateTime(from.UtcDateTime); ; day = day.AddDays(1)) { diff --git a/src/Anubis/Trading/LiveEngine.cs b/src/Anubis/Trading/LiveEngine.cs index 9f58aaf..841944e 100644 --- a/src/Anubis/Trading/LiveEngine.cs +++ b/src/Anubis/Trading/LiveEngine.cs @@ -138,6 +138,12 @@ public sealed partial class LiveEngine : IDisposable ///
public Func Ready { get; init; } = () => true; + /// + /// Whether an account finished its startup (SPEC 9.4): reconciled, its leftovers canceled or resumed, its stops + /// aligned. Until then nothing is decided on it and no planned order is sent to it. + /// + public Func AccountReady { get; init; } = _ => true; + /// /// The jobs of SPEC 5.5. The pulse every minute does the work; the others are the same pulse at the times the /// user reads in "Prossime mosse", so the work starts on time. @@ -245,11 +251,14 @@ public sealed partial class LiveEngine : IDisposable return; } + // SPEC 5.6: the signals are redone after an absence only before the next open; made after it, only the exits + // and the stops of the decision are kept. + var late = now >= next.OpenUtc; foreach (var strategy in new[] { StrategyNames.EquityMomentum, StrategyNames.EquityMeanrev }) { var ordersDue = next.OpenUtc + Options.OrdersAfterOpen; var entriesUntil = strategy == StrategyNames.EquityMeanrev ? next.OpenUtc + Options.MeanrevEntryWindow : SecondSessionOfWeek(next).CloseUtc; - await DecideAsync(new Moment(strategy, last.Date, Key(strategy, last.Date), last.CloseUtc + Options.SignalsAfterClose, false, next.OpenUtc, now, ordersDue, + await DecideAsync(new Moment(strategy, last.Date, Key(strategy, last.Date), last.CloseUtc + Options.SignalsAfterClose, late, next.OpenUtc, now, ordersDue, entriesUntil), cancellationToken).ConfigureAwait(false); } } @@ -323,7 +332,7 @@ public sealed partial class LiveEngine : IDisposable { var accounts = await _db.ReadAsync(s => s.QueryAsync("SELECT id FROM accounts WHERE broker = @b", r => r.Id("id"), ("b", Venues.Alpaca)), cancellationToken) .ConfigureAwait(false); - return [.. accounts.Select(_managers).OfType()]; + return [.. accounts.Where(AccountReady).Select(_managers).OfType()]; } /// @@ -340,12 +349,17 @@ public sealed partial class LiveEngine : IDisposable } var stage = await _stages.GetAsync(StrategyNames.EquityMeanrev, cancellationToken).ConfigureAwait(false); - if (stage?.OrdersAccount is not { } accountId || _managers(accountId) is not { } manager) + if (stage?.OrdersAccount is not { } accountId || _managers(accountId) is null) { await ClaimOnlyAsync(StrategyNames.EquityMeanrev, key, session.Date, cancellationToken).ConfigureAwait(false); return; } + if (!AccountReady(accountId)) + { + return; + } + var book = await BookAsync(accountId, StrategyNames.EquityMeanrev, cancellationToken).ConfigureAwait(false); if (book.Holdings.Count == 0) { @@ -364,16 +378,10 @@ public sealed partial class LiveEngine : IDisposable var record = BacktestEngine.DecideOnce(strategy, data.Data, book.State, session.Date, options); var decisionId = Ids.NewId(_clock); var exits = record.Final.Where(i => i.AtClose && i.TargetWeight == 0m && book.Holdings.ContainsKey(i.Symbol)).ToList(); - var submitted = new List<(Intent Intent, Guid? Execution, string? Refusal)>(); - foreach (var exit in exits) - { - var held = book.Holdings[exit.Symbol]; - var (execution, refusal) = await manager.SubmitAsync(new TradeIntent(held.InstrumentId, StrategyNames.EquityMeanrev, OrderSide.Sell, held.Holding.Quantity, OrderPurpose.Exit, - decisionId) - { StartAggressive = true }, cancellationToken).ConfigureAwait(false); - submitted.Add((exit, execution, refusal)); - } + // The exits are planned in the same transaction as the run key, like every other decision, and leave at once + // from the release below: a restart finds them planned and proposes them again (SPEC 9.4), and a failed + // attempt never sends the same exit twice with two keys. The deadline at the close makes them start aggressive. await _db.WriteAsync(async s => { if (!await ClaimAsync(s, StrategyNames.EquityMeanrev, key, session.Date, decisionId, DecisionModes.Full, null, null, cancellationToken).ConfigureAwait(false)) @@ -381,13 +389,23 @@ public sealed partial class LiveEngine : IDisposable return; } - foreach (var (intent, execution, refusal) in submitted) + foreach (var exit in exits) { - await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, StrategyNames.EquityMeanrev, accountId, intent.Symbol, DecisionStages.Strategy, DecisionOutcomes.Proposed, - [intent.Reason], new Dictionary { ["weight"] = 0m, ["at_close"] = true }, now), cancellationToken).ConfigureAwait(false); - await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, StrategyNames.EquityMeanrev, accountId, intent.Symbol, DecisionStages.Order, - refusal is null ? DecisionOutcomes.Passed : DecisionOutcomes.Refused, refusal is null ? [] : [refusal], - new Dictionary { ["execution"] = execution }, now), cancellationToken).ConfigureAwait(false); + var held = book.Holdings[exit.Symbol]; + var instrument = data.Data.Instruments.FirstOrDefault(i => i.Symbol == exit.Symbol); + var reference = instrument is null ? 0m : Close(instrument, session.Date) ?? 0m; + var id = Ids.NewId(_clock); + await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, StrategyNames.EquityMeanrev, accountId, exit.Symbol, DecisionStages.Strategy, DecisionOutcomes.Proposed, + [exit.Reason], new Dictionary { ["weight"] = 0m, ["at_close"] = true }, now), cancellationToken).ConfigureAwait(false); + await s.ExecuteAsync( + "INSERT INTO planned_orders (id, decision_id, strategy, account_id, instrument_id, side, purpose, quantity, exit_all, stop_level, stop_offset, reference_price, reason, due_at, valid_until, status, created_at, updated_at) " + + "VALUES (@id, @d, @s, @a, @i, @side, @p, @q, @all, NULL, NULL, @ref, @r, @due, @until, @st, @now, @now)", cancellationToken, + ("id", id), ("d", decisionId), ("s", StrategyNames.EquityMeanrev), ("a", accountId), ("i", held.InstrumentId), ("side", Wire.Text(OrderSide.Sell)), + ("p", Wire.Text(OrderPurpose.Exit)), ("q", DbValues.Money(held.Holding.Quantity)), ("all", true), ("ref", reference), ("r", exit.Reason), ("due", now), + ("until", session.CloseUtc), ("st", PlannedStates.Pending), ("now", now)).ConfigureAwait(false); + await DecisionLog.WriteAsync(s, _clock, new DecisionRow(decisionId, StrategyNames.EquityMeanrev, accountId, exit.Symbol, DecisionStages.Sizing, DecisionOutcomes.Passed, [], + new Dictionary { ["side"] = Wire.Text(OrderSide.Sell), ["quantity"] = held.Holding.Quantity, ["close"] = reference, ["planned"] = id }, now), + cancellationToken).ConfigureAwait(false); } }, cancellationToken).ConfigureAwait(false); } @@ -422,6 +440,12 @@ public sealed partial class LiveEngine : IDisposable return; } + if (!observation && !AccountReady(account)) + { + // Its ledger is not reconciled yet: the decision waits for the next pulse, late if it must (SPEC 5.6). + return; + } + var book = observation ? Book.Empty : await BookAsync(account, m.Strategy, cancellationToken).ConfigureAwait(false); var loaded = await LoadAsync(m.Strategy, m.Day, book, provisional: false, cancellationToken).ConfigureAwait(false); if (loaded.Data is null || loaded.Missing.Count > 0) @@ -858,7 +882,7 @@ public sealed partial class LiveEngine : IDisposable return; } - if (_managers(order.AccountId) is not { } manager) + if (!AccountReady(order.AccountId) || _managers(order.AccountId) is not { } manager) { return; } @@ -908,8 +932,13 @@ public sealed partial class LiveEngine : IDisposable } } - var (execution, refusal) = await manager.SubmitAsync(new TradeIntent(order.InstrumentId, order.Strategy, order.Side, quantity, order.Purpose, order.Id) { StopLevel = stopLevel }, - cancellationToken).ConfigureAwait(false); + // A sale never expires; one with a deadline (the exits at the close) starts aggressive: there are minutes left. + var aggressive = order.Side == OrderSide.Sell && order.ValidUntil is not null; + var (execution, refusal) = await manager.SubmitAsync(new TradeIntent(order.InstrumentId, order.Strategy, order.Side, quantity, order.Purpose, order.Id) + { + StopLevel = stopLevel, + StartAggressive = aggressive, + }, cancellationToken).ConfigureAwait(false); var recovered = late ? DiaryText.Recovered(OrderWords(order, instrument.Symbol), order.Due, Zone) : null; await CloseAsync(order, refusal is null ? PlannedStates.Submitted : PlannedStates.Refused, refusal, execution, recovered, cancellationToken).ConfigureAwait(false); } @@ -927,23 +956,25 @@ public sealed partial class LiveEngine : IDisposable var again = 0; foreach (var execution in canceled) { - var row = await _db.ReadAsync(s => s.FirstOrDefaultAsync( - "SELECT p.id, p.decision_id, p.strategy, p.account_id, p.instrument_id, p.side, p.purpose, p.quantity, p.exit_all, p.stop_level, p.stop_offset, " + - "p.reference_price, p.reason, p.due_at, p.valid_until, e.filled FROM planned_orders p JOIN executions e ON e.id = p.execution_id WHERE p.execution_id = @e", - r => new Interrupted(new Planned(r.Id("id"), r.Id("decision_id"), r.Text("strategy"), r.Id("account_id"), r.Id("instrument_id"), Wire.Side(r.Text("side")), - Wire.Purpose(r.Text("purpose")), r.Money("quantity"), r.Bool("exit_all"), r.MoneyOrNull("stop_level"), r.MoneyOrNull("stop_offset"), r.Money("reference_price"), - r.Text("reason"), r.Moment("due_at"), r.MomentOrNull("valid_until")), r.Money("filled")), ("e", execution)), cancellationToken).ConfigureAwait(false); + var row = await InterruptedAsync(execution, cancellationToken).ConfigureAwait(false); if (row is not { } found || (found.Order.Quantity - found.Filled <= 0m && !found.Order.ExitAll)) { continue; } - var (order, filled) = found; + var (order, filled, unlinked) = found; var symbol = (await _catalog.GetAsync(order.InstrumentId, cancellationToken).ConfigureAwait(false))?.Symbol ?? "?"; var now = _clock.UtcNow; var sale = order.Side == OrderSide.Sell; await _db.WriteAsync(async s => { + if (unlinked) + { + // The process stopped between sending it and marking it sent: it is marked now, so it never goes again. + await s.ExecuteAsync("UPDATE planned_orders SET status = @st, execution_id = @e, updated_at = @now WHERE id = @id AND status = @p", cancellationToken, + ("st", PlannedStates.Submitted), ("e", execution), ("now", now), ("id", order.Id), ("p", PlannedStates.Pending)).ConfigureAwait(false); + } + await s.ExecuteAsync( "INSERT INTO planned_orders (id, decision_id, strategy, account_id, instrument_id, side, purpose, quantity, exit_all, stop_level, stop_offset, reference_price, " + "reason, due_at, valid_until, status, outcome, execution_id, created_at, updated_at) VALUES (@id, @d, @s, @a, @i, @side, @p, @q, @x, @sl, @so, @r, @reason, " + @@ -961,7 +992,42 @@ public sealed partial class LiveEngine : IDisposable return again; } - private sealed record Interrupted(Planned Order, decimal Filled); + private sealed record Interrupted(Planned Order, decimal Filled, bool Unlinked); + + private const string PlannedColumns = + "p.id, p.decision_id, p.strategy, p.account_id, p.instrument_id, p.side, p.purpose, p.quantity, p.exit_all, p.stop_level, p.stop_offset, p.reference_price, p.reason, p.due_at, p.valid_until"; + + private static Planned ReadPlanned(DbRow r) => + new(r.Id("id"), r.Id("decision_id"), r.Text("strategy"), r.Id("account_id"), r.Id("instrument_id"), Wire.Side(r.Text("side")), Wire.Purpose(r.Text("purpose")), + r.Money("quantity"), r.Bool("exit_all"), r.MoneyOrNull("stop_level"), r.MoneyOrNull("stop_offset"), r.Money("reference_price"), r.Text("reason"), r.Moment("due_at"), + r.MomentOrNull("valid_until")); + + /// + /// The planned order behind a canceled execution: the one that points to it, or, when the process stopped between + /// sending it and marking it sent, the pending one whose key the execution carries. + /// + private Task InterruptedAsync(Guid execution, CancellationToken cancellationToken) => + _db.ReadAsync(async s => + { + var info = await s.FirstOrDefaultAsync("SELECT account_id, instrument_id, order_key, filled FROM executions WHERE id = @e", + r => (Account: r.Id("account_id"), Instrument: r.Id("instrument_id"), Key: r.Text("order_key"), Filled: r.Money("filled")), ("e", execution)).ConfigureAwait(false); + if (info.Key is null) + { + return null; + } + + var linked = await s.FirstOrDefaultAsync("SELECT " + PlannedColumns + " FROM planned_orders p WHERE p.execution_id = @e", ReadPlanned, ("e", execution)) + .ConfigureAwait(false); + if (linked is not null) + { + return new Interrupted(linked, info.Filled, false); + } + + var pending = await s.QueryAsync("SELECT " + PlannedColumns + " FROM planned_orders p WHERE p.account_id = @a AND p.instrument_id = @i AND p.status = @p AND p.execution_id IS NULL", + ReadPlanned, ("a", info.Account), ("i", info.Instrument), ("p", PlannedStates.Pending)).ConfigureAwait(false); + var unlinked = pending.FirstOrDefault(p => ClientOrderIds.Key(p.Id) == info.Key); + return unlinked is null ? (Interrupted?)null : new Interrupted(unlinked, info.Filled, true); + }, cancellationToken); private static string OrderWords(Planned order, string symbol) => (order.Side == OrderSide.Buy ? "l'acquisto di " : "la vendita di ") + DiaryText.Shown(symbol); diff --git a/src/Anubis/Trading/TradingService.cs b/src/Anubis/Trading/TradingService.cs index bd44a26..f17a3ee 100644 --- a/src/Anubis/Trading/TradingService.cs +++ b/src/Anubis/Trading/TradingService.cs @@ -188,6 +188,7 @@ public sealed partial class TradingService : IDisposable { WantData = market is null ? null : _ => market.WakeWorker(), Ready = () => _started, + AccountReady = AccountReady, }; } @@ -305,36 +306,12 @@ public sealed partial class TradingService : IDisposable } await GuardAsync("azioni societarie nei registri", () => CorporateActionsAsync(cancellationToken), cancellationToken).ConfigureAwait(false); - var notes = GuardFiles is null ? [] : Supervision.GuardFiles.ReadNotes(GuardFiles); foreach (var manager in _managers.Values) { - await GuardAsync("avvio " + manager.Account.Name, async () => - { - if (manager.Broker is PaperBroker paper) - { - await paper.CatchUpAsync(MinuteBarsAsync, cancellationToken).ConfigureAwait(false); - } - else - { - await Reconciler.CheckKeyAsync(manager, cancellationToken).ConfigureAwait(false); - } - - // The stops the guard put back while the engine was stopped become the engine's own, before anything compares. - foreach (var placed in notes.SelectMany(n => n.Note.Placed).Where(p => p.AccountId == manager.Account.AccountId)) - { - await manager.AdoptStopAsync(placed, cancellationToken).ConfigureAwait(false); - } - - Guard?.Step("riconciliazione " + manager.Account.Name); - await Reconciler.ReconcileAsync(manager, cancellationToken).ConfigureAwait(false); - Guard?.Step("ordini rimasti aperti " + manager.Account.Name); - await Engine.ResumeAsync(manager, cancellationToken).ConfigureAwait(false); - Guard?.Step("stop " + manager.Account.Name); - await manager.AlignStopsAsync(cancellationToken).ConfigureAwait(false); - }, cancellationToken).ConfigureAwait(false); + await StartAccountAsync(manager, cancellationToken).ConfigureAwait(false); } - await GuardAsync("note della guardia", () => TakeGuardNotesAsync(notes, cancellationToken), cancellationToken).ConfigureAwait(false); + _accountsRetryAt = _clock.UtcNow + AccountRetry; await GuardAsync("patrimonio", () => PhotographAsync(cancellationToken), cancellationToken).ConfigureAwait(false); await GuardAsync("stato per la guardia", () => WriteGuardStateAsync(cancellationToken), cancellationToken).ConfigureAwait(false); await GuardAsync("chiavi per la guardia", () => SendGuardKeysAsync(alpaca, okx, cancellationToken), cancellationToken).ConfigureAwait(false); @@ -363,14 +340,97 @@ public sealed partial class TradingService : IDisposable _guardStateAt = _clock.UtcNow; } - // The guard's notes go in the diary once their stops are adopted; then they are gone. - private async Task TakeGuardNotesAsync(IReadOnlyList<(string Path, GuardNote Note)> notes, CancellationToken cancellationToken) + /// The accounts whose startup of SPEC 9.4 is done: only these are ticked, decided on and sent orders. + public bool AccountReady(Guid accountId) => _ready.ContainsKey(accountId); + + private readonly ConcurrentDictionary _ready = new(); + + /// An account whose startup failed (broker unreachable) is tried again this often. + public TimeSpan AccountRetry { get; init; } = TimeSpan.FromMinutes(1); + + private DateTimeOffset _accountsRetryAt; + + /// + /// The startup of one account (SPEC 9.4): the guard's stops adopted first, whatever else fails; then the key, the + /// complete reconciliation, the purchases and sales left open canceled (exits restart, entries are proposed again) + /// and every position checked for its stop. Until all of it is done the account is not ready. + /// + private async Task StartAccountAsync(OrderManager manager, CancellationToken cancellationToken) { - foreach (var (path, note) in notes) + var name = manager.Account.Name; + await GuardAsync("stop della guardia " + name, () => AdoptGuardStopsAsync(manager, cancellationToken), cancellationToken).ConfigureAwait(false); + var started = await TryAsync("avvio " + name, async () => { - await _db.WriteAsync(s => Diary.WriteAsync(s, _clock, DiaryKinds.System, "guard_intervention", string.Join(" ", note.Lines), - new { at = note.At, reason = note.Reason, stops = note.Placed.Count, stopFile = note.StopFileCreated }, cancellationToken), cancellationToken).ConfigureAwait(false); - File.Delete(path); + if (manager.Broker is PaperBroker paper) + { + await paper.CatchUpAsync(MinuteBarsAsync, cancellationToken).ConfigureAwait(false); + } + else + { + await Reconciler.CheckKeyAsync(manager, cancellationToken).ConfigureAwait(false); + } + + Guard?.Step("riconciliazione " + name); + await Reconciler.ReconcileAsync(manager, cancellationToken).ConfigureAwait(false); + Guard?.Step("ordini rimasti aperti " + name); + await Engine.ResumeAsync(manager, cancellationToken).ConfigureAwait(false); + Guard?.Step("stop " + name); + await manager.AlignStopsAsync(cancellationToken).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); + if (started) + { + _ready[manager.Account.AccountId] = true; + } + } + + /// + /// The stops the guard put back while the engine was stopped become the engine's own, before anything compares + /// them. A note goes in the diary and is deleted only when every stop it placed is adopted, for every account: a + /// stop left unknown would be put back a second time. + /// + private async Task AdoptGuardStopsAsync(OrderManager manager, CancellationToken cancellationToken) + { + if (GuardFiles is null) + { + return; + } + + foreach (var (path, note) in Supervision.GuardFiles.ReadNotes(GuardFiles)) + { + foreach (var placed in note.Placed.Where(p => p.AccountId == manager.Account.AccountId)) + { + await manager.AdoptStopAsync(placed, cancellationToken).ConfigureAwait(false); + } + + var adopted = true; + foreach (var placed in note.Placed) + { + adopted &= await _db.ReadAsync(async s => await s.CountAsync("SELECT COUNT(*) FROM orders WHERE client_order_id = @c", ("c", placed.ClientOrderId)) + .ConfigureAwait(false) > 0, cancellationToken).ConfigureAwait(false); + } + + if (adopted) + { + await _db.WriteAsync(s => Diary.WriteAsync(s, _clock, DiaryKinds.System, "guard_intervention", string.Join(" ", note.Lines), + new { at = note.At, reason = note.Reason, stops = note.Placed.Count, stopFile = note.StopFileCreated }, cancellationToken), cancellationToken).ConfigureAwait(false); + File.Delete(path); + } + } + } + + /// The accounts whose startup failed are tried again, once a minute. + private async Task RetryAccountsAsync(CancellationToken cancellationToken) + { + if (_clock.UtcNow < _accountsRetryAt) + { + return; + } + + _accountsRetryAt = _clock.UtcNow + AccountRetry; + foreach (var manager in _managers.Values.Where(m => !AccountReady(m.Account.AccountId))) + { + await LimitedAsync("nuovo avvio " + manager.Account.Name, RetryLimit, ct => StartAccountAsync(manager, ct), cancellationToken).ConfigureAwait(false); + BeatIfAlive(); } } @@ -504,7 +564,7 @@ public sealed partial class TradingService : IDisposable } await TickAllAsync(cancellationToken).ConfigureAwait(false); - Guard?.Beat(); + BeatIfAlive(); if (GuardFiles is not null && _clock.UtcNow - _guardStateAt >= GuardStateEvery) { await GuardAsync("stato per la guardia", () => WriteGuardStateAsync(cancellationToken), cancellationToken).ConfigureAwait(false); @@ -550,20 +610,52 @@ public sealed partial class TradingService : IDisposable public async Task TickAllAsync(CancellationToken cancellationToken) { - foreach (var manager in _managers.Values) + await RetryAccountsAsync(cancellationToken).ConfigureAwait(false); + + // An account not started yet keeps what it left open untouched: its startup cancels or resumes it first. + foreach (var manager in _managers.Values.Where(m => AccountReady(m.Account.AccountId))) { - await GuardAsync("ordini " + manager.Account.Name, async () => + await LimitedAsync("ordini " + manager.Account.Name, TickLimit, async ct => { if (manager.Broker is PaperBroker paper) { - await paper.PumpAsync(cancellationToken).ConfigureAwait(false); + await paper.PumpAsync(ct).ConfigureAwait(false); } - await manager.TickAsync(cancellationToken).ConfigureAwait(false); + await manager.TickAsync(ct).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false); + BeatIfAlive(); } } + /// + /// The longest one account's turn of the loop may take. A broker that stops answering (timeouts, retries) must + /// not keep the loop from beating for the two minutes after which the guard steps in: the turn is cut, written in + /// the log, and tried again at the next round. A loop that is truly stuck still falls silent. + /// + public TimeSpan TickLimit { get; init; } = TimeSpan.FromSeconds(45); + + /// The longest an account's startup may take when it is tried again from the loop. + public TimeSpan RetryLimit { get; init; } = TimeSpan.FromSeconds(60); + + /// Whether the other loops of the engine are alive (the scheduler): without them the beat is withheld. + public Func? OthersAlive { get; init; } + + private void BeatIfAlive() + { + if (OthersAlive is null || OthersAlive()) + { + Guard?.Beat(); + } + } + + private async Task LimitedAsync(string what, TimeSpan limit, Func work, CancellationToken cancellationToken) + { + using var limited = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + limited.CancelAfter(limit); + await GuardAsync(what, () => work(limited.Token), cancellationToken).ConfigureAwait(false); + } + public async Task ReconcileAllAsync(CancellationToken cancellationToken) { await RefreshSpecsAsync(cancellationToken).ConfigureAwait(false); @@ -816,11 +908,15 @@ public sealed partial class TradingService : IDisposable } } - private async Task GuardAsync(string what, Func work, CancellationToken cancellationToken) + private Task GuardAsync(string what, Func work, CancellationToken cancellationToken) => TryAsync(what, work, cancellationToken); + + /// Runs a step; a failure is logged and the answer is false. Only the stop of the service passes through. + private async Task TryAsync(string what, Func work, CancellationToken cancellationToken) { try { await work().ConfigureAwait(false); + return true; } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { @@ -829,6 +925,7 @@ public sealed partial class TradingService : IDisposable catch (Exception ex) { LogWorkFailed(_logger, ex, what); + return false; } } diff --git a/tests/Anubis.Tests/LiveEngineTests.cs b/tests/Anubis.Tests/LiveEngineTests.cs index a8ad544..5c02e28 100644 --- a/tests/Anubis.Tests/LiveEngineTests.cs +++ b/tests/Anubis.Tests/LiveEngineTests.cs @@ -71,6 +71,8 @@ public sealed class LiveEngineTests var last = LiveFrom.AddDays(13); await using var live = await LiveRig.CreateAsync(LiveFrom, last).ConfigureAwait(false); var restarted = false; + var waited = false; + (int Runs, int Sent) before = default; for (var day = LiveFrom; day <= last; day = day.AddDays(1)) { var index = day.DayNumber - LiveFrom.DayNumber; @@ -90,6 +92,25 @@ public sealed class LiveEngineTests } , + // The account has not finished its startup (the broker did not answer it): for three minutes nothing is + // decided or sent on it, then the decision is made late. + 5 => async minute => + { + var runs = (await live.Rig.QueryAsync("SELECT run_key FROM engine_runs", r => r.Text("run_key")).ConfigureAwait(false)).Count; + if (minute == 0) + { + before = (runs, live.Sent.Count); + } + else if (minute == 3) + { + Assert.AreEqual(before, (runs, live.Sent.Count), "Nothing is decided or sent on an account not started."); + waited = true; + } + + live.AccountStarted = minute >= 3; + } + , + // The process dies with a purchase working at the broker and starts again. 11 => async minute => { @@ -118,6 +139,7 @@ public sealed class LiveEngineTests } Assert.IsTrue(restarted, "The run must restart halfway through an order."); + Assert.IsTrue(waited, "The run must hold an account not started."); Assert.AreEqual(1, live.Restarts); Assert.IsGreaterThan(0, live.Failures, "The faults must have hit the work."); diff --git a/tests/Anubis.Tests/LiveSupport.cs b/tests/Anubis.Tests/LiveSupport.cs index cb7fcd9..d42b353 100644 --- a/tests/Anubis.Tests/LiveSupport.cs +++ b/tests/Anubis.Tests/LiveSupport.cs @@ -36,6 +36,9 @@ internal sealed class LiveRig : IAsyncDisposable public LiveEngine Engine { get; private set; } = null!; + /// Whether the account finished its startup (SPEC 9.4); while false the engine leaves it alone. + public bool AccountStarted { get; set; } = true; + public EquityBook Equity { get; private set; } = null!; public Reconciler Reconciler { get; private set; } = null!; @@ -103,7 +106,10 @@ internal sealed class LiveRig : IAsyncDisposable { Broker = new FaultyBroker(Paper); Manager = Rig.Manager(Broker, Okx); - Engine = new LiveEngine(Rig.Db, Rig.Clock, Rig.Ledger, Stages, id => id == Okx.AccountId ? Manager : null, Rig.QuoteAsync); + Engine = new LiveEngine(Rig.Db, Rig.Clock, Rig.Ledger, Stages, id => id == Okx.AccountId ? Manager : null, Rig.QuoteAsync) + { + AccountReady = _ => AccountStarted, + }; } /// diff --git a/tests/Anubis.Tests/OverviewScreenTests.cs b/tests/Anubis.Tests/OverviewScreenTests.cs index 035fb36..f875548 100644 --- a/tests/Anubis.Tests/OverviewScreenTests.cs +++ b/tests/Anubis.Tests/OverviewScreenTests.cs @@ -130,6 +130,19 @@ public sealed class OverviewScreenTests StringAssert.Contains(diary, "Come sta il sistema"); StringAssert.Contains(diary, "non configurato"); StringAssert.Contains(diary, "Il computer che lo ospita"); + + // SPEC 5.6: an absence longer than a day stays at the top of the Panoramica until "Ho visto". + var now = server.Host.Clock.UtcNow; + var id = Guid.NewGuid(); + await server.Host.Services!.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO absences (id, started_at, ended_at, acknowledged_at, created_at) VALUES (@id, @s, @e, NULL, @e)", + CancellationToken.None, ("id", id), ("s", now.AddDays(-3).AddHours(-2)), ("e", now))); + StringAssert.Contains(await server.TextAsync("/"), "Sono stato spento per 3 giorni e 2 ore, fino a oggi alle"); + using (var seen = await server.PostFormAsync("/", $"/azioni/assenza/{id}/vista")) + { + Assert.AreEqual("/", ServerHarness.Location(seen)); + } + + Assert.DoesNotContain("Sono stato spento", await server.TextAsync("/")); } [TestMethod] diff --git a/tests/Anubis.Tests/ServerTests.cs b/tests/Anubis.Tests/ServerTests.cs index a770a45..630e7c1 100644 --- a/tests/Anubis.Tests/ServerTests.cs +++ b/tests/Anubis.Tests/ServerTests.cs @@ -200,23 +200,27 @@ public sealed class ServerTests ServerHarness.UsePostgres(env, empty); } - await using var server = await ServerHarness.StartAsync("docker", env, dataDir: data, waitReady: false); - await server.WaitForAsync(HostMode.IdentityProblem); - Assert.AreEqual(IdentityVerdict.EmptyDatabase, server.Host.Status.Identity!.Verdict); - using (var restore = await server.PostFormAsync("/", "/azioni/servizio/ripristina", ("password", ServerHarness.AdminPassword), ("salvataggio", backup.Name))) + // The server stops before its data folder is removed: a running one may still hold the database file. + await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data, waitReady: false)) { - Assert.AreEqual("/", ServerHarness.Location(restore)); + await server.WaitForAsync(HostMode.IdentityProblem); + Assert.AreEqual(IdentityVerdict.EmptyDatabase, server.Host.Status.Identity!.Verdict); + using (var restore = await server.PostFormAsync("/", "/azioni/servizio/ripristina", ("password", ServerHarness.AdminPassword), ("salvataggio", backup.Name))) + { + Assert.AreEqual("/", ServerHarness.Location(restore)); + } + + await server.WaitForAsync(HostMode.Ready); + + // SPEC 15.1: back with "Ferma tutto" on, a new fingerprint, and nobody signed in. + var state = await server.Host.Services!.Settings.GetAsync(SettingsStore.BotState.Key); + Assert.AreEqual("stopped", state.Value); + var row = await Installation.ReadRowAsync(server.Host.Services.Db); + Assert.IsTrue(row!.ProtectedRestart); + Assert.AreEqual(row.Fingerprint, Installation.ReadFile(new DataDirectory(data))!.Fingerprint); + Assert.AreEqual(0, await server.Host.Services.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM sessions"))); } - await server.WaitForAsync(HostMode.Ready); - - // SPEC 15.1: back with "Ferma tutto" on, a new fingerprint, and nobody signed in. - var state = await server.Host.Services!.Settings.GetAsync(SettingsStore.BotState.Key); - Assert.AreEqual("stopped", state.Value); - var row = await Installation.ReadRowAsync(server.Host.Services.Db); - Assert.IsTrue(row!.ProtectedRestart); - Assert.AreEqual(row.Fingerprint, Installation.ReadFile(new DataDirectory(data))!.Fingerprint); - Assert.AreEqual(0, await server.Host.Services.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM sessions"))); TempFolder.Delete(data); } diff --git a/tests/Anubis.Tests/SoakReportTests.cs b/tests/Anubis.Tests/SoakReportTests.cs index b8c0e75..3291b0b 100644 --- a/tests/Anubis.Tests/SoakReportTests.cs +++ b/tests/Anubis.Tests/SoakReportTests.cs @@ -17,7 +17,8 @@ public sealed class SoakReportTests { Assert.AreEqual(2, SoakReporter.DailyCloses(From, To)); // 12 and 13 November at 00:05 UTC var close = new DateTimeOffset(2026, 11, 11, 0, 5, 0, TimeSpan.Zero); - Assert.AreEqual(1, SoakReporter.DailyCloses(close, close)); + Assert.AreEqual(1, SoakReporter.DailyCloses(close, close + SoakReporter.DecisionTime)); + Assert.AreEqual(0, SoakReporter.DailyCloses(close, close.AddMinutes(10)), "A decision just started is not expected yet."); Assert.AreEqual(3, SoakReporter.DailyCloses(close, To)); Assert.AreEqual(0, SoakReporter.DailyCloses(From, From.AddHours(5))); } diff --git a/tests/Anubis.Tests/TelegramTests.cs b/tests/Anubis.Tests/TelegramTests.cs index cb55257..8e3bac0 100644 --- a/tests/Anubis.Tests/TelegramTests.cs +++ b/tests/Anubis.Tests/TelegramTests.cs @@ -168,6 +168,9 @@ public sealed class TelegramTests Assert.IsNull(Heartbeat.Check("https://hc-ping.com/uuid")); Assert.IsNull(Heartbeat.Check("http://192.168.30.23:8000/ping/x")); Assert.IsNotNull(Heartbeat.Check("http://hc-ping.com/uuid")); + Assert.IsNotNull(Heartbeat.Check("http://8.8.8.8/ping/x"), "A public address in plain http travels in clear."); + Assert.IsNull(Heartbeat.Check("http://10.0.0.5/ping/x")); + Assert.IsNull(Heartbeat.Check("http://[fd00::5]/ping/x")); Assert.IsNotNull(Heartbeat.Check("ftp://example.com")); Assert.IsNotNull(Heartbeat.Check("non è un indirizzo")); } From be6d5fb91f6d76ffd8a7a741abeb50e23c305275 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 11 Nov 2026 21:35:03 +0100 Subject: [PATCH 10/12] Let a late decision wait for its bars; read the soak run's continuity from jobs and absences (refs #49 #53) Starting the 48-hour run showed two defects. After an absence, a decision made past 12:00 UTC was written off as "no data" at the first pulse, because the data step had not yet brought the bars of the close: the recovered decision was lost. A late decision now asks for its bars and waits up to 30 minutes for them. The 20-hour absence test pulses before the bar arrives and fails without the fix. The soak report measured coverage and silences from reconciliation rows, but a clean round writes none, so a healthy run would have been reported as never covered. It now reads when the scheduled jobs first ran and last finished, the absences written at each restart, the guard interventions, and each account's status (reconciled within the last 15 minutes and normal). The test no longer fakes a row every 5 minutes. Co-Authored-By: Claude Opus 5.5 --- docs/adr/0012-scelte-fase-6.md | 8 +++- src/Anubis/Supervision/SoakReport.cs | 67 +++++++++++++++------------ src/Anubis/Trading/LiveEngine.cs | 24 +++++++++- tests/Anubis.Tests/AbsenceTests.cs | 7 ++- tests/Anubis.Tests/SoakReportTests.cs | 66 ++++++++++++++------------ 5 files changed, 109 insertions(+), 63 deletions(-) diff --git a/docs/adr/0012-scelte-fase-6.md b/docs/adr/0012-scelte-fase-6.md index 73e2859..0405654 100644 --- a/docs/adr/0012-scelte-fase-6.md +++ b/docs/adr/0012-scelte-fase-6.md @@ -114,7 +114,7 @@ La Fase 6 porta il bot che lavora da solo in simulazione: la giornata di 5.5, il **11. La prova di durata.** - `anubis soak` legge i registri del bot su una finestra di tempo e scrive un rapporto, senza cambiare niente. Può girare mentre il bot lavora, in Docker con `docker exec`. I suoi controlli: - durata coperta; - - nessun silenzio oltre 15 minuti (la riconciliazione scrive una riga ogni 5); + - bot al lavoro dall'inizio alla fine (vedi il punto 12); - nessun ordine né decisione doppia; - nessuna differenza inspiegata e ultima riconciliazione in regola per ogni conto; - nessuno spegnimento; @@ -133,6 +133,12 @@ La Fase 6 porta il bot che lavora da solo in simulazione: la giornata di 5.5, il - **Una decisione azionaria fatta dopo l'apertura** (per esempio dopo un'assenza) è segnata in ritardo e segue le regole del recupero. - **I cicli di Telegram non si fermano per un errore inatteso** (database occupato, rete): scrivono nel registro e riprovano. - **Lo spegnimento lungo si vede in Panoramica** (SPEC 5.6): un avviso in cima dice per quanto il bot è rimasto spento e rimanda al diario, finché l'utente non preme "Ho visto". +- **Una decisione in ritardo aspetta i suoi dati.** Dopo uno spegnimento, al primo battito i dati del giorno prima non sono ancora arrivati: una decisione fatta dopo le 12:00 UTC li chiede e li aspetta fino a 30 minuti, invece di chiudersi subito come "senza dati" e andare persa. Il difetto si è visto all'avvio della prova di durata. +- **Il rapporto della prova di durata non conta più le righe di riconciliazione**, che si scrivono solo quando c'è una differenza. Legge invece: + - quando i lavori in programma hanno cominciato e quando hanno finito l'ultima volta; + - gli spegnimenti, scritti a ogni ripartenza dopo almeno 5 minuti; + - gli interventi della guardia, per un ciclo fermo con il processo vivo; + - lo stato di ogni conto: riconciliato negli ultimi 15 minuti della finestra e in modalità normale. - Il segnale di vita in `http://` è accettato solo verso indirizzi della rete di casa (10.x, 172.16-31.x, 192.168.x, locali e i loro equivalenti IPv6); il rapporto della prova di durata non conta una chiusura giornaliera avvenuta meno di 30 minuti prima della fine della finestra. ## Conseguenze diff --git a/src/Anubis/Supervision/SoakReport.cs b/src/Anubis/Supervision/SoakReport.cs index aedbc97..b3e979b 100644 --- a/src/Anubis/Supervision/SoakReport.cs +++ b/src/Anubis/Supervision/SoakReport.cs @@ -53,7 +53,10 @@ public sealed record SoakReport(DateTimeOffset From, DateTimeOffset To, IReadOnl /// Builds the from the database. public static class SoakReporter { - /// The reconciliation runs every 5 minutes: a longer silence than this means the bot stopped working. + /// + /// The reconciliation and the other frequent jobs run every 5 minutes: a job last finished longer ago than this, or an + /// account last reconciled longer ago, means the bot stopped working. + /// public static readonly TimeSpan MaxSilence = TimeSpan.FromMinutes(15); public static async Task BuildAsync(Database db, DateTimeOffset from, DateTimeOffset to, TimeSpan minimum, TimeZoneInfo zone, @@ -72,27 +75,28 @@ public static class SoakReporter var facts = new List(); (string Name, object? Value)[] window = [("from", from), ("to", to)]; - // Continuity: the reconciliation writes a row every 5 minutes, whatever it finds. - var beats = await s.QueryAsync("SELECT occurred_at FROM reconciliations WHERE occurred_at >= @from AND occurred_at <= @to ORDER BY occurred_at", - r => r.Moment("occurred_at"), window).ConfigureAwait(false); - var covered = beats.Count == 0 ? TimeSpan.Zero : beats[^1] - beats[0]; + // Continuity. A clean reconciliation writes no row, so the bot's life is read elsewhere: its scheduled jobs + // say when it first ran and when it last finished something; every stop of 5 minutes or more is written as an + // absence at the restart (SPEC 5.6); a loop stuck while the process lives is a guard intervention (below). + var jobs = await s.FirstOrDefaultAsync("SELECT MIN(created_at) AS first, MAX(last_finished_at) AS last FROM jobs", + r => (First: r.IsNull("first") ? (DateTimeOffset?)null : r.Moment("first"), Last: r.IsNull("last") ? (DateTimeOffset?)null : r.Moment("last"))) + .ConfigureAwait(false); + var absences = await s.QueryAsync("SELECT started_at, ended_at FROM absences WHERE ended_at >= @from AND started_at <= @to ORDER BY started_at", + r => (Start: r.Moment("started_at"), End: r.Moment("ended_at")), window).ConfigureAwait(false); + var start = jobs.First is { } first && first > from ? first : from; + var end = jobs.Last is { } lastJob && lastJob < to ? lastJob : to; + var covered = jobs.First is null || jobs.Last is null || end <= start ? TimeSpan.Zero + : end - start - absences.Aggregate(TimeSpan.Zero, (sum, a) => sum + (Min(a.End, end) - Max(a.Start, start) is { } span && span > TimeSpan.Zero ? span : TimeSpan.Zero)); checks.Add(new SoakCheck($"Durata coperta dal lavoro del bot: {SoakReport.Hours(covered)} (servono almeno {SoakReport.Hours(minimum)}).", covered >= minimum)); - var silences = new List<(DateTimeOffset Start, TimeSpan Length)>(); - var edges = new List { from }; - edges.AddRange(beats); - edges.Add(to); - for (var i = 1; i < edges.Count; i++) + var startedInTime = jobs.First is { } began && began <= from + MaxSilence; + var workingAtEnd = jobs.Last is { } finished && finished >= to - MaxSilence; + checks.Add(new SoakCheck((jobs.First, jobs.Last) switch { - if (edges[i] - edges[i - 1] > MaxSilence) - { - silences.Add((edges[i - 1], edges[i] - edges[i - 1])); - } - } - - checks.Add(new SoakCheck(silences.Count == 0 - ? $"Nessun silenzio più lungo di {Minutes(MaxSilence)} ({beats.Count} riconciliazioni)." - : $"Silenzi più lunghi di {Minutes(MaxSilence)}: " + - string.Join(", ", silences.Select(g => $"dal {SoakReport.Moment(g.Start, zone)} per {Minutes(g.Length)}")) + ".", silences.Count == 0)); + (null, _) or (_, null) => "Nessun lavoro in programma è mai finito.", + _ when !startedInTime => $"Il bot ha cominciato a lavorare solo il {SoakReport.Moment(jobs.First!.Value, zone)}.", + _ when !workingAtEnd => $"L'ultimo lavoro in programma è finito il {SoakReport.Moment(jobs.Last!.Value, zone)}: da allora il bot tace.", + _ => "Al lavoro dall'inizio alla fine della finestra.", + }, startedInTime && workingAtEnd)); // No order twice: one order per client id, one execution per order key, one decision per run key. var doubled = await s.CountAsync("SELECT COUNT(*) FROM (SELECT client_order_id FROM orders GROUP BY client_order_id HAVING COUNT(*) > 1) d").ConfigureAwait(false) @@ -107,22 +111,23 @@ public static class SoakReporter r => (Account: r.Text("account"), Outcome: r.Text("outcome"), Count: r.Number("n")), window).ConfigureAwait(false); var different = outcomes.Where(o => o.Outcome == ReconcileOutcomes.Different).Sum(o => o.Count); checks.Add(new SoakCheck(different == 0 ? "Nessuna differenza inspiegata tra registro e conti." : $"Riconciliazioni con differenze inspiegate: {different}.", different == 0)); - var last = await s.QueryAsync( - "SELECT a.name AS account, r.outcome AS outcome FROM reconciliations r JOIN accounts a ON a.id = r.account_id " + - "WHERE r.occurred_at = (SELECT MAX(x.occurred_at) FROM reconciliations x WHERE x.account_id = r.account_id AND x.occurred_at <= @to) ORDER BY a.name", - r => (Account: r.Text("account"), Outcome: r.Text("outcome")), ("to", to)).ConfigureAwait(false); - var agreed = last.All(l => l.Outcome is ReconcileOutcomes.Clean or ReconcileOutcomes.Healed); - checks.Add(new SoakCheck(last.Count == 0 + var accounts = await s.QueryAsync( + "SELECT a.name AS account, st.mode AS mode, st.last_reconciled_at AS at FROM account_status st JOIN accounts a ON a.id = st.account_id ORDER BY a.name", + r => (Account: r.Text("account"), Mode: r.Text("mode"), At: r.IsNull("at") ? (DateTimeOffset?)null : r.Moment("at"))).ConfigureAwait(false); + var behind = accounts.Where(a => a.At is not { } at || at < to - MaxSilence || a.Mode != AccountModes.Normal).ToList(); + checks.Add(new SoakCheck(accounts.Count == 0 ? "Nessun conto riconciliato." - : "Ultima riconciliazione: " + string.Join(", ", last.Select(l => $"{l.Account} {Outcome(l.Outcome)}")) + ".", last.Count > 0 && agreed)); + : behind.Count == 0 + ? "Ogni conto riconciliato fino alla fine e in regola: " + string.Join(", ", accounts.Select(a => a.Account)) + "." + : "Conti non riconciliati fino alla fine o non in regola: " + string.Join(", ", behind.Select(a => + a.Mode != AccountModes.Normal ? $"{a.Account} in modalità {(a.Mode == AccountModes.Prudent ? "prudente" : a.Mode)}" : $"{a.Account} (ultima riconciliazione {(a.At is { } at ? SoakReport.Moment(at, zone) : "mai")})")) + ".", + accounts.Count > 0 && behind.Count == 0)); foreach (var group in outcomes.GroupBy(o => o.Account, StringComparer.Ordinal)) { facts.Add($"Riconciliazioni di {group.Key}: " + string.Join(", ", group.Select(o => $"{o.Count} {Outcome(o.Outcome)}")) + "."); } // The bot was never away and the guard never had to step in. - var absences = await s.QueryAsync("SELECT started_at, ended_at FROM absences WHERE ended_at >= @from AND started_at <= @to ORDER BY started_at", - r => (Start: r.Moment("started_at"), End: r.Moment("ended_at")), window).ConfigureAwait(false); checks.Add(new SoakCheck(absences.Count == 0 ? "Il bot non si è mai spento." : "Spento: " + string.Join(", ", absences.Select(a => $"dal {SoakReport.Moment(a.Start, zone)} per {Minutes(a.End - a.Start)}")) + ".", absences.Count == 0)); @@ -188,6 +193,10 @@ public static class SoakReporter } } + private static DateTimeOffset Min(DateTimeOffset a, DateTimeOffset b) => a < b ? a : b; + + private static DateTimeOffset Max(DateTimeOffset a, DateTimeOffset b) => a > b ? a : b; + private static Task> GroupAsync(DbSession s, string sql, (string Name, object? Value)[] window) => s.QueryAsync(sql, r => (Key: r.TextOrNull("k") ?? "?", Count: r.Number("n")), window); diff --git a/src/Anubis/Trading/LiveEngine.cs b/src/Anubis/Trading/LiveEngine.cs index 841944e..ab478c7 100644 --- a/src/Anubis/Trading/LiveEngine.cs +++ b/src/Anubis/Trading/LiveEngine.cs @@ -104,6 +104,15 @@ public sealed partial class LiveEngine : IDisposable private readonly IMarketCalendar? _calendar; private readonly ILogger _logger; private readonly Dictionary _dataAsked = new(StringComparer.Ordinal); + + // When this engine first tried each late decision: after an absence the bars it needs arrive a few minutes later. + private readonly Dictionary _lateSince = new(StringComparer.Ordinal); + + /// + /// How long a late decision (made after an absence, SPEC 5.6) waits for its bars, asking for them every 5 minutes, + /// before it is written off as "no data". At a restart the data step has not run yet when the first pulse comes. + /// + public static readonly TimeSpan LateDataWait = TimeSpan.FromMinutes(30); private readonly SemaphoreSlim _gate = new(1, 1); public LiveEngine(Database db, IClock clock, Ledger ledger, StageBook stages, Func managers, Func> quotes, @@ -450,10 +459,11 @@ public sealed partial class LiveEngine : IDisposable var loaded = await LoadAsync(m.Strategy, m.Day, book, provisional: false, cancellationToken).ConfigureAwait(false); if (loaded.Data is null || loaded.Missing.Count > 0) { - if (m.Now < m.WaitUntil && !m.Late) + var lateSince = m.Late ? LateSince(m.Key, m.Now) : m.Due; + if (m.Late ? m.Now < lateSince + LateDataWait : m.Now < m.WaitUntil) { // The bars of the close have not arrived yet: ask for them and try again at the next pulse (SPEC 5.5). - await AskForDataAsync(m.Key, m.Now, m.Due, cancellationToken).ConfigureAwait(false); + await AskForDataAsync(m.Key, m.Now, lateSince, cancellationToken).ConfigureAwait(false); return; } @@ -495,6 +505,16 @@ public sealed partial class LiveEngine : IDisposable await WriteDecisionAsync(m, stage, account, mode, record, plan, book, specs, oneStep, cancellationToken).ConfigureAwait(false); } + private DateTimeOffset LateSince(string key, DateTimeOffset now) + { + if (!_lateSince.TryGetValue(key, out var since)) + { + _lateSince[key] = since = now; + } + + return since; + } + private async Task AskForDataAsync(string key, DateTimeOffset now, DateTimeOffset due, CancellationToken cancellationToken) { // Every 5 minutes for the first 45, then every hour (SPEC 5.5). diff --git a/tests/Anubis.Tests/AbsenceTests.cs b/tests/Anubis.Tests/AbsenceTests.cs index baa204c..64bccd0 100644 --- a/tests/Anubis.Tests/AbsenceTests.cs +++ b/tests/Anubis.Tests/AbsenceTests.cs @@ -71,8 +71,13 @@ public sealed class AbsenceTests AbsenceBook.MissedLine(jobs.Skipped[0], Zones.Rome)); Assert.IsNull(await new AbsenceBook(live.Rig.Db, live.Rig.Clock).DeclaredAsync(_none).ConfigureAwait(false)); - await live.StoreBarAsync(LiveFrom.AddDays(-1)).ConfigureAwait(false); + // The engine pulses before the data step has brought yesterday's bar: the late decision waits for it and + // asks for it, instead of being written off as "no data" at the first pulse. live.Quotes(LiveFrom, b => b.Close); + await live.MinutesAsync(3).ConfigureAwait(false); + Assert.IsEmpty(await live.Rig.QueryAsync("SELECT run_key FROM engine_runs", r => r.Text("run_key")).ConfigureAwait(false), "A late decision waits for its bars."); + + await live.StoreBarAsync(LiveFrom.AddDays(-1)).ConfigureAwait(false); await live.MinutesAsync(10).ConfigureAwait(false); var runs = await live.Rig.QueryAsync("SELECT mode FROM engine_runs", r => r.Text("mode")).ConfigureAwait(false); CollectionAssert.AreEqual(new[] { DecisionModes.ExitsOnly }, runs.ToList()); diff --git a/tests/Anubis.Tests/SoakReportTests.cs b/tests/Anubis.Tests/SoakReportTests.cs index 3291b0b..5a534ff 100644 --- a/tests/Anubis.Tests/SoakReportTests.cs +++ b/tests/Anubis.Tests/SoakReportTests.cs @@ -29,58 +29,64 @@ public sealed class SoakReportTests { await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); var okx = await rig.AccountAsync("okx", "demo").ConfigureAwait(false); - var reconciliations = new List(); - for (var at = From.AddMinutes(1); at <= To; at += TimeSpan.FromMinutes(5)) - { - reconciliations.Add(await ReconciledAsync(rig, okx.AccountId, at, ReconcileOutcomes.Clean).ConfigureAwait(false)); - } - foreach (var day in new[] { 12, 13 }) + // A quiet run: the scheduler at work from the first minute to the end, the account reconciled and normal at the + // end (a clean round writes no reconciliation row), a crypto decision at each daily close. + await rig.Db.WriteAsync(async s => { - var at = new DateTimeOffset(2026, 11, day, 0, 5, 0, TimeSpan.Zero); - await rig.Db.WriteAsync(s => s.ExecuteAsync( - "INSERT INTO engine_runs (id, strategy, run_key, decision_day, decision_id, mode, state, proposed, created_at) VALUES (@id, @s, @k, @d, @dec, @m, NULL, NULL, @at)", - CancellationToken.None, ("id", Guid.NewGuid()), ("s", StrategyNames.CryptoTrend), ("k", $"{StrategyNames.CryptoTrend}:2026-11-{day - 1}"), - ("d", $"2026-11-{day - 1}"), ("dec", Guid.NewGuid()), ("m", DecisionModes.Observation), ("at", at))).ConfigureAwait(false); - } + await s.ExecuteAsync("INSERT INTO jobs (id, name, description, last_due_at, last_started_at, last_finished_at, last_outcome, last_error, created_at, updated_at) " + + "VALUES (@id, 'riconciliazione', 'Riconciliazione dei conti', @to, @to, @to, 'ok', NULL, @from, @to)", CancellationToken.None, + ("id", Guid.NewGuid()), ("from", From.AddMinutes(1)), ("to", To)).ConfigureAwait(false); + await s.ExecuteAsync("INSERT INTO account_status (id, account_id, mode, mode_since, mode_reason, differences, last_reconciled_at, last_outcome, created_at, updated_at) " + + "VALUES (@id, @a, 'normal', NULL, NULL, @d, @to, 'clean', @from, @to)", CancellationToken.None, + ("id", Guid.NewGuid()), ("a", okx.AccountId), ("d", new Anubis.Db.DbJson("{\"Current\":[],\"Excluded\":[]}")), ("from", From), ("to", To)).ConfigureAwait(false); + foreach (var day in new[] { 12, 13 }) + { + var at = new DateTimeOffset(2026, 11, day, 0, 5, 0, TimeSpan.Zero); + await s.ExecuteAsync( + "INSERT INTO engine_runs (id, strategy, run_key, decision_day, decision_id, mode, state, proposed, created_at) VALUES (@id, @s, @k, @d, @dec, @m, NULL, NULL, @at)", + CancellationToken.None, ("id", Guid.NewGuid()), ("s", StrategyNames.CryptoTrend), ("k", $"{StrategyNames.CryptoTrend}:2026-11-{day - 1}"), + ("d", $"2026-11-{day - 1}"), ("dec", Guid.NewGuid()), ("m", DecisionModes.Observation), ("at", at)).ConfigureAwait(false); + } + }).ConfigureAwait(false); var report = await SoakReporter.BuildAsync(rig.Db, From, To, TimeSpan.FromHours(48), Zones.Rome).ConfigureAwait(false); - Assert.IsTrue(report.Passed, report.Markdown(Zones.Rome)); var text = report.Markdown(Zones.Rome); + Assert.IsTrue(report.Passed, text); Assert.Contains("**Esito: regolare.**", text); + Assert.Contains("Durata coperta dal lavoro del bot: 49,0 ore", text); + Assert.Contains("Al lavoro dall'inizio alla fine della finestra.", text); + Assert.Contains("Ogni conto riconciliato fino alla fine e in regola: ", text); Assert.Contains("Decisioni di crypto_trend: 2 su 2 chiusure giornaliere.", text); Assert.Contains("crypto_trend 2 (in osservazione)", text); Assert.Contains("Ordini: nessuno.", text); - // Half an hour of silence, an unexplained difference at the end and a guard intervention: each one is named. + // Off for 35 minutes, a guard intervention, an unexplained difference at the end: each one is named. await rig.Db.WriteAsync(async s => { - foreach (var id in reconciliations.Skip(100).Take(6)) - { - await s.ExecuteAsync("DELETE FROM reconciliations WHERE id = @id", CancellationToken.None, ("id", id)).ConfigureAwait(false); - } - + var off = From.AddHours(8).AddMinutes(16); + await s.ExecuteAsync("INSERT INTO absences (id, started_at, ended_at, acknowledged_at, created_at) VALUES (@id, @s, @e, NULL, @e)", CancellationToken.None, + ("id", Guid.NewGuid()), ("s", off), ("e", off.AddMinutes(35))).ConfigureAwait(false); rig.Clock.Set(From.AddHours(20)); await Diary.WriteAsync(s, rig.Clock, DiaryKinds.System, "guard_intervention", "La guardia è intervenuta.", null, CancellationToken.None).ConfigureAwait(false); + await s.ExecuteAsync("INSERT INTO reconciliations (id, account_id, outcome, details, occurred_at, created_at) VALUES (@id, @a, @o, @d, @at, @at)", + CancellationToken.None, ("id", Guid.NewGuid()), ("a", okx.AccountId), ("o", ReconcileOutcomes.Different), ("d", new Anubis.Db.DbJson("{}")), ("at", To)).ConfigureAwait(false); + await s.ExecuteAsync("UPDATE account_status SET mode = 'prudent' WHERE account_id = @a", CancellationToken.None, ("a", okx.AccountId)).ConfigureAwait(false); }).ConfigureAwait(false); - await ReconciledAsync(rig, okx.AccountId, To, ReconcileOutcomes.Different).ConfigureAwait(false); report = await SoakReporter.BuildAsync(rig.Db, From, To, TimeSpan.FromHours(48), Zones.Rome).ConfigureAwait(false); Assert.IsFalse(report.Passed); var failed = report.Checks.Where(c => !c.Ok).Select(c => c.Text).ToList(); Assert.HasCount(4, failed, string.Join(" | ", failed)); - Assert.IsTrue(failed.Any(f => f.StartsWith("Silenzi più lunghi di 15 minuti: dal 12/11/2026 03:16 per 35 minuti", StringComparison.Ordinal)), string.Join(" | ", failed)); - Assert.Contains("Riconciliazioni con differenze inspiegate: 1.", failed); + Assert.Contains("Spento: dal 12/11/2026 03:16 per 35 minuti.", failed); Assert.Contains("Interventi della guardia: 1.", failed); - Assert.IsTrue(failed.Any(f => f.Contains("con differenze", StringComparison.Ordinal))); + Assert.Contains("Riconciliazioni con differenze inspiegate: 1.", failed); + Assert.IsTrue(failed.Any(f => f.Contains("in modalità prudente", StringComparison.Ordinal)), string.Join(" | ", failed)); Assert.Contains("**Esito: da guardare.**", report.Markdown(Zones.Rome)); - } - private static async Task ReconciledAsync(TradingRig rig, Guid account, DateTimeOffset at, string outcome) - { - var id = Guid.NewGuid(); - await rig.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO reconciliations (id, account_id, outcome, details, occurred_at, created_at) VALUES (@id, @a, @o, @d, @at, @at)", - CancellationToken.None, ("id", id), ("a", account), ("o", outcome), ("d", new Anubis.Db.DbJson("{}")), ("at", at))).ConfigureAwait(false); - return id; + // A bot that fell silent before the end of the window: its last job and the account's last round say when. + var later = await SoakReporter.BuildAsync(rig.Db, From.AddHours(2), To.AddHours(2), TimeSpan.FromHours(48), Zones.Rome).ConfigureAwait(false); + Assert.IsTrue(later.Checks.Any(c => !c.Ok && c.Text.EndsWith("da allora il bot tace.", StringComparison.Ordinal)), later.Markdown(Zones.Rome)); + Assert.IsTrue(later.Checks.Any(c => !c.Ok && c.Text.StartsWith("Durata coperta dal lavoro del bot: 46,4 ore", StringComparison.Ordinal)), later.Markdown(Zones.Rome)); } } From 1c7205024f0a03b3ba8da84ec6634143b8d62f16 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 11 Nov 2026 21:40:41 +0100 Subject: [PATCH 11/12] Count short gaps at the edges of the soak window as covered (refs #53) The scheduler's first jobs finish about a minute after the bot starts, so a run started exactly at the window's start was reported as covering slightly less than 48 hours. A gap shorter than the allowed silence (15 minutes) at either edge now counts as covered, like one in the middle. Co-Authored-By: Claude Opus 5.5 --- src/Anubis/Supervision/SoakReport.cs | 6 ++++-- tests/Anubis.Tests/SoakReportTests.cs | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/Anubis/Supervision/SoakReport.cs b/src/Anubis/Supervision/SoakReport.cs index b3e979b..da54803 100644 --- a/src/Anubis/Supervision/SoakReport.cs +++ b/src/Anubis/Supervision/SoakReport.cs @@ -83,8 +83,10 @@ public static class SoakReporter .ConfigureAwait(false); var absences = await s.QueryAsync("SELECT started_at, ended_at FROM absences WHERE ended_at >= @from AND started_at <= @to ORDER BY started_at", r => (Start: r.Moment("started_at"), End: r.Moment("ended_at")), window).ConfigureAwait(false); - var start = jobs.First is { } first && first > from ? first : from; - var end = jobs.Last is { } lastJob && lastJob < to ? lastJob : to; + // A gap shorter than the longest silence allowed at either end (the first jobs come a minute after the start, + // the last one up to 5 minutes before the end) is no more a hole than one in the middle. + var start = jobs.First is { } first && first > from + MaxSilence ? first : from; + var end = jobs.Last is { } lastJob && lastJob < to - MaxSilence ? lastJob : to; var covered = jobs.First is null || jobs.Last is null || end <= start ? TimeSpan.Zero : end - start - absences.Aggregate(TimeSpan.Zero, (sum, a) => sum + (Min(a.End, end) - Max(a.Start, start) is { } span && span > TimeSpan.Zero ? span : TimeSpan.Zero)); checks.Add(new SoakCheck($"Durata coperta dal lavoro del bot: {SoakReport.Hours(covered)} (servono almeno {SoakReport.Hours(minimum)}).", covered >= minimum)); diff --git a/tests/Anubis.Tests/SoakReportTests.cs b/tests/Anubis.Tests/SoakReportTests.cs index 5a534ff..02620a6 100644 --- a/tests/Anubis.Tests/SoakReportTests.cs +++ b/tests/Anubis.Tests/SoakReportTests.cs @@ -54,7 +54,7 @@ public sealed class SoakReportTests var text = report.Markdown(Zones.Rome); Assert.IsTrue(report.Passed, text); Assert.Contains("**Esito: regolare.**", text); - Assert.Contains("Durata coperta dal lavoro del bot: 49,0 ore", text); + Assert.Contains("Durata coperta dal lavoro del bot: 49 ore", text); Assert.Contains("Al lavoro dall'inizio alla fine della finestra.", text); Assert.Contains("Ogni conto riconciliato fino alla fine e in regola: ", text); Assert.Contains("Decisioni di crypto_trend: 2 su 2 chiusure giornaliere.", text); From 9a4e31aa48aedbabb7a67feb736c344656ef3650 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 11 Nov 2026 21:49:12 +0100 Subject: [PATCH 12/12] Record the start of the 48-hour run and how to read its report (refs #53) The run started on 11 November 2026 at 21:44 Italian time in the anubis-prova container, from the image of this branch. STATE says when and how to make the report so that it spans both US sessions; its check is the first step of Phase 7 (#55). Co-Authored-By: Claude Opus 5.5 --- docs/ROADMAP.md | 4 ++-- docs/STATE.md | 6 ++++-- docs/SVILUPPO.md | 2 +- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index c69b63b..88278c9 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -190,7 +190,7 @@ Il bot che lavora da solo, in simulazione, giorno e notte, e lo racconta. - [x] [#50](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/50) Diario con frasi in italiano dai codici motivo e confronto "senza bot" - [x] [#51](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/51) Schermate Panoramica e Diario e sistema - [x] [#52](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/52) Telegram e segnale di vita -- [ ] [#53](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/53) Prova di durata di 48 ore in tempo reale +- [x] [#53](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/53) Prova di durata di 48 ore in tempo reale - [ ] [#54](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/54) Chiusura della fase, revisione indipendente e tag `fase-6` **Criteri di accettazione** @@ -199,7 +199,7 @@ Il bot che lavora da solo, in simulazione, giorno e notte, e lo racconta. - [x] Una prova accelerata con orologio simulato copre almeno 10 giorni di mercato con guasti iniettati e termina con registro e conti riconciliati e senza ordini duplicati (`TenDaysWithFaultsEndReconciledWithoutDuplicateOrders`: 14 giorni con rete giù, risposta persa, ripartenza con un ordine a metà e database irraggiungibile, su SQLite e PostgreSQL) - [x] Un test blocca il ciclo principale con una vendita a metà e verifica che dopo la guardia la posizione abbia di nuovo i suoi stop e il motore sia ripartito; la stessa prova passa dentro l'immagine Docker (`ALoopBlockedWithASaleHalfwayGetsItsStopBackAndTheEngineRestarts`, `TheGuardDrillPassesWithTheRealEngineAsChildProcess`; `docker run --rm drill` in `tasks ci` e nella CI: 7 controlli su 7) - [x] Un test con orologio simulato spegne il bot per 3 ore, 20 ore e 3 giorni e verifica le righe di 5.6 i cui lavori esistono (`ThreeHoursOffRecoverTheCryptoDecisionAndDropAnEntryThatMovedTooFar`, `TwentyHoursOffLetTheLateDecisionsUpdateOnlyExitsAndDropExpiredEntries`, `ThreeDaysOffAreDeclaredUntilSeenAndMissedRunsAreMadeOnce`) -- [ ] A fine fase parte una prova di durata in tempo reale di almeno 48 ore a cavallo di due sedute USA (solo crypto senza chiavi Alpaca) +- [x] A fine fase parte una prova di durata in tempo reale di almeno 48 ore a cavallo di due sedute USA (solo crypto senza chiavi Alpaca) — partita l'11/11/2026 alle 21:44 nel container `anubis-prova`; il rapporto si verifica in Fase 7 (#55) - [x] In modalità dimostrativa la Panoramica corrisponde agli screen 01 (1440 px) e 09 (390 px) (`TheDemoPanoramicaShowsAccountsPositionsAndLimits`; fotografie di `tasks screenshots`, confronto nella prova di #51) - [x] Il Diario corrisponde allo screen 08 a 1440 px e a 390 px non scorre in orizzontale (`TheDiaryFiltersAndSearches`; a 390 px `scrollWidth` uguale alla larghezza su `/`, `/diario` e `/diario?cerca=…`) - [x] I comandi Telegram funzionano (o, senza token, superano i test con un finto server) — senza token, con un finto server: `TheCommandsWorkFromThePhoneThroughTheRealServer`, `FermaWantsAConfirmationWithinTwoMinutes`, `OnlyTheChatOfTheSettingsIsObeyedAndOldMessagesAreNot` e gli altri di `TelegramTests` diff --git a/docs/STATE.md b/docs/STATE.md index e9db65a..623c900 100644 --- a/docs/STATE.md +++ b/docs/STATE.md @@ -4,7 +4,7 @@ Aggiornato: 2026-11-11 ## Fase corrente -**Fase 6 — Motore dal vivo in simulazione: completata.** La prova di durata di 48 ore è partita a fine fase sull'immagine Docker di questo PC (solo crypto, senza chiavi); il suo rapporto si controlla come primo passo della Fase 7 (Notizie), da iniziare con il via dell'utente. Nessuna strategia manda ordini: `crypto_trend` non ha superato il backtest e decide solo in osservazione, le due azionarie aspettano le chiavi di Alpaca. +**Fase 6 — Motore dal vivo in simulazione: completata.** La prova di durata di 48 ore è partita a fine fase, l'11 novembre 2026 alle 21:44 (ora italiana), sull'immagine Docker di questo PC (solo crypto, senza chiavi); il suo rapporto si controlla come primo passo della Fase 7 (Notizie), da iniziare con il via dell'utente. Nessuna strategia manda ordini: `crypto_trend` non ha superato il backtest e decide solo in osservazione, le due azionarie aspettano le chiavi di Alpaca. ## Fatto @@ -92,7 +92,9 @@ Nulla. ## Prossimo passo -1. Controllare il rapporto della prova di durata. Il container è `anubis-prova`; il comando è in `docs/SVILUPPO.md`, sezione "Guardia e prova di durata". +1. Controllare il rapporto della prova di durata, da venerdì 13 novembre dopo le 22:45 (ora italiana), così la finestra comprende per intero le sedute USA di giovedì e venerdì. Il container è `anubis-prova`, l'ora di partenza è in `artifacts/prova-48h/inizio.txt`: + `docker exec -u 99:100 -e HOME=/tmp anubis-prova dotnet /app/Anubis.Server.dll soak --from 2026-11-11T20:44:31Z --hours 49 --platform docker --out /tmp/prova.md` + poi `docker cp anubis-prova:/tmp/prova.md docs/prova-di-durata-fase-6.md` (issue #55). 2. Poi la Fase 7, notizie. Con le chiavi del conto paper di Alpaca si possono anche fare i backtest azionari (`anubis backtest base`) e chiudere i criteri delle Fasi 2 e 3 in attesa. ## Da sapere diff --git a/docs/SVILUPPO.md b/docs/SVILUPPO.md index aedd9ed..c2670fa 100644 --- a/docs/SVILUPPO.md +++ b/docs/SVILUPPO.md @@ -98,7 +98,7 @@ Le attività `check`, `test` e `dev` sono anche in Terminale → Esegui attivit - `docker run --rm drill` dentro l'immagine. La fanno anche `tasks ci` e la CI. -- Il rapporto di una prova di durata si legge mentre il bot lavora: `docker exec -u 99:100 -e HOME=/tmp dotnet /app/Anubis.Server.dll soak --hours 48 --platform docker`, con l'utente del bot (`PUID:PGID`) perché i file del database restino suoi. Esce con 0 se tutto è regolare e con 4 se qualcosa va guardato. +- Il rapporto di una prova di durata si legge mentre il bot lavora: `docker exec -u 99:100 -e HOME=/tmp dotnet /app/Anubis.Server.dll soak --hours 48 --platform docker`, con l'utente del bot (`PUID:PGID`) perché i file del database restino suoi. Esce con 0 se tutto è regolare e con 4 se qualcosa va guardato. Senza `--from` la finestra sono le ultime `--hours` ore; con `--from` comincia lì e dura `--hours` ore, che sono anche la durata minima richiesta. - Gli appigli per le prove (`ANUBIS_FAULT`, `ANUBIS_DRILL_OKX_URL`) non si usano mai su un'installazione vera. ## Pacchetti e consegne