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];
+}
--
2.54.1
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();
+ }
+}
--
2.54.1
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()
{
--
2.54.1
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;
--
2.54.1
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")
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)
+ {
+
@@ -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.
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)
{
@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") };
+}
--
2.54.1
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
+
@(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)
+ {
+
+
+
+
+
@if (e.Lead is { } lead) {@lead}@foreach (var piece in e.Main) {if (piece.Class is { } css) {@piece.Text} else {@piece.Text}}
+ 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);
+
+
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.Signalssu @m.Needed necessari