diff --git a/deploy/docker/entrypoint.sh b/deploy/docker/entrypoint.sh index ec68e96..9b6a8ee 100644 --- a/deploy/docker/entrypoint.sh +++ b/deploy/docker/entrypoint.sh @@ -6,6 +6,13 @@ set -eu app="/app/Anubis.Guard.dll" +# A command ("docker run db import ...") runs once and ends: without the guard, which would start it again. +case "${1:-}" in + db|access|data|diagnostics|soak) + app="/app/Anubis.Server.dll" + ;; +esac + if [ "$(id -u)" != "0" ]; then exec dotnet "$app" "$@" fi diff --git a/docs/API-NOTES.md b/docs/API-NOTES.md index 05e9441..b71c508 100644 --- a/docs/API-NOTES.md +++ b/docs/API-NOTES.md @@ -208,6 +208,7 @@ Fatti controllati sulla documentazione ufficiale il 10/11/2026, scrivendo la par | Alpaca | Il flusso `trade_updates` ha due eventi in più (`order_replace_rejected`, `order_cancel_rejected`) e lo stato `held`. | Lo stato si prende dall'ordine dentro il messaggio; uno stato sconosciuto conta come "inviato" e le esecuzioni arrivano comunque dalla richiesta REST. | | OKX | `clOrdId` è unico solo tra gli ordini aperti; il doppione dà 51016 ("Client order ID already exists"), 51065 per gli algoritmici. | 51016 e 51065 vogliono dire "l'invio precedente è arrivato": si rilegge l'ordine invece di rimandarlo. | | OKX | Un ordine annullato senza esecuzioni sparisce dallo storico dopo 2 ore. | Un ordine OKX sconosciuto al broker da più di 2 ore si considera annullato (ADR 0009). | +| OKX | `/trade/fills` copre gli ultimi 3 giorni (60 richieste ogni 2 s), `/trade/fills-history` gli ultimi 3 mesi (10 ogni 2 s, `instType` obbligatorio); entrambe accettano `begin`/`end` su `ts` e si sfogliano con `after`/`before` su `billId`, 100 righe per pagina. Quanto a lungo si possa rileggere un ordine trigger scattato non è scritto. (Verificato il 30/11/2026, #69.) | Se si deve tornare indietro più di 60 ore si leggono entrambe, contando ogni esecuzione una volta, fino a 89 giorni; più indietro Anubis lo dice e il conto va controllato a mano. Un'esecuzione il cui ordine OKX non ricorda più resta senza nome e la mostra la riconciliazione. | | OKX | Le esecuzioni non hanno un `fillId`: la chiave è `tradeId`, unica per strumento. | Ogni esecuzione si registra una volta come `instId:tradeId`. | | OKX | Un ordine market spot che supera il saldo viene ridotto e eseguito, non rifiutato. | Il registro prende la quantità eseguita davvero, non quella chiesta. | | OKX | Gli ordini trigger (stop) non bloccano le monete: se allo scatto il saldo è minore, OKX vende quello che c'è. | Gli stop seguono la quantità della posizione dopo ogni esecuzione. | diff --git a/src/Anubis.Server/AccessCommand.cs b/src/Anubis.Server/AccessCommand.cs new file mode 100644 index 0000000..7cd3a6a --- /dev/null +++ b/src/Anubis.Server/AccessCommand.cs @@ -0,0 +1,56 @@ +using System.Collections; +using Anubis.Access; +using Anubis.Core; +using Anubis.Db; +using Anubis.Platform; + +namespace Anubis.Server; + +/// +/// "anubis access reset": a temporary password printed once, the second factor off, every session closed. Only whoever +/// can run a command on the computer or in the container gets here, and that person owns the data folder already. Used +/// after a lost password, a lost phone or a changed secret key (RUNBOOK). +/// +internal static class AccessCommand +{ + public static async Task RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary? environment = null, int? iterations = null) + { + output ??= Console.Out; + if (args.Length < 1 || args[0] != "reset") + { + await output.WriteLineAsync("Uso: anubis access reset [--platform docker|desktop] [--data-dir ]").ConfigureAwait(false); + return 2; + } + + environment ??= Environment.GetEnvironmentVariables().Cast().ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal); + var config = ServerOptions.Parse(args[1..], environment).LoadConfig(environment); + if (config.Db is not { } settings) + { + await output.WriteLineAsync("La configurazione d'avvio non indica il database.").ConfigureAwait(false); + return 1; + } + + Redactor.Register(settings.Password); + var clock = new SystemClock(); + try + { + await using var db = Database.Open(settings, allowCreate: false); + var access = new AccessStore(db, clock, new SecretStore(db, clock, new byte[32]), iterations ?? Passwords.DefaultIterations); + var temporary = Ids.NewToken()[..16]; + if (!await access.ResetAsync(temporary).ConfigureAwait(false)) + { + await output.WriteLineAsync("Non c'è ancora nessun utente: apri Anubis e fai il primo accesso.").ConfigureAwait(false); + return 1; + } + + await output.WriteLineAsync("Password provvisoria: " + temporary + Environment.NewLine + + "Accedi subito: ti chiederà di sceglierne una nuova. Il secondo fattore è tolto e tutte le sessioni sono chiuse.").ConfigureAwait(false); + return 0; + } + catch (Exception ex) when (Forms.IsArchiveProblem(ex)) + { + await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false); + return 1; + } + } +} diff --git a/src/Anubis.Server/AnubisHost.cs b/src/Anubis.Server/AnubisHost.cs index 898c526..1216a94 100644 --- a/src/Anubis.Server/AnubisHost.cs +++ b/src/Anubis.Server/AnubisHost.cs @@ -96,6 +96,9 @@ internal sealed partial class AnubisHost( public int PasswordIterations => overrides?.PasswordIterations ?? Passwords.DefaultIterations; + /// Why the last migration failed; the error page's "Riprova" clears it. + internal string? MigrationFailed { get; set; } + /// Asks the loop to check again now (after the wizard or an error-page choice). public void Wake() { @@ -286,7 +289,7 @@ internal sealed partial class AnubisHost( } catch (SchemaException ex) { - SetStatus(HostMode.SchemaProblem, ex.Message); + SetStatus(HostMode.SchemaProblem, Redactor.Redact(ex.Message)); return; } @@ -396,9 +399,27 @@ internal sealed partial class AnubisHost( SetStatus(HostMode.Ready, null); } - private async Task MigrateAsync(Backups backups, CancellationToken cancellationToken) + internal async Task MigrateAsync(Backups backups, CancellationToken cancellationToken) { - var applied = await Migrations.MigrateAsync(_db!, clock, ct => backups.TakeAsync(_db!, "prima-della-migrazione", ct), cancellationToken).ConfigureAwait(false); + // SPEC 9.4: after a migration that failed the engine stays off. It is not tried again by itself, because every + // attempt would take one more backup; the user tries again from the error page or with a restart. + if (MigrationFailed is { } failed) + { + throw new SchemaException(failed); + } + + int applied; + try + { + applied = await Migrations.MigrateAsync(_db!, clock, ct => backups.TakeAsync(_db!, Backups.BeforeMigration, ct), cancellationToken).ConfigureAwait(false); + } + catch (SchemaException ex) when (ex.InnerException is not null) + { + LogMigrationFailed(logger, ex); + MigrationFailed = ex.Message; + throw; + } + if (applied > 0) { LogMigrated(logger, applied, Migrations.Latest); @@ -739,6 +760,9 @@ internal sealed partial class AnubisHost( [LoggerMessage(Level = LogLevel.Warning, Message = "Demo mode: separate database in {Folder}")] private static partial void LogDemo(ILogger logger, string folder); + [LoggerMessage(Level = LogLevel.Error, Message = "Migration failed: the engine stays off until the user tries again")] + private static partial void LogMigrationFailed(ILogger logger, Exception exception); + [LoggerMessage(Level = LogLevel.Information, Message = "Applied {Count} migrations, schema version {Version}")] private static partial void LogMigrated(ILogger logger, int count, int version); diff --git a/src/Anubis.Server/Components/IdentityChoices.razor b/src/Anubis.Server/Components/IdentityChoices.razor index 10f9076..69837fa 100644 --- a/src/Anubis.Server/Components/IdentityChoices.razor +++ b/src/Anubis.Server/Components/IdentityChoices.razor @@ -18,6 +18,9 @@ case IdentityVerdict.DifferentInstallation:

Il database appartiene a un'altra installazione di Anubis. Il motore resta spento: due registri sugli stessi conti produrrebbero ordini doppi.

break; + case IdentityVerdict.MissingFile: +

Il database appartiene a un'installazione, ma la cartella dei dati non ha il suo file d'identità: non posso sapere se questo database è quello giusto o una copia vecchia. Il motore resta spento finché non lo dici tu.

+ break; case IdentityVerdict.StaleDatabase:

È il database di questa installazione, ma una copia più vecchia: dopo l'ultimo ripristino o spostamento ne è nata una più recente. Il motore resta spento per non lavorare su dati superati.

break; diff --git a/src/Anubis.Server/Components/Pages/Accesso.razor b/src/Anubis.Server/Components/Pages/Accesso.razor index d628729..1d765b6 100644 --- a/src/Anubis.Server/Components/Pages/Accesso.razor +++ b/src/Anubis.Server/Components/Pages/Accesso.razor @@ -40,6 +40,7 @@ { "password" => "Password sbagliata. Riprova: dopo 5 tentativi sbagliati l'accesso si blocca per 15 minuti.", "codice" => "Il codice non è giusto o è scaduto. Usa quello che l'app mostra adesso.", + "chiave" => "La password è giusta, ma la chiave dei segreti (ANUBIS_SECRET_KEY) non è più quella di prima e il codice non si può controllare. Rimetti la vecchia chiave, oppure azzera l'accesso dal computer che ospita Anubis: il manuale dice come.", "attesa" => $"Troppi tentativi sbagliati. Riprova tra {Minuti ?? "15"} minuti.", _ => null, }; diff --git a/src/Anubis.Server/Components/Pages/Impostazioni.razor b/src/Anubis.Server/Components/Pages/Impostazioni.razor index 48fd3a6..f4ff63e 100644 --- a/src/Anubis.Server/Components/Pages/Impostazioni.razor +++ b/src/Anubis.Server/Components/Pages/Impostazioni.razor @@ -812,6 +812,7 @@ private string KeyState(SecretStatus status) => status switch { { FromEnvironment: true } => "Dalle variabili d'ambiente", + { Unreadable: true } => "Non si legge più: la chiave dei segreti è cambiata, inseriscila di nuovo", { IsSet: true, UpdatedAt: { } at } => "Impostata " + Inline(Format.ShortDate(at, Shell.Now, Shell.Zone)), { IsSet: true } => "Impostata", _ => "Non impostata", diff --git a/src/Anubis.Server/Components/Pages/Panoramica.razor b/src/Anubis.Server/Components/Pages/Panoramica.razor index 6d4538b..f6d3985 100644 --- a/src/Anubis.Server/Components/Pages/Panoramica.razor +++ b/src/Anubis.Server/Components/Pages/Panoramica.razor @@ -17,6 +17,10 @@ var phoneMoves = moves.Select((m, i) => (m, i)).Where(x => !x.m.Calendar).Take(2).Select(x => x.i).ToHashSet(); var v = p.Accounts; } +@if (p.ProtectedRestart) +{ +
Ripartenza protetta. Dopo un ripristino o un'importazione sono fermo: non apro posizioni finché non hai controllato e non confermi dalla pagina Rischio.
+} @if (_absence is { } away) {
diff --git a/src/Anubis.Server/Components/Pages/Rischio.razor b/src/Anubis.Server/Components/Pages/Rischio.razor index d7ba40f..397890e 100644 --- a/src/Anubis.Server/Components/Pages/Rischio.razor +++ b/src/Anubis.Server/Components/Pages/Rischio.razor @@ -22,6 +22,34 @@

Interruttore d'emergenza

@BotText(v.BotState)
+ @if (v.ProtectedRestart is { } restart) + { +
+

Ripartenza protetta. Il database è cambiato il @Moment(restart.Since) (ripristino, importazione o copia più vecchia del conto): prima di ripartire guarda cosa ho ricostruito.

+
    + @foreach (var line in restart.Rebuilt) + { +
  • @line
  • + } + @if (restart.Working) + { +
  • Sto ancora leggendo i conti.
  • + } + else if (restart.Waiting.Count > 0) + { +
  • Non ho ancora letto: @string.Join(", ", restart.Waiting). Riprovo ogni minuto; se una chiave è scaduta, cambiala nelle Impostazioni.
  • + } + else if (restart.Rebuilt.Count == 0) + { +
  • Sui conti non c'era niente che il database non conoscesse già.
  • + } + @if (restart.ToReconfirm.Count > 0) + { +
  • Da riconfermare nella pagina Strategie, altrimenti restano in sola uscita: @string.Join(", ", restart.ToReconfirm).
  • + } +
+
+ } @if (v.WaitsForRestart) {

@@ -51,7 +79,7 @@

- + } } @@ -293,7 +321,9 @@ private static string Where(string world) => world == Worlds.Real ? "sui conti veri" : "nel mondo simulato"; - private static string RestartText(RiskView v) => v.Tripped.Count > 0 + private static string RestartText(RiskView v) => v.ProtectedRestart is not null + ? "Riparti dopo il ripristino: hai controllato posizioni e operazioni ricostruite? Il bot torna a operare; le strategie con soldi veri restano in sola uscita finché non le riconfermi. Confermi?" + : v.Tripped.Count > 0 ? "Riparti: il massimo di riferimento riparte dal patrimonio di adesso e il bot torna a operare. Confermi?" : "Riparti: il bot torna a operare. Confermi?"; diff --git a/src/Anubis.Server/Components/Pages/Servizio.razor b/src/Anubis.Server/Components/Pages/Servizio.razor index ce8803f..2d0f0d1 100644 --- a/src/Anubis.Server/Components/Pages/Servizio.razor +++ b/src/Anubis.Server/Components/Pages/Servizio.razor @@ -65,6 +65,25 @@ case HostMode.SchemaProblem:

@_status.Detail

+ @if (Host.MigrationFailed is not null) + { + var copies = new Backups(Host.Config.Data, Clock).List(); +

Il motore resta spento. + @if (copies.Count > 0) + { + L'ultimo salvataggio è @copies[0].Name, in @Host.Config.Data.Backups: per tornarci, indica nella configurazione un database nuovo e vuoto e sceglilo in questa pagina. + } + Se il problema è passeggero (spazio sul disco, permessi), risolvilo e riprova.

+ @if (Host.Config.Platform == PlatformKind.Docker || _local) + { +
+ + + + + } + break; + }

Per non rovinare i dati il motore resta spento. Aggiorna Anubis alla versione che ha creato questo database, oppure ripristina un salvataggio in un database vuoto.

break; @@ -82,7 +101,7 @@ diff --git a/src/Anubis.Server/Components/Pages/Strategie.razor b/src/Anubis.Server/Components/Pages/Strategie.razor index e5b782a..0c657ce 100644 --- a/src/Anubis.Server/Components/Pages/Strategie.razor +++ b/src/Anubis.Server/Components/Pages/Strategie.razor @@ -51,7 +51,7 @@ var up = s.ResultEur >= 0;
-

@s.Name @(s.Stage.ExitOnly ? "Sola uscita" : "In " + StrategyStages.Label(s.Stage.Stage).ToLower(CultureInfo.GetCultureInfo("it-IT")))

+

@s.Name @(s.Stage.WaitsForReconfirmation ? "Da riconfermare" : s.Stage.ExitOnly ? "Sola uscita" : "In " + StrategyStages.Label(s.Stage.Stage).ToLower(CultureInfo.GetCultureInfo("it-IT")))

@s.Description

    @foreach (var rule in s.Rules) @@ -92,7 +92,30 @@ }
