From c618f9fc017aa5f4ab8b9147a101f7e1ac11106d Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 30 Sep 2026 23:55:07 +0200 Subject: [PATCH] =?UTF-8?q?5.1=20revisione,=20conti:=20stato=20separato=20?= =?UTF-8?q?per=20conto=20e=20cambio=20Demo=E2=86=94Live=20deciso=20dal=20m?= =?UTF-8?q?otore,=20saldo=20all'avvio=20giudicato=20solo=20con=20lo=20stor?= =?UTF-8?q?ico=20completo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit La revisione ha trovato che la guardia del cambio di conto leggeva la vista pubblicata (piatta a metà di un ingresso e durante l'avvio), che il file di stato unico veniva riscritto dal motore dell'altro conto (perdendo chiusure in attesa del P&L, equity stop, kill-switch, residuo, pausa e picco) e che all'avvio una perdita non ancora nello storico eToro veniva registrata come prelievo. - Stato per conto (D-53): data/state/baskets_state.demo.json e baskets_state.live.json. Il cambio non sovrascrive né scarta basket, ingressi in attesa, chiusure in attesa del P&L, picco, flussi di cassa, blocchi, residuo, pausa e giornata della perdita giornaliera dell'altro conto: tornando lo si ritrova com'era. Il file unico della 5.0/5.1 va una volta sola al conto scritto nel suo mode (il più recente vince) e resta come .migrato; niente viene cancellato. I basket di un conto non seguito oltre la soglia ricevono il recupero dopo inattività. - Registro degli ordini: pending_orders.json resta unico, ma ogni motore vede, risolve, fa fallire e pota solo gli ordini del suo conto. - Guardia C8 autorevole: a motore acceso è un comando sul thread di decisione che prima blocca nuove entrate e aggiunte, poi conta sui propri slot (posizioni, gambe in attesa, ingressi/aggiunte/uscite in corso, errori con una gamba, ordini senza esito, orfane e residui, chiusure in attesa dello storico); le entrate restano bloccate fino al riavvio, il blocco si toglie se il cambio non avviene. Rifiutato mentre il motore si avvia o si ferma o se non risponde in 30 s. Dopo l'arresto il file del conto lasciato dal motore viene ricontrollato: se non è piatto (o parte un kill-switch nel frattempo) encelado.json e strategy.json tornano byte per byte come prima e il motore resta fermo. A motore fermo decide il file del conto in uso. Il messaggio dice cosa resta e cosa fare. - Saldo all'avvio: si giudica solo quando lo storico mostra ogni posizione chiusa dopo l'ultimo saldo (sparite dal conto, sparite senza verdetto, chiusure in attesa); altrimenti il saldo salvato resta il riferimento e giudica la riconciliazione che le vede, come in sessione. In sessione le posizioni che spiegano il saldo si dimenticano solo dopo un verdetto su una lettura riuscita del conto. - Test: cambio rifiutato con un ingresso in corso che la vista mostra piatto, con chiusure in attesa (motore acceso e fermo), durante l'avvio e il riscaldamento, senza risposta del motore; annullamento dopo l'arresto e con un kill-switch partito nel frattempo; Live→Demo→Live che conserva equity stop, kill-switch, residuo, pausa e picco; chiusure in attesa scritte quando il conto torna; migrazione del file unico; registro per conto; avvio con storico in ritardo senza prelievo e con prelievo vero ancora giudicato. - docs/API.md: i motivi del rifiuto del cambio di conto e l'annullamento dopo l'arresto. Co-Authored-By: Claude Opus 5.5 --- Encelado/docs/API.md | 4 +- .../src/Encelado.Core/Baskets/OrderTracker.cs | 48 +- .../src/Encelado.Core/Baskets/StartupCash.cs | 82 +++ .../Baskets/AccountStateFiles.cs | 159 +++++ .../Baskets/BasketEngine.Commands.cs | 71 ++- .../Baskets/BasketEngine.Realized.cs | 3 +- .../Baskets/BasketEngine.Reconcile.cs | 125 +++- .../Baskets/BasketEngine.State.cs | 119 +++- .../Baskets/BasketEngine.View.cs | 2 +- .../Encelado.Engine/Baskets/BasketEngine.cs | 43 +- .../Encelado.Engine/Engine/BotSupervisor.cs | 93 +++ .../src/Encelado.Engine/Engine/IEngine.cs | 15 + .../Settings/AccountActivity.cs | 156 ++++- .../Settings/SettingsRuntime.cs | 201 ++++++- .../tests/Encelado.Tests/AccountStateTests.cs | 545 ++++++++++++++++++ .../Encelado.Tests/SettingsRuntimeTests.cs | 204 ++++++- 16 files changed, 1766 insertions(+), 104 deletions(-) create mode 100644 Encelado/src/Encelado.Core/Baskets/StartupCash.cs create mode 100644 Encelado/src/Encelado.Engine/Baskets/AccountStateFiles.cs create mode 100644 Encelado/tests/Encelado.Tests/AccountStateTests.cs diff --git a/Encelado/docs/API.md b/Encelado/docs/API.md index bafdd62..7431159 100644 --- a/Encelado/docs/API.md +++ b/Encelado/docs/API.md @@ -407,7 +407,9 @@ Risposta: version: number } ``` -Con `restart = "needsPhrase"` (HTTP 409) niente è stato scritto: il client chiede la frase e ripete con `confirm`. Con `restart = "refused"` (HTTP 409) niente è stato scritto: il cambio di conto (o delle coppie dei basket) è rifiutato finché ci sono basket aperti, in attesa o ordini senza esito, oppure mancano le chiavi del conto scelto a motore acceso, oppure il cambio riavvierebbe il motore mentre è in corso un kill-switch, una chiusura o la chiusura dei residui. Valori non validi: HTTP 400 con `errors`. +Con `restart = "needsPhrase"` (HTTP 409) niente è stato scritto: il client chiede la frase e ripete con `confirm`. Con `restart = "refused"` (HTTP 409) niente è stato scritto, e `message` dice perché: mancano le chiavi del conto scelto a motore acceso, oppure il cambio riavvierebbe il motore mentre è in corso un kill-switch, una chiusura o la chiusura dei residui, oppure — per il cambio di conto (Demo ↔ Live) o delle coppie dei basket — sul conto in uso c'è ancora qualcosa in sospeso: basket aperti o in attesa di una gamba, ingressi, aggiunte o uscite in corso, basket in errore con una gamba sul conto, ordini senza esito, gambe orfane del bot o residui del kill-switch, chiusure in attesa dello storico eToro (al più 30 minuti). Il messaggio elenca solo ciò che c'è e dice cosa fare. Lo stesso cambio è rifiutato mentre il motore si avvia (finché il ciclo di decisione non è partito non ha letto il suo stato), mentre si ferma, o se il motore, occupato, non risponde al controllo entro 30 s. Valori non validi: HTTP 400 con `errors`. + +Il controllo del cambio di conto (decisione C8) a motore acceso lo fa il motore stesso, sul suo thread di decisione, dopo aver bloccato le nuove entrate e le aggiunte: mai la vista pubblicata, dove un basket a metà ingresso sembra piatto. Se il conto è libero le entrate restano bloccate fino al riavvio (`alarms.entriesBlockedReason` lo dice nel frattempo); se il cambio poi non avviene, il blocco viene tolto. A motore fermo decide il file di stato del conto in uso. Dopo l'arresto, prima di avviare l'altro conto, il file lasciato dal motore fermato viene giudicato di nuovo: se il conto non è piatto — o se nel frattempo è partito un kill-switch, una chiusura o la chiusura dei residui, o FERMA ha lasciato il conto non piatto — `encelado.json` e `strategy.json` tornano byte per byte come prima del salvataggio e la risposta è 409 `refused` con il motivo; il motore resta fermo (o acceso sul conto di prima, se non era stato fermato). Ogni conto ha il suo stato (basket, blocchi, residui, pausa, picco, chiusure in attesa del P&L), che il cambio non tocca: tornando sull'altro conto lo si ritrova com'era. Il riavvio automatico riavvia solo un motore che è ancora acceso quando tocca a lui: se nel frattempo è arrivato FERMA, il motore resta fermo e i valori salvati valgono al prossimo avvio (`applied = "stored"`, `restart = "none"`). diff --git a/Encelado/src/Encelado.Core/Baskets/OrderTracker.cs b/Encelado/src/Encelado.Core/Baskets/OrderTracker.cs index 5e11176..942019a 100644 --- a/Encelado/src/Encelado.Core/Baskets/OrderTracker.cs +++ b/Encelado/src/Encelado.Core/Baskets/OrderTracker.cs @@ -156,6 +156,13 @@ public sealed class TrackedOrder /// matches it appears on the account. The register is persisted to /// data/state/pending_orders.json with atomic writes and reloaded at startup, so /// nothing sent is ever forgotten across a restart. +/// +/// One file for both accounts, every order marked with the mode that sent it (5.1 review): +/// a register opened for an account sees, resolves, fails and prunes only that account's +/// orders; the other account's stay in the file untouched until an engine of that account +/// runs again. An order without a mode (written before modes were recorded) belongs to +/// whichever account opens the register, as it always did. +/// /// public sealed class OrderTracker { @@ -166,12 +173,16 @@ public sealed class OrderTracker public static readonly TimeSpan Retention = TimeSpan.FromHours(48); private readonly string _path; + private readonly ExecutionMode? _account; private readonly Lock _gate = new(); private readonly Dictionary _orders = new(StringComparer.Ordinal); - public OrderTracker(string path) + /// The register's file; empty for one kept in memory only. + /// The account whose orders this register works on (its mode); null for every order in the file. + public OrderTracker(string path, ExecutionMode? account = null) { _path = path ?? string.Empty; + _account = account; Load(); } @@ -180,13 +191,22 @@ public sealed class OrderTracker public string Path => _path; + /// + /// Whether an order sent in belongs to : + /// the same account (Demo or Live, whatever name a version gave the mode), or no mode recorded. + /// + public static bool BelongsTo(string? orderMode, ExecutionMode? account) => + account is not { } a || !ExecutionModeExtensions.TryParse(orderMode, out ExecutionMode m) || m.IsLive() == a.IsLive(); + + private bool Owns(TrackedOrder o) => BelongsTo(o.Mode, _account); + public IReadOnlyList Pending { get { lock (_gate) { - return [.. _orders.Values.Where(static o => o.IsPending).OrderBy(static o => o.SentUtc)]; + return [.. _orders.Values.Where(o => o.IsPending && Owns(o)).OrderBy(static o => o.SentUtc)]; } } } @@ -197,7 +217,7 @@ public sealed class OrderTracker { lock (_gate) { - return [.. _orders.Values.OrderBy(static o => o.SentUtc)]; + return [.. _orders.Values.Where(Owns).OrderBy(static o => o.SentUtc)]; } } } @@ -208,7 +228,19 @@ public sealed class OrderTracker { lock (_gate) { - return _orders.Values.Count(static o => o.IsPending); + return _orders.Values.Count(o => o.IsPending && Owns(o)); + } + } + } + + /// Orders of the other account still without an outcome: kept in the file, never touched here. + public int OtherAccountPendingCount + { + get + { + lock (_gate) + { + return _orders.Values.Count(o => o.IsPending && !Owns(o)); } } } @@ -250,7 +282,7 @@ public sealed class OrderTracker Dictionary map = []; foreach (TrackedOrder o in _orders.Values) { - if (o.Resolution == OrderResolution.Filled && o.PositionId > 0 && o.Leg is not (OrderLeg.Close or OrderLeg.Unwind)) + if (Owns(o) && o.Resolution == OrderResolution.Filled && o.PositionId > 0 && o.Leg is not (OrderLeg.Close or OrderLeg.Unwind)) { map[o.PositionId] = o.Basket; } @@ -260,12 +292,12 @@ public sealed class OrderTracker } } - /// Drops resolved orders older than . Pending ones are never dropped. + /// Drops resolved orders older than . Pending ones are never dropped, nor the other account's. public int Prune(DateTime now) { lock (_gate) { - List gone = [.. _orders.Values.Where(o => !o.IsPending && o.ResolvedUtc is { } r && now - r > Retention).Select(static o => o.ClientRef)]; + List gone = [.. _orders.Values.Where(o => Owns(o) && !o.IsPending && o.ResolvedUtc is { } r && now - r > Retention).Select(static o => o.ClientRef)]; foreach (string key in gone) { _orders.Remove(key); @@ -294,7 +326,7 @@ public sealed class OrderTracker HashSet claimed; lock (_gate) { - claimed = [.. _orders.Values.Where(static o => o.PositionId > 0).Select(static o => o.PositionId)]; + claimed = [.. _orders.Values.Where(o => o.PositionId > 0 && Owns(o)).Select(static o => o.PositionId)]; } foreach (TrackedOrder order in Pending) diff --git a/Encelado/src/Encelado.Core/Baskets/StartupCash.cs b/Encelado/src/Encelado.Core/Baskets/StartupCash.cs new file mode 100644 index 0000000..ca06313 --- /dev/null +++ b/Encelado/src/Encelado.Core/Baskets/StartupCash.cs @@ -0,0 +1,82 @@ +using Encelado.Core.Broker; + +namespace Encelado.Core.Baskets; + +/// +/// What the venue's history says, at startup, about the balance saved before the stop: +/// is the realised net result (netProfit − fees) of every +/// close after the saved reading, and the positions known to have +/// closed since then that the history does not show yet. +/// +public sealed record StartupCashVerdict(double ClosedNet, IReadOnlyList Missing) +{ + /// Every known close is in the history: the balance can be judged now. + public bool Complete => Missing.Count == 0; +} + +/// +/// The cash-movement check at startup (5.1 review): the saved balance against the account's, +/// explained by the closes made since. The history lags a close by seconds to minutes, so a +/// loss realised just before a restart would read as a withdrawal (a profit as a deposit) +/// if the balance were judged while it does not show it. The verdict is given only when +/// every position known to have closed since the saved reading — gone from the account +/// since the last reconciliation, vanished and still unexplained before the stop, or closed +/// by the bot and waiting for its settlement — appears in the history; otherwise the saved +/// balance stays the reference and a later reconciliation judges, as it does in session. +/// +public static class StartupCash +{ + /// + /// The positions whose close the balance must already reflect: those on the account at + /// the last reconciliation and gone now, those that vanished before the stop without a + /// verdict, and those of the closes waiting for their settlement closed after the saved + /// reading (earlier ones were judged with that reading). + /// + public static IReadOnlyList Expected( + IEnumerable lastPositionIds, + IReadOnlySet onAccount, + IEnumerable vanishedUnsettled, + IEnumerable<(IReadOnlyCollection Ids, DateTime ClosedUtc)> pendingSettlements, + DateTime lastObservedUtc) + { + ArgumentNullException.ThrowIfNull(lastPositionIds); + ArgumentNullException.ThrowIfNull(onAccount); + ArgumentNullException.ThrowIfNull(vanishedUnsettled); + ArgumentNullException.ThrowIfNull(pendingSettlements); + HashSet ids = [.. lastPositionIds.Where(id => !onAccount.Contains(id))]; + ids.UnionWith(vanishedUnsettled); + foreach ((IReadOnlyCollection settlementIds, DateTime closedUtc) in pendingSettlements) + { + if (closedUtc > lastObservedUtc) + { + ids.UnionWith(settlementIds.Where(id => !onAccount.Contains(id))); + } + } + + ids.Remove(0); + return [.. ids.Order()]; + } + + /// + /// The closes after summed from the history (as the + /// startup always summed them: every close changes the balance), and which of + /// the history does not show. + /// + public static StartupCashVerdict Judge(DateTime lastObservedUtc, IEnumerable expected, IReadOnlyList history) + { + ArgumentNullException.ThrowIfNull(expected); + ArgumentNullException.ThrowIfNull(history); + HashSet seen = []; + double net = 0; + foreach (ClosedTrade t in history) + { + seen.Add(t.PositionId); + if (t.ClosedUtc > lastObservedUtc) + { + net += t.NetUsd; + } + } + + return new StartupCashVerdict(net, [.. expected.Distinct().Where(id => !seen.Contains(id))]); + } +} diff --git a/Encelado/src/Encelado.Engine/Baskets/AccountStateFiles.cs b/Encelado/src/Encelado.Engine/Baskets/AccountStateFiles.cs new file mode 100644 index 0000000..96161c1 --- /dev/null +++ b/Encelado/src/Encelado.Engine/Baskets/AccountStateFiles.cs @@ -0,0 +1,159 @@ +using System.Globalization; +using System.Text.Json; +using Encelado.Core.Baskets; + +namespace Encelado.Engine.Baskets; + +/// +/// The engine's state on disk, one file per account (5.1 review, decision D-53): +/// data/state/baskets_state.demo.json and data/state/baskets_state.live.json. +/// Switching account never overwrites nor discards the other account's open baskets, closes +/// waiting for their P&L, equity peak, cash flow, halts, residue, pause and day; switching +/// back finds them where they were. +/// +/// The single baskets_state.json of 5.0 and of the first 5.1 builds goes, once, to the +/// account its mode names — whichever account the engine that finds it trades — and +/// stays beside it renamed .migrato: never deleted, never saved over. Only an engine +/// holding the data folder's instance lock migrates; a reader (the account-switch guard) +/// reads the old file for its own account until then. +/// +/// +public static class AccountStateFiles +{ + /// The single file of 5.0 and of the first 5.1 builds. + public const string LegacyName = "baskets_state.json"; + + /// The state of one account: data/state/baskets_state.demo.json or .live.json. + public static string PathFor(string dataPath, ExecutionMode account) + { + ArgumentException.ThrowIfNullOrWhiteSpace(dataPath); + return Path.Combine(dataPath, "state", $"baskets_state.{account.Account()}.json"); + } + + public static string LegacyPath(string dataPath) + { + ArgumentException.ThrowIfNullOrWhiteSpace(dataPath); + return Path.Combine(dataPath, "state", LegacyName); + } + + /// The account a saved state names in its mode (any name a version gave it); null when it names none. + public static ExecutionMode? ModeOf(JsonElement root) => + root.ValueKind == JsonValueKind.Object && root.TryGetProperty("mode", out JsonElement m) && m.ValueKind == JsonValueKind.String && + ExecutionModeExtensions.TryParse(m.GetString(), out ExecutionMode mode) ? mode : null; + + /// When a saved state was written (savedUtc); the minimum when unknown. + public static DateTime SavedUtcOf(JsonElement root) => + root.ValueKind == JsonValueKind.Object && root.TryGetProperty("savedUtc", out JsonElement s) && s.ValueKind == JsonValueKind.String && + DateTime.TryParse(s.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime t) ? t : DateTime.MinValue; + + /// + /// The file a reader takes for : the account's own, or — before + /// an engine migrated it — the single old file when it is that account's (or names none). + /// Null when there is neither. Reads only: the guard of the settings page must not touch + /// the engine's files. + /// + public static string? ReadablePathFor(string dataPath, ExecutionMode account) + { + string own = PathFor(dataPath, account); + if (File.Exists(own)) + { + return own; + } + + string legacy = LegacyPath(dataPath); + if (!File.Exists(legacy)) + { + return null; + } + + try + { + using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(legacy)); + return ModeOf(doc.RootElement) is not { } mode || mode.IsLive() == account.IsLive() ? legacy : null; + } + catch (JsonException) + { + // Unreadable: whose it is cannot be told, so it counts for whoever asks (the prudent answer). + return legacy; + } + } + + /// + /// Moves the single old file to the account its mode names ('s + /// when it names none, as 5.0 read it), then renames it .migrato. When that account + /// already has its own file, the more recent of the two wins (a return to an older version + /// and back) and the other stays beside it. Returns what happened for the log, or null when + /// there was nothing to do. Throws on a file-system error: the start must not go on and + /// save an empty state over what it could not move. + /// + public static string? MigrateLegacy(string dataPath, ExecutionMode running) + { + string legacy = LegacyPath(dataPath); + if (!File.Exists(legacy)) + { + return null; + } + + byte[] bytes = File.ReadAllBytes(legacy); + ExecutionMode account; + DateTime saved; + try + { + using JsonDocument doc = JsonDocument.Parse(bytes); + account = ModeOf(doc.RootElement) ?? running; + saved = SavedUtcOf(doc.RootElement); + } + catch (JsonException ex) + { + string aside = MoveAside(legacy, "illeggibile"); + return $"{LegacyName} non leggibile ({ex.Message}): spostato in {Path.GetFileName(aside)}, il motore riparte dalla riconciliazione con il conto"; + } + + string target = PathFor(dataPath, account); + string outcome; + if (!File.Exists(target)) + { + AtomicFile.Write(target, bytes); + outcome = $"diventa {Path.GetFileName(target)}"; + } + else if (saved > SavedUtcOfFile(target)) + { + string previous = MoveAside(target, "precedente"); + AtomicFile.Write(target, bytes); + outcome = $"è più recente di {Path.GetFileName(target)} e ne prende il posto (il precedente resta come {Path.GetFileName(previous)})"; + } + else + { + outcome = $"è meno recente di {Path.GetFileName(target)}, che resta com'è"; + } + + string migrated = MoveAside(legacy, "migrato"); + return $"stato del conto {account.Account()} della versione precedente ({LegacyName}): {outcome}; l'originale resta come {Path.GetFileName(migrated)}"; + } + + /// Renames a file beside itself with a tag (and the time, when the name is taken); returns the new path. + public static string MoveAside(string path, string tag) + { + string aside = $"{path}.{tag}"; + for (int n = 1; File.Exists(aside); n++) + { + aside = string.Create(CultureInfo.InvariantCulture, $"{path}.{tag}-{DateTime.UtcNow:yyyyMMddHHmmss}{(n > 1 ? $"-{n}" : string.Empty)}"); + } + + File.Move(path, aside); + return aside; + } + + private static DateTime SavedUtcOfFile(string path) + { + try + { + using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(path)); + return SavedUtcOf(doc.RootElement); + } + catch (JsonException) + { + return DateTime.MinValue; + } + } +} diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Commands.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Commands.cs index a7e2298..57dec06 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Commands.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Commands.cs @@ -2,6 +2,7 @@ using System.Globalization; using System.Text; using Encelado.Engine; using Encelado.Engine.Logging; +using Encelado.Engine.Settings; using Encelado.Core.Baskets; using Encelado.Core.Baskets.History; using Encelado.Core.Baskets.Learning; @@ -34,6 +35,12 @@ public sealed partial class BasketEngine /// Set by : this engine opens nothing new until it is gone. private bool _stopping; + /// + /// Set by when the account is idle: no + /// new entry and no add until the restart on the other account (or the switch is cancelled). + /// + private string? _switchBlock; + /// The answer of a command the engine will never finish: it stopped before taking it, or in the middle of it. private static CommandResult Interrupted => new(false, "comando interrotto: il motore si è fermato") { Code = CommandResult.Refused }; @@ -155,7 +162,8 @@ public sealed partial class BasketEngine return new CommandResult(left == 0, summary); } - private async Task RunCommandAsync(EngineCommand c, CancellationToken ct) + /// One command, on the decision thread (internal: the tests run one as the loop would). + internal async Task RunCommandAsync(EngineCommand c, CancellationToken ct) { switch (c.Kind) { @@ -234,11 +242,72 @@ public sealed partial class BasketEngine case EngineCommandKind.Shutdown: return await PrepareStopAsync(c, ct).ConfigureAwait(false); + case EngineCommandKind.PrepareAccountSwitch: + return PrepareAccountSwitch(c); + + case EngineCommandKind.CancelAccountSwitch: + return CancelAccountSwitch(c); + default: return new CommandResult(false, $"comando {c.Kind} non supportato"); } } + // ----------------------------------------------------------------------- + // The change of account (5.1 review, decision C8) + // ----------------------------------------------------------------------- + + /// + /// What this engine still has in hand on its account, counted on its own slots and never + /// on a published picture (where a basket in the middle of its entry looks flat): the + /// positions, the pending legs, the operations under way, the errors with a leg, the + /// register's orders, the orphans and the residue of a kill-switch, the closes waiting for + /// the venue's history. Decision thread only. + /// + internal AccountActivity CurrentActivity() + { + HashSet orphans = [.. _classified.Where(static c => c.Origin == PositionOrigin.OrphanBot).Select(static c => c.Position.PositionId)]; + orphans.UnionWith(_haltResidue.Select(static r => r.PositionId)); + orphans.Remove(0); + return Settings.AccountActivity.FromEngine( + _slots.Select(static s => new SlotActivity(s.State, s.Position is not null, s.LegPositionIds().Any(), s.Busy)), + _tracker.PendingCount, orphans.Count, _settlements.Queue.Count, _stateLoaded); + } + + /// + /// The guard of a change of account or of the basket pairs: first no new entry and no add, + /// then the count. With something still in hand the block is lifted and the switch refused; + /// with nothing, the entries stay blocked until the restart on the other account. + /// + private CommandResult PrepareAccountSwitch(EngineCommand c) + { + string what = c.Argument.Length > 0 ? c.Argument : "cambio di conto"; + _switchBlock = $"{what} in corso: nessuna nuova entrata fino al riavvio"; + AccountActivity activity = CurrentActivity(); + if (activity.Busy) + { + _switchBlock = null; + Log.Info($"{what} rifiutato: sul conto {(_mode.IsLive() ? "reale" : "demo")} c'è ancora qualcosa in sospeso ({activity.Describe()})"); + return new CommandResult(false, activity.Describe()) { Code = CommandResult.Refused, Payload = activity }; + } + + Log.Warn($"{what}: sul conto {(_mode.IsLive() ? "reale" : "demo")} non c'è niente in sospeso; nessuna nuova entrata fino al riavvio"); + return new CommandResult(true, $"{what}: conto senza niente in sospeso, entrate bloccate fino al riavvio") { Payload = activity }; + } + + /// A prepared switch that will not happen: the entries are allowed again. + private CommandResult CancelAccountSwitch(EngineCommand c) + { + if (_switchBlock is null) + { + return new CommandResult(true, "nessun cambio di conto in corso"); + } + + _switchBlock = null; + Log.Info($"cambio annullato ({(c.Reason.Length > 0 ? c.Reason : "impostazioni")}): entrate di nuovo permesse{(_entriesBlocked is not null ? " salvo " + _entriesBlocked : string.Empty)}"); + return new CommandResult(true, "entrate di nuovo permesse"); + } + private static string FirstLine(string s) { int i = s.IndexOf('\n', StringComparison.Ordinal); diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Realized.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Realized.cs index 285d8b4..20f4ed5 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Realized.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Realized.cs @@ -53,8 +53,9 @@ public sealed partial class BasketEngine /// Settles the closes the history shows (or that waited past 30 minutes), then /// recomputes today's realised result. Runs when due (see ); /// a history that cannot be read leaves today's number as it was and is asked again in 30 s. + /// Internal: the tests drive it over their own venue. /// - private async Task RefreshRealizedAsync(DateTime now, CancellationToken ct, bool force = false) + internal async Task RefreshRealizedAsync(DateTime now, CancellationToken ct, bool force = false) { if (!force && now < _nextHistoryUtc) { diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Reconcile.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Reconcile.cs index 661a848..40e8db6 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Reconcile.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Reconcile.cs @@ -36,9 +36,10 @@ public sealed partial class BasketEngine /// closed since the last reading. NaN means "not explained yet": no verdict on cash /// movements (the tracker keeps its reference), or — with at /// startup — the balance becomes the new reference without a verdict. The first reading - /// of a UTC day fixes the day's starting net equity. + /// of a UTC day fixes the day's starting net equity. False when the account could not be + /// read: nothing was judged, and what explains the balance must wait for the next reading. /// - private async Task RefreshAccountAsync(double closedNetSinceLast, CancellationToken ct, bool rebase = false) + private async Task RefreshAccountAsync(double closedNetSinceLast, CancellationToken ct, bool rebase = false) { try { @@ -47,7 +48,7 @@ public sealed partial class BasketEngine catch (Exception ex) when (ex is not OperationCanceledException) { Log.Warn($"conto non letto: {ex.Message}"); - return; + return false; } CashMovement? movement = null; @@ -79,50 +80,106 @@ public sealed partial class BasketEngine }); SaveState(); } + + return true; } /// - /// At startup the saved balance is compared with the account's: the trades closed - /// while the bot was off explain part of the difference, a cash movement the rest. + /// At startup the saved balance is compared with the account's: the trades closed since + /// that reading explain part of the difference, a cash movement the rest. The verdict is + /// taken only when the history shows every position known to have closed since then (5.1 + /// review): gone from the account since the last reconciliation, vanished before the stop + /// without a verdict, or closed by the bot and waiting for its settlement. A loss realised + /// just before a restart, still missing from a lagging history, would otherwise be booked + /// as a withdrawal (a profit as a deposit) and never reach the equity stop nor the daily + /// loss. When something is missing the saved balance stays the reference — no verdict, no + /// rebase — and a reconciliation judges the whole difference once the history shows it, + /// exactly as it does in session (, one hour at most). + /// Internal: the tests drive it over their own venue. /// - private async Task StartupEquityAsync(CancellationToken ct) + internal async Task StartupEquityAsync(CancellationToken ct) { - double closedNet = 0; - if (double.IsFinite(_equity.LastBalance) && _equity.LastObservedUtc != default) + if (!double.IsFinite(_equity.LastBalance) || _equity.LastObservedUtc == default) { - try - { - IReadOnlyList closed = await _broker.GetClosedTradesAsync(_equity.LastObservedUtc.AddDays(-1), ct).ConfigureAwait(false); - closedNet = closed.Where(c => c.ClosedUtc > _equity.LastObservedUtc).Sum(static c => c.NetUsd); - } - catch (Exception ex) when (ex is not OperationCanceledException) - { - // Without the closes made while the bot was off, the balance cannot be judged: - // it becomes the new reference, and nothing is booked as a deposit or a withdrawal. - Log.Warn($"storico delle chiusure non letto all'avvio: {ex.Message}; il saldo attuale diventa il riferimento, senza giudicare i movimenti di cassa"); - closedNet = double.NaN; - } + // The first reading of this account: nothing to judge; the first reconciliation starts the positions. + _vanishedUnsettled.Clear(); + _lastPositionIds = []; + await RefreshAccountAsync(0, ct, rebase: true).ConfigureAwait(false); + return; } - await RefreshAccountAsync(closedNet, ct, rebase: true).ConfigureAwait(false); + HashSet onAccount; + IReadOnlyList closed; + try + { + onAccount = [.. (await _broker.GetPositionsAsync(ct).ConfigureAwait(false)).Select(static p => p.PositionId)]; + closed = await _broker.GetClosedTradesAsync(_equity.LastObservedUtc.AddDays(-1), ct).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + // Without the closes made since the saved reading, the balance cannot be judged: + // it becomes the new reference, and nothing is booked as a deposit or a withdrawal. + Log.Warn($"storico delle chiusure o posizioni non letti all'avvio: {ex.Message}; il saldo attuale diventa il riferimento, senza giudicare i movimenti di cassa"); + _vanishedUnsettled.Clear(); + _lastPositionIds = []; + await RefreshAccountAsync(double.NaN, ct, rebase: true).ConfigureAwait(false); + return; + } + + IReadOnlyList expected = StartupCash.Expected(_lastPositionIds, onAccount, _vanishedUnsettled, + _settlements.Queue.Items.Select(static s => ((IReadOnlyCollection)s.Ids, s.ClosedUtc)), _equity.LastObservedUtc); + StartupCashVerdict verdict = StartupCash.Judge(_equity.LastObservedUtc, expected, closed); + + // From here the reconciliation compares with the account as it is now; what closed before is in the verdict. + _lastPositionIds = onAccount; + _pendingClosedNet = verdict.ClosedNet; + if (verdict.Complete) + { + _vanishedUnsettled.Clear(); + if (await RefreshAccountAsync(verdict.ClosedNet, ct, rebase: true).ConfigureAwait(false)) + { + _pendingClosedNet = 0; + } + + return; + } + + if (_vanishedUnsettled.Count == 0 || _vanishedSinceUtc == default) + { + _vanishedSinceUtc = DateTime.UtcNow; + } + + _vanishedUnsettled.Clear(); + _vanishedUnsettled.UnionWith(verdict.Missing); + Log.Info(string.Create(CultureInfo.InvariantCulture, + $"lo storico eToro non mostra ancora le posizioni {string.Join(", ", verdict.Missing)} chiuse dopo l'ultimo saldo letto ({_equity.LastBalance:F2} alle {_equity.LastObservedUtc:HH:mm:ss} UTC): quel saldo resta il riferimento e i movimenti di cassa si giudicano alla riconciliazione che le vede")); + await RefreshAccountAsync(double.NaN, ct).ConfigureAwait(false); } /// Positions that vanished from the account and the venue's history does not show yet. private readonly HashSet _vanishedUnsettled = []; private DateTime _vanishedSinceUtc; + /// + /// The realised net result of the closes since the saved balance that the history already + /// showed at startup, while a verdict waits for the missing ones: part of that verdict. + /// + private double _pendingClosedNet; + /// /// The realised net result of the positions that vanished since the last verdict, from - /// the venue's history. NaN — no verdict on cash movements — while the history does not - /// show all of them yet (it lags a close by seconds to minutes) or cannot be read; the - /// balance is then judged at a later reconciliation, with every close explained. After - /// an hour the positions still missing are given up and the verdict is taken without them. + /// the venue's history (plus what the startup already explained). NaN — no verdict on + /// cash movements — while the history does not show all of them yet (it lags a close by + /// seconds to minutes) or cannot be read; the balance is then judged at a later + /// reconciliation, with every close explained. After an hour the positions still missing + /// are given up and the verdict is taken without them. The set is emptied by the caller + /// once the verdict was taken on a fresh reading of the account, never before. /// private async Task ClosedNetAsync(IReadOnlyCollection vanished, CancellationToken ct) { if (vanished.Count == 0 && _vanishedUnsettled.Count == 0) { - return 0; + return _pendingClosedNet; } if (_vanishedUnsettled.Count == 0) @@ -153,16 +210,16 @@ public sealed partial class BasketEngine Log.Warn($"lo storico eToro non mostra da oltre un'ora le posizioni {string.Join(", ", s.Missing)} sparite dal conto: il saldo viene giudicato senza il loro risultato"); } - _vanishedUnsettled.Clear(); - return s.NetUsd; + return s.NetUsd + _pendingClosedNet; } /// /// Positions on the venue against the local state: a leg that vanished closes its /// sibling; every position is classified; orphans of ours are adopted and closed; /// strangers are reported once and left alone; the two pictures are compared. + /// Internal: the tests drive it over their own venue. /// - private async Task ReconcileAsync(CancellationToken ct) + internal async Task ReconcileAsync(CancellationToken ct) { IReadOnlyList positions; try @@ -180,7 +237,15 @@ public sealed partial class BasketEngine HashSet onVenue = [.. positions.Select(static p => p.PositionId)]; List vanished = [.. _lastPositionIds.Where(id => !onVenue.Contains(id))]; _lastPositionIds = onVenue; - await RefreshAccountAsync(await ClosedNetAsync(vanished, ct).ConfigureAwait(false), ct).ConfigureAwait(false); + double closedNet = await ClosedNetAsync(vanished, ct).ConfigureAwait(false); + if (await RefreshAccountAsync(closedNet, ct).ConfigureAwait(false) && double.IsFinite(closedNet)) + { + // Judged on a fresh reading: what explained it is done with. An account that could not + // be read keeps it for the next reconciliation (5.1 review: never a close lost from a verdict). + _vanishedUnsettled.Clear(); + _pendingClosedNet = 0; + } + await MarginGuardAsync(ct).ConfigureAwait(false); // 1. The baskets the engine holds. diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.State.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.State.cs index b05795b..79e9d3c 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.State.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.State.cs @@ -8,10 +8,12 @@ using Encelado.Core.Baskets.History; namespace Encelado.Engine.Baskets; /// -/// The state on disk (data/state/baskets_state.json): open baskets, entries in -/// flight, the equity tracker, the session's counters and the halts. Written atomically +/// The state on disk, one file per account (: +/// data/state/baskets_state.demo.json, baskets_state.live.json): open baskets, +/// entries in flight, the equity tracker, the session's counters, the halts, the closes +/// waiting for their P&L and the positions the last reconciliation saw. Written atomically /// () after every change that matters; read at startup before the -/// reconciliation. +/// reconciliation. The other account's file is never read nor written by this engine. /// public sealed partial class BasketEngine { @@ -22,7 +24,8 @@ public sealed partial class BasketEngine /// private bool _stateLoaded; - private void SaveState() + /// Written by the decision thread; internal: the tests read back what an engine keeps. + internal void SaveState() { if (!_stateLoaded) { @@ -50,6 +53,12 @@ public sealed partial class BasketEngine // history. What is saved is every close still waiting for it. _settlements.Queue.Write(w, "pendingSettlements"); + // What explains the balance at the next start (5.1 review): the positions the last + // reconciliation saw, and those that vanished without a verdict yet. + WriteIds(w, "lastPositionIds", _lastPositionIds); + WriteIds(w, "vanishedUnsettled", _vanishedUnsettled); + w.WriteString("vanishedSinceUtc", _vanishedUnsettled.Count > 0 && _vanishedSinceUtc != default ? _vanishedSinceUtc.ToString("O", CultureInfo.InvariantCulture) : string.Empty); + // The operator's pause and a warm-up block survive a restart (5.1): a restart // after a settings change, or the container's, must not lift them silently. w.WriteBoolean("pausedByOperator", _pausedByOperator); @@ -137,10 +146,40 @@ public sealed partial class BasketEngine { Log.Warn($"stato non salvato: {ex.Message}"); } + + static void WriteIds(Utf8JsonWriter w, string name, IEnumerable ids) + { + w.WriteStartArray(name); + foreach (long id in ids.Order()) + { + w.WriteNumberValue(id); + } + + w.WriteEndArray(); + } } - private void LoadState() + /// + /// Reads this account's state (internal: the tests load it without a venue). The single + /// file of the previous versions first goes to the account it names — this one or the + /// other — so it is never read by the wrong account nor saved over (5.1 review, D-53). + /// + internal void LoadState() { + // Under the instance lock: one migration, by the engine that owns the folder. A failure + // stops the start before anything could be saved over what was not moved. + try + { + if (AccountStateFiles.MigrateLegacy(_dataDir, _mode) is { } migrated) + { + Log.Info(migrated); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + throw new InvalidOperationException($"lo stato della versione precedente ({AccountStateFiles.LegacyName}) non è stato spostato nel file del suo conto ({ex.Message}): il motore non parte, per non scrivergli sopra. Controlla i permessi di data/state e riprova.", ex); + } + _stateLoaded = true; if (!File.Exists(_statePath)) { @@ -151,10 +190,11 @@ public sealed partial class BasketEngine { using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(_statePath)); JsonElement root = doc.RootElement; - string savedMode = root.TryGetProperty("mode", out JsonElement m) ? m.GetString() ?? string.Empty : string.Empty; - if (!savedMode.Equals(ModeLabel, StringComparison.OrdinalIgnoreCase) && savedMode.Length > 0) + if (AccountStateFiles.ModeOf(root) is { } saved && saved.IsLive() != _mode.IsLive()) { - Log.Warn($"stato salvato in modalità {savedMode}, ora {ModeLabel}: le posizioni salvate non vengono riprese (riconciliazione dal conto)"); + // A file copied by hand into the other account's name: kept aside, never used for this account. + string aside = AccountStateFiles.MoveAside(_statePath, "altro-conto"); + Log.Warn($"{Path.GetFileName(_statePath)} contiene lo stato del conto {saved.Account()}, non del conto {_mode.Account()}: spostato in {Path.GetFileName(aside)}, riparto dalla riconciliazione con il conto"); return; } @@ -197,6 +237,16 @@ public sealed partial class BasketEngine Log.Info($"{_settlements.Queue.Count} chiusure riprese dallo stato salvato: il loro P&L arriva dallo storico eToro{(already > 0 ? $" ({already} già scritte in baskets.csv, scartate)" : string.Empty)}"); } + // The positions the last reconciliation saw and those that vanished without a verdict: + // the startup judges the balance only when the history shows every one that closed. + _lastPositionIds = ReadIds(root, "lastPositionIds"); + _vanishedUnsettled.UnionWith(ReadIds(root, "vanishedUnsettled")); + if (_vanishedUnsettled.Count > 0 && root.TryGetProperty("vanishedSinceUtc", out JsonElement vs) && vs.ValueKind == JsonValueKind.String && + DateTime.TryParse(vs.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime vanishedSince)) + { + _vanishedSinceUtc = vanishedSince; + } + if (_equityStopped) { Log.Warn($"equity stop ancora attivo dal run precedente: {_haltReason}"); @@ -284,10 +334,61 @@ public sealed partial class BasketEngine Log.Warn($"[{name}] ingresso in sospeso ripreso dallo stato salvato ({slot.State}, basket {plan.BasketId}): il registro degli ordini lo risolve prima di ogni decisione"); } } + + ScheduleRecoveryForAnUnattendedAccount(AccountStateFiles.SavedUtcOf(root), DateTime.UtcNow); } catch (Exception ex) when (ex is IOException or JsonException or KeyNotFoundException or InvalidOperationException or FormatException) { - Log.Warn($"stato salvato non leggibile ({ex.Message}): riparto dalla riconciliazione con il conto"); + // Kept aside for a person to look at: the next save must not write over it. + string kept = TryMoveAside(_statePath, "illeggibile"); + Log.Warn($"stato salvato non leggibile ({ex.Message}): riparto dalla riconciliazione con il conto{(kept.Length > 0 ? $"; il file resta come {Path.GetFileName(kept)}" : string.Empty)}"); + } + + static HashSet ReadIds(JsonElement root, string name) + { + HashSet ids = []; + if (root.TryGetProperty(name, out JsonElement arr) && arr.ValueKind == JsonValueKind.Array) + { + foreach (JsonElement x in arr.EnumerateArray()) + { + if (x.ValueKind == JsonValueKind.Number && x.TryGetInt64(out long id) && id > 0) + { + ids.Add(id); + } + } + } + + return ids; + } + } + + /// + /// An account whose baskets nobody watched for longer than the recovery threshold — the + /// bot ran on the other account meanwhile, so the shared heartbeat looks fresh — gets the + /// recovery a restart after an inactivity gets: every open basket judged again with the + /// bars that went by, before any new entry. + /// + private void ScheduleRecoveryForAnUnattendedAccount(DateTime savedUtc, DateTime now) + { + bool holds = _slots.Any(static s => s.Position is not null || s.State.IsPending()); + TimeSpan gap = now - savedUtc; + if (!holds || savedUtc == DateTime.MinValue || gap <= TimeSpan.FromMinutes(_strategy.Recovery.ThresholdMinutes)) + { + return; + } + + ScheduleRecovery(gap, string.Create(CultureInfo.InvariantCulture, $"i basket del conto {(_mode.IsLive() ? "reale" : "demo")} non erano seguiti da {gap.TotalMinutes:0} minuti (stato salvato il {savedUtc:yyyy-MM-dd HH:mm} UTC)")); + } + + private static string TryMoveAside(string path, string tag) + { + try + { + return File.Exists(path) ? AccountStateFiles.MoveAside(path, tag) : string.Empty; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return string.Empty; } } } diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.View.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.View.cs index 72e15e3..220aaf6 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.View.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.View.cs @@ -138,7 +138,7 @@ public sealed partial class BasketEngine EquityStopped = _equityStopped, HaltReason = _haltReason ?? string.Empty, HaltResidue = [.. _haltResidue], - EntriesBlockedReason = _entriesBlocked ?? string.Empty, + EntriesBlockedReason = _switchBlock ?? _entriesBlocked ?? string.Empty, EntriesBlockedUntilUtc = _entriesBlockedUntilUtc, Paused = _pausedByOperator, Unreconciled = IsUnreconciled, diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.cs index d940167..19e10b8 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.cs @@ -247,6 +247,20 @@ public sealed partial class BasketEngine : IEngine /// Where the engine tells the outside world what it did. /// The section versions of the process (the web layer reads them); a private set when null. public BasketEngine(BotConfig config, EtoroKeys? keys, bool startConfirmed, IContextProvider? context = null, INotifier? notifier = null, SectionVersions? versions = null) + : this(config, keys, startConfirmed, context, notifier, versions, venue: null) + { + } + + /// + /// The tests' seam: the same engine with another venue for the account, the positions, the + /// orders and the history. The eToro client stays for what only it has (the key check at + /// the start, the clock, the HTTP statistics), so such an engine is driven step by step, + /// never through . + /// + internal static BasketEngine OverVenue(BotConfig config, IBroker venue, bool startConfirmed = false, INotifier? notifier = null) => + new(config, null, startConfirmed, null, notifier, null, venue ?? throw new ArgumentNullException(nameof(venue))); + + private BasketEngine(BotConfig config, EtoroKeys? keys, bool startConfirmed, IContextProvider? context, INotifier? notifier, SectionVersions? versions, IBroker? venue) { ArgumentNullException.ThrowIfNull(config); _config = config.Validate(); @@ -307,11 +321,14 @@ public sealed partial class BasketEngine : IEngine _dataDir = config.Run.DataPath; _marketDir = Path.Combine(_dataDir, "market"); - _statePath = Path.Combine(_dataDir, "state", "baskets_state.json"); + + // One state per account (5.1 review, D-53): the other account's baskets, halts and + // closes waiting for their P&L stay in its own file while this engine runs. + _statePath = AccountStateFiles.PathFor(_dataDir, _mode); _stopFile = Path.Combine(config.Run.BaseDirectory, "STOP"); Directory.CreateDirectory(_marketDir); Directory.CreateDirectory(Path.GetDirectoryName(_statePath)!); - _broker = _feed; + _broker = venue ?? _feed; // The Paper simulator is gone (5.1): its files stay where they are, never read again. foreach (string leftover in new[] { "paper_state.json", "pending_orders_paper.json" }) @@ -324,7 +341,10 @@ public sealed partial class BasketEngine : IEngine _ledger = new Ledger(Path.Combine(_dataDir, "ledger")); _origins = new PositionOrigins(_ledger.ReadOrders(), _ledger.ReadBaskets()); - _tracker = new OrderTracker(Path.Combine(_dataDir, "state", "pending_orders.json")); + + // The register works on this account's orders only: the other account's stay in the + // file, never looked up here, never failed, never pruned (5.1 review). + _tracker = new OrderTracker(Path.Combine(_dataDir, "state", "pending_orders.json"), _mode); _tracker.Changed += (order, evento) => { OrderRecord line = OrderRecord.From(order, _runId, evento); @@ -417,6 +437,11 @@ public sealed partial class BasketEngine : IEngine await ResolvePendingOrdersAsync(ct, force: true).ConfigureAwait(false); } + if (_tracker.OtherAccountPendingCount is > 0 and int other) + { + Log.Info($"registro ordini: {other} ordine/i senza esito del conto {(_mode.IsLive() ? "demo" : "reale")} restano nel registro: li risolve il motore di quel conto"); + } + await ReconcileAsync(ct).ConfigureAwait(false); _sessionDate = DateOnly.FromDateTime(DateTime.UtcNow); @@ -483,7 +508,8 @@ public sealed partial class BasketEngine : IEngine /// The pairs that price the display currencies against USD (D-33): polled with the rest, never traded. private static readonly string[] ConversionPairs = ["EURUSD", "GBPUSD", "USDCHF", "USDJPY", "AUDUSD", "USDCAD", "NZDUSD"]; - private async Task LoadInstrumentsAsync(CancellationToken ct) + /// The instruments and the basket slots (internal: the tests build the slots over their own venue). + internal async Task LoadInstrumentsAsync(CancellationToken ct) { List symbols = _strategy.Symbols(_strategy.PreferDirectCross); foreach (string extra in ConversionPairs) @@ -1172,8 +1198,9 @@ public sealed partial class BasketEngine : IEngine EquityStopped = _equityStopped, KillSwitched = _killSwitched, - // The stop began (FERMA, the container's stop): nothing new until the loop is cancelled. - EntriesBlockedReason = _stopping ? StopReason : _entriesBlocked ?? StaleQuoteReason(slot, now), + // The stop began (FERMA, the container's stop), or a change of account is being + // saved: nothing new until the loop is cancelled. + EntriesBlockedReason = _stopping ? StopReason : _switchBlock ?? _entriesBlocked ?? StaleQuoteReason(slot, now), IsBarClose = isBarClose, MinutesToNextHigh = f.MinutesToNextHigh, MinutesSinceLastHigh = f.MinutesSinceLastHigh, @@ -1259,7 +1286,7 @@ public sealed partial class BasketEngine : IEngine // live mode, the kill-switch and the reset after an equity stop. private async Task ExecuteEntryAsync(BasketSlot slot, BasketContext ctx, BasketDecision d, CancellationToken ct) { - if (_stopping || slot.Position is not null || slot.State != BasketState.Idle) + if (_stopping || _switchBlock is not null || slot.Position is not null || slot.State != BasketState.Idle) { return; } @@ -1399,7 +1426,7 @@ public sealed partial class BasketEngine : IEngine private async Task ExecuteAddAsync(BasketSlot slot, BasketContext ctx, BasketDecision d, CancellationToken ct) { - if (_stopping || slot.Position is null || slot.State != BasketState.Open) + if (_stopping || _switchBlock is not null || slot.Position is null || slot.State != BasketState.Open) { return; } diff --git a/Encelado/src/Encelado.Engine/Engine/BotSupervisor.cs b/Encelado/src/Encelado.Engine/Engine/BotSupervisor.cs index e13a95c..1f53218 100644 --- a/Encelado/src/Encelado.Engine/Engine/BotSupervisor.cs +++ b/Encelado/src/Encelado.Engine/Engine/BotSupervisor.cs @@ -623,6 +623,99 @@ public sealed class BotSupervisor : IAsyncDisposable public Task CloseAsync(string basket, CancellationToken ct) => ExecuteAsync(new EngineCommand(EngineCommandKind.Close, basket, "chiusura manuale"), ct); + /// How long the guard of a change of account waits for the engine (it takes commands between two ticks); the tests shorten it. + internal TimeSpan SwitchCheckWait { get; set; } = TimeSpan.FromSeconds(30); + + /// How long a cancelled switch waits for the engine to lift its block before it leaves the command queued. + private static readonly TimeSpan SwitchCancelWait = TimeSpan.FromSeconds(5); + + /// + /// The guard of a change of account or of the basket pairs (5.1 review, decision C8), asked + /// of the running engine on its decision thread (): + /// it blocks its new entries, then counts what is still in hand on its account. Null when no + /// engine runs — the account's files decide. Refused () + /// while the engine starts — until its decision loop runs it has not read its state, and its + /// picture looks flat — or stops, when it does not answer within + /// (the block is then cancelled behind it), or when it is busy (the payload says with what). + /// Ok: the entries stay blocked until the restart, or until . + /// + public async Task PrepareAccountSwitchAsync(string what, CancellationToken ct) + { + IEngine? engine; + BotState state; + lock (_gate) + { + engine = _engine; + state = _state; + } + + switch (state) + { + case BotState.Starting: + case BotState.Running when engine is not null && !engine.LoopStarted: + return Refused("il motore si sta avviando (verifica, riscaldamento, riconciliazione) e non ha ancora letto il suo stato: riprova appena il ciclo di decisione è partito"); + case BotState.Stopping: + return Refused("il motore si sta fermando: riprova fra qualche secondo"); + case BotState.Running when engine is not null: + break; + default: + return null; + } + + using CancellationTokenSource wait = CancellationTokenSource.CreateLinkedTokenSource(ct); + wait.CancelAfter(SwitchCheckWait); + CommandResult r; + try + { + r = await ExecuteAsync(new EngineCommand(EngineCommandKind.PrepareAccountSwitch, what, "impostazioni"), wait.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + // Still queued: it will block the entries when the engine takes it; the cancel queued behind it lifts the block at once. + await CancelAccountSwitchAsync("il motore non ha risposto in tempo").ConfigureAwait(false); + return Refused(string.Create(CultureInfo.InvariantCulture, $"il motore è occupato e non ha risposto entro {SwitchCheckWait.TotalSeconds:0} s: riprova fra poco")); + } + + if (r.Ok || r.Code.Length > 0) + { + return r; + } + + // Nobody took it: the engine stopped meanwhile. + return Refused($"il motore ha cambiato stato durante il controllo ({r.Message}): riprova"); + } + + /// A prepared switch that will not happen: the running engine allows its entries again. Never throws; a stopped engine needs nothing. + public async Task CancelAccountSwitchAsync(string reason) + { + IEngine? engine; + lock (_gate) + { + engine = _state == BotState.Running ? _engine : null; + } + + if (engine is null) + { + return; + } + + try + { + // Not awaited for long: the command runs after the ones already queued, the prepare + // included, and an engine too busy to take it now takes it in order anyway. + using CancellationTokenSource wait = new(SwitchCancelWait); + CommandResult r = await engine.ExecuteAsync(new EngineCommand(EngineCommandKind.CancelAccountSwitch, string.Empty, reason), wait.Token).ConfigureAwait(false); + if (!r.Ok) + { + Log.Warn($"cambio annullato ma il motore non l'ha preso: {r.Message}"); + } + } + catch (Exception ex) when (ex is OperationCanceledException or TimeoutException) + { + Log.Warn("cambio annullato: il motore lo prenderà appena libero (resta in coda)"); + } + } + /// What the engine has in hand that a stop or a restart would cut in half, described for the operator; null when nothing. public string? CommandInProgress { diff --git a/Encelado/src/Encelado.Engine/Engine/IEngine.cs b/Encelado/src/Encelado.Engine/Engine/IEngine.cs index d60e010..d09e2bb 100644 --- a/Encelado/src/Encelado.Engine/Engine/IEngine.cs +++ b/Encelado/src/Encelado.Engine/Engine/IEngine.cs @@ -61,6 +61,21 @@ public enum EngineCommandKind /// kill-switch in progress finishes first (5.1: nothing closes from another thread). /// Shutdown, + + /// + /// The guard of a change of account or of the basket pairs (5.1 review, decision C8), asked + /// by the settings before anything is written: the engine blocks its new entries and adds, + /// then counts on its own slots what is still in hand on the account (open or pending + /// baskets, entries, adds and exits under way, errors with a leg, orders without an + /// outcome, orphans and residue, closes waiting for the history). Busy: the block is lifted + /// and the answer is with the + /// as payload. Idle: the entries stay blocked until the restart (or ). + /// Argument = what changes, for the log. + /// + PrepareAccountSwitch, + + /// A prepared switch that will not happen (the save failed or was undone): the entries are allowed again. + CancelAccountSwitch, } public sealed record EngineCommand(EngineCommandKind Kind, string Argument = "", string Reason = "") diff --git a/Encelado/src/Encelado.Engine/Settings/AccountActivity.cs b/Encelado/src/Encelado.Engine/Settings/AccountActivity.cs index 40c6043..e366562 100644 --- a/Encelado/src/Encelado.Engine/Settings/AccountActivity.cs +++ b/Encelado/src/Encelado.Engine/Settings/AccountActivity.cs @@ -1,52 +1,157 @@ using System.Globalization; using System.Text.Json; using Encelado.Core.Baskets; +using Encelado.Engine.Baskets; namespace Encelado.Engine.Settings; +/// One basket slot as the account-switch guard sees it, taken on the engine's decision thread. +public readonly record struct SlotActivity(BasketState State, bool HasPosition, bool HasLegs, bool Busy); + /// -/// What the bot holds on the account right now: open baskets, entries waiting for a leg, -/// orders without an outcome. A change of account (Demo ↔ Live) or of the basket pairs is -/// refused while any of these exists (5.1, decision C8): the other account does not have -/// them, and a basket left behind would be watched by nobody but the native stop-loss. +/// What the bot still has in hand on an account: open baskets, entries waiting for a leg, +/// entries, adds and exits under way, baskets in error with a leg on the account, orders +/// without an outcome, orphan legs and the residue of a kill-switch, closes waiting for the +/// venue's history. A change of account (Demo ↔ Live) or of the basket pairs is refused while +/// any of these exists (5.1, decision C8; 5.1 review): the other account does not have them, +/// and a basket left behind would be watched by nobody but the native stop-loss. +/// +/// A running engine answers on its decision thread (), after it blocked +/// its new entries: the published picture of a basket in the middle of its entry, or of an +/// engine that has not read its state yet, looks flat. A stopped engine is judged on the +/// account's own state file and on the order register (). +/// /// public sealed record AccountActivity(int OpenBaskets, int PendingBaskets, int PendingOrders) { public static readonly AccountActivity None = new(0, 0, 0); - public bool Busy => OpenBaskets + PendingBaskets + PendingOrders > 0; + /// Entries, adds and exits the engine has in hand (the slot has no position yet, or no longer). + public int InFlight { get; init; } - public string Describe() => string.Create(CultureInfo.InvariantCulture, - $"{OpenBaskets} basket aperti, {PendingBaskets} in attesa di una gamba, {PendingOrders} ordini senza esito"); + /// Baskets in error with a leg still on the account. + public int ErrorLegs { get; init; } - /// From the running engine's picture. - public static AccountActivity FromSnapshot(BotSnapshot snapshot) + /// Orphan legs of the bot on the account, and the residue of a kill-switch. + public int OrphanLegs { get; init; } + + /// Closes waiting for the venue's history (at most 30 minutes, then the estimate). + public int PendingSettlements { get; init; } + + /// The engine has not read its state yet, or the state on disk cannot be read: busy, the prudent answer. + public bool Unknown { get; init; } + + public bool Busy => OpenBaskets + PendingBaskets + PendingOrders + InFlight + ErrorLegs + OrphanLegs + PendingSettlements > 0 || Unknown; + + /// What is still open, in Italian, naming only what there is. + public string Describe() { - ArgumentNullException.ThrowIfNull(snapshot); - return new AccountActivity(snapshot.OpenBaskets, snapshot.PendingBaskets, snapshot.PendingOrders); + List parts = []; + Add(OpenBaskets, "basket aperto", "basket aperti"); + Add(PendingBaskets, "basket in attesa di una gamba", "basket in attesa di una gamba"); + Add(InFlight, "ingresso, aggiunta o uscita in corso", "ingressi, aggiunte o uscite in corso"); + Add(ErrorLegs, "basket in errore con una gamba sul conto", "basket in errore con una gamba sul conto"); + Add(PendingOrders, "ordine senza esito", "ordini senza esito"); + Add(OrphanLegs, "gamba orfana del bot (o residuo del kill-switch)", "gambe orfane del bot (o residui del kill-switch)"); + Add(PendingSettlements, "chiusura in attesa dello storico eToro", "chiusure in attesa dello storico eToro"); + if (Unknown) + { + parts.Add("uno stato non ancora letto o non leggibile"); + } + + return parts.Count == 0 ? "niente in sospeso" : string.Join(", ", parts); + + void Add(int n, string one, string many) + { + if (n > 0) + { + parts.Add(n == 1 ? $"1 {one}" : string.Create(CultureInfo.InvariantCulture, $"{n} {many}")); + } + } } /// - /// From the files a stopped engine left: data/state/baskets_state.json (open and - /// pending baskets) and data/state/pending_orders.json (orders without an outcome). - /// An unreadable state counts as busy: refusing a switch is the prudent answer. + /// What the operator can do about it. The closes waiting for the history are settled only + /// by an engine running on the account ( false: it must be + /// started on it for a while — they are never lost meanwhile, they stay in its state). /// - public static AccountActivity FromDisk(string dataPath) + public string Advice(bool engineRunning = true) + { + bool positions = OpenBaskets + PendingBaskets + InFlight + ErrorLegs + PendingOrders + OrphanLegs > 0; + string settle = engineRunning + ? "aspetta che lo storico eToro confermi le chiusure (al più 30 minuti)" + : "le chiusure in attesa si confermano solo con il motore acceso su questo conto: avvialo finché lo storico eToro le conferma (al più 30 minuti)"; + return positions + ? "Chiudili (anche con il kill-switch) o aspetta che si risolvano, poi riprova" + (PendingSettlements > 0 ? $"; {settle}" : string.Empty) + : PendingSettlements > 0 + ? $"{char.ToUpperInvariant(settle[0])}{settle[1..]}, poi riprova" + : "Riprova fra qualche secondo"; + } + + /// + /// The running engine's own count, on its decision thread: every slot with a position, a + /// pending leg, an operation in hand or an error with a leg; the register's orders without + /// an outcome; the orphans and the residue; the closes waiting for the history. + /// + public static AccountActivity FromEngine(IEnumerable slots, int pendingOrders, int orphanLegs, int pendingSettlements, bool stateLoaded) + { + ArgumentNullException.ThrowIfNull(slots); + int open = 0, pending = 0, inFlight = 0, errors = 0; + foreach (SlotActivity s in slots) + { + if (s.HasPosition) + { + open++; + } + else if (s.State.IsPending()) + { + pending++; + } + else if (s.Busy || s.State is BasketState.Entering or BasketState.Adding or BasketState.Exiting) + { + inFlight++; + } + else if (s.State == BasketState.Error && s.HasLegs) + { + errors++; + } + } + + return new AccountActivity(open, pending, pendingOrders) + { + InFlight = inFlight, + ErrorLegs = errors, + OrphanLegs = orphanLegs, + PendingSettlements = pendingSettlements, + Unknown = !stateLoaded, + }; + } + + /// + /// From the files a stopped engine left for : its own state + /// (: open and pending baskets, closes waiting + /// for the history, the residue of a kill-switch) and the orders of that account without an + /// outcome in data/state/pending_orders.json. An unreadable file counts as busy: + /// refusing a switch is the prudent answer. + /// + public static AccountActivity FromDisk(string dataPath, ExecutionMode account) { ArgumentException.ThrowIfNullOrWhiteSpace(dataPath); - string state = Path.Combine(dataPath, "state", "baskets_state.json"); - int open = 0, pending = 0; - if (File.Exists(state)) + int open = 0, pending = 0, settlements = 0, residue = 0; + bool unknown = false; + if (AccountStateFiles.ReadablePathFor(dataPath, account) is { } state) { try { using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(state)); open = Count(doc.RootElement, "baskets"); pending = Count(doc.RootElement, "pendingEntries"); + settlements = Count(doc.RootElement, "pendingSettlements"); + residue = Count(doc.RootElement, "haltResidue"); } catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException) { - open = 1; + unknown = true; } } @@ -63,8 +168,8 @@ public sealed record AccountActivity(int OpenBaskets, int PendingBaskets, int Pe { foreach (JsonElement o in all.EnumerateArray()) { - string resolution = o.TryGetProperty("resolution", out JsonElement r) && r.ValueKind == JsonValueKind.String ? r.GetString() ?? string.Empty : string.Empty; - if (!Enum.TryParse(resolution, out OrderResolution parsed) || parsed == OrderResolution.Pending) + string resolution = Text(o, "resolution"); + if ((!Enum.TryParse(resolution, out OrderResolution parsed) || parsed == OrderResolution.Pending) && OrderTracker.BelongsTo(Text(o, "mode"), account)) { orders++; } @@ -73,13 +178,16 @@ public sealed record AccountActivity(int OpenBaskets, int PendingBaskets, int Pe } catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException) { - orders = 1; + unknown = true; } } - return new AccountActivity(open, pending, orders); + return new AccountActivity(open, pending, orders) { PendingSettlements = settlements, OrphanLegs = residue, Unknown = unknown }; static int Count(JsonElement root, string name) => - root.TryGetProperty(name, out JsonElement a) && a.ValueKind == JsonValueKind.Array ? a.GetArrayLength() : 0; + root.ValueKind == JsonValueKind.Object && root.TryGetProperty(name, out JsonElement a) && a.ValueKind == JsonValueKind.Array ? a.GetArrayLength() : 0; + + static string Text(JsonElement o, string name) => + o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? string.Empty : string.Empty; } } diff --git a/Encelado/src/Encelado.Engine/Settings/SettingsRuntime.cs b/Encelado/src/Encelado.Engine/Settings/SettingsRuntime.cs index 264f3c8..243d2d5 100644 --- a/Encelado/src/Encelado.Engine/Settings/SettingsRuntime.cs +++ b/Encelado/src/Encelado.Engine/Settings/SettingsRuntime.cs @@ -4,6 +4,7 @@ using System.Text.Json; using Encelado.Core.Baskets; using Encelado.Core.Broker; using Encelado.Core.Notifications; +using Encelado.Engine.Baskets; using Encelado.Engine.Configuration; using Encelado.Engine.Logging; using Encelado.Etoro; @@ -66,8 +67,18 @@ public sealed record SecretActionResult(bool Ok, string Message, string Restart /// decision thread. Restart-scoped changes (the account, the pairs, the direct crosses) /// stop the engine without closing a basket and start it again — never into Live without /// the phrase: a save that would restart a Live engine is answered 409 needsPhrase -/// before anything is written, and a change of account is refused while baskets or orders -/// are open (). +/// before anything is written. +/// +/// +/// A change of account or of the basket pairs (decision C8, 5.1 review) is refused while the +/// account in use still has anything in hand (). A running engine +/// answers on its decision thread, after it blocked its new entries — never its published +/// picture, where a basket in the middle of its entry or an engine still starting looks flat; +/// the entries stay blocked until the restart. A stopped engine is judged on the account's own +/// state file. After the stop, and before anything starts on the other account, the file the +/// stopped engine saved is judged again: if it is not flat, the save is undone byte for byte +/// and the engine stays stopped. Each account keeps its own state (D-53), so the other one's +/// baskets, halts and closes waiting for their P&L are there when it runs again. /// /// /// The restart itself runs under the supervisor's lifecycle lock @@ -229,16 +240,14 @@ public sealed class SettingsRuntime List restartFields = [.. plan.Changed.Values.Where(static f => f.Scope == SettingScope.Restart)]; bool accountChange = before != after; bool pairsChange = plan.Changed.Values.Any(static f => f.Target == SettingTarget.Strategy && f.FilePath.StartsWith("baskets[", StringComparison.Ordinal) && !f.FilePath.EndsWith(".enabled", StringComparison.Ordinal)); + bool guarded = accountChange || pairsChange; + string what = accountChange ? "il cambio di conto" : "il cambio delle coppie dei basket"; - // The guards come before any write: a refused save changes nothing. - if (accountChange || pairsChange) + // The guards come before any write: a refused save changes nothing. The cheap ones first, + // so that a refusal never blocks the engine's entries even for a moment. + if (guarded && Supervisor.State == BotState.Stopping) { - AccountActivity activity = running ? AccountActivity.FromSnapshot(Supervisor.Snapshot()) : AccountActivity.FromDisk(Config.Run.DataPath); - if (activity.Busy) - { - string what = accountChange ? "il cambio di conto" : "il cambio delle coppie dei basket"; - return Refused($"{what} è rifiutato: sul conto ci sono {activity.Describe()}. Chiudili (anche con il kill-switch) e riprova."); - } + return Refused($"{what} è rifiutato: il motore si sta fermando; riprova fra qualche secondo (niente è stato salvato)"); } if (accountChange && running && Secrets.Etoro(demo: !after.IsLive()) is null) @@ -258,17 +267,109 @@ public sealed class SettingsRuntime [.. restartFields.Select(static f => new SettingsPathResult(f.Path, "error", $"serve {LiveConfirmation.Phrase}"))], SettingsResult.RestartNeedsPhrase, new Dictionary()); } + // Decision C8, authoritative (5.1 review): a running engine answers on its decision thread + // after it blocked its new entries — its published picture shows a basket in the middle of + // its entry, or an engine that has not read its state yet, as flat; a stopped one is judged + // on the account's own state file. + bool prepared = false; + if (guarded) + { + if (running && await Supervisor.PrepareAccountSwitchAsync(accountChange ? $"cambio di conto verso {(after.IsLive() ? "il reale" : "il demo")}" : "cambio delle coppie dei basket", ct).ConfigureAwait(false) is { } check) + { + if (!check.Ok) + { + return Refused(SwitchRefusal(what, before, check)); + } + + prepared = true; + } + else + { + // Stopped (or stopped since): the files of the account in use decide. + running = false; + AccountActivity activity = AccountActivity.FromDisk(Config.Run.DataPath, before); + if (activity.Busy) + { + return Refused($"{what} è rifiutato: sul conto {Label(before)} c'è ancora qualcosa in sospeso ({activity.Describe()}). {activity.Advice(engineRunning: false)} (niente è stato salvato)."); + } + } + } + + // From here on a prepared switch that does not reach its restart is cancelled on every way out. + bool switched = false; try { - SettingsService.Write(ConfigPath, Strategy.Path, plan); + FilesBefore saved; + try + { + saved = guarded ? FilesBefore.Read(ConfigPath, Strategy.Path) : FilesBefore.None; + SettingsService.Write(ConfigPath, Strategy.Path, plan); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException) + { + return Failure($"salvataggio non riuscito: {ex.Message}"); + } + + await RefreshMemoryAsync(plan.Changed.Keys, accountChange).ConfigureAwait(false); + if (guarded && running) + { + // Restarted under the supervisor's lifecycle lock; after the stop the account's own file, + // just saved by the stopped engine, is judged again before anything starts on the other. + string paths = string.Join(", ", plan.Changed.Keys); + string? leftBehind = null; + RestartResult rr = await RestartCoreAsync(confirmed, $"impostazioni salvate: {paths}", () => + { + AccountActivity left = AccountActivity.FromDisk(Config.Run.DataPath, before); + if (!left.Busy) + { + return null; + } + + leftBehind = left.Describe(); + return new CommandResult(false, $"dopo l'arresto sul conto {Label(before)} c'è ancora qualcosa in sospeso ({leftBehind})") { Code = CommandResult.Refused }; + }).ConfigureAwait(false); + switched = rr.Stopped; + string? undo = leftBehind is not null + ? $"{what} è stato annullato dopo l'arresto del motore: sul conto {Label(before)} c'è ancora qualcosa in sospeso ({leftBehind}). Il motore resta fermo: controlla il conto e premi AVVIA." + : !rr.Stopped && rr.Result.Code == CommandResult.Refused + ? $"{what} non è stato applicato: {rr.Result.Message}. Il motore resta acceso sul conto {Label(before)}." + : !rr.Stopped && StoppedAccountActivity(before) is { } afterFerma + ? $"{what} è stato annullato: il motore è stato fermato nel frattempo e sul conto {Label(before)} c'è ancora qualcosa in sospeso ({afterFerma})." + : null; + if (undo is not null) + { + // After the stop something was still on the account, or a kill-switch, a close or a + // residue close started meanwhile (the engine still runs on its own account), or a + // FERMA left the account busy: the files go back to how they were, byte for byte. + string? failed = saved.PutBack(ConfigPath, Strategy.Path); + await RefreshMemoryAsync(plan.Changed.Keys, accountChange).ConfigureAwait(false); + string why = failed is null + ? $"{undo} Le impostazioni sono tornate come prima (niente è stato salvato)." + : $"{undo} ATTENZIONE: le impostazioni NON sono tornate come prima ({failed}): controllale in Impostazioni prima di premere AVVIA."; + Log.Warn($"impostazioni: {why}"); + return Refused(why); + } + + return Summarize(plan, Restarted(rr)); + } + + return await ApplyAfterWriteAsync(plan, restartFields, running, confirmed, ct).ConfigureAwait(false); } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException) + finally { - return Failure($"salvataggio non riuscito: {ex.Message}"); + if (prepared && !switched) + { + await Supervisor.CancelAccountSwitchAsync("il cambio non è stato applicato").ConfigureAwait(false); + } } + } - await RefreshMemoryAsync(plan.Changed.Keys, accountChange).ConfigureAwait(false); - + /// + /// What a save does to the engine once the files are written (every save that is not a + /// guarded change of account or pairs): the restart, the hot apply, or nothing. + /// + private async Task ApplyAfterWriteAsync(SettingsPlan plan, List restartFields, bool running, bool confirmed, CancellationToken ct) + { // The running engine. "running" was read before the write: a FERMA may have come since, and // then the files simply count at the next start (the restart reads the state again under the // supervisor's lifecycle lock and never undoes a stop). @@ -310,6 +411,13 @@ public sealed class SettingsRuntime } } + return Summarize(plan, (restart, engineOk, engineMessage, running)); + } + + /// The answer of a written save: per path what happened, and one line for the page and the log. + private static SettingsResult Summarize(SettingsPlan plan, (string Restart, bool EngineOk, string EngineMessage, bool Running) outcome) + { + (string restart, bool engineOk, string engineMessage, bool running) = outcome; List results = []; foreach (SettingField f in plan.Changed.Values) { @@ -507,8 +615,63 @@ public sealed class SettingsRuntime /// one with a kill-switch, a close or a residue close in progress; the new engine takes /// the baskets over from the state. /// - private Task RestartCoreAsync(bool liveConfirmed, string reason) => - Supervisor.RestartAsync(reason, Config.Run.Mode.IsLive() && liveConfirmed, () => StartRefusal(liveConfirmed)); + private Task RestartCoreAsync(bool liveConfirmed, string reason, Func? afterStop = null) => + Supervisor.RestartAsync(reason, Config.Run.Mode.IsLive() && liveConfirmed, () => afterStop?.Invoke() ?? StartRefusal(liveConfirmed)); + + /// What a stopped engine left on , described; null when it is flat or an engine runs again. + private string? StoppedAccountActivity(ExecutionMode account) + { + if (Supervisor.State is not (BotState.Stopped or BotState.Faulted)) + { + return null; + } + + AccountActivity left = AccountActivity.FromDisk(Config.Run.DataPath, account); + return left.Busy ? left.Describe() : null; + } + + /// The refusal of a change the running engine found busy (the payload says with what), or that it could not check. + private static string SwitchRefusal(string what, ExecutionMode account, CommandResult check) => + check.Payload is AccountActivity activity + ? $"{what} è rifiutato: sul conto {Label(account)} c'è ancora qualcosa in sospeso ({activity.Describe()}). {activity.Advice()} (niente è stato salvato)." + : $"{what} è rifiutato: {check.Message} (niente è stato salvato)."; + + private static string Label(ExecutionMode account) => account.IsLive() ? "reale" : "demo"; + + /// + /// The two files as they were before a change of account or pairs: a switch that cannot + /// complete puts them back byte for byte, so nothing of the save remains (5.1 review). + /// + private sealed record FilesBefore(byte[]? ConfigBytes, byte[]? StrategyBytes) + { + public static readonly FilesBefore None = new(null, null); + + public static FilesBefore Read(string configPath, string strategyPath) => + new(File.Exists(configPath) ? File.ReadAllBytes(configPath) : null, File.Exists(strategyPath) ? File.ReadAllBytes(strategyPath) : null); + + /// Writes them back atomically; the reason when it could not (null when done). + public string? PutBack(string configPath, string strategyPath) + { + try + { + if (StrategyBytes is { } s) + { + AtomicFile.Write(strategyPath, s); + } + + if (ConfigBytes is { } c) + { + AtomicFile.Write(configPath, c); + } + + return null; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return ex.Message; + } + } + } // ----------------------------------------------------------------------- // Secrets @@ -804,9 +967,9 @@ public sealed class SettingsRuntime return new SecretActionResult(false, "ferma il motore prima di ripristinare la configurazione", HttpStatus: 409); } - if (Config.Run.Mode.IsLive() && AccountActivity.FromDisk(Config.Run.DataPath).Busy) + if (Config.Run.Mode.IsLive() && AccountActivity.FromDisk(Config.Run.DataPath, ExecutionMode.Live) is { Busy: true } live) { - return new SecretActionResult(false, "il ripristino riporta il conto a Demo, ma sul conto reale ci sono basket o ordini aperti: chiudili prima", HttpStatus: 409); + return new SecretActionResult(false, $"il ripristino riporta il conto a Demo, ma sul conto reale c'è ancora qualcosa in sospeso ({live.Describe()}). {live.Advice(engineRunning: false)}", HttpStatus: 409); } backup = ConfigDefaults.Restore(ConfigPath); diff --git a/Encelado/tests/Encelado.Tests/AccountStateTests.cs b/Encelado/tests/Encelado.Tests/AccountStateTests.cs new file mode 100644 index 0000000..bec837e --- /dev/null +++ b/Encelado/tests/Encelado.Tests/AccountStateTests.cs @@ -0,0 +1,545 @@ +using System.Globalization; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; +using Encelado.Core.Baskets; +using Encelado.Core.Baskets.Data; +using Encelado.Core.Baskets.History; +using Encelado.Core.Broker; +using Encelado.Engine; +using Encelado.Engine.Baskets; +using Encelado.Engine.Configuration; +using Encelado.Engine.Settings; + +namespace Encelado.Tests; + +/// +/// A venue for the account tests: the account, the positions on it and the closed-trade +/// history, all set by the test. It never takes an order. +/// +internal sealed class AccountVenue : IBroker +{ + public double Balance { get; set; } = 10_000; + + public double Equity { get; set; } = 10_000; + + public List Positions { get; } = []; + + public List History { get; } = []; + + /// The orders asked about, by the venue's id. + public List Lookups { get; } = []; + + public BrokerEnvironment Environment => BrokerEnvironment.Demo; + + public string Name => "conto di prova"; + + public bool SupportsTrading => true; + + public TimeSpan ClockSkew => TimeSpan.Zero; + + public Task> GetInstrumentsAsync(IReadOnlyList symbols, CancellationToken ct) => + Task.FromResult>([.. symbols.Select(static (s, i) => new Instrument(i + 1, s, s, "Forex", PipMath.Pip(s), PipMath.Digits(s), 0.01, 2_000_000, 1000, [1, 2, 5, 10], true, true, 0, 50, string.Empty))]); + + public Task> GetQuotesAsync(IReadOnlyList instrumentIds, CancellationToken ct) => Task.FromResult>([]); + + public Task> GetCandlesAsync(long instrumentId, TimeSpan interval, int count, CancellationToken ct) => Task.FromResult>([]); + + public Task GetAccountAsync(CancellationToken ct) => Task.FromResult(new AccountSnapshot(DateTime.UtcNow, "USD", Balance, Equity, Equity, 0, Equity - Balance)); + + public Task> GetPositionsAsync(CancellationToken ct) => Task.FromResult>([.. Positions]); + + public Task OpenAsync(OrderRequest request, CancellationToken ct) => throw new NotSupportedException("nessun ordine nei test del conto"); + + public Task LookupOrderAsync(string clientRef, CancellationToken ct) => Task.FromResult(null); + + public Task LookupOrderByIdAsync(long orderId, CancellationToken ct) + { + Lookups.Add(orderId); + return Task.FromResult(null); + } + + public Task CancelOrderAsync(long orderId, CancellationToken ct) => Task.FromResult(false); + + public Task CloseAsync(long positionId, long instrumentId, CancellationToken ct) => throw new NotSupportedException("nessuna chiusura nei test del conto"); + + public Task UpdateStopsAsync(long positionId, double? stopLoss, double? takeProfit, CancellationToken ct) => Task.FromResult(true); + + public Task GetCostAsync(OrderRequest request, CancellationToken ct) => Task.FromResult(null); + + public Task> GetClosedTradesAsync(DateTime fromUtc, CancellationToken ct) => Task.FromResult>([.. History]); + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; +} + +/// +/// Each account keeps its own state (5.1 review, D-53): a switch Demo ↔ Live never +/// overwrites nor discards the other account's halts, residue, pause, peak, cash flow and +/// closes waiting for their P&L; the single file of the previous versions goes to the +/// account it names; the register works on its own account's orders; the guard counts on +/// the engine's own slots; the startup never books a lagging close as a cash movement. +/// +public sealed class AccountStateTests : TempFolderTests +{ + private static readonly DateTime Opened = DateTime.UtcNow.AddHours(-3); + + private string DataPath => Path.Combine(Root, "data"); + + private string StateDir => Path.Combine(DataPath, "state"); + + private string Legacy => Path.Combine(StateDir, AccountStateFiles.LegacyName); + + private string StateOf(ExecutionMode account) => AccountStateFiles.PathFor(DataPath, account); + + private BotConfig Config(ExecutionMode mode) + { + BotConfig c = new(); + c.Run.BaseDirectory = Root; + c.Run.ExecutionMode = mode.ToString(); + c.Run.AllowLive = mode.IsLive(); + return c; + } + + private BasketEngine Engine(ExecutionMode mode) => new(Config(mode), null, startConfirmed: mode.IsLive()); + + private void WriteState(string path, JsonObject state) + { + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, state.ToJsonString(), new UTF8Encoding(false)); + } + + private static JsonElement Read(string path) + { + using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(path)); + return doc.RootElement.Clone(); + } + + private static long[] Ids(JsonElement root, string name) => [.. root.GetProperty(name).EnumerateArray().Select(static e => e.GetInt64())]; + + /// What the engine wrote to decisions.jsonl (nothing yet: empty). + private string LedgerText() + { + string path = Path.Combine(DataPath, "ledger", "decisions.jsonl"); + return File.Exists(path) ? File.ReadAllText(path) : string.Empty; + } + + private static BasketOutcomeRow LiveRow() => new("B20260930100000-EURUSDUSDCHF", "run-live", "EURUSD/USDCHF", "Live", "MODERATE", Opened, Opened.AddHours(2), + true, -2.1, 0.1, -140, -140, 0, 0, 0, 0, 0, 12, "kill_switch", 100_000, double.NaN, $"kill-switch | {PositionMap.Mark([11, 12])}"); + + private static JsonObject Settlement(BasketOutcomeRow row) => new() + { + ["key"] = PnlCorrectionRecord.KeyOf(row), + ["rowCsv"] = row.ToCsv(), + ["ids"] = new JsonArray(11, 12), + ["estimate"] = -140, + ["closedUtc"] = row.ClosedUtc.ToString("O", CultureInfo.InvariantCulture), + ["learn"] = false, + ["volContext"] = 1, + ["title"] = string.Empty, + ["detail"] = string.Empty, + }; + + /// A real account stopped by its equity stop and a kill-switch with one position left, paused by the operator, with a close waiting for the history. + private static JsonObject HaltedLiveState(bool withSettlement = false) => new() + { + ["savedUtc"] = DateTime.UtcNow.AddMinutes(-2).ToString("O", CultureInfo.InvariantCulture), + ["mode"] = "Live", + ["peakNetEquity"] = 10_000, + ["cumulativeCashFlow"] = 0, + ["lastBalance"] = 9_100, + ["lastBalanceUtc"] = DateTime.UtcNow.AddMinutes(-2).ToString("O", CultureInfo.InvariantCulture), + ["sessionDate"] = DateTime.UtcNow.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + ["dayStartEquity"] = 9_500, + ["pendingSettlements"] = withSettlement ? new JsonArray(Settlement(LiveRow())) : new JsonArray(), + ["pausedByOperator"] = true, + ["killSwitched"] = true, + ["equityStopped"] = true, + ["haltReason"] = "equity 9100 a 9 % dal picco 10000", + ["haltResidue"] = new JsonArray(new JsonObject + { + ["positionId"] = 77, ["symbol"] = "EURUSD", ["isBuy"] = true, ["units"] = 1000, ["openedUtc"] = Opened.ToString("O", CultureInfo.InvariantCulture), + ["origin"] = "orfana-bot", ["basket"] = string.Empty, ["reason"] = "non chiusa dal kill-switch", + }), + ["baskets"] = new JsonArray(), + ["pendingEntries"] = new JsonArray(), + }; + + // ----------------------------------------------------------------------- + // One state per account + // ----------------------------------------------------------------------- + + [Fact] + public async Task LiveToDemoToLiveKeepsTheLiveHaltsResiduePauseAndPeak() + { + WriteState(StateOf(ExecutionMode.Live), HaltedLiveState()); + byte[] live = File.ReadAllBytes(StateOf(ExecutionMode.Live)); + + // Live → Demo: the demo engine reads and writes its own account's file only. + BasketEngine demo = Engine(ExecutionMode.Demo); + demo.LoadState(); + Assert.False(demo.CurrentActivity().Busy); + demo.SaveState(); + await demo.DisposeAsync(); + Assert.Equal(live, File.ReadAllBytes(StateOf(ExecutionMode.Live))); + JsonElement d = Read(StateOf(ExecutionMode.Demo)); + Assert.Equal("Demo", d.GetProperty("mode").GetString()); + Assert.False(d.GetProperty("equityStopped").GetBoolean()); + Assert.False(d.GetProperty("pausedByOperator").GetBoolean()); + + // Demo → Live: the real account is exactly where it was left, halts and all. + BasketEngine again = Engine(ExecutionMode.Live); + again.LoadState(); + AccountActivity activity = again.CurrentActivity(); + again.SaveState(); + await again.DisposeAsync(); + + JsonElement r = Read(StateOf(ExecutionMode.Live)); + Assert.True(r.GetProperty("equityStopped").GetBoolean()); + Assert.True(r.GetProperty("killSwitched").GetBoolean()); + Assert.True(r.GetProperty("pausedByOperator").GetBoolean()); + Assert.Equal("equity 9100 a 9 % dal picco 10000", r.GetProperty("haltReason").GetString()); + Assert.Equal(77, r.GetProperty("haltResidue")[0].GetProperty("positionId").GetInt64()); + Assert.Equal(10_000, r.GetProperty("peakNetEquity").GetDouble()); + Assert.Equal(9_100, r.GetProperty("lastBalance").GetDouble()); + Assert.Equal(9_500, r.GetProperty("dayStartEquity").GetDouble()); + + // The residue is a position of the bot still on the account: the account is busy for a switch. + Assert.Equal(1, activity.OrphanLegs); + Assert.True(activity.Busy); + Assert.True(AccountActivity.FromDisk(DataPath, ExecutionMode.Live).Busy); + Assert.False(AccountActivity.FromDisk(DataPath, ExecutionMode.Demo).Busy); + } + + [Fact] + public async Task PendingSettlementsSurviveASwitchAndAreWrittenWhenTheAccountRunsAgain() + { + BasketOutcomeRow row = LiveRow(); + JsonObject state = HaltedLiveState(withSettlement: true); + state["haltResidue"] = new JsonArray(); + WriteState(StateOf(ExecutionMode.Live), state); + + BasketEngine demo = Engine(ExecutionMode.Demo); + demo.LoadState(); + Assert.Equal(0, demo.CurrentActivity().PendingSettlements); + demo.SaveState(); + await demo.DisposeAsync(); + Assert.Equal(1, AccountActivity.FromDisk(DataPath, ExecutionMode.Live).PendingSettlements); + Assert.Equal(0, AccountActivity.FromDisk(DataPath, ExecutionMode.Demo).PendingSettlements); + + // Live again: the close is still waiting, and the history settles it with the venue's number. + AccountVenue venue = new(); + venue.History.Add(new ClosedTrade(11, 1, true, 10_000, 1.1, 1.097, row.OpenedUtc, row.ClosedUtc, -30, 1)); + venue.History.Add(new ClosedTrade(12, 6, true, 10_000, 0.9, 0.898, row.OpenedUtc, row.ClosedUtc, -20, 1)); + BasketEngine live = BasketEngine.OverVenue(Config(ExecutionMode.Live), venue, startConfirmed: true); + live.LoadState(); + Assert.Equal(1, live.CurrentActivity().PendingSettlements); + await live.RefreshRealizedAsync(DateTime.UtcNow, CancellationToken.None, force: true); + Assert.Equal(0, live.CurrentActivity().PendingSettlements); + await live.DisposeAsync(); + + using Ledger ledger = new(Path.Combine(DataPath, "ledger")); + BasketOutcomeRow written = Assert.Single(ledger.ReadBaskets()); + Assert.Equal(row.BasketId, written.BasketId); + Assert.Equal("Live", written.Mode); + Assert.Equal(-52, written.PnlNetUsd, 6); + Assert.Contains(BasketCorrections.VenueMarker, written.Motivazione, StringComparison.Ordinal); + Assert.Equal(0, Read(StateOf(ExecutionMode.Live)).GetProperty("pendingSettlements").GetArrayLength()); + } + + [Fact] + public async Task TheSingleFileOfTheVersionBeforeGoesToTheAccountItNames() + { + WriteState(Legacy, HaltedLiveState(withSettlement: true)); + byte[] legacy = File.ReadAllBytes(Legacy); + + // Before an engine moves it, the guard reads it for its own account only. + Assert.True(AccountActivity.FromDisk(DataPath, ExecutionMode.Live).Busy); + Assert.False(AccountActivity.FromDisk(DataPath, ExecutionMode.Demo).Busy); + + // A demo engine finds the file of the real account: it goes to the real account, untouched, and the demo starts clean. + BasketEngine demo = Engine(ExecutionMode.Demo); + demo.LoadState(); + Assert.False(demo.CurrentActivity().Busy); + demo.SaveState(); + await demo.DisposeAsync(); + + Assert.False(File.Exists(Legacy)); + Assert.Equal(legacy, File.ReadAllBytes(Legacy + ".migrato")); + Assert.Equal(legacy, File.ReadAllBytes(StateOf(ExecutionMode.Live))); + Assert.Equal("Demo", Read(StateOf(ExecutionMode.Demo)).GetProperty("mode").GetString()); + AccountActivity live = AccountActivity.FromDisk(DataPath, ExecutionMode.Live); + Assert.Equal(1, live.PendingSettlements); + Assert.Equal(1, live.OrphanLegs); + } + + [Fact] + public async Task TheSingleFileOfTheSameAccountIsTakenOverWithItsPause() + { + WriteState(Legacy, new JsonObject + { + ["mode"] = "Demo", + ["peakNetEquity"] = 5_000, + ["pausedByOperator"] = true, + ["baskets"] = new JsonArray(), + ["pendingEntries"] = new JsonArray(), + }); + + BasketEngine demo = Engine(ExecutionMode.Demo); + demo.LoadState(); + demo.SaveState(); + await demo.DisposeAsync(); + + JsonElement d = Read(StateOf(ExecutionMode.Demo)); + Assert.True(d.GetProperty("pausedByOperator").GetBoolean()); + Assert.Equal(5_000, d.GetProperty("peakNetEquity").GetDouble()); + Assert.False(File.Exists(StateOf(ExecutionMode.Live))); + Assert.True(File.Exists(Legacy + ".migrato")); + } + + [Fact] + public void AMigrationKeepsTheMoreRecentStateAndNeverDeletesTheOther() + { + DateTime now = DateTime.UtcNow; + WriteState(StateOf(ExecutionMode.Live), new JsonObject { ["savedUtc"] = now.AddHours(-1).ToString("O", CultureInfo.InvariantCulture), ["mode"] = "Live", ["peakNetEquity"] = 1 }); + WriteState(Legacy, new JsonObject { ["savedUtc"] = now.ToString("O", CultureInfo.InvariantCulture), ["mode"] = "Live", ["peakNetEquity"] = 2 }); + + string? note = AccountStateFiles.MigrateLegacy(DataPath, ExecutionMode.Demo); + + Assert.NotNull(note); + Assert.Equal(2, Read(StateOf(ExecutionMode.Live)).GetProperty("peakNetEquity").GetDouble()); + Assert.Equal(1, Read(StateOf(ExecutionMode.Live) + ".precedente").GetProperty("peakNetEquity").GetDouble()); + Assert.Equal(2, Read(Legacy + ".migrato").GetProperty("peakNetEquity").GetDouble()); + + // An older single file (a return to a previous version) leaves the account's own file as it is. + WriteState(Legacy, new JsonObject { ["savedUtc"] = now.AddDays(-1).ToString("O", CultureInfo.InvariantCulture), ["mode"] = "Live", ["peakNetEquity"] = 3 }); + Assert.NotNull(AccountStateFiles.MigrateLegacy(DataPath, ExecutionMode.Demo)); + Assert.Equal(2, Read(StateOf(ExecutionMode.Live)).GetProperty("peakNetEquity").GetDouble()); + Assert.False(File.Exists(Legacy)); + Assert.Equal(2, Directory.GetFiles(StateDir, AccountStateFiles.LegacyName + ".migrato*").Length); + Assert.Null(AccountStateFiles.MigrateLegacy(DataPath, ExecutionMode.Demo)); + } + + // ----------------------------------------------------------------------- + // The guard on the engine's own slots + // ----------------------------------------------------------------------- + + [Fact] + public void AnEntryInFlightIsBusyEvenWithoutLegs() + { + // What the published picture shows between Transition(Entering) and leg A: no position, no leg, no order. + AccountActivity entering = AccountActivity.FromEngine([new SlotActivity(BasketState.Entering, false, false, true)], 0, 0, 0, stateLoaded: true); + Assert.True(entering.Busy); + Assert.Equal(1, entering.InFlight); + Assert.Contains("in corso", entering.Describe(), StringComparison.Ordinal); + + Assert.True(AccountActivity.FromEngine([new SlotActivity(BasketState.Exiting, false, false, false)], 0, 0, 0, true).Busy); + Assert.True(AccountActivity.FromEngine([new SlotActivity(BasketState.Error, false, true, false)], 0, 0, 0, true).Busy); + Assert.False(AccountActivity.FromEngine([new SlotActivity(BasketState.Error, false, false, false), new SlotActivity(BasketState.Idle, false, false, false)], 0, 0, 0, true).Busy); + + // An engine that has not read its state yet does not know: busy. + AccountActivity unread = AccountActivity.FromEngine([], 0, 0, 0, stateLoaded: false); + Assert.True(unread.Busy); + Assert.True(unread.Unknown); + } + + [Fact] + public void ClosesWaitingForTheHistoryAloneKeepTheAccountBusy() + { + AccountActivity waiting = AccountActivity.FromEngine([new SlotActivity(BasketState.Idle, false, false, false)], 0, 0, pendingSettlements: 2, stateLoaded: true); + + Assert.True(waiting.Busy); + Assert.Contains("2 chiusure in attesa dello storico eToro", waiting.Describe(), StringComparison.Ordinal); + Assert.Contains("30 minuti", waiting.Advice(), StringComparison.Ordinal); + Assert.DoesNotContain("kill-switch", waiting.Advice(), StringComparison.Ordinal); + } + + [Fact] + public async Task TheEngineBlocksItsEntriesOnlyWhenItsAccountIsIdle() + { + AccountVenue venue = new(); + WriteState(StateOf(ExecutionMode.Demo), new JsonObject + { + ["mode"] = "Demo", + ["baskets"] = new JsonArray(), + ["pendingEntries"] = new JsonArray(new JsonObject + { + ["name"] = "EURUSD/USDCHF", + ["state"] = "PendingA", + ["basketId"] = "B1", + ["pending"] = new JsonObject + { + ["basketId"] = "B1", ["buyCross"] = true, ["entryZ"] = -2.1, ["unitsA"] = 10_000, ["unitsB"] = 9_000, ["tpPips"] = 20, ["maxLossUsd"] = 1_500, + ["entryCostPips"] = 1, ["equityAtEntry"] = 10_000, ["motivazione"] = "prova", ["decidedUtc"] = DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture), + ["clientRefA"] = "c1", ["clientRefB"] = string.Empty, + }, + }), + }); + + BasketEngine engine = BasketEngine.OverVenue(Config(ExecutionMode.Demo), venue); + await engine.LoadInstrumentsAsync(CancellationToken.None); + engine.LoadState(); + + CommandResult busy = await engine.RunCommandAsync(new EngineCommand(EngineCommandKind.PrepareAccountSwitch, "cambio di conto verso il reale", "prova"), CancellationToken.None); + Assert.False(busy.Ok); + Assert.Equal(CommandResult.Refused, busy.Code); + Assert.Equal(1, Assert.IsType(busy.Payload).PendingBaskets); + + // A refused check lifts its own block at once. + Assert.Equal("nessun cambio di conto in corso", (await engine.RunCommandAsync(new EngineCommand(EngineCommandKind.CancelAccountSwitch), CancellationToken.None)).Message); + await engine.DisposeAsync(); + + // The same account, idle: the check passes and the entries stay blocked until a cancel (or the restart). + File.Delete(StateOf(ExecutionMode.Demo)); + BasketEngine idle = BasketEngine.OverVenue(Config(ExecutionMode.Demo), venue); + await idle.LoadInstrumentsAsync(CancellationToken.None); + idle.LoadState(); + CommandResult ready = await idle.RunCommandAsync(new EngineCommand(EngineCommandKind.PrepareAccountSwitch, "cambio di conto verso il reale", "prova"), CancellationToken.None); + Assert.True(ready.Ok, ready.Message); + Assert.Equal("entrate di nuovo permesse", (await idle.RunCommandAsync(new EngineCommand(EngineCommandKind.CancelAccountSwitch), CancellationToken.None)).Message); + await idle.DisposeAsync(); + } + + // ----------------------------------------------------------------------- + // The order register works on its own account + // ----------------------------------------------------------------------- + + [Fact] + public async Task TheRegisterNeverTouchesTheOtherAccountsOrders() + { + Directory.CreateDirectory(StateDir); + string path = Path.Combine(StateDir, "pending_orders.json"); + DateTime old = DateTime.UtcNow.AddDays(-5); + OrderTracker writer = new(path); + writer.Register(Order("demo-1", 101, "Demo", DateTime.UtcNow.AddMinutes(-1))); + writer.Register(Order("live-1", 201, "Live", DateTime.UtcNow.AddMinutes(-1))); + TrackedOrder liveOld = writer.Register(Order("live-old", 202, "Live", old)); + writer.Apply(liveOld, new OrderOutcome(false, true, 202, 0, 0, 0, old, 0, "Rejected", "rifiutato"), old); + + OrderTracker demo = new(path, ExecutionMode.Demo); + Assert.Equal(1, demo.PendingCount); + Assert.Equal(1, demo.OtherAccountPendingCount); + Assert.Equal("demo-1", Assert.Single(demo.Pending).ClientRef); + Assert.DoesNotContain(demo.All, static o => o.Mode == "Live"); + + AccountVenue venue = new(); + foreach (TrackedOrder o in demo.Pending) + { + o.LastCheckUtc = default; + } + + await demo.ResolveAsync(venue, DateTime.UtcNow, null, CancellationToken.None); + Assert.Equal([101L], venue.Lookups); + Assert.Equal(0, demo.Prune(DateTime.UtcNow)); + + // The real account's orders are still in the file as they were, the old resolved one included. + OrderTracker live = new(path, ExecutionMode.Live); + Assert.Equal(["live-1", "live-old"], live.All.Select(static o => o.ClientRef).Order()); + Assert.Equal(1, live.PendingCount); + Assert.Equal(1, AccountActivity.FromDisk(DataPath, ExecutionMode.Live).PendingOrders); + Assert.Equal(1, AccountActivity.FromDisk(DataPath, ExecutionMode.Demo).PendingOrders); + Assert.Equal(1, live.Prune(DateTime.UtcNow)); + + static TrackedOrder Order(string clientRef, long orderId, string mode, DateTime sent) => new() + { + ClientRef = clientRef, OrderId = orderId, Symbol = "EURUSD", InstrumentId = 1, IsBuy = true, RequestedUnits = 10_000, + Basket = "EURUSD/USDCHF", BasketId = "B-" + clientRef, Leg = OrderLeg.A, SentUtc = sent, Mode = mode, + }; + } + + // ----------------------------------------------------------------------- + // The balance at startup (soldi-rischio-06) + // ----------------------------------------------------------------------- + + [Fact] + public void TheStartupVerdictWaitsForEveryKnownClose() + { + DateTime seen = DateTime.UtcNow.AddMinutes(-1); + IReadOnlyList expected = StartupCash.Expected([11, 12, 13], new HashSet { 13 }, [14], [([15, 16], seen.AddSeconds(10)), ([17], seen.AddSeconds(-10))], seen); + Assert.Equal([11L, 12, 14, 15, 16], expected); + + List lagging = [new(14, 1, true, 1, 1, 1, seen.AddHours(-1), seen.AddSeconds(5), -100, 0), new(99, 1, true, 1, 1, 1, seen.AddHours(-1), seen.AddSeconds(-30), 500, 0)]; + StartupCashVerdict early = StartupCash.Judge(seen, expected, lagging); + Assert.False(early.Complete); + Assert.Equal([11L, 12, 15, 16], early.Missing); + Assert.Equal(-100, early.ClosedNet); + } + + [Fact] + public async Task AStartupWithTheHistoryLaggingBooksNoWithdrawal() + { + DateTime seen = DateTime.UtcNow.AddSeconds(-30); + WriteState(StateOf(ExecutionMode.Demo), new JsonObject + { + ["mode"] = "Demo", + ["peakNetEquity"] = 149_000, + ["cumulativeCashFlow"] = 0, + ["lastBalance"] = 149_000, + ["lastBalanceUtc"] = seen.ToString("O", CultureInfo.InvariantCulture), + ["lastPositionIds"] = new JsonArray(11, 12, 13), + ["baskets"] = new JsonArray(), + ["pendingEntries"] = new JsonArray(), + }); + + // A basket stop realised −2 000 just before the restart; the history does not show it yet. + AccountVenue venue = new() { Balance = 147_000, Equity = 147_000 }; + venue.Positions.Add(new BrokerPosition(13, 1, true, 1_000, 1.1, DateTime.UtcNow.AddHours(-2), 0, 0, 1, 110, 0, 0, 1.1)); + BasketEngine engine = BasketEngine.OverVenue(Config(ExecutionMode.Demo), venue); + engine.LoadState(); + await engine.StartupEquityAsync(CancellationToken.None); + engine.SaveState(); + + JsonElement waiting = Read(StateOf(ExecutionMode.Demo)); + Assert.Equal(149_000, waiting.GetProperty("lastBalance").GetDouble()); + Assert.Equal(0, waiting.GetProperty("cumulativeCashFlow").GetDouble()); + Assert.Equal([11L, 12], Ids(waiting, "vanishedUnsettled")); + Assert.Equal([13L], Ids(waiting, "lastPositionIds")); + + // The history catches up: the next reconciliation explains the whole difference with the loss. + venue.History.Add(new ClosedTrade(11, 1, true, 10_000, 1.1, 1.098, DateTime.UtcNow.AddHours(-2), seen.AddSeconds(7), -1_200, 0)); + venue.History.Add(new ClosedTrade(12, 6, true, 10_000, 0.9, 0.899, DateTime.UtcNow.AddHours(-2), seen.AddSeconds(7), -800, 0)); + await engine.ReconcileAsync(CancellationToken.None); + engine.SaveState(); + await engine.DisposeAsync(); + + JsonElement judged = Read(StateOf(ExecutionMode.Demo)); + Assert.Equal(147_000, judged.GetProperty("lastBalance").GetDouble()); + Assert.Equal(0, judged.GetProperty("cumulativeCashFlow").GetDouble()); + Assert.Empty(Ids(judged, "vanishedUnsettled")); + + // The loss stays a loss: the peak is still 149 000, nothing was booked as a withdrawal. + Assert.Equal(149_000, judged.GetProperty("peakNetEquity").GetDouble()); + Assert.DoesNotContain("movimento_di_cassa", LedgerText(), StringComparison.Ordinal); + } + + [Fact] + public async Task AStartupWithTheWholeHistoryStillJudgesARealWithdrawal() + { + DateTime seen = DateTime.UtcNow.AddSeconds(-30); + WriteState(StateOf(ExecutionMode.Demo), new JsonObject + { + ["mode"] = "Demo", + ["peakNetEquity"] = 149_000, + ["cumulativeCashFlow"] = 0, + ["lastBalance"] = 149_000, + ["lastBalanceUtc"] = seen.ToString("O", CultureInfo.InvariantCulture), + ["lastPositionIds"] = new JsonArray(11, 12), + ["baskets"] = new JsonArray(), + ["pendingEntries"] = new JsonArray(), + }); + + // −2 000 from the closes, −5 000 withdrawn: the history shows both closes already. + AccountVenue venue = new() { Balance = 142_000, Equity = 142_000 }; + venue.History.Add(new ClosedTrade(11, 1, true, 10_000, 1.1, 1.098, DateTime.UtcNow.AddHours(-2), seen.AddSeconds(7), -1_200, 0)); + venue.History.Add(new ClosedTrade(12, 6, true, 10_000, 0.9, 0.899, DateTime.UtcNow.AddHours(-2), seen.AddSeconds(7), -800, 0)); + BasketEngine engine = BasketEngine.OverVenue(Config(ExecutionMode.Demo), venue); + engine.LoadState(); + await engine.StartupEquityAsync(CancellationToken.None); + engine.SaveState(); + await engine.DisposeAsync(); + + JsonElement judged = Read(StateOf(ExecutionMode.Demo)); + Assert.Equal(142_000, judged.GetProperty("lastBalance").GetDouble()); + Assert.Equal(-5_000, judged.GetProperty("cumulativeCashFlow").GetDouble()); + Assert.Contains("movimento_di_cassa", LedgerText(), StringComparison.Ordinal); + } +} diff --git a/Encelado/tests/Encelado.Tests/SettingsRuntimeTests.cs b/Encelado/tests/Encelado.Tests/SettingsRuntimeTests.cs index a44ca69..b69359b 100644 --- a/Encelado/tests/Encelado.Tests/SettingsRuntimeTests.cs +++ b/Encelado/tests/Encelado.Tests/SettingsRuntimeTests.cs @@ -40,8 +40,18 @@ public sealed class SettingsRuntimeTests : IAsyncLifetime public List Commands { get; } = []; + /// What the published picture says (the 5.0 snapshot): the guard never reads it. public int OpenBaskets { get; set; } + /// What the engine counts on its own slots when asked by the guard; null: the open baskets of the picture. + public AccountActivity? Activity { get; set; } + + /// False while the engine would still be warming up (its decision loop not started). + public bool LoopStarted { get; set; } = true; + + /// The stopped engine's last save (a real one writes its account's state before it lets go of the folder). + public Action? OnDispose { get; set; } + public Func? Answer { get; set; } /// A command that takes its time (a kill-switch closing baskets): the task the test completes, or null to answer at once. @@ -61,15 +71,38 @@ public sealed class SettingsRuntimeTests : IAsyncLifetime return held.WaitAsync(ct); } - return Task.FromResult(Answer?.Invoke(command) ?? new CommandResult(true, "applicato")); + if (Answer?.Invoke(command) is { } answer) + { + return Task.FromResult(answer); + } + + if (command.Kind == EngineCommandKind.PrepareAccountSwitch) + { + AccountActivity a = Activity ?? new AccountActivity(OpenBaskets, 0, 0); + return Task.FromResult(a.Busy + ? new CommandResult(false, a.Describe()) { Code = CommandResult.Refused, Payload = a } + : new CommandResult(true, "entrate bloccate fino al riavvio") { Payload = a }); + } + + return Task.FromResult(new CommandResult(true, "applicato")); } public BotSnapshot Snapshot(BotState state, string? error, DateTime? startedUtc, EventRow[] events) => SampleSnapshot.Minimal(state) with { OpenBaskets = OpenBaskets, Account = Mode.Account() }; - public ValueTask DisposeAsync() => ValueTask.CompletedTask; + public ValueTask DisposeAsync() + { + OnDispose?.Invoke(); + return ValueTask.CompletedTask; + } } + /// When set, the factory waits for it (a real engine reads the ledger and the register while it is built). + private ManualResetEventSlim? _buildGate; + + /// Set by the factory when it starts building an engine. + private TaskCompletionSource? _building; + private string ConfigPath => Path.Combine(_dir, "encelado.json"); private string StrategyPath => Path.Combine(_dir, "strategy.json"); @@ -96,6 +129,8 @@ public sealed class SettingsRuntimeTests : IAsyncLifetime secrets.SaveEtoro(demo: false, new EtoroKeys("api-real", "user-real", DateTime.UtcNow)); _supervisor = new BotSupervisor(config, (c, confirmed) => { + _building?.TrySetResult(); + _buildGate?.Wait(TimeSpan.FromSeconds(15)); FakeEngine e = new(confirmed, c.Run.Mode); lock (_engines) { @@ -413,6 +448,171 @@ public sealed class SettingsRuntimeTests : IAsyncLifetime Assert.True(_engines[1].LiveConfirmed); Assert.Equal("real", Runtime.Config.Etoro.Environment); Assert.True(_historyInvalidated > 0); + + // The demo engine was asked on its decision thread, blocked its entries and was replaced: never cancelled. + Assert.Equal([EngineCommandKind.PrepareAccountSwitch], _engines[0].Commands.Select(static c => c.Kind)); + } + + [Fact] + public async Task AnEntryInFlightRefusesTheSwitchEvenWhenThePictureLooksFlat() + { + Build(); + Assert.True((await Runtime.StartEngineAsync(null)).Ok); + + // Between Transition(Entering) and leg A the published picture is flat; the engine's own count is not. + _engines[0].Activity = new AccountActivity(0, 0, 0) { InFlight = 1 }; + string config = File.ReadAllText(ConfigPath); + + SettingsResult r = await Runtime.ApplyAsync(new Dictionary { ["run.allowLive"] = "true", ["run.executionMode"] = "Live" }, "CONFERMO LIVE", CancellationToken.None); + + Assert.Equal(0, Supervisor.Snapshot().OpenBaskets); + Assert.Equal(SettingsResult.RestartRefused, r.Restart); + Assert.Equal(409, r.HttpStatus); + Assert.Contains("ingresso, aggiunta o uscita in corso", r.Message, StringComparison.Ordinal); + Assert.Contains("conto demo", r.Message, StringComparison.Ordinal); + Assert.Equal(config, File.ReadAllText(ConfigPath)); + Assert.Single(_engines); + Assert.Equal(BotState.Running, Supervisor.State); + } + + [Fact] + public async Task ClosesWaitingForTheHistoryRefuseTheSwitch() + { + Build(); + Assert.True((await Runtime.StartEngineAsync(null)).Ok); + _engines[0].Activity = new AccountActivity(0, 0, 0) { PendingSettlements = 1 }; + + SettingsResult running = await Runtime.ApplyAsync(new Dictionary { ["run.allowLive"] = "true", ["run.executionMode"] = "Live" }, "CONFERMO LIVE", CancellationToken.None); + Assert.Equal(SettingsResult.RestartRefused, running.Restart); + Assert.Contains("chiusura in attesa dello storico eToro", running.Message, StringComparison.Ordinal); + + // Stopped: the demo account's own file decides; the real account's file is not its business. + Assert.True((await Supervisor.StopAsync()).Ok); + string state = Path.Combine(Runtime.Config.Run.DataPath, "state"); + Directory.CreateDirectory(state); + File.WriteAllText(Path.Combine(state, "baskets_state.live.json"), """{ "mode": "Live", "baskets": [ { "name": "EURUSD/USDCHF" } ], "pendingEntries": [] }"""); + File.WriteAllText(Path.Combine(state, "baskets_state.demo.json"), """{ "mode": "Demo", "baskets": [], "pendingEntries": [], "pendingSettlements": [ { "key": "k" } ] }"""); + + SettingsResult stopped = await Runtime.ApplyAsync(new Dictionary { ["run.allowLive"] = "true", ["run.executionMode"] = "Live" }, null, CancellationToken.None); + Assert.Equal(SettingsResult.RestartRefused, stopped.Restart); + Assert.Contains("1 chiusura in attesa", stopped.Message, StringComparison.Ordinal); + Assert.Contains("solo con il motore acceso su questo conto", stopped.Message, StringComparison.Ordinal); + Assert.DoesNotContain("basket aperto", stopped.Message, StringComparison.Ordinal); + Assert.Equal(ExecutionMode.Demo, ConfigLoader.Load(ConfigPath, out _).Run.Mode); + + // Settled: the switch goes through, and the real account's basket waits for its own engine. + File.WriteAllText(Path.Combine(state, "baskets_state.demo.json"), """{ "mode": "Demo", "baskets": [], "pendingEntries": [], "pendingSettlements": [] }"""); + SettingsResult done = await Runtime.ApplyAsync(new Dictionary { ["run.allowLive"] = "true", ["run.executionMode"] = "Live" }, null, CancellationToken.None); + Assert.True(done.Ok, done.Message); + Assert.Equal(ExecutionMode.Live, ConfigLoader.Load(ConfigPath, out _).Run.Mode); + } + + [Fact] + public async Task TheSwitchIsRefusedWhileTheEngineStarts() + { + Build(); + using ManualResetEventSlim gate = new(false); + _buildGate = gate; + _building = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + string config = File.ReadAllText(ConfigPath); + + // The supervisor is building the engine. + Task start = Task.Run(() => Supervisor.StartAsync()); + await _building.Task.WaitAsync(TimeSpan.FromSeconds(15)); + Assert.Equal(BotState.Starting, Supervisor.State); + SettingsResult building = await Runtime.ApplyAsync(new Dictionary { ["run.allowLive"] = "true", ["run.executionMode"] = "Live" }, "CONFERMO LIVE", CancellationToken.None); + Assert.Equal(SettingsResult.RestartRefused, building.Restart); + Assert.Contains("si sta avviando", building.Message, StringComparison.Ordinal); + Assert.Equal(config, File.ReadAllText(ConfigPath)); + + gate.Set(); + Assert.True((await start).Ok); + + // Built, but still warming up: it has not read its state yet, and nothing is asked of it. + _engines[0].LoopStarted = false; + SettingsResult warming = await Runtime.ApplyAsync(new Dictionary { ["run.allowLive"] = "true", ["run.executionMode"] = "Live" }, "CONFERMO LIVE", CancellationToken.None); + Assert.Equal(SettingsResult.RestartRefused, warming.Restart); + Assert.Contains("non ha ancora letto il suo stato", warming.Message, StringComparison.Ordinal); + Assert.DoesNotContain(_engines[0].Commands, static c => c.Kind == EngineCommandKind.PrepareAccountSwitch); + Assert.Equal(config, File.ReadAllText(ConfigPath)); + Assert.Single(_engines); + } + + [Fact] + public async Task AnEngineThatDoesNotAnswerTheCheckRefusesTheSwitchAndLiftsTheBlockBehindIt() + { + Build(); + Supervisor.SwitchCheckWait = TimeSpan.FromMilliseconds(200); + Assert.True((await Runtime.StartEngineAsync(null)).Ok); + TaskCompletionSource busy = new(TaskCreationOptions.RunContinuationsAsynchronously); + _engines[0].Hold = c => c.Kind == EngineCommandKind.PrepareAccountSwitch ? busy.Task : null; + string config = File.ReadAllText(ConfigPath); + + SettingsResult r = await Runtime.ApplyAsync(new Dictionary { ["run.allowLive"] = "true", ["run.executionMode"] = "Live" }, "CONFERMO LIVE", CancellationToken.None); + + Assert.Equal(SettingsResult.RestartRefused, r.Restart); + Assert.Contains("non ha risposto", r.Message, StringComparison.Ordinal); + Assert.Equal(config, File.ReadAllText(ConfigPath)); + Assert.Equal([EngineCommandKind.PrepareAccountSwitch, EngineCommandKind.CancelAccountSwitch], _engines[0].Commands.Select(static c => c.Kind)); + Assert.Single(_engines); + } + + [Fact] + public async Task TheSwitchIsUndoneWhenTheStoppedEngineLeftSomethingOnTheAccount() + { + Build(); + Assert.True((await Runtime.StartEngineAsync(null)).Ok); + string config = File.ReadAllText(ConfigPath); + string state = Path.Combine(Runtime.Config.Run.DataPath, "state"); + + // Between the check and the stop something appeared (a late fill): the stopped engine saves it. + _engines[0].OnDispose = () => + { + Directory.CreateDirectory(state); + File.WriteAllText(Path.Combine(state, "baskets_state.demo.json"), """{ "mode": "Demo", "baskets": [ { "name": "EURUSD/USDCHF" } ], "pendingEntries": [] }"""); + }; + + SettingsResult r = await Runtime.ApplyAsync(new Dictionary { ["run.allowLive"] = "true", ["run.executionMode"] = "Live" }, "CONFERMO LIVE", CancellationToken.None); + + Assert.False(r.Ok); + Assert.Equal(SettingsResult.RestartRefused, r.Restart); + Assert.Contains("annullato dopo l'arresto", r.Message, StringComparison.Ordinal); + Assert.Contains("1 basket aperto", r.Message, StringComparison.Ordinal); + Assert.Contains("tornate come prima", r.Message, StringComparison.Ordinal); + Assert.Equal(config, File.ReadAllText(ConfigPath)); + Assert.Equal(ExecutionMode.Demo, Runtime.Config.Run.Mode); + Assert.Single(_engines); + Assert.Equal(BotState.Stopped, Supervisor.State); + } + + [Fact] + public async Task AKillSwitchStartedDuringTheSwitchUndoesItAndLiftsTheBlock() + { + Build(); + Assert.True((await Runtime.StartEngineAsync(null)).Ok); + TaskCompletionSource killing = new(TaskCreationOptions.RunContinuationsAsynchronously); + _engines[0].Hold = c => c.Kind == EngineCommandKind.KillSwitch ? killing.Task : null; + Task? kill = null; + + // After the check and the write, before the restart: a kill-switch from Telegram. + _duringRefresh = () => kill ??= Supervisor.ExecuteAsync(new EngineCommand(EngineCommandKind.KillSwitch, string.Empty, "prova"), CancellationToken.None); + string config = File.ReadAllText(ConfigPath); + + SettingsResult r = await Runtime.ApplyAsync(new Dictionary { ["run.allowLive"] = "true", ["run.executionMode"] = "Live" }, "CONFERMO LIVE", CancellationToken.None); + + Assert.Equal(SettingsResult.RestartRefused, r.Restart); + Assert.Contains("kill-switch", r.Message, StringComparison.Ordinal); + Assert.Contains("resta acceso sul conto demo", r.Message, StringComparison.Ordinal); + Assert.Equal(config, File.ReadAllText(ConfigPath)); + Assert.Equal(ExecutionMode.Demo, Runtime.Config.Run.Mode); + Assert.Single(_engines); + Assert.Equal(BotState.Running, Supervisor.State); + Assert.Equal( + [EngineCommandKind.PrepareAccountSwitch, EngineCommandKind.KillSwitch, EngineCommandKind.CancelAccountSwitch], + _engines[0].Commands.Select(static c => c.Kind)); + + killing.SetResult(new CommandResult(true, "kill-switch eseguito")); + Assert.True((await kill!).Ok); } [Fact]