5.1 revisione, conti: stato separato per conto e cambio Demo↔Live deciso dal motore, saldo all'avvio giudicato solo con lo storico completo

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 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-09-30 23:55:07 +02:00
1 parent b80638d949
commit c618f9fc01
16 files changed
+1766 -104

No files matched your search

+3 -1
View File
@@ -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"`).
@@ -156,6 +156,13 @@ public sealed class TrackedOrder
/// matches it appears on the account. The register is persisted to
/// <c>data/state/pending_orders.json</c> with atomic writes and reloaded at startup, so
/// nothing sent is ever forgotten across a restart.
/// <para>
/// 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.
/// </para>
/// </summary>
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<string, TrackedOrder> _orders = new(StringComparer.Ordinal);
public OrderTracker(string path)
/// <param name="path">The register's file; empty for one kept in memory only.</param>
/// <param name="account">The account whose orders this register works on (its mode); null for every order in the file.</param>
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;
/// <summary>
/// Whether an order sent in <paramref name="orderMode"/> belongs to <paramref name="account"/>:
/// the same account (Demo or Live, whatever name a version gave the mode), or no mode recorded.
/// </summary>
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<TrackedOrder> 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));
}
}
}
/// <summary>Orders of the other account still without an outcome: kept in the file, never touched here.</summary>
public int OtherAccountPendingCount
{
get
{
lock (_gate)
{
return _orders.Values.Count(o => o.IsPending && !Owns(o));
}
}
}
@@ -250,7 +282,7 @@ public sealed class OrderTracker
Dictionary<long, string> 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
}
}
/// <summary>Drops resolved orders older than <see cref="Retention"/>. Pending ones are never dropped.</summary>
/// <summary>Drops resolved orders older than <see cref="Retention"/>. Pending ones are never dropped, nor the other account's.</summary>
public int Prune(DateTime now)
{
lock (_gate)
{
List<string> gone = [.. _orders.Values.Where(o => !o.IsPending && o.ResolvedUtc is { } r && now - r > Retention).Select(static o => o.ClientRef)];
List<string> 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<long> 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)
@@ -0,0 +1,82 @@
using Encelado.Core.Broker;
namespace Encelado.Core.Baskets;
/// <summary>
/// What the venue's history says, at startup, about the balance saved before the stop:
/// <paramref name="ClosedNet"/> is the realised net result (<c>netProfit − fees</c>) of every
/// close after the saved reading, and <paramref name="Missing"/> the positions known to have
/// closed since then that the history does not show yet.
/// </summary>
public sealed record StartupCashVerdict(double ClosedNet, IReadOnlyList<long> Missing)
{
/// <summary>Every known close is in the history: the balance can be judged now.</summary>
public bool Complete => Missing.Count == 0;
}
/// <summary>
/// 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.
/// </summary>
public static class StartupCash
{
/// <summary>
/// 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).
/// </summary>
public static IReadOnlyList<long> Expected(
IEnumerable<long> lastPositionIds,
IReadOnlySet<long> onAccount,
IEnumerable<long> vanishedUnsettled,
IEnumerable<(IReadOnlyCollection<long> Ids, DateTime ClosedUtc)> pendingSettlements,
DateTime lastObservedUtc)
{
ArgumentNullException.ThrowIfNull(lastPositionIds);
ArgumentNullException.ThrowIfNull(onAccount);
ArgumentNullException.ThrowIfNull(vanishedUnsettled);
ArgumentNullException.ThrowIfNull(pendingSettlements);
HashSet<long> ids = [.. lastPositionIds.Where(id => !onAccount.Contains(id))];
ids.UnionWith(vanishedUnsettled);
foreach ((IReadOnlyCollection<long> settlementIds, DateTime closedUtc) in pendingSettlements)
{
if (closedUtc > lastObservedUtc)
{
ids.UnionWith(settlementIds.Where(id => !onAccount.Contains(id)));
}
}
ids.Remove(0);
return [.. ids.Order()];
}
/// <summary>
/// The closes after <paramref name="lastObservedUtc"/> summed from the history (as the
/// startup always summed them: every close changes the balance), and which of
/// <paramref name="expected"/> the history does not show.
/// </summary>
public static StartupCashVerdict Judge(DateTime lastObservedUtc, IEnumerable<long> expected, IReadOnlyList<ClosedTrade> history)
{
ArgumentNullException.ThrowIfNull(expected);
ArgumentNullException.ThrowIfNull(history);
HashSet<long> 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))]);
}
}
@@ -0,0 +1,159 @@
using System.Globalization;
using System.Text.Json;
using Encelado.Core.Baskets;
namespace Encelado.Engine.Baskets;
/// <summary>
/// The engine's state on disk, one file per account (5.1 review, decision D-53):
/// <c>data/state/baskets_state.demo.json</c> and <c>data/state/baskets_state.live.json</c>.
/// Switching account never overwrites nor discards the other account's open baskets, closes
/// waiting for their P&amp;L, equity peak, cash flow, halts, residue, pause and day; switching
/// back finds them where they were.
/// <para>
/// The single <c>baskets_state.json</c> of 5.0 and of the first 5.1 builds goes, once, to the
/// account its <c>mode</c> names — whichever account the engine that finds it trades — and
/// stays beside it renamed <c>.migrato</c>: 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.
/// </para>
/// </summary>
public static class AccountStateFiles
{
/// <summary>The single file of 5.0 and of the first 5.1 builds.</summary>
public const string LegacyName = "baskets_state.json";
/// <summary>The state of one account: <c>data/state/baskets_state.demo.json</c> or <c>.live.json</c>.</summary>
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);
}
/// <summary>The account a saved state names in its <c>mode</c> (any name a version gave it); null when it names none.</summary>
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;
/// <summary>When a saved state was written (<c>savedUtc</c>); the minimum when unknown.</summary>
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;
/// <summary>
/// The file a reader takes for <paramref name="account"/>: 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.
/// </summary>
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;
}
}
/// <summary>
/// Moves the single old file to the account its <c>mode</c> names (<paramref name="running"/>'s
/// when it names none, as 5.0 read it), then renames it <c>.migrato</c>. 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.
/// </summary>
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)}";
}
/// <summary>Renames a file beside itself with a tag (and the time, when the name is taken); returns the new path.</summary>
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;
}
}
}
@@ -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
/// <summary>Set by <see cref="EngineCommandKind.Shutdown"/>: this engine opens nothing new until it is gone.</summary>
private bool _stopping;
/// <summary>
/// Set by <see cref="EngineCommandKind.PrepareAccountSwitch"/> when the account is idle: no
/// new entry and no add until the restart on the other account (or the switch is cancelled).
/// </summary>
private string? _switchBlock;
/// <summary>The answer of a command the engine will never finish: it stopped before taking it, or in the middle of it.</summary>
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<CommandResult> RunCommandAsync(EngineCommand c, CancellationToken ct)
/// <summary>One command, on the decision thread (internal: the tests run one as the loop would).</summary>
internal async Task<CommandResult> 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)
// -----------------------------------------------------------------------
/// <summary>
/// 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.
/// </summary>
internal AccountActivity CurrentActivity()
{
HashSet<long> 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);
}
/// <summary>
/// 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.
/// </summary>
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 };
}
/// <summary>A prepared switch that will not happen: the entries are allowed again.</summary>
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);
@@ -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 <see cref="SettlementQueue.NextCheckIn"/>);
/// 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.
/// </summary>
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)
{
@@ -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 <paramref name="rebase"/> 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.
/// </summary>
private async Task RefreshAccountAsync(double closedNetSinceLast, CancellationToken ct, bool rebase = false)
private async Task<bool> 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;
}
/// <summary>
/// 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 (<see cref="ClosedNetAsync"/>, one hour at most).
/// Internal: the tests drive it over their own venue.
/// </summary>
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<ClosedTrade> 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<long> onAccount;
IReadOnlyList<ClosedTrade> 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<long> expected = StartupCash.Expected(_lastPositionIds, onAccount, _vanishedUnsettled,
_settlements.Queue.Items.Select(static s => ((IReadOnlyCollection<long>)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);
}
/// <summary>Positions that vanished from the account and the venue's history does not show yet.</summary>
private readonly HashSet<long> _vanishedUnsettled = [];
private DateTime _vanishedSinceUtc;
/// <summary>
/// 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.
/// </summary>
private double _pendingClosedNet;
/// <summary>
/// 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.
/// </summary>
private async Task<double> ClosedNetAsync(IReadOnlyCollection<long> 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;
}
/// <summary>
/// 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.
/// </summary>
private async Task ReconcileAsync(CancellationToken ct)
internal async Task ReconcileAsync(CancellationToken ct)
{
IReadOnlyList<BrokerPosition> positions;
try
@@ -180,7 +237,15 @@ public sealed partial class BasketEngine
HashSet<long> onVenue = [.. positions.Select(static p => p.PositionId)];
List<long> 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.
@@ -8,10 +8,12 @@ using Encelado.Core.Baskets.History;
namespace Encelado.Engine.Baskets;
/// <summary>
/// The state on disk (<c>data/state/baskets_state.json</c>): 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 (<see cref="AccountStateFiles"/>:
/// <c>data/state/baskets_state.demo.json</c>, <c>baskets_state.live.json</c>): open baskets,
/// entries in flight, the equity tracker, the session's counters, the halts, the closes
/// waiting for their P&amp;L and the positions the last reconciliation saw. Written atomically
/// (<see cref="AtomicFile"/>) 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.
/// </summary>
public sealed partial class BasketEngine
{
@@ -22,7 +24,8 @@ public sealed partial class BasketEngine
/// </summary>
private bool _stateLoaded;
private void SaveState()
/// <summary>Written by the decision thread; internal: the tests read back what an engine keeps.</summary>
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<long> ids)
{
w.WriteStartArray(name);
foreach (long id in ids.Order())
{
w.WriteNumberValue(id);
}
w.WriteEndArray();
}
}
private void LoadState()
/// <summary>
/// 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).
/// </summary>
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<long> ReadIds(JsonElement root, string name)
{
HashSet<long> 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;
}
}
/// <summary>
/// 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.
/// </summary>
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;
}
}
}
@@ -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,
@@ -247,6 +247,20 @@ public sealed partial class BasketEngine : IEngine
/// <param name="notifier">Where the engine tells the outside world what it did.</param>
/// <param name="versions">The section versions of the process (the web layer reads them); a private set when null.</param>
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)
{
}
/// <summary>
/// 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 <see cref="RunAsync"/>.
/// </summary>
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
/// <summary>The pairs that price the display currencies against USD (D-33): polled with the rest, never traded.</summary>
private static readonly string[] ConversionPairs = ["EURUSD", "GBPUSD", "USDCHF", "USDJPY", "AUDUSD", "USDCAD", "NZDUSD"];
private async Task LoadInstrumentsAsync(CancellationToken ct)
/// <summary>The instruments and the basket slots (internal: the tests build the slots over their own venue).</summary>
internal async Task LoadInstrumentsAsync(CancellationToken ct)
{
List<string> 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;
}
@@ -623,6 +623,99 @@ public sealed class BotSupervisor : IAsyncDisposable
public Task<CommandResult> CloseAsync(string basket, CancellationToken ct) =>
ExecuteAsync(new EngineCommand(EngineCommandKind.Close, basket, "chiusura manuale"), ct);
/// <summary>How long the guard of a change of account waits for the engine (it takes commands between two ticks); the tests shorten it.</summary>
internal TimeSpan SwitchCheckWait { get; set; } = TimeSpan.FromSeconds(30);
/// <summary>How long a cancelled switch waits for the engine to lift its block before it leaves the command queued.</summary>
private static readonly TimeSpan SwitchCancelWait = TimeSpan.FromSeconds(5);
/// <summary>
/// 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 (<see cref="EngineCommandKind.PrepareAccountSwitch"/>):
/// 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 (<see cref="CommandResult.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 <see cref="SwitchCheckWait"/>
/// (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 <see cref="CancelAccountSwitchAsync"/>.
/// </summary>
public async Task<CommandResult?> 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");
}
/// <summary>A prepared switch that will not happen: the running engine allows its entries again. Never throws; a stopped engine needs nothing.</summary>
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)");
}
}
/// <summary>What the engine has in hand that a stop or a restart would cut in half, described for the operator; null when nothing.</summary>
public string? CommandInProgress
{
@@ -61,6 +61,21 @@ public enum EngineCommandKind
/// kill-switch in progress finishes first (5.1: nothing closes from another thread).
/// </summary>
Shutdown,
/// <summary>
/// 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 <see cref="CommandResult.Refused"/> with the <see cref="Settings.AccountActivity"/>
/// as payload. Idle: the entries stay blocked until the restart (or <see cref="CancelAccountSwitch"/>).
/// <c>Argument</c> = what changes, for the log.
/// </summary>
PrepareAccountSwitch,
/// <summary>A prepared switch that will not happen (the save failed or was undone): the entries are allowed again.</summary>
CancelAccountSwitch,
}
public sealed record EngineCommand(EngineCommandKind Kind, string Argument = "", string Reason = "")
@@ -1,52 +1,157 @@
using System.Globalization;
using System.Text.Json;
using Encelado.Core.Baskets;
using Encelado.Engine.Baskets;
namespace Encelado.Engine.Settings;
/// <summary>One basket slot as the account-switch guard sees it, taken on the engine's decision thread.</summary>
public readonly record struct SlotActivity(BasketState State, bool HasPosition, bool HasLegs, bool Busy);
/// <summary>
/// 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.
/// <para>
/// A running engine answers on its decision thread (<see cref="FromEngine"/>), 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 (<see cref="FromDisk"/>).
/// </para>
/// </summary>
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;
/// <summary>Entries, adds and exits the engine has in hand (the slot has no position yet, or no longer).</summary>
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");
/// <summary>Baskets in error with a leg still on the account.</summary>
public int ErrorLegs { get; init; }
/// <summary>From the running engine's picture.</summary>
public static AccountActivity FromSnapshot(BotSnapshot snapshot)
/// <summary>Orphan legs of the bot on the account, and the residue of a kill-switch.</summary>
public int OrphanLegs { get; init; }
/// <summary>Closes waiting for the venue's history (at most 30 minutes, then the estimate).</summary>
public int PendingSettlements { get; init; }
/// <summary>The engine has not read its state yet, or the state on disk cannot be read: busy, the prudent answer.</summary>
public bool Unknown { get; init; }
public bool Busy => OpenBaskets + PendingBaskets + PendingOrders + InFlight + ErrorLegs + OrphanLegs + PendingSettlements > 0 || Unknown;
/// <summary>What is still open, in Italian, naming only what there is.</summary>
public string Describe()
{
ArgumentNullException.ThrowIfNull(snapshot);
return new AccountActivity(snapshot.OpenBaskets, snapshot.PendingBaskets, snapshot.PendingOrders);
List<string> 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}"));
}
}
}
/// <summary>
/// From the files a stopped engine left: <c>data/state/baskets_state.json</c> (open and
/// pending baskets) and <c>data/state/pending_orders.json</c> (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 (<paramref name="engineRunning"/> false: it must be
/// started on it for a while — they are never lost meanwhile, they stay in its state).
/// </summary>
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";
}
/// <summary>
/// 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.
/// </summary>
public static AccountActivity FromEngine(IEnumerable<SlotActivity> 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,
};
}
/// <summary>
/// From the files a stopped engine left for <paramref name="account"/>: its own state
/// (<see cref="AccountStateFiles.ReadablePathFor"/>: 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 <c>data/state/pending_orders.json</c>. An unreadable file counts as busy:
/// refusing a switch is the prudent answer.
/// </summary>
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;
}
}
@@ -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 <c>needsPhrase</c>
/// before anything is written, and a change of account is refused while baskets or orders
/// are open (<see cref="AccountActivity"/>).
/// before anything is written.
/// </para>
/// <para>
/// 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 (<see cref="AccountActivity"/>). 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&amp;L are there when it runs again.
/// </para>
/// <para>
/// The restart itself runs under the supervisor's lifecycle lock
@@ -229,16 +240,14 @@ public sealed class SettingsRuntime
List<SettingField> 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<string, string>());
}
// 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);
/// <summary>
/// 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.
/// </summary>
private async Task<SettingsResult> ApplyAfterWriteAsync(SettingsPlan plan, List<SettingField> 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));
}
/// <summary>The answer of a written save: per path what happened, and one line for the page and the log.</summary>
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<SettingsPathResult> 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.
/// </summary>
private Task<RestartResult> RestartCoreAsync(bool liveConfirmed, string reason) =>
Supervisor.RestartAsync(reason, Config.Run.Mode.IsLive() && liveConfirmed, () => StartRefusal(liveConfirmed));
private Task<RestartResult> RestartCoreAsync(bool liveConfirmed, string reason, Func<CommandResult?>? afterStop = null) =>
Supervisor.RestartAsync(reason, Config.Run.Mode.IsLive() && liveConfirmed, () => afterStop?.Invoke() ?? StartRefusal(liveConfirmed));
/// <summary>What a stopped engine left on <paramref name="account"/>, described; null when it is flat or an engine runs again.</summary>
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;
}
/// <summary>The refusal of a change the running engine found busy (the payload says with what), or that it could not check.</summary>
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";
/// <summary>
/// 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).
/// </summary>
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);
/// <summary>Writes them back atomically; the reason when it could not (null when done).</summary>
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);
@@ -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;
/// <summary>
/// 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.
/// </summary>
internal sealed class AccountVenue : IBroker
{
public double Balance { get; set; } = 10_000;
public double Equity { get; set; } = 10_000;
public List<BrokerPosition> Positions { get; } = [];
public List<ClosedTrade> History { get; } = [];
/// <summary>The orders asked about, by the venue's id.</summary>
public List<long> Lookups { get; } = [];
public BrokerEnvironment Environment => BrokerEnvironment.Demo;
public string Name => "conto di prova";
public bool SupportsTrading => true;
public TimeSpan ClockSkew => TimeSpan.Zero;
public Task<IReadOnlyList<Instrument>> GetInstrumentsAsync(IReadOnlyList<string> symbols, CancellationToken ct) =>
Task.FromResult<IReadOnlyList<Instrument>>([.. 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<IReadOnlyList<QuoteSnapshot>> GetQuotesAsync(IReadOnlyList<long> instrumentIds, CancellationToken ct) => Task.FromResult<IReadOnlyList<QuoteSnapshot>>([]);
public Task<IReadOnlyList<BidAskBar>> GetCandlesAsync(long instrumentId, TimeSpan interval, int count, CancellationToken ct) => Task.FromResult<IReadOnlyList<BidAskBar>>([]);
public Task<AccountSnapshot> GetAccountAsync(CancellationToken ct) => Task.FromResult(new AccountSnapshot(DateTime.UtcNow, "USD", Balance, Equity, Equity, 0, Equity - Balance));
public Task<IReadOnlyList<BrokerPosition>> GetPositionsAsync(CancellationToken ct) => Task.FromResult<IReadOnlyList<BrokerPosition>>([.. Positions]);
public Task<OrderOutcome> OpenAsync(OrderRequest request, CancellationToken ct) => throw new NotSupportedException("nessun ordine nei test del conto");
public Task<OrderOutcome?> LookupOrderAsync(string clientRef, CancellationToken ct) => Task.FromResult<OrderOutcome?>(null);
public Task<OrderOutcome?> LookupOrderByIdAsync(long orderId, CancellationToken ct)
{
Lookups.Add(orderId);
return Task.FromResult<OrderOutcome?>(null);
}
public Task<bool> CancelOrderAsync(long orderId, CancellationToken ct) => Task.FromResult(false);
public Task<CloseOutcome> CloseAsync(long positionId, long instrumentId, CancellationToken ct) => throw new NotSupportedException("nessuna chiusura nei test del conto");
public Task<bool> UpdateStopsAsync(long positionId, double? stopLoss, double? takeProfit, CancellationToken ct) => Task.FromResult(true);
public Task<CostEstimate?> GetCostAsync(OrderRequest request, CancellationToken ct) => Task.FromResult<CostEstimate?>(null);
public Task<IReadOnlyList<ClosedTrade>> GetClosedTradesAsync(DateTime fromUtc, CancellationToken ct) => Task.FromResult<IReadOnlyList<ClosedTrade>>([.. History]);
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
/// <summary>
/// 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&amp;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.
/// </summary>
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())];
/// <summary>What the engine wrote to decisions.jsonl (nothing yet: empty).</summary>
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,
};
/// <summary>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.</summary>
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<AccountActivity>(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<long> expected = StartupCash.Expected([11, 12, 13], new HashSet<long> { 13 }, [14], [([15, 16], seen.AddSeconds(10)), ([17], seen.AddSeconds(-10))], seen);
Assert.Equal([11L, 12, 14, 15, 16], expected);
List<ClosedTrade> 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);
}
}
@@ -40,8 +40,18 @@ public sealed class SettingsRuntimeTests : IAsyncLifetime
public List<EngineCommand> Commands { get; } = [];
/// <summary>What the published picture says (the 5.0 snapshot): the guard never reads it.</summary>
public int OpenBaskets { get; set; }
/// <summary>What the engine counts on its own slots when asked by the guard; null: the open baskets of the picture.</summary>
public AccountActivity? Activity { get; set; }
/// <summary>False while the engine would still be warming up (its decision loop not started).</summary>
public bool LoopStarted { get; set; } = true;
/// <summary>The stopped engine's last save (a real one writes its account's state before it lets go of the folder).</summary>
public Action? OnDispose { get; set; }
public Func<EngineCommand, CommandResult>? Answer { get; set; }
/// <summary>A command that takes its time (a kill-switch closing baskets): the task the test completes, or null to answer at once.</summary>
@@ -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;
}
}
/// <summary>When set, the factory waits for it (a real engine reads the ledger and the register while it is built).</summary>
private ManualResetEventSlim? _buildGate;
/// <summary>Set by the factory when it starts building an engine.</summary>
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<string, string> { ["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<string, string> { ["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<string, string> { ["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<string, string> { ["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<CommandResult> 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<string, string> { ["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<string, string> { ["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<CommandResult> 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<string, string> { ["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<string, string> { ["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<CommandResult> killing = new(TaskCreationOptions.RunContinuationsAsynchronously);
_engines[0].Hold = c => c.Kind == EngineCommandKind.KillSwitch ? killing.Task : null;
Task<CommandResult>? 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<string, string> { ["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]