- @if (s.Stage.ExitOnly) + @if (s.Stage.WaitsForReconfirmation) + { +

Dopo un ripristino non compra con soldi veri finché non la riconfermi: vende e tiene gli stop. I giorni e i conteggi restano quelli di prima.

+ @if (!Shell.IsDemo) + { +
+ Riconferma +
+ +

Ecco con che cosa riprende @s.Name:

+
    + @foreach (var line in s.Summary) + { +
  • @line
  • + } +
+ + + + +
+ } + } + else if (s.Stage.ExitOnly) {

Tornata indietro con posizioni vere ancora aperte: le gestisce fino a zero, con i loro stop, senza nuovi acquisti.

} @@ -220,6 +243,7 @@ ("simulazione", _) => ("Fatto: la strategia è in simulazione, con ordini finti su prezzi veri.", true), ("osservazione", _) => ("Fatto: la strategia è in osservazione.", true), ("reale", _) => ("Fatto: la strategia usa soldi veri da adesso. Se peggiora torna indietro da sola.", true), + ("riconferma", _) => ("Fatto: la strategia è riconfermata e torna a operare con soldi veri.", true), (_, "backtest") => ("Solo una strategia che ha superato il backtest può andare in simulazione.", false), (_, "osservazione-giorni") => ($"Prima della simulazione servono almeno {StageBook.ObservationDays} giorni di segnali raccolti dal vivo in osservazione.", false), (_, "frase") => ("La frase non corrisponde: scrivila esattamente come è mostrata.", false), diff --git a/src/Anubis.Server/DatabaseCommand.cs b/src/Anubis.Server/DatabaseCommand.cs index 9ec3798..a9f95d1 100644 --- a/src/Anubis.Server/DatabaseCommand.cs +++ b/src/Anubis.Server/DatabaseCommand.cs @@ -40,7 +40,15 @@ internal static class DatabaseCommand var folder = Path.GetFullPath(args[1]); try { - await using var db = Database.Open(config.Db!, allowCreate: args[0] == "import" && !File.Exists(config.Data.InstallationFile)); + if (args[0] == "import") + { + // Read before the database is opened: a wrong folder must not leave a new empty SQLite file behind. + await Archive.ReadIndexAsync(folder).ConfigureAwait(false); + config.Data.Ensure(); + } + + // Moving to SQLite, the file does not exist yet: the user asked for it by name, unlike a start (trap 20). + await using var db = Database.Open(config.Db!, allowCreate: args[0] == "import"); if (args[0] == "export") { var index = await Archive.ExportAsync(db, folder, clock).ConfigureAwait(false); @@ -48,14 +56,13 @@ internal static class DatabaseCommand return 0; } - config.Data.Ensure(); var imported = await Archive.ImportAsync(db, folder, clock).ConfigureAwait(false); - await Installation.RenewAsync(db, config.Data, clock, adoptDatabaseIdentity: !File.Exists(config.Data.InstallationFile)).ConfigureAwait(false); + await Installation.RenewAsync(db, config.Data, clock, "Archivio importato").ConfigureAwait(false); await output.WriteLineAsync($"Importate {imported.Tables.Sum(t => t.Count)} righe di {imported.Tables.Count} tabelle: conteggi e totali coincidono. " + "Al prossimo avvio il bot riparte protetto.").ConfigureAwait(false); return 0; } - catch (Exception ex) when (ex is IOException or InvalidOperationException or SchemaException or System.Text.Json.JsonException or System.Data.Common.DbException) + catch (Exception ex) when (Forms.IsArchiveProblem(ex)) { await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false); return 1; diff --git a/src/Anubis.Server/Endpoints.cs b/src/Anubis.Server/Endpoints.cs index 1aef93a..588b13a 100644 --- a/src/Anubis.Server/Endpoints.cs +++ b/src/Anubis.Server/Endpoints.cs @@ -330,6 +330,16 @@ internal static partial class Endpoints : "Comando non ammesso nello stato attuale del bot."); } + var restart = command is "restart" or "riattiva" + && await Platform.Installation.ReadRowAsync(host.Services.Db, ct).ConfigureAwait(false) is { ProtectedRestart: true }; + if (restart && (host.Services.Trading is not { Risk: not null, Started: true } engineOn || engineOn.AccountsToRebuild.Count > 0)) + { + // SPEC 15.1: first the executions after the archive, then the user's confirmation. + var waiting = host.Services.Trading?.AccountsToRebuild ?? []; + return (false, "Dopo il ripristino devo prima ricostruire dal broker le esecuzioni successive al salvataggio" + + (waiting.Count == 0 ? "." : $". Aspetto: {string.Join(", ", waiting)}.")); + } + if (host.Services.Trading is { Risk: { } risk } trading) { // The switch of SPEC 9.3 goes through the risk engine: it cancels the orders under way and keeps the stops. @@ -346,6 +356,11 @@ internal static partial class Endpoints try { await risk.RestartAsync(by, ct).ConfigureAwait(false); + if (restart) + { + await Platform.Installation.ClearProtectedRestartAsync(host.Services.Db, ct).ConfigureAwait(false); + } + await NotifyBotAsync(host, "bot_restarted", $"Il bot è ripartito dopo «Ferma tutto» (da {by}).", ct).ConfigureAwait(false); return (true, target); } diff --git a/src/Anubis.Server/Forms.cs b/src/Anubis.Server/Forms.cs index 553b7c8..087e801 100644 --- a/src/Anubis.Server/Forms.cs +++ b/src/Anubis.Server/Forms.cs @@ -173,6 +173,8 @@ internal static partial class Forms case LoginResult.SecondFactorNeeded: limiter.Forgive(address); return Results.Redirect(With(With("/accesso", "fattore", "1"), "ritorno", back)); + case LoginResult.UnreadableSecondFactor: + return Results.Redirect(With("/accesso", "errore", "chiave")); case LoginResult.WrongSecondFactor: return Results.Redirect(With(With(With("/accesso", "fattore", "1"), "errore", "codice"), "ritorno", back)); default: @@ -590,6 +592,10 @@ internal static partial class Forms await stages.ConfirmLiveAsync(new Anubis.Trading.LiveConfirmation(strategy, account, form["frase"].ToString(), form["password"].ToString(), string.IsNullOrWhiteSpace(code) ? null : code.Trim(), by), ct).ConfigureAwait(false); return Results.Redirect("/strategie?ok=reale"); + case "riconferma": + var second = form["codice"].ToString(); + await stages.ReconfirmAsync(strategy, form["password"].ToString(), string.IsNullOrWhiteSpace(second) ? null : second.Trim(), by, ct).ConfigureAwait(false); + return Results.Redirect("/strategie?ok=riconferma"); default: return Results.Redirect("/strategie?errore=scelta"); } @@ -1041,6 +1047,14 @@ internal static partial class Forms using var exclusive = await host.ExclusiveAsync(ct).ConfigureAwait(false); var status = host.Status; var db = host.Database; + if (choice == "riprova" && status.Mode == HostMode.SchemaProblem) + { + host.MigrationFailed = null; + exclusive.Dispose(); + host.Wake(); + return Results.Redirect("/"); + } + if (status.Mode != HostMode.IdentityProblem || status.Identity is null || db is null) { return Results.Redirect("/"); @@ -1059,7 +1073,7 @@ internal static partial class Forms } await Archive.ImportAsync(db, Path.Combine(backup.Folder, Backups.ArchiveFolder), clock, ct).ConfigureAwait(false); - await Installation.RenewAsync(db, config.Data, clock, adoptDatabaseIdentity: false, ct).ConfigureAwait(false); + await Installation.RenewAsync(db, config.Data, clock, "Salvataggio ripristinato", ct).ConfigureAwait(false); break; case "importa" when verdict == IdentityVerdict.EmptyDatabase: var folder = ServiceChoices.ImportFolders(config.Data).FirstOrDefault(f => Path.GetFileName(f) == form["archivio"].ToString()); @@ -1069,13 +1083,15 @@ internal static partial class Forms } await Archive.ImportAsync(db, folder, clock, ct).ConfigureAwait(false); - await Installation.RenewAsync(db, config.Data, clock, adoptDatabaseIdentity: false, ct).ConfigureAwait(false); + await Installation.RenewAsync(db, config.Data, clock, "Archivio importato", ct).ConfigureAwait(false); break; case "da-capo" when verdict == IdentityVerdict.EmptyDatabase: Installation.StartOver(config.Data, clock); break; - case "usa-questo" when verdict is IdentityVerdict.DifferentInstallation or IdentityVerdict.StaleDatabase: - await Installation.RenewAsync(db, config.Data, clock, adoptDatabaseIdentity: true, ct).ConfigureAwait(false); + case "usa-questo" when verdict is IdentityVerdict.DifferentInstallation or IdentityVerdict.StaleDatabase or IdentityVerdict.MissingFile: + // An old copy may have an old schema: it is brought up to date, after its own backup, before it is protected. + await host.MigrateAsync(new Backups(config.Data, clock), ct).ConfigureAwait(false); + await Installation.RenewAsync(db, config.Data, clock, "Database scelto dalla pagina d'errore", ct).ConfigureAwait(false); break; default: return Results.Redirect("/?errore=scelta"); diff --git a/src/Anubis.Server/PanoramaView.cs b/src/Anubis.Server/PanoramaView.cs index 4693515..c28f569 100644 --- a/src/Anubis.Server/PanoramaView.cs +++ b/src/Anubis.Server/PanoramaView.cs @@ -40,6 +40,9 @@ internal sealed record PanoramaView( LearningSummary Learning, DateTimeOffset? FractionStops) { + /// After a restore the bot waits for the user (SPEC 15.1). + public bool ProtectedRestart { get; init; } + private static readonly CultureInfo _it = CultureInfo.InvariantCulture; /// "Notizie che contano" (SPEC 13.6): first those with an effect in force, then the latest on the positions or their markets. @@ -97,7 +100,10 @@ internal sealed record PanoramaView( { var board = await new Anubis.News.NewsBoard(services.Db, clock, services.Settings).LoadAsync(cancellationToken).ConfigureAwait(false); return new PanoramaView(accounts, trends, limits, kept, cards, anyLive, system, null, null, Decision(overview.NextDecision, shell.Now, shell.Zone), - services.MarketData is null && board.Rows.Count == 0 ? null : Matters(board, shell), learning, fractions); + services.MarketData is null && board.Rows.Count == 0 ? null : Matters(board, shell), learning, fractions) + { + ProtectedRestart = risk.ProtectedRestart is not null, + }; } var root = aggregates.RootElement; diff --git a/src/Anubis.Server/Program.cs b/src/Anubis.Server/Program.cs index f38827b..aebdd22 100644 --- a/src/Anubis.Server/Program.cs +++ b/src/Anubis.Server/Program.cs @@ -6,6 +6,12 @@ if (args.Length >= 1 && args[0] == "db") return await DatabaseCommand.RunAsync(args[1..]).ConfigureAwait(false); } +// "anubis access reset": a new password for whoever holds the computer, the second factor off (RUNBOOK). +if (args.Length >= 1 && args[0] == "access") +{ + return await AccessCommand.RunAsync(args[1..]).ConfigureAwait(false); +} + // "anubis data report|binance|csv": the data quality report and the research imports (Phase 2). if (args.Length >= 1 && args[0] == "data") { diff --git a/src/Anubis.Server/RiskView.cs b/src/Anubis.Server/RiskView.cs index f514ae8..99deff5 100644 --- a/src/Anubis.Server/RiskView.cs +++ b/src/Anubis.Server/RiskView.cs @@ -9,6 +9,29 @@ namespace Anubis.Server; /// A row of the limits table: what is used now against the threshold, and what happens beyond it. internal sealed record LimitRow(string Label, string Now, string? Detail, decimal? Usage, string Threshold, string Beyond, string Key); +/// +/// The protected restart of SPEC 15.1: since when, the accounts still to rebuild, what was rebuilt, the strategies +/// that stay in exit only until they are confirmed again. +/// +internal sealed record ProtectedRestartView(DateTimeOffset Since, bool Working, IReadOnlyList Waiting, IReadOnlyList Rebuilt, IReadOnlyList ToReconfirm) +{ + public bool CanRestart => !Working && Waiting.Count == 0; + + public static async Task LoadAsync(AppServices services, CancellationToken cancellationToken) + { + if (await Platform.Installation.ReadRowAsync(services.Db, cancellationToken).ConfigureAwait(false) is not { ProtectedRestart: true } row) + { + return null; + } + + var rebuilt = await services.Db.ReadAsync(s => s.QueryAsync("SELECT message FROM journal WHERE code = 'ledger_rebuilt' AND occurred_at >= @f ORDER BY occurred_at, id", + r => r.Text("message"), ("f", row.RenewedAt)), cancellationToken).ConfigureAwait(false); + var stages = services.Trading is { } trading ? await trading.Stages.AllAsync(cancellationToken).ConfigureAwait(false) : []; + return new ProtectedRestartView(row.RenewedAt, services.Trading is { Started: false }, services.Trading?.AccountsToRebuild ?? [], rebuilt, + [.. stages.Where(s => s.WaitsForReconfirmation).Select(s => StrategyNames.Label(s.Strategy, withMarket: true))]); + } +} + /// A point of the fall from the high, as a fraction: 0 at the high, −0,03 three percent below. internal sealed record DrawdownPoint(DateTimeOffset At, decimal Drawdown); @@ -33,6 +56,9 @@ internal sealed record RiskView( bool HasPositions, IReadOnlyList Tripped) { + /// After a restore (SPEC 15.1): what the restart waits for, and what stays in exit only after it. + public ProtectedRestartView? ProtectedRestart { get; init; } + public bool AnyBlock => Tripped.Count > 0 || Risk.EntriesBlocked || Risk.Multiplier < 1m || BotState != "active"; /// The switch tripped by itself in a world (SPEC 9.2): it waits for the user's restart, like "Ferma tutto". @@ -133,7 +159,10 @@ internal sealed record RiskView( return new RiskView(bot, engine.StopRequested, (await engine.BotAsync(cancellationToken).ConfigureAwait(false)).CloseAll, world, risk, limits, rows, drawdown, scenarios, await engine.EventsAsync(8, cancellationToken).ConfigureAwait(false), next, last, await RiskSettings.PdtGuardAsync(services.Settings, cancellationToken).ConfigureAwait(false), - positions.Count > 0, tripped); + positions.Count > 0, tripped) + { + ProtectedRestart = await ProtectedRestartView.LoadAsync(services, cancellationToken).ConfigureAwait(false), + }; } private static decimal? Worst(IReadOnlyList index, DateTimeOffset? from) diff --git a/src/Anubis/Access/AccessStore.cs b/src/Anubis/Access/AccessStore.cs index 19aaaa9..e416b9e 100644 --- a/src/Anubis/Access/AccessStore.cs +++ b/src/Anubis/Access/AccessStore.cs @@ -15,6 +15,9 @@ public enum LoginResult WrongPassword, SecondFactorNeeded, WrongSecondFactor, + + /// The second factor was sealed with another secret key: no code can be checked. + UnreadableSecondFactor, Locked, NoUser, } @@ -169,6 +172,34 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets, } } + private static string SecondFactorName(Guid userId) => "totp:" + userId.ToString("D"); + + private bool CanReadSecondFactor(Guid userId, byte[] stored) => secrets.CanOpen(SecondFactorName(userId), stored); + + private bool AcceptSealedCode(Guid userId, byte[] stored, string? code) => + CanReadSecondFactor(userId, stored) && AcceptCode(Convert.FromBase64String(secrets.Open(SecondFactorName(userId), stored)), code); + + /// + /// For whoever holds the computer, from the command line (RUNBOOK): a new password to change at the next sign-in, the + /// second factor off, every session closed. The way back in after a lost password or a changed secret key. + /// + public async Task ResetAsync(string password, CancellationToken cancellationToken = default) + { + var hash = Passwords.Hash(password, iterations); + return await db.WriteAsync(async s => + { + if (await s.ExecuteAsync("UPDATE users SET password_hash = @h, must_change_password = @m, totp_secret = NULL, updated_at = @t WHERE username = @u", cancellationToken, + ("h", hash), ("m", true), ("t", clock.UtcNow), ("u", AdminName)).ConfigureAwait(false) == 0) + { + return false; + } + + await s.ExecuteAsync("DELETE FROM sessions", cancellationToken).ConfigureAwait(false); + await LogAsync(s, "security.access", "azzerato dalla riga di comando", cancellationToken).ConfigureAwait(false); + return true; + }, cancellationToken).ConfigureAwait(false); + } + public Task HasUserAsync(CancellationToken cancellationToken = default) => db.ReadAsync(async s => await s.CountAsync("SELECT COUNT(*) FROM users").ConfigureAwait(false) > 0, cancellationToken); @@ -216,8 +247,12 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets, return (LoginResult.SecondFactorNeeded, null); } - var secret = Convert.FromBase64String(secrets.Open("totp:" + user.Id.ToString("D"), user.Totp)); - if (!AcceptCode(secret, code)) + if (!CanReadSecondFactor(user.Id, user.Totp)) + { + return (LoginResult.UnreadableSecondFactor, null); + } + + if (!AcceptSealedCode(user.Id, user.Totp, code)) { return (LoginResult.WrongSecondFactor, null); } @@ -329,7 +364,7 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets, return false; } - if (user.Totp is null || AcceptCode(Convert.FromBase64String(secrets.Open("totp:" + user.Id.ToString("D"), user.Totp)), code)) + if (user.Totp is null || AcceptSealedCode(user.Id, user.Totp, code)) { _fresh.Succeeded(FreshAttempts); return true; @@ -348,7 +383,7 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets, return false; } - if (user.Totp is not null && !AcceptCode(Convert.FromBase64String(secrets.Open("totp:" + userId.ToString("D"), user.Totp)), code)) + if (user.Totp is not null && !AcceptSealedCode(userId, user.Totp, code)) { return false; } diff --git a/src/Anubis/Core/SecretStore.cs b/src/Anubis/Core/SecretStore.cs index 2d11b21..d4dca47 100644 --- a/src/Anubis/Core/SecretStore.cs +++ b/src/Anubis/Core/SecretStore.cs @@ -6,7 +6,7 @@ using Anubis.Db; namespace Anubis.Core; /// Whether a secret is set and where it comes from. Never the value (SPEC 13.5, 15.4). -public sealed record SecretStatus(string Name, bool IsSet, bool FromEnvironment, DateTimeOffset? UpdatedAt); +public sealed record SecretStatus(string Name, bool IsSet, bool FromEnvironment, DateTimeOffset? UpdatedAt, bool Unreadable = false); /// /// Secrets encrypted in the database with AES-GCM under the installation's secret key (SPEC 15.4). The name is @@ -65,7 +65,10 @@ public sealed class SecretStore(Database db, IClock clock, byte[] key, IReadOnly }, cancellationToken).ConfigureAwait(false); } - /// The plain value, for the code that needs it (adapters). Never pass it to the interface. + /// + /// The plain value, for the code that needs it (adapters). Never pass it to the interface. A value sealed with another + /// key (a restore on a new server) counts as missing: whoever asked goes on without it, and the Settings say so. + /// public async Task RevealAsync(string name, CancellationToken cancellationToken = default) { if (_environment.TryGetValue(name, out var fromEnvironment)) @@ -80,9 +83,16 @@ public sealed class SecretStore(Database db, IClock clock, byte[] key, IReadOnly return null; } - var value = Open(name, stored); - Redactor.Register(value); - return value; + try + { + var value = Open(name, stored); + Redactor.Register(value); + return value; + } + catch (CryptographicException) + { + return null; + } } public async Task StatusAsync(string name, CancellationToken cancellationToken = default) @@ -92,9 +102,22 @@ public sealed class SecretStore(Database db, IClock clock, byte[] key, IReadOnly return new SecretStatus(name, true, true, null); } - var updated = await db.ReadAsync(s => s.QueryAsync("SELECT updated_at FROM secrets WHERE name = @n", r => r.Moment("updated_at"), ("n", name)), cancellationToken) - .ConfigureAwait(false); - return new SecretStatus(name, updated.Count > 0, false, updated.Count > 0 ? updated[0] : null); + var stored = await db.ReadAsync(s => s.QueryAsync("SELECT ciphertext, updated_at FROM secrets WHERE name = @n", r => (Sealed: r.Bytes("ciphertext"), At: r.Moment("updated_at")), ("n", name)), + cancellationToken).ConfigureAwait(false); + return stored.Count == 0 ? new SecretStatus(name, false, false, null) : new SecretStatus(name, true, false, stored[0].At, !CanOpen(name, stored[0].Sealed)); + } + + internal bool CanOpen(string name, byte[] stored) + { + try + { + Open(name, stored); + return true; + } + catch (CryptographicException) + { + return false; + } } internal byte[] Seal(string name, string value) diff --git a/src/Anubis/Db/Archive.cs b/src/Anubis/Db/Archive.cs index 8798c2b..04cfcbe 100644 --- a/src/Anubis/Db/Archive.cs +++ b/src/Anubis/Db/Archive.cs @@ -91,6 +91,12 @@ public static class Archive throw new InvalidDataException("Formato d'archivio sconosciuto."); } + // The index of an archive that came from elsewhere is only data: it never points outside its own folder. + if (index.Tables.Any(t => t.File != Path.GetFileName(t.File) || t.File.Length == 0) || index.Tables.DistinctBy(t => t.Name).Count() != index.Tables.Count) + { + throw new InvalidDataException("L'indice dell'archivio non è valido."); + } + return index; } @@ -120,9 +126,12 @@ public static class Archive throw new InvalidOperationException("Il database di arrivo ha già uno schema più recente dell'archivio: usa un database vuoto."); } - await Migrations.MigrateAsync(db, clock, null, cancellationToken, upTo: index.SchemaVersion).ConfigureAwait(false); var tables = Schema.Parse(Migrations.All.Take(index.SchemaVersion)); + // The whole archive is read and checked before the database is touched: a damaged one leaves it as it was. + await VerifyAsync(index, folder, tables, cancellationToken).ConfigureAwait(false); + await Migrations.MigrateAsync(db, clock, null, cancellationToken, upTo: index.SchemaVersion).ConfigureAwait(false); + await db.WriteAsync(async s => { foreach (var entry in index.Tables) @@ -178,12 +187,62 @@ public static class Archive throw new InvalidDataException($"Il totale {key} non coincide: {value} nell'archivio, {actual ?? "nessuno"} nel database."); } } + + await Installation.SealAsync(s, cancellationToken).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false); await Migrations.MigrateAsync(db, clock, null, cancellationToken).ConfigureAwait(false); return index; } + private static async Task VerifyAsync(ArchiveIndex index, string folder, IReadOnlyList tables, CancellationToken cancellationToken) + { + var totals = new Totals(); + foreach (var entry in index.Tables) + { + var table = tables.FirstOrDefault(t => t.Name == entry.Name) ?? throw new InvalidDataException($"L'archivio contiene la tabella sconosciuta {entry.Name}."); + long count = 0; + using var reader = new StreamReader(Path.Combine(folder, entry.File), Encoding.UTF8); + while (await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false) is { } line) + { + if (line.Length == 0) + { + continue; + } + + var row = JsonNode.Parse(line) as JsonObject ?? throw new InvalidDataException($"La tabella {entry.Name} ha una riga che non si legge."); + foreach (var column in table.Columns) + { + _ = FromJson(row[column.Name], column); + } + + totals.Add(table, row); + count++; + } + + if (count != entry.Count) + { + throw new InvalidDataException($"La tabella {entry.Name} ha {count} righe nel file e {entry.Count} nell'indice: archivio incompleto."); + } + } + + // A table missing from the index would be silently empty: an export always writes every table of its version. + var missing = tables.FirstOrDefault(t => index.Tables.All(e => e.Name != t.Name)); + if (missing is not null) + { + throw new InvalidDataException($"Nell'archivio manca la tabella {missing.Name}."); + } + + var read = totals.ToDictionary(); + foreach (var (key, value) in index.AccountingTotals) + { + if (!read.TryGetValue(key, out var actual) || actual != value) + { + throw new InvalidDataException($"Il totale {key} non coincide: {value} nell'indice, {actual ?? "nessuno"} nei file."); + } + } + } + /// Row counts of every table, for comparisons in tests and on the System page. public static async Task> CountsAsync(Database db, CancellationToken cancellationToken = default) { @@ -191,7 +250,8 @@ public static class Archive return await db.ReadAsync(async s => { var counts = new Dictionary(StringComparer.Ordinal); - foreach (var table in Schema.Tables) + // The tables the database has: an import that stopped half way may have left an older schema. + foreach (var table in Schema.Parse(Migrations.All.Take(await CurrentVersionAsync(s).ConfigureAwait(false)))) { counts[table.Name] = await s.CountAsync($"SELECT COUNT(*) FROM {table.Name}").ConfigureAwait(false); } diff --git a/src/Anubis/Db/Backups.cs b/src/Anubis/Db/Backups.cs index fecd744..f957951 100644 --- a/src/Anubis/Db/Backups.cs +++ b/src/Anubis/Db/Backups.cs @@ -9,11 +9,13 @@ public sealed record BackupInfo(string Folder, string Name, DateTimeOffset Taken /// /// Backups (SPEC 5.4): the engine-independent archive, plus a consistent copy of the SQLite file made with the -/// backup API. Nightly at 03:30 Italian time, before every migration, and on request. The last 14 are kept. +/// backup API. Nightly at 03:30 Italian time, before every migration, and on request. The last 14 nightly ones are +/// kept, and separately the last 14 of each other kind, so a series of one kind never pushes out the others. /// public sealed class Backups(DataDirectory data, IClock clock) { public const int Keep = 14; + public const string BeforeMigration = "prima-della-migrazione"; public const string ArchiveFolder = "archivio"; public const string SqliteCopy = "anubis.sqlite3"; @@ -37,6 +39,7 @@ public sealed class Backups(DataDirectory data, IClock clock) if (db.Engine == DbEngine.Sqlite) { await db.BackupSqliteFileAsync(Path.Combine(temp, SqliteCopy), cancellationToken).ConfigureAwait(false); + await Installation.SealCopyAsync(Path.Combine(temp, SqliteCopy), cancellationToken).ConfigureAwait(false); } Directory.Move(temp, folder); @@ -69,10 +72,23 @@ public sealed class Backups(DataDirectory data, IClock clock) private void Prune() { - foreach (var old in List().Skip(Keep)) + foreach (var old in List().GroupBy(b => Kind(b.Reason)).SelectMany(g => g.Skip(Keep))) { Directory.Delete(old.Folder, recursive: true); } + + // What a backup cut off by a power failure left behind; one under way right now is younger than a day. + foreach (var partial in Directory.EnumerateDirectories(data.Backups, "*.partial").Where(d => clock.UtcNow - new DateTimeOffset(Directory.GetLastWriteTimeUtc(d)) > TimeSpan.FromDays(1))) + { + Directory.Delete(partial, recursive: true); + } + } + + // "notturno-2" is the second of the same second: the number is not part of the kind. + private static string Kind(string reason) + { + var dash = reason.LastIndexOf('-'); + return dash > 0 && int.TryParse(reason[(dash + 1)..], NumberStyles.None, CultureInfo.InvariantCulture, out _) ? reason[..dash] : reason; } private static BackupInfo? Describe(string folder) diff --git a/src/Anubis/Db/Migrator.cs b/src/Anubis/Db/Migrator.cs index 188f3db..c3076f0 100644 --- a/src/Anubis/Db/Migrator.cs +++ b/src/Anubis/Db/Migrator.cs @@ -121,12 +121,53 @@ public static partial class Migrations if (!status.IsEmpty && backupBeforeMigrating is not null) { - await backupBeforeMigrating(cancellationToken).ConfigureAwait(false); + try + { + await backupBeforeMigrating(cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + throw new SchemaException($"Non sono riuscito a salvare il database prima di aggiornarlo, quindi non l'ho toccato: {ex.Message}", ex); + } } foreach (var migration in pending) { - await db.WriteAsync(async s => + try + { + await ApplyAsync(db, clock, migration, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + if (!await AnswersAsync(db, cancellationToken).ConfigureAwait(false)) + { + throw; + } + + // The database is there and refuses the change: trying again in five seconds would fail the same way. + throw new SchemaException($"L'aggiornamento {migration.Version:D4} del database non è riuscito: {ex.Message} " + + $"Il database è rimasto alla versione {migration.Version - 1}, senza modifiche a metà.", ex); + } + } + + return pending.Count; + } + + private static async Task AnswersAsync(Database db, CancellationToken cancellationToken) + { + try + { + await db.PingAsync(cancellationToken).ConfigureAwait(false); + return true; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + return false; + } + } + + private static Task ApplyAsync(Database db, IClock clock, Migration migration, CancellationToken cancellationToken) => + db.WriteAsync(async s => { if (migration.Version == 1) { @@ -138,11 +179,7 @@ public static partial class Migrations await s.ExecuteAsync(migration.SqlFor(db.Engine), cancellationToken).ConfigureAwait(false); await s.ExecuteAsync($"INSERT INTO {VersionTable} (version, name, checksum, applied_at) VALUES (@v, @n, @c, @t)", cancellationToken, ("v", migration.Version), ("n", migration.Name), ("c", migration.Checksum), ("t", clock.UtcNow)).ConfigureAwait(false); - }, cancellationToken).ConfigureAwait(false); - } - - return pending.Count; - } + }, cancellationToken); public static async Task TableExistsAsync(DbSession session, string table) { @@ -155,4 +192,4 @@ public static partial class Migrations } /// The database schema cannot be used by this version: shown on the error page. -public sealed class SchemaException(string message) : Exception(message); +public sealed class SchemaException(string message, Exception? inner = null) : Exception(message, inner); diff --git a/src/Anubis/Platform/Installation.cs b/src/Anubis/Platform/Installation.cs index 21b8346..88ae990 100644 --- a/src/Anubis/Platform/Installation.cs +++ b/src/Anubis/Platform/Installation.cs @@ -18,8 +18,8 @@ public enum IdentityVerdict /// Empty database and a data folder that belongs to nobody: a new installation was created. Created, - /// The database knows the installation but the data folder lost its file: it was rewritten from the database. - FileRestored, + /// The database belongs to an installation but the data folder has no file saying which: the fingerprints cannot coincide. + MissingFile, /// The database is empty while the data folder belongs to an existing installation. EmptyDatabase, @@ -33,7 +33,7 @@ public enum IdentityVerdict public sealed record IdentityCheck(IdentityVerdict Verdict, InstallationFile? File, InstallationRow? Row) { - public bool CanStart => Verdict is IdentityVerdict.Match or IdentityVerdict.Created or IdentityVerdict.FileRestored; + public bool CanStart => Verdict is IdentityVerdict.Match or IdentityVerdict.Created; } /// @@ -83,15 +83,17 @@ public static class Installation var row = await ReadRowAsync(db, cancellationToken).ConfigureAwait(false); switch (row, file) { + case (null, _) when await HasDataAsync(db, cancellationToken).ConfigureAwait(false): + // Rows without an installation (a dump, an import cut short): never adopted in silence, never "empty". + return new IdentityCheck(IdentityVerdict.DifferentInstallation, file, null); case (null, null): var created = await CreateAsync(db, data, clock, cancellationToken).ConfigureAwait(false); return new IdentityCheck(IdentityVerdict.Created, created.File, created.Row); case (null, not null): return new IdentityCheck(IdentityVerdict.EmptyDatabase, file, null); case (not null, null): - var restored = new InstallationFile(row.Id, row.Fingerprint, row.Engine, row.CreatedAt, row.RenewedAt); - WriteFile(data, restored); - return new IdentityCheck(IdentityVerdict.FileRestored, restored, row); + // An old database put back in front of a new data folder looks exactly like this: nobody can tell, so the user does. + return new IdentityCheck(IdentityVerdict.MissingFile, null, row); default: if (row.Id != file.InstallationId) { @@ -104,6 +106,21 @@ public static class Installation } } + private static readonly string[] _dataTables = ["users", "accounts", "orders", "fills", "cash_ledger"]; + + private static Task HasDataAsync(Database db, CancellationToken cancellationToken) => db.ReadAsync(async s => + { + foreach (var table in _dataTables) + { + if (await s.CountAsync($"SELECT COUNT(*) FROM {table}").ConfigureAwait(false) > 0) + { + return true; + } + } + + return false; + }, cancellationToken); + private static async Task<(InstallationFile File, InstallationRow Row)> CreateAsync(Database db, DataDirectory data, IClock clock, CancellationToken cancellationToken) { var now = clock.UtcNow; @@ -117,11 +134,32 @@ public static class Installation } /// - /// After an import, a restore, a move, or when the user adopts this database: a new fingerprint in the database - /// and in installation.json, the installation id of the data folder kept (or taken from the database when - /// ), and the protected restart switched on (SPEC 15.1). + /// Written inside the import itself (SPEC 15.1): the rows come with the fingerprint they had, often the very one of + /// installation.json. Until gives a new one to both sides the database must not be accepted, + /// so an import cut in half stops at the error page instead of starting on old data. /// - public static async Task RenewAsync(Database db, DataDirectory data, IClock clock, bool adoptDatabaseIdentity, CancellationToken cancellationToken = default) + internal static Task SealAsync(DbSession s, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(s); + return s.ExecuteAsync("UPDATE installation SET fingerprint = @f, protected_restart = @p", cancellationToken, ("f", Ids.NewToken()), ("p", true)); + } + + /// + /// The SQLite file inside a backup gets a fingerprint of its own and the protected restart, so copied by hand over the + /// live file it is recognised as an old copy (SPEC 15.1). The archive next to it keeps the rows as they were. + /// + internal static async Task SealCopyAsync(string sqliteFile, CancellationToken cancellationToken) + { + await using var copy = Database.Open(new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = sqliteFile }, allowCreate: false); + await copy.WriteAsync(s => SealAsync(s, cancellationToken), cancellationToken).ConfigureAwait(false); + } + + /// + /// After an import, a restore, a move, or when the user adopts this database: a new fingerprint in the database and + /// in installation.json and the protected restart switched on (SPEC 15.1). The database keeps its installation id: + /// the orders in its ledger carry that code, and by that code they are found again on the accounts. + /// + public static async Task RenewAsync(Database db, DataDirectory data, IClock clock, string reason, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(db); ArgumentNullException.ThrowIfNull(clock); @@ -129,7 +167,7 @@ public static class Installation var fingerprint = Ids.NewToken(); var file = ReadFile(data); var row = await ReadRowAsync(db, cancellationToken).ConfigureAwait(false); - var id = adoptDatabaseIdentity || file is null ? row?.Id ?? Ids.NewId(clock) : file.InstallationId; + var id = row?.Id ?? file?.InstallationId ?? Ids.NewId(clock); var createdAt = row?.CreatedAt ?? file?.CreatedAt ?? now; var engine = db.Engine.ToString().ToLowerInvariant(); await db.WriteAsync(async s => @@ -141,27 +179,68 @@ public static class Installation // Sessions of the old database do not survive: everyone signs in again. await s.ExecuteAsync("DELETE FROM sessions", cancellationToken).ConfigureAwait(false); - - // SPEC 15.1: after an import, a restore or a move the bot restarts with "Ferma tutto" on, whatever the archive said. - var key = Core.SettingsStore.BotState.Key; - var stopped = new DbJson(JsonSerializer.Serialize("stopped")); - var old = await s.FirstOrDefaultAsync("SELECT value FROM config WHERE key = @k", r => r.Json("value").Text, ("k", key)).ConfigureAwait(false); - if (old != stopped.Text) - { - await s.ExecuteAsync(old is null - ? "INSERT INTO config (id, key, value, created_at, updated_at) VALUES (@id, @k, @v, @t, @t)" - : "UPDATE config SET value = @v, updated_at = @t WHERE key = @k", - cancellationToken, ("id", Ids.NewId(clock)), ("k", key), ("v", stopped), ("t", now)).ConfigureAwait(false); - await s.ExecuteAsync("INSERT INTO config_history (id, key, old_value, new_value, changed_by, created_at) VALUES (@id, @k, @o, @n, @by, @t)", cancellationToken, - ("id", Ids.NewId(clock)), ("k", key), ("o", new DbJson(old ?? JsonSerializer.Serialize(Core.SettingsStore.BotState.Default))), ("n", stopped), - ("by", "ripartenza protetta"), ("t", now)).ConfigureAwait(false); - } + await DisarmAsync(s, clock, cancellationToken).ConfigureAwait(false); + await Trading.Diary.NotifyAsync(s, clock, "protected_restart", + $"{reason}: il database ha una nuova impronta e il bot riparte protetto, con \"Ferma tutto\" acceso. Guarda cosa ho ricostruito e riparti dalla pagina Rischio.", + cancellationToken).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false); var renewed = new InstallationFile(id, fingerprint, engine, createdAt, now); WriteFile(data, renewed); return renewed; } + /// + /// Switches the protected restart on without changing the fingerprint: the accounts hold orders this database never + /// saw, so it is an old copy put back by hand (a file, a dump), whatever its fingerprint says. + /// + public static Task ProtectAsync(Database db, IClock clock, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(db); + ArgumentNullException.ThrowIfNull(clock); + return db.WriteAsync(async s => + { + await s.ExecuteAsync("UPDATE installation SET protected_restart = @p, renewed_at = @r", cancellationToken, ("p", true), ("r", clock.UtcNow)).ConfigureAwait(false); + await DisarmAsync(s, clock, cancellationToken).ConfigureAwait(false); + }, cancellationToken); + } + + /// + /// SPEC 15.1: "Ferma tutto" on, every strategy with real money in exit only until it is confirmed again, and no + /// order planned before the restore still waiting to leave (it may already have left, after the archive). + /// + private static async Task DisarmAsync(DbSession s, IClock clock, CancellationToken cancellationToken) + { + var now = clock.UtcNow; + var key = Core.SettingsStore.BotState.Key; + var stopped = new DbJson(JsonSerializer.Serialize("stopped")); + var old = await s.FirstOrDefaultAsync("SELECT value FROM config WHERE key = @k", r => r.Json("value").Text, ("k", key)).ConfigureAwait(false); + if (old != stopped.Text) + { + await s.ExecuteAsync(old is null + ? "INSERT INTO config (id, key, value, created_at, updated_at) VALUES (@id, @k, @v, @t, @t)" + : "UPDATE config SET value = @v, updated_at = @t WHERE key = @k", + cancellationToken, ("id", Ids.NewId(clock)), ("k", key), ("v", stopped), ("t", now)).ConfigureAwait(false); + await s.ExecuteAsync("INSERT INTO config_history (id, key, old_value, new_value, changed_by, created_at) VALUES (@id, @k, @o, @n, @by, @t)", cancellationToken, + ("id", Ids.NewId(clock)), ("k", key), ("o", new DbJson(old ?? JsonSerializer.Serialize(Core.SettingsStore.BotState.Default))), ("n", stopped), + ("by", "ripartenza protetta"), ("t", now)).ConfigureAwait(false); + } + + foreach (var (strategy, stage) in await s.QueryAsync("SELECT strategy, stage FROM strategy_state WHERE exit_only = @no AND stage IN (@a, @b)", + r => (r.Text("strategy"), r.Text("stage")), ("no", false), ("a", Trading.StrategyStages.Reduced), ("b", Trading.StrategyStages.Real)).ConfigureAwait(false)) + { + await s.ExecuteAsync("INSERT INTO strategy_stage_history (id, strategy, from_stage, to_stage, reason, created_at) VALUES (@id, @s, @f, @f, @r, @t)", cancellationToken, + ("id", Ids.NewId(clock)), ("s", strategy), ("f", stage), ("r", "exit_only_after_restore"), ("t", now)).ConfigureAwait(false); + } + + await s.ExecuteAsync("UPDATE strategy_state SET exit_only = @x, updated_at = @t WHERE stage IN (@a, @b)", cancellationToken, + ("x", true), ("t", now), ("a", Trading.StrategyStages.Reduced), ("b", Trading.StrategyStages.Real)).ConfigureAwait(false); + await s.ExecuteAsync("UPDATE planned_orders SET status = @d, outcome = @o, updated_at = @t WHERE status = @p", cancellationToken, + ("d", Trading.PlannedStates.Dropped), ("o", ProtectedRestartReason), ("t", now), ("p", Trading.PlannedStates.Pending)).ConfigureAwait(false); + } + + /// Why an order planned before a restore did not leave. + public const string ProtectedRestartReason = "protected_restart"; + /// "Comincia da capo": the data folder forgets its installation so an empty database can start a new one. public static void StartOver(DataDirectory data, IClock clock) { @@ -174,7 +253,7 @@ public static class Installation } } - /// The user confirmed the protected restart (phase 9 adds the full procedure of SPEC 15.1). + /// The user confirmed the restart, after the executions were rebuilt from the brokers (SPEC 15.1). public static Task ClearProtectedRestartAsync(Database db, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(db); diff --git a/src/Anubis/Trading/LiveEngine.cs b/src/Anubis/Trading/LiveEngine.cs index 45594a9..83b62a2 100644 --- a/src/Anubis/Trading/LiveEngine.cs +++ b/src/Anubis/Trading/LiveEngine.cs @@ -1145,6 +1145,12 @@ public sealed partial class LiveEngine : IDisposable ArgumentNullException.ThrowIfNull(manager); var canceled = await manager.CancelWorkingAsync(LiveReasons.Restart, cancellationToken: cancellationToken).ConfigureAwait(false); var again = 0; + if (await Platform.Installation.ReadRowAsync(_db, cancellationToken).ConfigureAwait(false) is { ProtectedRestart: true }) + { + // After a restore what was interrupted in the archive may have been finished since: the strategies decide again. + return 0; + } + foreach (var execution in canceled) { var row = await InterruptedAsync(execution, cancellationToken).ConfigureAwait(false); diff --git a/src/Anubis/Trading/OkxTrading.cs b/src/Anubis/Trading/OkxTrading.cs index d434674..8ddd27b 100644 --- a/src/Anubis/Trading/OkxTrading.cs +++ b/src/Anubis/Trading/OkxTrading.cs @@ -175,15 +175,45 @@ public sealed class OkxTrading : IBrokerAccount return stop ? ReadAlgo(data[0]) : ReadOrder(data[0]); } + /// What fills-history covers, with a day of margin (API-NOTES). + public static readonly TimeSpan HistoryReach = TimeSpan.FromDays(89); + + // /trade/fills covers the last three days: half a day less, so a request near the limit misses nothing. + private static readonly TimeSpan _recentReach = TimeSpan.FromHours(60); + + public TimeSpan? FillHistory => HistoryReach; + + /// + /// The recent executions, and before them those of the history: after a long absence or a restore the recent ones + /// alone would leave a hole nobody notices. An execution told by both counts once. + /// public async Task> GetFillsAsync(DateTimeOffset since, CancellationToken cancellationToken) { var fills = new List(); - string? after = null; - for (var page = 0; page < 30; page++) + if (_clock.UtcNow - since > _recentReach) { - var path = "/api/v5/trade/fills?instType=SPOT&limit=100&begin=" + since.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture) + var oldest = _clock.UtcNow - HistoryReach; + await AddFillsAsync(fills, "/api/v5/trade/fills-history", since > oldest ? since : oldest, _read, cancellationToken).ConfigureAwait(false); + } + + await AddFillsAsync(fills, "/api/v5/trade/fills", since, _trade, cancellationToken).ConfigureAwait(false); + return [.. fills.DistinctBy(f => (f.Symbol, f.ExecutionId))]; + } + + private async Task AddFillsAsync(List fills, string endpoint, DateTimeOffset since, RateLimiter limiter, CancellationToken cancellationToken) + { + string? after = null; + for (var page = 0; ; page++) + { + if (page == 300) + { + // Thirty thousand executions: better an error, and the account not ready, than a list cut short in silence. + throw new BrokerException("Troppe esecuzioni da leggere in una volta sola.", retryable: false); + } + + var path = endpoint + "?instType=SPOT&limit=100&begin=" + since.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture) + (after is null ? "" : "&after=" + after); - var data = await CallAsync(HttpMethod.Get, path, null, _trade, cancellationToken).ConfigureAwait(false); + var data = await CallAsync(HttpMethod.Get, path, null, limiter, cancellationToken).ConfigureAwait(false); foreach (var item in data) { var clientId = Text(item, "clOrdId"); @@ -198,13 +228,11 @@ public sealed class OkxTrading : IBrokerAccount if (data.Count < 100) { - break; + return; } after = Text(data[^1], "billId"); } - - return fills; } /// Spot crypto has no dividends; deposits and withdrawals do not change the bot's capital (SPEC 7.1). @@ -403,8 +431,21 @@ public sealed class OkxTrading : IBrokerAccount private async Task AlgoClientIdAsync(string instrument, string orderId, CancellationToken cancellationToken) { - var data = await CallAsync(HttpMethod.Get, $"/api/v5/trade/order?instId={Uri.EscapeDataString(instrument)}&ordId={Uri.EscapeDataString(orderId)}", null, _trade, cancellationToken) - .ConfigureAwait(false); + var path = $"/api/v5/trade/order?instId={Uri.EscapeDataString(instrument)}&ordId={Uri.EscapeDataString(orderId)}"; + var url = new Uri(_options.RestUrl, path); + var answer = await _http.SendAsync(HttpMethod.Get, url, null, b => Sign("GET", path, b), _trade, retry: true, cancellationToken).ConfigureAwait(false); + var (code, _, data) = Envelope(answer); + if (code == "51603") + { + // An order too old for OKX to remember: an execution without a name, which the reconciliation shows. + return null; + } + + if (code != "0") + { + throw _http.Failure(url, answer); + } + return data.Count == 0 ? null : Text(data[0], "algoClOrdId") is { Length: > 0 } id ? id : Text(data[0], "clOrdId"); } diff --git a/src/Anubis/Trading/OrderManager.Protection.cs b/src/Anubis/Trading/OrderManager.Protection.cs index cd7ef7e..5760ee2 100644 --- a/src/Anubis/Trading/OrderManager.Protection.cs +++ b/src/Anubis/Trading/OrderManager.Protection.cs @@ -345,7 +345,13 @@ public sealed partial class OrderManager /// A stable id for the stops of a position: account, instrument and strategy. private Guid StopKey(Guid instrumentId, string strategy) { - var bytes = System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(_account.AccountId.ToString("N") + instrumentId.ToString("N") + strategy)); + var text = _account.AccountId.ToString("N") + instrumentId.ToString("N") + strategy; + if (StopGeneration != 0) + { + text += StopGeneration.ToString(System.Globalization.CultureInfo.InvariantCulture); + } + + var bytes = System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(text)); return new Guid(bytes.AsSpan(0, 16)); } } diff --git a/src/Anubis/Trading/OrderManager.Rebuild.cs b/src/Anubis/Trading/OrderManager.Rebuild.cs new file mode 100644 index 0000000..33029c8 --- /dev/null +++ b/src/Anubis/Trading/OrderManager.Rebuild.cs @@ -0,0 +1,196 @@ +using Anubis.Core; +using Anubis.Db; + +namespace Anubis.Trading; + +/// What the broker knew of this installation and the database did not (SPEC 15.1). +public sealed record RebuildReport(int Orders, int Fills, IReadOnlyList Unclear, bool OnlyRestingStops = false) +{ + public static RebuildReport Nothing { get; } = new(0, 0, []); + + /// + /// The account did something the database never saw: the database is older than the account. Stops that never fired + /// are not enough to say so: the guard may have put them while the engine was off, and lost the note about it. + /// + public bool FoundAnything => (Orders > 0 && !OnlyRestingStops) || Unclear.Count > 0; +} + +/// +/// After a restore the ledger is older than the account (SPEC 15.1): the orders and the executions made after the +/// archive are written back from the broker. The client order id says which strategy and which environment each one +/// belongs to (SPEC 7.2), so nothing has to be guessed. +/// +public sealed partial class OrderManager +{ + /// + /// Tells apart the stops sent before a restore from those sent after it: the sequence numbers start again from + /// what the archive knew, and a name already used on the account must not come back. Zero until the first restore. + /// + public long StopGeneration { get; set; } + + /// + /// Writes back every order of this installation the database does not know, then its executions. Run at every + /// start, before reconciliation: on a database that is up to date it finds nothing and writes nothing. + /// + public async Task RebuildAsync(CancellationToken cancellationToken) + { + if (_account.Environment == TradingEnvironments.Simulation) + { + // The internal simulator lives in the database: it went back in time together with the ledger. + return RebuildReport.Nothing; + } + + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + return await RebuildCoreAsync(cancellationToken).ConfigureAwait(false); + } + finally + { + _gate.Release(); + } + } + + private async Task RebuildCoreAsync(CancellationToken cancellationToken) + { + var since = await RebuildSinceAsync(cancellationToken).ConfigureAwait(false); + var fills = (await _broker.GetFillsAsync(since, cancellationToken).ConfigureAwait(false)).Where(f => IsMine(f.ClientOrderId)).OrderBy(f => f.ExecutedAt).ToList(); + var open = (await _broker.GetOpenOrdersAsync(cancellationToken).ConfigureAwait(false)).Where(o => IsMine(o.ClientOrderId)).ToList(); + var unclear = new List(); + var orders = 0; + var onlyStops = true; + foreach (var clientId in fills.Select(f => f.ClientOrderId).Concat(open.Select(o => o.ClientOrderId)).Distinct(StringComparer.Ordinal)) + { + if (await OrderByClientIdAsync(clientId, cancellationToken).ConfigureAwait(false) is not null) + { + continue; + } + + var parts = ClientOrderIds.Parse(clientId)!; + var own = fills.Where(f => f.ClientOrderId == clientId).ToList(); + var resting = open.FirstOrDefault(o => o.ClientOrderId == clientId); + var symbol = own.FirstOrDefault()?.Symbol ?? resting!.Symbol; + if (await InstrumentBySymbolAsync(symbol, cancellationToken).ConfigureAwait(false) is not { } instrumentId) + { + unclear.Add($"{symbol}: non è nel catalogo, l'ordine {clientId} resta da controllare a mano."); + continue; + } + + var remote = resting ?? await _broker.GetOrderAsync(clientId, symbol, cancellationToken).ConfigureAwait(false); + if (resting is not null && parts.Purpose != OrderPurpose.Stop) + { + // A purchase or a sale nobody follows any more: canceled like every working order at a restart (SPEC 9.4). + await _broker.CancelOrderAsync(clientId, symbol, cancellationToken).ConfigureAwait(false); + remote = await _broker.GetOrderAsync(clientId, symbol, cancellationToken).ConfigureAwait(false) ?? resting with { Status = OrderStatus.Canceled }; + } + + await InsertRebuiltAsync(clientId, parts, instrumentId, remote, own, cancellationToken).ConfigureAwait(false); + onlyStops &= parts.Purpose == OrderPurpose.Stop && own.Count == 0; + orders++; + } + + if (orders > 0) + { + var recorded = await SyncFillsFromAsync(since, cancellationToken).ConfigureAwait(false); + await TakeStopLevelsAsync(open, cancellationToken).ConfigureAwait(false); + foreach (var position in (await _ledger.PositionsAsync(_account.AccountId, cancellationToken).ConfigureAwait(false)).Where(p => p.Quantity > 0m && p.StopPrice is null)) + { + var symbol = (await _instruments(position.InstrumentId, cancellationToken).ConfigureAwait(false))?.Symbol ?? "?"; + unclear.Add($"{symbol}: la posizione ricostruita non ha uno stop, controllala prima di ripartire."); + } + + var message = $"Conto {_account.Name}: sul conto c'erano {orders} ordini che il database non conosceva. Ho ricostruito dal broker {recorded} esecuzioni." + + (unclear.Count == 0 ? "" : " " + string.Join(" ", unclear)) + Beyond(since); + await _db.WriteAsync(s => Diary.NotifyAsync(s, _clock, "ledger_rebuilt", message, cancellationToken), cancellationToken).ConfigureAwait(false); + return new RebuildReport(orders, recorded, unclear, onlyStops); + } + + if (unclear.Count > 0) + { + await _db.WriteAsync(s => Diary.NotifyAsync(s, _clock, "ledger_rebuilt", $"Conto {_account.Name}: {string.Join(" ", unclear)}", cancellationToken), cancellationToken) + .ConfigureAwait(false); + } + + return new RebuildReport(0, 0, unclear); + } + + private string Beyond(DateTimeOffset since) => _broker.FillHistory is { } reach && since < _clock.UtcNow - reach + ? $" Il broker racconta solo gli ultimi {reach.Days} giorni: quello che è successo prima va confrontato a mano." + : ""; + + private bool IsMine(string? clientId) => + ClientOrderIds.Parse(clientId) is { } parts && parts.Installation == _installation && parts.Environment == _account.Environment; + + /// + /// A day before the last execution the database has, or before the birth of the installation when it has none: + /// whatever the archive holds is earlier than that, and an execution read twice is recorded once. + /// + private Task RebuildSinceAsync(CancellationToken cancellationToken) => _db.ReadAsync(async s => + { + var last = (await s.QueryAsync("SELECT executed_at FROM fills WHERE account_id = @a", r => r.Moment("executed_at"), ("a", _account.AccountId)).ConfigureAwait(false)) + .DefaultIfEmpty(DateTimeOffset.MinValue).Max(); + if (last != DateTimeOffset.MinValue) + { + return last.AddDays(-1); + } + + var born = (await s.QueryAsync("SELECT created_at FROM installation", r => r.Moment("created_at")).ConfigureAwait(false)).DefaultIfEmpty(_clock.UtcNow).Min(); + return born.AddDays(-1); + }, cancellationToken); + + private Task InstrumentBySymbolAsync(string symbol, CancellationToken cancellationToken) => _db.ReadAsync(async s => + { + var id = await s.FirstOrDefaultAsync("SELECT id FROM instruments WHERE venue = @v AND symbol = @s", r => r.Id("id"), ("v", _account.Broker), ("s", symbol)).ConfigureAwait(false); + return id == Guid.Empty ? (Guid?)null : id; + }, cancellationToken); + + private async Task InsertRebuiltAsync(string clientId, ClientOrderIdParts parts, Guid instrumentId, BrokerOrder? remote, List own, CancellationToken cancellationToken) + { + var filled = own.Sum(f => f.Quantity); + var side = remote?.Side ?? own[0].Side; + var kind = remote?.Kind ?? (parts.Purpose == OrderPurpose.Stop ? OrderKind.Stop : OrderKind.Limit); + var created = own.Count > 0 ? own[0].ExecutedAt : remote!.UpdatedAt; + var row = new OrderRow(Ids.NewId(_clock), null, instrumentId, parts.Strategy, clientId, side, kind, parts.Purpose, remote?.Quantity ?? filled, remote?.LimitPrice, + remote?.StopPrice, OrderStatus.Created, 0m, null, remote?.StopPrice ?? remote?.LimitPrice, null, remote?.TimeInForce ?? TimeInForce.Gtc, false, created); + await _db.WriteAsync(async s => + { + await InsertOrderAsync(s, row, cancellationToken).ConfigureAwait(false); + await s.ExecuteAsync("UPDATE orders SET broker_order_id = @b, submitted_at = @at, reason = 'rebuilt from the broker' WHERE id = @id", cancellationToken, + ("b", remote?.BrokerOrderId), ("at", created), ("id", row.Id)).ConfigureAwait(false); + if (_account.Environment == TradingEnvironments.Live) + { + // The archive may be older than the promotion: what the bot holds on the real account gets its stops and + // its exits, and nothing else until the user confirms the strategy again. + await s.ExecuteAsync("UPDATE strategy_state SET live_account_id = @a, exit_only = @x, updated_at = @now WHERE strategy = @s AND live_account_id IS NULL", cancellationToken, + ("a", _account.AccountId), ("x", true), ("now", _clock.UtcNow), ("s", parts.Strategy)).ConfigureAwait(false); + } + }, cancellationToken).ConfigureAwait(false); + remote ??= new BrokerOrder(clientId, null, own[0].Symbol, side, kind, filled, OrderStatus.Filled, filled, own[^1].ExecutedAt) + { + AverageFillPrice = DbValues.Money(own.Sum(f => f.Quantity * f.Price) / filled), + }; + await ApplyRemoteAsync(row, remote, "rebuilt from the broker", cancellationToken).ConfigureAwait(false); + } + + /// + /// The stop levels of the positions as they are on the account: a stop raised after the archive never goes back + /// down, and a rebuilt position takes the level its stop has. + /// + private async Task TakeStopLevelsAsync(List open, CancellationToken cancellationToken) + { + foreach (var stop in open.Where(o => o.Kind == OrderKind.Stop && o.Side == OrderSide.Sell && o.StopPrice is not null)) + { + var parts = ClientOrderIds.Parse(stop.ClientOrderId)!; + if (parts.Purpose != OrderPurpose.Stop || await InstrumentBySymbolAsync(stop.Symbol, cancellationToken).ConfigureAwait(false) is not { } instrumentId) + { + continue; + } + + var position = await _ledger.PositionAsync(_account.AccountId, instrumentId, parts.Strategy, cancellationToken).ConfigureAwait(false); + if (position is { Quantity: > 0m } && (position.StopPrice is null || position.StopPrice < stop.StopPrice)) + { + await _ledger.SetStopAsync(_account.AccountId, instrumentId, parts.Strategy, stop.StopPrice, cancellationToken).ConfigureAwait(false); + } + } + } +} diff --git a/src/Anubis/Trading/OrderManager.cs b/src/Anubis/Trading/OrderManager.cs index 7e2412f..05c592c 100644 --- a/src/Anubis/Trading/OrderManager.cs +++ b/src/Anubis/Trading/OrderManager.cs @@ -731,6 +731,11 @@ public sealed partial class OrderManager : IDisposable .DefaultIfEmpty(_clock.UtcNow).Min(); return last == DateTimeOffset.MinValue ? firstOrder.AddMinutes(-10) : last.AddMinutes(-10); }, cancellationToken).ConfigureAwait(false); + return await SyncFillsFromAsync(since, cancellationToken).ConfigureAwait(false); + } + + private async Task SyncFillsFromAsync(DateTimeOffset since, CancellationToken cancellationToken) + { var fills = await _broker.GetFillsAsync(since, cancellationToken).ConfigureAwait(false); var recorded = 0; foreach (var fill in fills.OrderBy(f => f.ExecutedAt)) diff --git a/src/Anubis/Trading/Orders.cs b/src/Anubis/Trading/Orders.cs index 709b552..db66fbb 100644 --- a/src/Anubis/Trading/Orders.cs +++ b/src/Anubis/Trading/Orders.cs @@ -263,6 +263,9 @@ public interface IBrokerAccount /// The order with this client id, or null when the broker never received it. Task GetOrderAsync(string clientOrderId, string symbol, CancellationToken cancellationToken); + /// How far back the broker tells executions; null when it tells them all. + TimeSpan? FillHistory => null; + Task> GetFillsAsync(DateTimeOffset since, CancellationToken cancellationToken); Task> GetCashActivitiesAsync(DateTimeOffset since, CancellationToken cancellationToken); diff --git a/src/Anubis/Trading/ReasonCatalog.cs b/src/Anubis/Trading/ReasonCatalog.cs index 90ab5f6..53a5b1e 100644 --- a/src/Anubis/Trading/ReasonCatalog.cs +++ b/src/Anubis/Trading/ReasonCatalog.cs @@ -94,6 +94,7 @@ public static class ReasonCatalog ["order_in_progress"] = "Un ordine sullo stesso strumento era ancora in corso.", ["nothing_held"] = "Niente da vendere: la posizione era già chiusa.", ["restart"] = "Annullato alla ripartenza del bot: se era ancora dovuto, è stato riproposto.", + ["protected_restart"] = "Deciso prima del ripristino: non parte, potrebbe essere già partito allora.", ["recovered"] = "Recuperato dopo un'assenza.", }; diff --git a/src/Anubis/Trading/Stages.cs b/src/Anubis/Trading/Stages.cs index 85ebb7c..3f59aee 100644 --- a/src/Anubis/Trading/Stages.cs +++ b/src/Anubis/Trading/Stages.cs @@ -98,6 +98,9 @@ public sealed record StrategyStage( _ => LiveAccountId, }; + /// With real money but in exit only: a restore put it there, and only the user takes it out (SPEC 15.1). + public bool WaitsForReconfirmation => ExitOnly && StrategyStages.IsLive(Stage); + /// A strategy with real money keeps running in simulation too: the simulated twin (SPEC 12.3). public bool HasTwin => StrategyStages.IsLive(Stage); } @@ -412,6 +415,41 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent, /// The phrase that confirms more risk while real money is in play. public const string RaisePhrase = "confermo più rischio con soldi veri"; + /// + /// After a restore every strategy with real money is in exit only until the user confirms it again (SPEC 15.1): + /// password and second factor. The counts of the stage go on and no requirement is measured a second time. + /// + public async Task ReconfirmAsync(string strategy, string password, string? code, string by, CancellationToken cancellationToken) + { + if (!consent.AllowLive) + { + throw new LiveConfirmationException(RiskReasons.NoConsent, $"La configurazione d'avvio non consente i soldi veri ({consent.Source})."); + } + + var stage = await GetAsync(strategy, cancellationToken).ConfigureAwait(false) ?? throw new ArgumentException("Strategia sconosciuta: " + strategy, nameof(strategy)); + if (!stage.WaitsForReconfirmation) + { + throw new LiveConfirmationException("stage", "Questa strategia non aspetta una riconferma."); + } + + if (!await reauthenticate(password, code, cancellationToken).ConfigureAwait(false)) + { + throw new LiveConfirmationException("password", "Password o codice a due fattori non corretti."); + } + + var now = clock.UtcNow; + await db.WriteAsync(async s => + { + await s.ExecuteAsync("UPDATE strategy_state SET exit_only = @no, updated_at = @t WHERE strategy = @s", cancellationToken, + ("no", false), ("t", now), ("s", strategy)).ConfigureAwait(false); + await s.ExecuteAsync("INSERT INTO strategy_stage_history (id, strategy, from_stage, to_stage, reason, created_at) VALUES (@id, @s, @f, @f, @r, @t)", cancellationToken, + ("id", Ids.NewId(clock)), ("s", strategy), ("f", stage.Stage), ("r", "reconfirmed_after_restore · " + by), ("t", now)).ConfigureAwait(false); + await LogChangeAsync(s, strategy, stage.Stage + " (da riconfermare)", stage.Stage, by, cancellationToken).ConfigureAwait(false); + await Diary.WriteAsync(s, clock, DiaryKinds.System, "strategy_reconfirmed", + $"{StrategyNames.Label(strategy, withMarket: true)}: riconfermata dopo il ripristino, può di nuovo comprare con soldi veri ({by}).", null, cancellationToken).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); + } + /// True when a strategy, of or of any broker when null, is in reduced or real. public async Task AnyLiveAsync(string? broker, CancellationToken cancellationToken) => (await AllAsync(cancellationToken).ConfigureAwait(false)).Any(s => StrategyStages.IsLive(s.Stage) && (broker is null || StrategyNames.BrokerOf(s.Strategy) == broker)); @@ -485,7 +523,7 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent, { ArgumentNullException.ThrowIfNull(ledger); var released = 0; - foreach (var stage in (await AllAsync(cancellationToken).ConfigureAwait(false)).Where(s => s.ExitOnly && s.LiveAccountId is not null)) + foreach (var stage in (await AllAsync(cancellationToken).ConfigureAwait(false)).Where(s => s.ExitOnly && s.LiveAccountId is not null && !s.WaitsForReconfirmation)) { var open = (await ledger.PositionsAsync(stage.LiveAccountId, cancellationToken).ConfigureAwait(false)).Any(p => p.Strategy == stage.Strategy && p.Quantity > 0m); if (open) diff --git a/src/Anubis/Trading/TradingService.cs b/src/Anubis/Trading/TradingService.cs index a3c0ef4..8a1ea84 100644 --- a/src/Anubis/Trading/TradingService.cs +++ b/src/Anubis/Trading/TradingService.cs @@ -301,6 +301,7 @@ public sealed partial class TradingService : IDisposable await RefreshSpecsAsync(cancellationToken).ConfigureAwait(false); await RefreshLimitsAsync(cancellationToken).ConfigureAwait(false); Guard?.Step("connessione ai broker"); + var generation = await StopGenerationAsync(cancellationToken).ConfigureAwait(false); var hang = Fault == GuardChannel.HangMidSale; foreach (var account in accounts) { @@ -313,6 +314,7 @@ public sealed partial class TradingService : IDisposable _managers[account.AccountId] = new OrderManager(_db, _clock, Ledger, broker, account, InstallationCode, (id, ct) => _catalog.GetAsync(id, ct), Quotes.GetAsync) { + StopGeneration = generation, ConfirmPrice = Quotes.ConfirmAsync, MarketOpen = MarketOpenAsync, PendingSplit = (instrument, ct) => PendingSplitAsync(account.AccountId, instrument, ct), @@ -402,6 +404,8 @@ public sealed partial class TradingService : IDisposable else { await Reconciler.CheckKeyAsync(manager, cancellationToken).ConfigureAwait(false); + Guard?.Step("esecuzioni dal broker " + name); + await RebuildAsync(manager, cancellationToken).ConfigureAwait(false); } Guard?.Step("riconciliazione " + name); @@ -417,6 +421,52 @@ public sealed partial class TradingService : IDisposable } } + /// + /// SPEC 15.1: what the account did after the archive is written back before anything compares ledger and account. + /// Finding something on a database nobody declared restored means it is an old copy put back by hand, or a dump: + /// the protected restart starts here, as it would have after an import. + /// + internal async Task RebuildAsync(OrderManager manager, CancellationToken cancellationToken) + { + var report = await manager.RebuildAsync(cancellationToken).ConfigureAwait(false); + if (!report.FoundAnything) + { + return; + } + + if (await Platform.Installation.ReadRowAsync(_db, cancellationToken).ConfigureAwait(false) is { ProtectedRestart: true } + && await _db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT value FROM config WHERE key = @k", r => r.Json("value").Text, ("k", SettingsStore.BotState.Key)), cancellationToken) + .ConfigureAwait(false) == "\"stopped\"") + { + return; + } + + await Platform.Installation.ProtectAsync(_db, _clock, cancellationToken).ConfigureAwait(false); + var generation = await StopGenerationAsync(cancellationToken).ConfigureAwait(false); + foreach (var each in _managers.Values) + { + each.StopGeneration = generation; + } + + await _db.WriteAsync(s => Diary.NotifyAsync(s, _clock, "protected_restart", + $"Sul conto {manager.Account.Name} ci sono ordini che questo database non conosce: è una copia più vecchia del conto. Ho fermato tutto: controlla e riparti dalla pagina Rischio.", + cancellationToken), cancellationToken).ConfigureAwait(false); + } + + /// Zero until the first restore, then the moment of the last one. + private async Task StopGenerationAsync(CancellationToken cancellationToken) => + await Platform.Installation.ReadRowAsync(_db, cancellationToken).ConfigureAwait(false) is { } row && row.RenewedAt != row.CreatedAt ? row.RenewedAt.UtcTicks : 0; + + /// + /// The accounts whose executions after the archive are not rebuilt yet: until then the user cannot confirm the + /// protected restart (SPEC 15.1). The internal simulator has nothing to rebuild and holds nobody back. + /// + public IReadOnlyList AccountsToRebuild => + [.. _managers.Values.Where(m => m.Account.Environment != TradingEnvironments.Simulation && !AccountReady(m.Account.AccountId)).Select(m => m.Account.Name).Order(StringComparer.Ordinal)]; + + /// The startup of SPEC 9.4 went through: every account with keys was tried at least once. + public bool Started => _started; + /// /// The stops the guard put back while the engine was stopped become the engine's own, before anything compares /// them. A note goes in the diary and is deleted only when every stop it placed is adopted, for every account: a diff --git a/tests/Anubis.Tests/ArchiveTests.cs b/tests/Anubis.Tests/ArchiveTests.cs index 01454e8..b108ee5 100644 --- a/tests/Anubis.Tests/ArchiveTests.cs +++ b/tests/Anubis.Tests/ArchiveTests.cs @@ -117,7 +117,7 @@ public sealed class ArchiveTests File.WriteAllLines(cash, lines.Skip(1)); await using var target = await TestDb.CreateAsync().ConfigureAwait(false); await Assert.ThrowsAsync(() => Archive.ImportAsync(target.Db, Path.Combine(folder, "a"), _clock)).ConfigureAwait(false); - Assert.AreEqual(0L, (await Archive.CountsAsync(target.Db).ConfigureAwait(false))["accounts"], "un'importazione fallita non lascia righe"); + Assert.IsEmpty(await Archive.CountsAsync(target.Db).ConfigureAwait(false), "un archivio guasto non lascia nemmeno lo schema"); await Assert.ThrowsAsync(() => Archive.ExportAsync(source.Db, Path.Combine(folder, "a"), _clock)).ConfigureAwait(false); } @@ -140,7 +140,7 @@ public sealed class ArchiveTests var backups = new Backups(new DataDirectory(folder), clock); for (var i = 0; i < 16; i++) { - await backups.TakeAsync(test.Db, i == 0 ? "prima-della-migrazione" : "notturno").ConfigureAwait(false); + await backups.TakeAsync(test.Db, "notturno").ConfigureAwait(false); clock.Advance(TimeSpan.FromDays(1)); } @@ -180,7 +180,176 @@ public sealed class ArchiveTests await test.Db.WriteAsync(s => s.ExecuteAsync($"DELETE FROM {Migrations.VersionTable} WHERE version = @v", ("v", Migrations.Latest))).ConfigureAwait(false); if (Migrations.Latest > 1) { - await Assert.ThrowsAsync(() => Migrations.MigrateAsync(test.Db, _clock, _ => throw new IOException("disco pieno"), CancellationToken.None)).ConfigureAwait(false); + await Assert.ThrowsAsync(() => Migrations.MigrateAsync(test.Db, _clock, _ => throw new IOException("disco pieno"), CancellationToken.None)).ConfigureAwait(false); } } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task ADamagedArchiveLeavesTheDatabaseUntouchedAndTheGoodOneGoesInAfterwards() + { + await using var source = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + await SeedAsync(source.Db).ConfigureAwait(false); + var folder = TempFolder.Create("archive-retry"); + try + { + var good = Path.Combine(folder, "a"); + await Archive.ExportAsync(source.Db, good, _clock).ConfigureAwait(false); + await using var target = await TestDb.CreateAsync().ConfigureAwait(false); + + async Task RefusedAsync(string file, Func damage) + { + var path = Path.Combine(good, file); + var before = await File.ReadAllTextAsync(path).ConfigureAwait(false); + await File.WriteAllTextAsync(path, damage(before)).ConfigureAwait(false); + try + { + await Archive.ImportAsync(target.Db, good, _clock).ConfigureAwait(false); + Assert.Fail("Accepted: " + file); + } + catch (Exception ex) when (Anubis.Server.Forms.IsArchiveProblem(ex)) + { + } + + await File.WriteAllTextAsync(path, before).ConfigureAwait(false); + Assert.IsTrue((await Migrations.StatusAsync(target.Db, CancellationToken.None).ConfigureAwait(false)).IsEmpty, "Not even the schema: " + file); + } + + // A row less, a number that is not one, a total that changed, a row that is not an object. + await RefusedAsync("cash_ledger.jsonl", t => t[(t.IndexOf('\n', StringComparison.Ordinal) + 1)..]).ConfigureAwait(false); + await RefusedAsync("fills.jsonl", t => t.Replace("68950", "novanta", StringComparison.Ordinal)).ConfigureAwait(false); + await RefusedAsync("fills.jsonl", t => t.Replace("0.0182", "0.0183", StringComparison.Ordinal).Replace("-0.0183", "-0.0182", StringComparison.Ordinal)).ConfigureAwait(false); + await RefusedAsync("accounts.jsonl", _ => "[]\n").ConfigureAwait(false); + + // An index that points outside its folder, or names a table twice. + await RefusedAsync(Archive.IndexFile, t => t.Replace("\"fills.jsonl\"", "\"../fills.jsonl\"", StringComparison.Ordinal)).ConfigureAwait(false); + await RefusedAsync(Archive.IndexFile, t => t.Replace("\"fills\"", "\"accounts\"", StringComparison.Ordinal)).ConfigureAwait(false); + + await Archive.ImportAsync(target.Db, good, _clock).ConfigureAwait(false); + Assert.AreEqual(2L, (await Archive.CountsAsync(target.Db).ConfigureAwait(false))["fills"]); + } + finally + { + TempFolder.Delete(folder); + } + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task AnOlderArchiveGoesInAfterAnImportThatStoppedHalfWay() + { + await using var old = await TestDb.CreateAsync().ConfigureAwait(false); + await Migrations.MigrateAsync(old.Db, _clock, null, CancellationToken.None, upTo: 8).ConfigureAwait(false); + var folder = TempFolder.Create("archive-old"); + try + { + await Archive.ExportAsync(old.Db, Path.Combine(folder, "a"), _clock).ConfigureAwait(false); + + // The first attempt created the schema of the archive and stopped there (power lost). + await using var target = await TestDb.CreateAsync().ConfigureAwait(false); + await Migrations.MigrateAsync(target.Db, _clock, null, CancellationToken.None, upTo: 5).ConfigureAwait(false); + await Archive.ImportAsync(target.Db, Path.Combine(folder, "a"), _clock).ConfigureAwait(false); + Assert.AreEqual(Migrations.Latest, (await Migrations.StatusAsync(target.Db, CancellationToken.None).ConfigureAwait(false)).Current); + } + finally + { + TempFolder.Delete(folder); + } + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task AnImportIsSealedUntilTheInstallationIsRenewedAndSoIsTheSqliteCopy() + { + await using var source = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + var folder = TempFolder.Create("seal"); + try + { + var data = new DataDirectory(Path.Combine(folder, "data")); + await Installation.CheckAsync(source.Db, data, _clock).ConfigureAwait(false); + var backup = await new Backups(data, _clock).TakeAsync(source.Db, "a-mano").ConfigureAwait(false); + + // The same fingerprint as installation.json is in the archive: without the seal the import would be accepted as it is. + await using var target = await TestDb.CreateAsync().ConfigureAwait(false); + await Archive.ImportAsync(target.Db, Path.Combine(backup.Folder, Backups.ArchiveFolder), _clock).ConfigureAwait(false); + Assert.AreEqual(IdentityVerdict.StaleDatabase, (await Installation.CheckAsync(target.Db, data, _clock).ConfigureAwait(false)).Verdict); + + if (backup.HasSqliteCopy) + { + var copy = new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = Path.Combine(backup.Folder, Backups.SqliteCopy) }; + await using var byHand = Database.Open(copy, allowCreate: false); + Assert.AreEqual(IdentityVerdict.StaleDatabase, (await Installation.CheckAsync(byHand, data, _clock).ConfigureAwait(false)).Verdict); + Assert.IsTrue((await Installation.ReadRowAsync(byHand).ConfigureAwait(false))!.ProtectedRestart); + } + + // Renewed, the new one is accepted and the source becomes the old copy. + await Installation.RenewAsync(target.Db, data, _clock, "prova").ConfigureAwait(false); + Assert.AreEqual(IdentityVerdict.Match, (await Installation.CheckAsync(target.Db, data, _clock).ConfigureAwait(false)).Verdict); + Assert.AreEqual(IdentityVerdict.StaleDatabase, (await Installation.CheckAsync(source.Db, data, _clock).ConfigureAwait(false)).Verdict); + Assert.AreEqual(Installation.ReadFile(data)!.InstallationId, (await Installation.ReadRowAsync(source.Db).ConfigureAwait(false))!.Id, "The orders of the ledger keep their installation."); + + // Rows without an installation are never taken for an empty database. + await SeedAsync(target.Db).ConfigureAwait(false); + await target.Db.WriteAsync(s => s.ExecuteAsync("DELETE FROM installation")).ConfigureAwait(false); + Assert.AreEqual(IdentityVerdict.DifferentInstallation, (await Installation.CheckAsync(target.Db, data, _clock).ConfigureAwait(false)).Verdict); + } + finally + { + TempFolder.Delete(folder); + } + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task ASeriesOfBackupsOfOneKindNeverPushesOutTheNightlyOnes() + { + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + var folder = TempFolder.Create("kinds"); + try + { + var clock = new ManualClock(_clock.UtcNow); + var data = new DataDirectory(folder); + var backups = new Backups(data, clock); + await backups.TakeAsync(test.Db, "notturno").ConfigureAwait(false); + var left = Directory.CreateDirectory(Path.Combine(data.Backups, "20260901-010101-notturno.partial")); + left.LastWriteTimeUtc = clock.UtcNow.UtcDateTime.AddDays(-3); + for (var i = 0; i < Backups.Keep + 3; i++) + { + // The same second twice: the second one takes a number. + await backups.TakeAsync(test.Db, Backups.BeforeMigration).ConfigureAwait(false); + clock.Advance(TimeSpan.FromSeconds(i % 2)); + } + + Assert.HasCount(1, backups.List().Where(b => b.Reason == "notturno").ToList()); + Assert.HasCount(Backups.Keep, backups.List().Where(b => b.Reason.StartsWith(Backups.BeforeMigration, StringComparison.Ordinal)).ToList()); + Assert.IsFalse(Directory.Exists(left.FullName), "What a power failure left is cleaned."); + } + finally + { + TempFolder.Delete(folder); + } + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task AMigrationThatFailsIsASchemaProblemAndLeavesTheVersionBefore() + { + await using var test = await TestDb.CreateAsync().ConfigureAwait(false); + await Migrations.MigrateAsync(test.Db, _clock, null, CancellationToken.None, upTo: 12).ConfigureAwait(false); + await test.Db.WriteAsync(s => s.ExecuteAsync("CREATE TABLE cost_estimates (x INTEGER)")).ConfigureAwait(false); + var backups = 0; + var error = await Assert.ThrowsExactlyAsync(() => Migrations.MigrateAsync(test.Db, _clock, _ => + { + backups++; + return Task.CompletedTask; + }, CancellationToken.None)).ConfigureAwait(false); + Assert.Contains("0013", error.Message); + Assert.AreEqual(1, backups); + Assert.AreEqual(12, (await Migrations.StatusAsync(test.Db, CancellationToken.None).ConfigureAwait(false)).Current); + + // Without room for the backup nothing is migrated. + var full = await Assert.ThrowsExactlyAsync(() => Migrations.MigrateAsync(test.Db, _clock, _ => throw new IOException("disco pieno"), CancellationToken.None)) + .ConfigureAwait(false); + Assert.Contains("disco pieno", full.Message); + } } diff --git a/tests/Anubis.Tests/LiveEngineTests.cs b/tests/Anubis.Tests/LiveEngineTests.cs index 5c02e28..96764b1 100644 --- a/tests/Anubis.Tests/LiveEngineTests.cs +++ b/tests/Anubis.Tests/LiveEngineTests.cs @@ -175,4 +175,44 @@ public sealed class LiveEngineTests Assert.IsLessThan(live.Instruments[symbol].Spec.LotSize ?? 0m, Math.Abs(quantity - ledger[symbol]), symbol); } } + + /// + /// A purchase was working when the process stopped. Normally it is proposed again; after a restore (SPEC 15.1) the + /// archive may be older than the account, so nothing is proposed: the strategies decide again. + /// + [TestMethod] + [TestCategory(Category.Integration)] + [DataRow(false)] + [DataRow(true)] + public async Task AfterARestoreAnInterruptedPurchaseIsNotProposedAgain(bool restored) + { + var last = LiveFrom.AddDays(120); + await using var live = await LiveRig.CreateAsync(LiveFrom, last).ConfigureAwait(false); + var found = false; + for (var day = LiveFrom; day <= last && !found; day = day.AddDays(1)) + { + await live.DayAsync(day, async _ => + { + if (found || await live.WorkingOrdersAsync().ConfigureAwait(false) == 0) + { + return; + } + + found = true; + await live.Rig.Db.WriteAsync(async s => + { + await s.ExecuteAsync("DELETE FROM installation").ConfigureAwait(false); + await s.ExecuteAsync("INSERT INTO installation (id, fingerprint, engine, protected_restart, created_at, renewed_at) VALUES (@id, @f, @e, @p, @now, @now)", CancellationToken.None, ("e", "sqlite"), + ("id", Guid.NewGuid()), ("f", Guid.NewGuid()), ("p", restored), ("now", live.Rig.Clock.UtcNow)).ConfigureAwait(false); + }).ConfigureAwait(false); + var again = await live.Engine.ResumeAsync(live.Manager, CancellationToken.None).ConfigureAwait(false); + Assert.AreEqual(restored ? 0 : 1, Math.Min(again, 1)); + Assert.AreEqual(0, await live.WorkingOrdersAsync().ConfigureAwait(false), "What was working is canceled either way."); + Assert.HasCount(restored ? 0 : again, await live.Rig.QueryAsync("SELECT id FROM planned_orders WHERE status = @s AND execution_id IS NULL", r => r.Id("id"), + ("s", PlannedStates.Pending)).ConfigureAwait(false)); + }).ConfigureAwait(false); + } + + Assert.IsTrue(found, "A purchase must have been working."); + } } diff --git a/tests/Anubis.Tests/OkxHistoryTests.cs b/tests/Anubis.Tests/OkxHistoryTests.cs new file mode 100644 index 0000000..b3699e7 --- /dev/null +++ b/tests/Anubis.Tests/OkxHistoryTests.cs @@ -0,0 +1,74 @@ +using System.Globalization; +using Anubis.Brokers; +using Anubis.Core; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// The executions of OKX after a long absence or a restore: recent and history, each counted once (issue #69). +[TestClass] +[TestCategory(Category.Unit)] +public sealed class OkxHistoryTests +{ + private static readonly DateTimeOffset _now = TradingRig.Start; + + private static string Fill(string trade, DateTimeOffset at, string client = "ANUtrnd00000000aE1") => + "{\"side\":\"buy\",\"fillSz\":\"0.01\",\"fillPx\":\"50000\",\"fee\":\"-0.5\",\"feeCcy\":\"EUR\",\"ordId\":\"1" + trade + "\",\"instId\":\"BTC-EUR\",\"instType\":\"SPOT\",\"clOrdId\":\"" + client + + "\",\"billId\":\"b" + trade + "\",\"tradeId\":\"" + trade + "\",\"fillTime\":\"" + Ms(at) + "\",\"ts\":\"" + Ms(at) + "\"}"; + + private static string Ms(DateTimeOffset at) => at.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture); + + private static string Envelope(IEnumerable items) => "{\"code\":\"0\",\"msg\":\"\",\"data\":[" + string.Join(',', items) + "]}"; + + private static OkxTrading Adapter(FakeHttp http) => + new(http.Client(), new ManualClock(_now), new OkxCredentials("doc-key", "doc-secret", "doc-pass"), new OkxTradingOptions { Environment = TradingEnvironments.Demo }, + TradingConsent.None); + + private static FakeHttp Http(IReadOnlyList history, IReadOnlyList recent) => new FakeHttp() + .On(u => u.AbsolutePath == "/api/v5/trade/fills-history", r => FakeHttp.Respond(Envelope( + r.RequestUri!.Query.Contains("after=", StringComparison.Ordinal) ? history.Skip(100) : history.Take(100)))) + .On(u => u.AbsolutePath == "/api/v5/trade/fills", _ => FakeHttp.Respond(Envelope(recent))) + .On(u => u.AbsolutePath == "/api/v5/trade/order", _ => FakeHttp.Respond("{\"code\":\"51603\",\"msg\":\"Order does not exist\",\"data\":[]}")); + + [TestMethod] + public async Task AfterALongAbsenceTheHistoryIsReadTooAndEachExecutionCountsOnce() + { + var since = _now.AddDays(-20); + string[] history = [.. Enumerable.Range(0, 150).Select(i => Fill((1000 + i).ToString(CultureInfo.InvariantCulture), _now.AddDays(-5).AddMinutes(-i)))]; + var http = Http(history, [Fill("2000", _now.AddHours(-1)), Fill("1000", _now.AddDays(-5))]); + var fills = await Adapter(http).GetFillsAsync(since, CancellationToken.None); + + Assert.HasCount(151, fills); + Assert.HasCount(151, fills.Select(f => f.ExecutionId).Distinct().ToList()); + var asked = http.Urls.Where(u => u.AbsolutePath.EndsWith("/fills-history", StringComparison.Ordinal)).ToList(); + Assert.HasCount(2, asked, "Two pages of history."); + StringAssert.Contains(asked[0].Query, "instType=SPOT"); + StringAssert.Contains(asked[0].Query, "begin=" + Ms(since)); + StringAssert.Contains(asked[1].Query, "after=b1099"); + } + + [TestMethod] + public async Task TheRecentOnesAloneAreEnoughForTheEverydayReading() + { + var http = Http([], [Fill("2000", _now.AddHours(-1))]); + Assert.HasCount(1, await Adapter(http).GetFillsAsync(_now.AddHours(-48), CancellationToken.None)); + Assert.IsTrue(http.Urls.All(u => u.AbsolutePath == "/api/v5/trade/fills")); + } + + [TestMethod] + public async Task TheHistoryIsAskedOnlyAsFarAsOkxKeepsIt() + { + var http = Http([], []); + var adapter = Adapter(http); + await adapter.GetFillsAsync(_now.AddDays(-400), CancellationToken.None); + StringAssert.Contains(http.Urls.First().Query, "begin=" + Ms(_now - OkxTrading.HistoryReach)); + Assert.AreEqual(OkxTrading.HistoryReach, adapter.FillHistory); + } + + [TestMethod] + public async Task AnOldExecutionWhoseOrderOkxForgotIsReadWithoutAName() + { + var http = Http([Fill("1000", _now.AddDays(-10), client: "")], []); + Assert.AreEqual("", (await Adapter(http).GetFillsAsync(_now.AddDays(-20), CancellationToken.None)).Single().ClientOrderId); + } +} diff --git a/tests/Anubis.Tests/RestoreServerTests.cs b/tests/Anubis.Tests/RestoreServerTests.cs new file mode 100644 index 0000000..32bc2b1 --- /dev/null +++ b/tests/Anubis.Tests/RestoreServerTests.cs @@ -0,0 +1,271 @@ +using System.Net; +using Anubis.Access; +using Anubis.Core; +using Anubis.Db; +using Anubis.Platform; +using Anubis.Server; + +namespace Anubis.Tests; + +/// Restore, old copies, failed migrations and a changed secret key as the user meets them (issue #69, SPEC 9.4, 15.1). +[TestClass] +[TestCategory(Category.Integration)] +public sealed class RestoreServerTests +{ + /// The database of the data folder is set aside and an empty one takes its place; the answer is how to put it back. + private static async Task<(Func PutBack, Func PutNew, TestDb? Empty)> EmptyDatabaseAsync(Dictionary env, string data, TestDb? postgres) + { + if (postgres is not null) + { + var empty = await TestDb.CreateAsync(DbEngine.Postgres); + ServerHarness.UsePostgres(env, empty); + return (() => + { + ServerHarness.UsePostgres(env, postgres); + return Task.CompletedTask; + }, () => + { + ServerHarness.UsePostgres(env, empty); + return Task.CompletedTask; + }, empty); + } + + var file = new DataDirectory(data).SqliteFile; + var old = data + "-vecchio.sqlite3"; + var fresh = data + "-nuovo.sqlite3"; + void Take(string from, string to) + { + Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools(); + File.Copy(from, to, overwrite: true); + foreach (var f in Directory.EnumerateFiles(Path.GetDirectoryName(file)!).Where(f => f.StartsWith(file, StringComparison.OrdinalIgnoreCase))) + { + File.Delete(f); + } + } + + Take(file, old); + await File.WriteAllBytesAsync(file, []); + return (() => + { + Take(file, fresh); + File.Copy(old, file); + return Task.CompletedTask; + }, () => + { + Take(file, old); + File.Copy(fresh, file); + return Task.CompletedTask; + }, null); + } + + [TestMethod] + public async Task AfterARestoreTheOldDatabaseIsRefusedAndTheNewOneWaitsForTheUser() + { + var (env, postgres) = await ServerHarness.DockerOnEngineAsync(); + await using var engine = postgres; + var data = TempFolder.Create("protected"); + string password; + await using (var first = await ServerHarness.StartAsync("docker", env, dataDir: data)) + { + password = await first.SignInFirstTimeAsync(); + using var saved = await first.PostFormAsync("/impostazioni", "/azioni/salvataggio"); + } + + var backup = new Backups(new DataDirectory(data), SystemClock.Instance).List().Single(b => b.Reason == "a-mano"); + var (putBack, putNew, empty) = await EmptyDatabaseAsync(env, data, postgres); + await using var second = empty; + await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data, waitReady: false)) + { + await server.WaitForAsync(HostMode.IdentityProblem); + using (var restore = await server.PostFormAsync("/", "/azioni/servizio/ripristina", ("password", ServerHarness.AdminPassword), ("salvataggio", backup.Name))) + { + Assert.AreEqual("/", ServerHarness.Location(restore)); + } + + // Without the trading engine nothing can be rebuilt: the restart waits. + await server.WaitForAsync(HostMode.Ready); + using (var signIn = await server.PostFormAsync("/accesso", "/azioni/accesso", ("password", password))) + { + Assert.AreEqual("/", ServerHarness.Location(signIn)); + } + + StringAssert.Contains(await server.TextAsync("/"), "Ripartenza protetta"); + using (var early = await server.PostFormAsync("/rischio", "/azioni/bot/riattiva")) + { + Assert.AreEqual("stopped", (await server.Host.Services!.Settings.GetAsync(SettingsStore.BotState.Key)).Value); + } + + Assert.HasCount(1, await server.Host.Services!.Db.ReadAsync(s => s.QueryAsync("SELECT message FROM journal WHERE code = 'protected_restart'", r => r.Text("message")))); + } + + // The database of before the restore comes back, by mistake: same installation, older fingerprint, engine off. + await putBack(); + await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data, waitReady: false)) + { + await server.WaitForAsync(HostMode.IdentityProblem); + Assert.AreEqual(IdentityVerdict.StaleDatabase, server.Host.Status.Identity!.Verdict); + StringAssert.Contains(await server.TextAsync("/"), "una copia più vecchia"); + using var health = await server.GetAsync("/health"); + Assert.AreEqual(HttpStatusCode.ServiceUnavailable, health.StatusCode); + Assert.IsNull(server.Host.Services); + } + + // The right one: protected until the user confirms, then as before. + await putNew(); + await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data, trading: true)) + { + using (var signIn = await server.PostFormAsync("/accesso", "/azioni/accesso", ("password", password))) + { + Assert.AreEqual("/", ServerHarness.Location(signIn)); + } + + for (var i = 0; i < 300 && server.Host.Services!.Trading is not { Started: true }; i++) + { + await Task.Delay(100); + } + + StringAssert.Contains(await server.TextAsync("/rischio"), "Sui conti non c'era niente che il database non conoscesse già"); + using (var go = await server.PostFormAsync("/rischio", "/azioni/bot/riattiva")) + { + Assert.AreEqual(HttpStatusCode.Redirect, go.StatusCode); + } + + Assert.AreEqual("active", (await server.Host.Services!.Settings.GetAsync(SettingsStore.BotState.Key)).Value); + Assert.IsFalse((await Installation.ReadRowAsync(server.Host.Services.Db))!.ProtectedRestart); + Assert.IsFalse((await server.TextAsync("/rischio")).Contains("Ripartenza protetta", StringComparison.Ordinal)); + } + + TempFolder.Delete(data); + foreach (var left in new[] { data + "-vecchio.sqlite3", data + "-nuovo.sqlite3" }) + { + File.Delete(left); + } + } + + [TestMethod] + public async Task AFailedMigrationKeepsTheEngineOffAndTakesOneBackup() + { + var (env, postgres) = await ServerHarness.DockerOnEngineAsync(); + await using var engine = postgres; + var data = TempFolder.Create("migration"); + var directory = new DataDirectory(data); + directory.Ensure(); + var settings = postgres?.Settings ?? new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = directory.SqliteFile }; + await using (var db = Database.Open(settings)) + { + await Migrations.MigrateAsync(db, SystemClock.Instance, null, CancellationToken.None, upTo: 12); + await Installation.CheckAsync(db, directory, SystemClock.Instance); + await db.WriteAsync(s => s.ExecuteAsync("CREATE TABLE cost_estimates (x INTEGER)")); + } + + await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data, waitReady: false)) + { + await server.WaitForAsync(HostMode.SchemaProblem); + await Task.Delay(1000); + Assert.HasCount(1, new Backups(directory, SystemClock.Instance).List(), "One backup, however long the page stays open."); + var html = await server.TextAsync("/"); + StringAssert.Contains(html, "0013"); + StringAssert.Contains(html, "prima-della-migrazione"); + + using (var wrong = await server.PostFormAsync("/", "/azioni/servizio/riprova", ("password", "wrong-password-123"))) + { + StringAssert.Contains(ServerHarness.Location(wrong), "errore=password"); + } + + await using (var db = Database.Open(settings)) + { + await db.WriteAsync(s => s.ExecuteAsync("DROP TABLE cost_estimates")); + } + + using (var again = await server.PostFormAsync("/", "/azioni/servizio/riprova", ("password", ServerHarness.AdminPassword))) + { + Assert.AreEqual("/", ServerHarness.Location(again)); + } + + await server.WaitForAsync(HostMode.Ready); + } + + TempFolder.Delete(data); + } + + [TestMethod] + public async Task WithAnotherSecretKeyNothingCrashesAndTheAccessIsResetFromTheCommandLine() + { + var (env, postgres) = await ServerHarness.DockerOnEngineAsync(); + await using var engine = postgres; + var data = TempFolder.Create("key"); + string password; + await using (var first = await ServerHarness.StartAsync("docker", env, dataDir: data)) + { + password = await first.SignInFirstTimeAsync(); + var services = first.Host.Services!; + var secret = Totp.NewSecret(); + var user = (await services.Access.GetUserAsync())!; + Assert.IsTrue(await services.Access.EnableSecondFactorAsync(user.Id, secret, Totp.Compute(secret, DateTimeOffset.UtcNow))); + await services.Secrets.SetAsync("FINNHUB_API_KEY", "chiave-di-prova-1", "test"); + } + + env["ANUBIS_SECRET_KEY"] = "another-secret-key-0123456789-abcdefghij"; + await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data)) + { + using (var refused = await server.PostFormAsync("/accesso", "/azioni/accesso", ("password", password), ("codice", "123456"))) + { + Assert.AreEqual("/accesso?errore=chiave", ServerHarness.Location(refused)); + } + + StringAssert.Contains(await server.TextAsync("/accesso?errore=chiave"), "ANUBIS_SECRET_KEY"); + using var output = new StringWriter(); + Assert.AreEqual(0, await AccessCommand.RunAsync(["reset", "--platform", "docker", "--data-dir", data], output, env, iterations: 1000), output.ToString()); + var temporary = output.ToString().Split("Password provvisoria: ")[1].Split('\n')[0].Trim(); + using (var signIn = await server.PostFormAsync("/accesso", "/azioni/accesso", ("password", temporary))) + { + Assert.AreEqual("/", ServerHarness.Location(signIn)); + } + + const string chosen = "chosen-test-pass-3"; + using (var change = await server.PostFormAsync("/primo-accesso", "/azioni/primo-accesso", ("attuale", temporary), ("nuova", chosen), ("conferma", chosen))) + { + Assert.AreEqual("/?ok=password", ServerHarness.Location(change)); + } + + StringAssert.Contains(await server.TextAsync("/impostazioni"), "Non si legge più: la chiave dei segreti è cambiata"); + } + + TempFolder.Delete(data); + } + + [TestMethod] + public async Task TheCommandLineImportsIntoANewSqliteFileOfTheSameFolder() + { + var data = TempFolder.Create("cli-same"); + var env = ServerHarness.DockerSqlite(); + await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data)) + { + await server.SignInFirstTimeAsync(); + } + + Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools(); + var root = TempFolder.Create("cli-same-archive"); + var archive = Path.Combine(root, "archivio"); + using var output = new StringWriter(); + Assert.AreEqual(0, await DatabaseCommand.RunAsync(["export", archive, "--platform", "docker", "--data-dir", data], output, env), output.ToString()); + var directory = new DataDirectory(data); + foreach (var f in Directory.EnumerateFiles(Path.GetDirectoryName(directory.SqliteFile)!)) + { + File.Delete(f); + } + + // A wrong folder creates nothing. + Assert.AreEqual(1, await DatabaseCommand.RunAsync(["import", root, "--platform", "docker", "--data-dir", data], output, env)); + Assert.IsFalse(File.Exists(directory.SqliteFile)); + + Assert.AreEqual(0, await DatabaseCommand.RunAsync(["import", archive, "--platform", "docker", "--data-dir", data], output, env), output.ToString()); + await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data)) + { + Assert.IsTrue((await Installation.ReadRowAsync(server.Host.Services!.Db))!.ProtectedRestart); + } + + TempFolder.Delete(data); + TempFolder.Delete(root); + } +} diff --git a/tests/Anubis.Tests/RestoreTests.cs b/tests/Anubis.Tests/RestoreTests.cs new file mode 100644 index 0000000..978168f --- /dev/null +++ b/tests/Anubis.Tests/RestoreTests.cs @@ -0,0 +1,303 @@ +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; +using Anubis.Platform; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// +/// After a restore (issue #69, SPEC 15.1): what the account did after the archive is written back from the broker, the +/// stops never go down, nothing planned before the archive leaves, and the bot waits for the user. +/// +[TestClass] +public sealed class RestoreTests +{ + private static readonly CancellationToken _none = CancellationToken.None; + private static readonly TimeSpan _minute = TimeSpan.FromSeconds(60); + + /// A demo account: a simulator whose book lives outside the database, as a broker's does. + private sealed class Account : IAsyncDisposable + { + private int _archives; + + public required TradingRig Rig { get; init; } + + public required AccountContext Context { get; init; } + + public required Instrument Btc { get; init; } + + public required Instrument Eth { get; init; } + + public required PaperBroker Paper { get; init; } + + public required FaultyBroker Broker { get; init; } + + public required OrderManager Manager { get; init; } + + public required string Folder { get; init; } + + public List Restored { get; } = []; + + public static async Task OpenAsync() + { + var rig = await TradingRig.CreateAsync(); + var folder = TempFolder.Create("restore"); + await Installation.CheckAsync(rig.Db, new DataDirectory(Path.Combine(folder, "data")), rig.Clock, _none); + var context = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Demo); + var btc = await rig.InstrumentAsync(TradingRig.Btc); + var eth = await rig.InstrumentAsync(MarketDataStoreTests.Okx("ETH-EUR") with { TickSize = 0.01m, LotSize = 0.000001m, MinSize = 0.0001m }); + rig.Quote(btc.Symbol, 60_000m, 60_010m); + rig.Quote(eth.Symbol, 2_000m, 2_001m); + var paper = rig.Paper(PaperOptions.Okx(), context.AccountId, persist: false); + await paper.DepositAsync(100_000m, "EUR", _none); + await rig.Ledger.RecordCapitalAsync(context.AccountId, StrategyNames.CryptoTrend, 100_000m, "EUR", "test", _none); + var broker = new FaultyBroker(paper, TradingEnvironments.Demo); + return new Account { Rig = rig, Context = context, Btc = btc, Eth = eth, Paper = paper, Broker = broker, Manager = rig.Manager(broker, context), Folder = folder }; + } + + public async Task BuyAsync(Instrument instrument, decimal quantity, decimal stop) + { + Rig.Refresh(); + var (id, refusal) = await Manager.SubmitAsync(new TradeIntent(instrument.Id, StrategyNames.CryptoTrend, OrderSide.Buy, quantity, OrderPurpose.Entry, Ids.NewId(Rig.Clock)) + { + StopLevel = stop, + StartAggressive = true, + }, _none); + Assert.IsNull(refusal); + Assert.IsNotNull(id); + await TurnsAsync(Manager, 3); + } + + public async Task SellAsync(Instrument instrument, decimal quantity) + { + Rig.Refresh(); + var (_, refusal) = await Manager.SubmitAsync(new TradeIntent(instrument.Id, StrategyNames.CryptoTrend, OrderSide.Sell, quantity, OrderPurpose.Exit, Ids.NewId(Rig.Clock)) + { + StartAggressive = true, + }, _none); + Assert.IsNull(refusal); + await TurnsAsync(Manager, 3); + } + + public async Task TurnsAsync(OrderManager manager, int turns) + { + for (var i = 0; i < turns; i++) + { + Rig.Refresh(); + await Paper.PumpAsync(_none); + await manager.TickAsync(_none); + Rig.Clock.Advance(_minute); + } + } + + public async Task ArchiveAsync() + { + var folder = Path.Combine(Folder, "archivio" + (++_archives).ToString(System.Globalization.CultureInfo.InvariantCulture)); + await Archive.ExportAsync(Rig.Db, folder, Rig.Clock, _none); + return folder; + } + + public async Task<(TradingRig Rig, OrderManager Manager)> RestoreAsync(string archive, DbEngine? engine = null) + { + var rig = await Rig.RestoreAsync(archive, engine); + Restored.Add(rig); + await Installation.RenewAsync(rig.Db, new DataDirectory(Path.Combine(Folder, "data")), rig.Clock, "Salvataggio ripristinato", _none); + var manager = rig.Manager(Broker, Context); + manager.StopGeneration = rig.Clock.UtcNow.UtcTicks; + return (rig, manager); + } + + public async Task SameLedgerAsync(TradingRig restored, string message) + { + async Task> PositionsAsync(TradingRig rig) => [.. (await rig.Ledger.PositionsAsync(Context.AccountId, _none)).Where(p => p.Quantity > 0m) + .Select(p => $"{p.InstrumentId} {p.Strategy} {DbValues.MoneyText(p.Quantity)} {p.StopPrice}").Order(StringComparer.Ordinal)]; + async Task> FillsAsync(TradingRig rig) => [.. (await rig.QueryAsync("SELECT execution_id, side, quantity, price, fee FROM fills", + r => $"{r.Text("execution_id")} {r.Text("side")} {r.Money("quantity")} {r.Money("price")} {r.Money("fee")}")).Order(StringComparer.Ordinal)]; + + CollectionAssert.AreEqual(await PositionsAsync(Rig), await PositionsAsync(restored), message); + CollectionAssert.AreEqual(await FillsAsync(Rig), await FillsAsync(restored), message); + } + + public async ValueTask DisposeAsync() + { + foreach (var rig in Restored) + { + await rig.DisposeAsync(); + } + + await Rig.DisposeAsync(); + TempFolder.Delete(Folder); + } + } + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task WhatTheAccountDidAfterTheArchiveIsRebuiltFromTheBroker() + { + await using var a = await Account.OpenAsync(); + await a.BuyAsync(a.Btc, 0.01m, 57_000m); + var archive = await a.ArchiveAsync(); + + // After the archive: the BTC stop rises, part is sold, ETH is bought, and one purchase is still working. + a.Rig.Clock.Advance(TimeSpan.FromHours(5)); + await a.Rig.Ledger.SetStopAsync(a.Context.AccountId, a.Btc.Id, StrategyNames.CryptoTrend, 58_500m, _none); + await a.TurnsAsync(a.Manager, 2); + await a.SellAsync(a.Btc, 0.004m); + await a.BuyAsync(a.Eth, 1m, 1_900m); + var stops = (await a.Paper.GetOpenOrdersAsync(_none)).Where(o => o.Kind == OrderKind.Stop).Select(o => o.ClientOrderId).ToList(); + Assert.HasCount(2, stops); + a.Rig.Refresh(); + Assert.IsNull((await a.Manager.SubmitAsync(new TradeIntent(a.Eth.Id, StrategyNames.CryptoTrend, OrderSide.Buy, 0.5m, OrderPurpose.Entry, Ids.NewId(a.Rig.Clock)) { StopLevel = 1_900m }, _none)).Refusal); + await a.TurnsAsync(a.Manager, 1); + Assert.HasCount(1, (await a.Paper.GetOpenOrdersAsync(_none)).Where(o => o.Side == OrderSide.Buy).ToList()); + + // The broker repeats its fills, as brokers do. + a.Broker.DuplicateFills = true; + var (rig, manager) = await a.RestoreAsync(archive); + var report = await manager.RebuildAsync(_none); + Assert.IsTrue(report.FoundAnything); + Assert.IsEmpty(report.Unclear, string.Join(" | ", report.Unclear)); + Assert.IsEmpty((await a.Paper.GetOpenOrdersAsync(_none)).Where(o => o.Side == OrderSide.Buy).ToList(), "The purchase nobody follows any more is canceled."); + await a.SameLedgerAsync(rig, "The rebuilt ledger is the one that was lost."); + Assert.AreEqual(58_500m, (await rig.Ledger.PositionAsync(a.Context.AccountId, a.Btc.Id, StrategyNames.CryptoTrend, _none))!.StopPrice, + "A stop raised after the archive never goes back down."); + + // A second pass finds nothing, reconciliation agrees, and the stops on the account are exactly those needed. + var second = await manager.RebuildAsync(_none); + Assert.AreEqual((0, 0, false), (second.Orders, second.Fills, second.FoundAnything)); + var reconciled = await new Reconciler(rig.Db, rig.Clock, rig.Ledger).ReconcileAsync(manager, _none); + Assert.IsEmpty(reconciled.Differences, string.Join(" | ", reconciled.Differences.Select(d => d.Message))); + await manager.AlignStopsAsync(_none); + await a.TurnsAsync(manager, 3); + var open = await a.Paper.GetOpenOrdersAsync(_none); + Assert.IsTrue(open.All(o => o.Kind == OrderKind.Stop), "Only stops."); + foreach (var position in (await rig.Ledger.PositionsAsync(a.Context.AccountId, _none)).Where(p => p.Quantity > 0m)) + { + var symbol = position.InstrumentId == a.Btc.Id ? a.Btc.Symbol : a.Eth.Symbol; + Assert.AreEqual(position.Quantity, open.Where(o => o.Symbol == symbol).Sum(o => o.Quantity), symbol); + } + + // A stop moved now takes a name of its own: the names used after the archive are gone from the ledger, not from the account. + await rig.Ledger.SetStopAsync(a.Context.AccountId, a.Btc.Id, StrategyNames.CryptoTrend, 59_000m, _none); + await a.TurnsAsync(manager, 2); + var moved = (await a.Paper.GetOpenOrdersAsync(_none)).Single(o => o.Symbol == a.Btc.Symbol); + Assert.AreEqual(59_000m, moved.StopPrice); + Assert.DoesNotContain(moved.ClientOrderId, stops); + Assert.HasCount(1, await rig.QueryAsync("SELECT message FROM journal WHERE code = 'ledger_rebuilt'", r => r.Text("message"))); + } + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task AStopThatFiredAfterTheArchiveClosesThePosition() + { + await using var a = await Account.OpenAsync(); + await a.BuyAsync(a.Btc, 0.01m, 57_000m); + var archive = await a.ArchiveAsync(); + a.Rig.Clock.Advance(TimeSpan.FromHours(2)); + a.Rig.Quote(a.Btc.Symbol, 56_500m, 56_510m); + await a.TurnsAsync(a.Manager, 3); + Assert.AreEqual(0m, (await a.Rig.Ledger.PositionAsync(a.Context.AccountId, a.Btc.Id, StrategyNames.CryptoTrend, _none))?.Quantity ?? 0m); + + var (rig, manager) = await a.RestoreAsync(archive); + await manager.RebuildAsync(_none); + await new Reconciler(rig.Db, rig.Clock, rig.Ledger).ReconcileAsync(manager, _none); + Assert.AreEqual(0m, (await rig.Ledger.PositionAsync(a.Context.AccountId, a.Btc.Id, StrategyNames.CryptoTrend, _none))?.Quantity ?? 0m); + await a.SameLedgerAsync(rig, "The sale made by the stop is in the rebuilt ledger."); + await a.TurnsAsync(manager, 2); + Assert.IsEmpty(await a.Paper.GetOpenOrdersAsync(_none), "Nothing is put back for a position that is gone."); + } + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task OrdersOfAnotherInstallationAreNotTakenAndAnUpToDateLedgerFindsNothing() + { + await using var a = await Account.OpenAsync(); + var foreign = new[] + { + ClientOrderIds.Build("OTHR", TradingEnvironments.Demo, StrategyNames.CryptoTrend, OrderPurpose.Entry, "AAAAAAAA", 1), + ClientOrderIds.Build(TradingRig.Installation, TradingEnvironments.Live, StrategyNames.CryptoTrend, OrderPurpose.Entry, "BBBBBBBB", 1), + "un-ordine-a-mano", + }; + foreach (var id in foreign) + { + await a.Paper.SubmitOrderAsync(new OrderRequest(id, a.Btc.Symbol, OrderSide.Buy, OrderKind.Limit, 0.001m, TimeInForce.Gtc) { LimitPrice = 50_000m }, _none); + } + + await a.BuyAsync(a.Btc, 0.01m, 57_000m); + Assert.IsFalse((await a.Manager.RebuildAsync(_none)).FoundAnything); + Assert.HasCount(0, await a.Rig.QueryAsync("SELECT client_order_id FROM orders WHERE client_order_id IN (@a, @b, @c)", r => r.Text("client_order_id"), + ("a", foreign[0]), ("b", foreign[1]), ("c", foreign[2]))); + Assert.HasCount(3, (await a.Paper.GetOpenOrdersAsync(_none)).Where(o => foreign.Contains(o.ClientOrderId)).ToList(), "Not ours, not touched."); + } + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task ARestoreFromOneEngineToTheOtherRebuildsTheSame() + { + if (!await TestDb.PostgresAvailableAsync()) + { + Assert.Inconclusive("PostgreSQL per i test non raggiungibile: la prova tra motori gira in CI e con `tasks ci`."); + } + + await using var a = await Account.OpenAsync(); + await a.BuyAsync(a.Btc, 0.01m, 57_000m); + var archive = await a.ArchiveAsync(); + await a.SellAsync(a.Btc, 0.003m); + var (rig, manager) = await a.RestoreAsync(archive, a.Rig.Db.Engine == DbEngine.Sqlite ? DbEngine.Postgres : DbEngine.Sqlite); + Assert.IsTrue((await manager.RebuildAsync(_none)).FoundAnything); + await a.SameLedgerAsync(rig, "The other engine gets the same ledger."); + } + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task AnOldCopyPutBackByHandIsRecognisedOnTheAccountAndStopsTheBot() + { + await using var a = await Account.OpenAsync(); + await a.BuyAsync(a.Btc, 0.01m, 57_000m); + var archive = await a.ArchiveAsync(); + await a.SellAsync(a.Btc, 0.003m); + + // A database dump put back with the fingerprint it had: nothing says it is old, except the account. + var rig = await a.Rig.RestoreAsync(archive); + a.Restored.Add(rig); + await rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE installation SET protected_restart = @no", _none, ("no", false)), _none); + using var service = new TradingService(rig.Db, rig.Clock, new EventBus(), new SecretStore(rig.Db, rig.Clock, new byte[32]), null, new FxStore(rig.Db, rig.Clock), + TradingConsent.None, new Guid("0193a7c0-0000-7000-8000-0000000000aa"), new FakeHttp()); + var manager = rig.Manager(a.Broker, a.Context); + await service.RebuildAsync(manager, _none); + + var settings = new SettingsStore(rig.Db, rig.Clock, new EventBus()); + Assert.AreEqual("stopped", (await settings.GetAsync(SettingsStore.BotState.Key)).Value); + Assert.IsTrue((await Installation.ReadRowAsync(rig.Db, _none))!.ProtectedRestart); + Assert.HasCount(1, await rig.QueryAsync("SELECT message FROM notifications WHERE kind = 'protected_restart'", r => r.Text("message"))); + await a.SameLedgerAsync(rig, "And the ledger is rebuilt all the same."); + + // Confirmed by the user, a start that finds nothing new leaves the bot as it is. + await settings.SetAsync(SettingsStore.BotState.Key, "active", "test"); + await Installation.ClearProtectedRestartAsync(rig.Db, _none); + await service.RebuildAsync(manager, _none); + Assert.AreEqual("active", (await settings.GetAsync(SettingsStore.BotState.Key)).Value); + } + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task AStopTheDatabaseDoesNotKnowIsAdoptedWithoutStoppingTheBot() + { + // The guard put a stop while the engine was off, and its note got lost. + await using var a = await Account.OpenAsync(); + await a.BuyAsync(a.Btc, 0.01m, 57_000m); + var own = (await a.Paper.GetOpenOrdersAsync(_none)).Single(); + await a.Paper.CancelOrderAsync(own.ClientOrderId, own.Symbol, _none); + var guard = ClientOrderIds.Build(TradingRig.Installation, TradingEnvironments.Demo, StrategyNames.CryptoTrend, OrderPurpose.Stop, "GGGGGGGG", 1); + await a.Paper.SubmitOrderAsync(new OrderRequest(guard, a.Btc.Symbol, OrderSide.Sell, OrderKind.Stop, own.Quantity, TimeInForce.Gtc) { StopPrice = 57_000m }, _none); + + var report = await a.Manager.RebuildAsync(_none); + Assert.AreEqual((1, false), (report.Orders, report.FoundAnything)); + await new Reconciler(a.Rig.Db, a.Rig.Clock, a.Rig.Ledger).ReconcileAsync(a.Manager, _none); + await a.Manager.AlignStopsAsync(_none); + await a.TurnsAsync(a.Manager, 2); + var open = await a.Paper.GetOpenOrdersAsync(_none); + Assert.AreEqual(own.Quantity, open.Sum(o => o.Quantity), "One stop, for the whole quantity."); + } +} diff --git a/tests/Anubis.Tests/RiskEngineTests.cs b/tests/Anubis.Tests/RiskEngineTests.cs index f9fcf75..782b204 100644 --- a/tests/Anubis.Tests/RiskEngineTests.cs +++ b/tests/Anubis.Tests/RiskEngineTests.cs @@ -480,6 +480,61 @@ public sealed class RiskEngineTests } } + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task AfterARestoreRealMoneyWaitsForThePasswordOfTheUser() + { + await using var s = await CreateAsync(Consent()); + var live = await FakeRealAccountAsync(s); + await s.Rig.Ledger.RecordCapitalAsync(live.Account.AccountId, StrategyNames.CryptoTrend, 2_500m, "EUR", "test", _none); + await RequirementsMetAsync(s); + await s.Stages.ConfirmLiveAsync(new LiveConfirmation(StrategyNames.CryptoTrend, live.Account.AccountId, + StageBook.Phrase(StrategyNames.CryptoTrend, StrategyStages.Reduced), Password, null, "utente"), _none); + var before = (await s.Stages.GetAsync(StrategyNames.CryptoTrend, _none))!; + Assert.AreEqual("stage", (await Assert.ThrowsExactlyAsync(() => s.Stages.ReconfirmAsync(StrategyNames.CryptoTrend, Password, null, "utente", _none))).Code, + "nothing to confirm before a restore"); + s.Rig.Refresh(); + await live.Manager.SubmitAsync(Buy(s, 0.002m) with { StartAggressive = true }, _none); + await s.Rig.TurnsAsync(live.Manager, 3, _minute); + var planned = Ids.NewId(s.Rig.Clock); + await s.Rig.Db.WriteAsync(x => x.ExecuteAsync( + "INSERT INTO planned_orders (id, decision_id, strategy, account_id, instrument_id, side, purpose, quantity, exit_all, reference_price, reason, due_at, valid_until, status, created_at, updated_at) " + + "VALUES (@id, @id, 'crypto_trend', @a, @i, 'buy', 'entry', 0.001, @no, 60000, 'trend_entry', @t, @t, 'pending', @t, @t)", _none, + ("id", planned), ("a", live.Account.AccountId), ("i", s.Btc.Id), ("no", false), ("t", s.Rig.Clock.UtcNow)), _none); + + await Installation.CheckAsync(s.Rig.Db, new DataDirectory(TempFolder.Create("reconfirm")), s.Rig.Clock, _none); + await Installation.ProtectAsync(s.Rig.Db, s.Rig.Clock, _none); + + // Stopped, exit only, with its counts untouched; what was planned does not leave; the stop stays. + Assert.AreEqual("stopped", (await s.Settings.GetAsync(SettingsStore.BotState.Key)).Value); + var waiting = (await s.Stages.GetAsync(StrategyNames.CryptoTrend, _none))!; + Assert.AreEqual((StrategyStages.Reduced, true, true, before.StageSince), (waiting.Stage, waiting.ExitOnly, waiting.WaitsForReconfirmation, waiting.StageSince)); + Assert.AreEqual("dropped/protected_restart", (await s.Rig.QueryAsync("SELECT status, outcome FROM planned_orders WHERE id = @id", + r => r.Text("status") + "/" + r.TextOrNull("outcome"), ("id", planned))).Single()); + Assert.HasCount(1, await s.Rig.QueryAsync("SELECT reason FROM strategy_stage_history WHERE reason = 'exit_only_after_restore'", r => r.Text("reason"))); + Assert.HasCount(1, await live.Paper.GetOpenOrdersAsync(_none), "the stop on the real account"); + + // The bot restarted: still no purchase with real money, while a sale goes; holding nothing does not free it. + await s.Risk.RestartAsync("utente", _none); + Assert.AreEqual(RiskReasons.ExitOnly, (await live.Manager.SubmitAsync(Buy(s, 0.001m), _none)).Refusal); + var held = (await s.Rig.Ledger.PositionAsync(live.Account.AccountId, s.Btc.Id, StrategyNames.CryptoTrend, _none))!.Quantity; + Assert.IsNull((await live.Manager.SubmitAsync(Sell(s, held) with { StartAggressive = true }, _none)).Refusal); + await s.Rig.TurnsAsync(live.Manager, 3, _minute); + Assert.AreEqual(0m, (await s.Rig.Ledger.PositionAsync(live.Account.AccountId, s.Btc.Id, StrategyNames.CryptoTrend, _none))?.Quantity ?? 0m); + await s.Stages.ReleaseExitOnlyAsync(s.Rig.Ledger, _none); + Assert.IsTrue((await s.Stages.GetAsync(StrategyNames.CryptoTrend, _none))!.WaitsForReconfirmation, "only the user takes it out"); + + Assert.AreEqual("password", (await Assert.ThrowsExactlyAsync(() => s.Stages.ReconfirmAsync(StrategyNames.CryptoTrend, "sbagliata", null, "utente", _none))).Code); + var closed = new StageBook(s.Rig.Db, s.Rig.Clock, TradingConsent.None, (_, _, _) => Task.FromResult(true)); + Assert.AreEqual(RiskReasons.NoConsent, (await Assert.ThrowsExactlyAsync(() => closed.ReconfirmAsync(StrategyNames.CryptoTrend, Password, null, "utente", _none))).Code); + await s.Stages.ReconfirmAsync(StrategyNames.CryptoTrend, Password, null, "utente", _none); + var back = (await s.Stages.GetAsync(StrategyNames.CryptoTrend, _none))!; + Assert.AreEqual((StrategyStages.Reduced, false, before.StageSince), (back.Stage, back.ExitOnly, back.StageSince)); + s.Rig.Refresh(); + Assert.IsNull((await live.Manager.SubmitAsync(Buy(s, 0.001m), _none)).Refusal); + Assert.HasCount(2, await s.Rig.QueryAsync("SELECT key FROM config_history WHERE key = @k", r => r.Text("key"), ("k", "strategy.crypto_trend.stage"))); + } + [TestMethod] [TestCategory(Category.Simulation)] public async Task ADemotedStrategyKeepsManagingItsRealPositionsDownToZero() diff --git a/tests/Anubis.Tests/StoresTests.cs b/tests/Anubis.Tests/StoresTests.cs index cef8229..92ef78a 100644 --- a/tests/Anubis.Tests/StoresTests.cs +++ b/tests/Anubis.Tests/StoresTests.cs @@ -27,12 +27,15 @@ public sealed class StoresTests Assert.IsTrue(File.Exists(data.InstallationFile)); Assert.AreEqual(IdentityVerdict.Match, (await Installation.CheckAsync(test.Db, data, clock).ConfigureAwait(false)).Verdict); - // Data folder lost: rewritten from the database. + // The file of the data folder is lost: nobody can tell this database from an old copy, so the engine does not start. + var before = Installation.ReadFile(data)!; File.Delete(data.InstallationFile); - Assert.AreEqual(IdentityVerdict.FileRestored, (await Installation.CheckAsync(test.Db, data, clock).ConfigureAwait(false)).Verdict); + var missing = await Installation.CheckAsync(test.Db, data, clock).ConfigureAwait(false); + Assert.AreEqual(IdentityVerdict.MissingFile, missing.Verdict); + Assert.IsFalse(missing.CanStart); + Assert.IsFalse(File.Exists(data.InstallationFile)); // A stale copy of the database: same installation, older fingerprint. - var before = Installation.ReadFile(data)!; Installation.WriteFile(data, before with { Fingerprint = "newer" }); var stale = await Installation.CheckAsync(test.Db, data, clock).ConfigureAwait(false); Assert.AreEqual(IdentityVerdict.StaleDatabase, stale.Verdict); @@ -43,7 +46,7 @@ public sealed class StoresTests Assert.AreEqual(IdentityVerdict.DifferentInstallation, (await Installation.CheckAsync(test.Db, data, clock).ConfigureAwait(false)).Verdict); // The user adopts this database: new fingerprint on both sides, protected restart on. - var renewed = await Installation.RenewAsync(test.Db, data, clock, adoptDatabaseIdentity: true).ConfigureAwait(false); + var renewed = await Installation.RenewAsync(test.Db, data, clock, "prova").ConfigureAwait(false); Assert.AreEqual(before.InstallationId, renewed.InstallationId); Assert.AreNotEqual(before.Fingerprint, renewed.Fingerprint); var row = await Installation.ReadRowAsync(test.Db).ConfigureAwait(false); @@ -124,10 +127,11 @@ public sealed class StoresTests Assert.IsTrue((await secrets.StatusAsync("OKX_API_KEY_DEMO").ConfigureAwait(false)).FromEnvironment); await Assert.ThrowsAsync(() => secrets.SetAsync("OKX_API_KEY_DEMO", "x-123456789", "admin")).ConfigureAwait(false); - // With another key the value cannot be read: the error says to enter it again. + // With another key the value cannot be read: whoever asks goes on without it, and the status says it must be entered again. var otherKey = new SecretStore(test.Db, clock, Enumerable.Repeat((byte)7, 32).ToArray()); - var error = await Assert.ThrowsAsync(() => otherKey.RevealAsync("ALPACA_API_SECRET_DEMO")).ConfigureAwait(false); - Assert.Contains("Reinserisci", error.Message); + Assert.IsNull(await otherKey.RevealAsync("ALPACA_API_SECRET_DEMO").ConfigureAwait(false)); + Assert.IsTrue((await otherKey.StatusAsync("ALPACA_API_SECRET_DEMO").ConfigureAwait(false)).Unreadable); + Assert.IsFalse((await secrets.StatusAsync("ALPACA_API_SECRET_DEMO").ConfigureAwait(false)).Unreadable); // A value sealed under one name does not open under another. var sealedValue = secrets.Seal("A", "x"); diff --git a/tests/Anubis.Tests/TradingSupport.cs b/tests/Anubis.Tests/TradingSupport.cs index 9456b3a..06b9ae4 100644 --- a/tests/Anubis.Tests/TradingSupport.cs +++ b/tests/Anubis.Tests/TradingSupport.cs @@ -29,6 +29,26 @@ internal sealed class TradingRig : IAsyncDisposable Catalog = new InstrumentCatalog(test.Db, Clock); } + // The same market and the same clock on another database: the account goes on while the ledger went back (SPEC 15.1). + private TradingRig(TestDb test, TradingRig before) + { + Test = test; + Clock = before.Clock; + Ledger = new Ledger(test.Db, Clock); + Catalog = new InstrumentCatalog(test.Db, Clock); + _quotes = before._quotes; + _specs = before._specs; + _instruments = before._instruments; + } + + /// An archive of this rig loaded in a new database of (that of the run when null). + public async Task RestoreAsync(string archive, Anubis.Platform.DbEngine? engine = null) + { + var test = engine is { } e ? await TestDb.CreateAsync(e).ConfigureAwait(false) : await TestDb.CreateAsync().ConfigureAwait(false); + await Archive.ImportAsync(test.Db, archive, Clock).ConfigureAwait(false); + return new TradingRig(test, this); + } + public TestDb Test { get; } public Database Db => Test.Db;