diff --git a/src/Anubis.Server/AnubisHost.cs b/src/Anubis.Server/AnubisHost.cs index a681eac..0df1017 100644 --- a/src/Anubis.Server/AnubisHost.cs +++ b/src/Anubis.Server/AnubisHost.cs @@ -136,7 +136,53 @@ internal sealed partial class AnubisHost( /// For an error-page choice that writes into a missing SQLite file: the only place where a known installation gets a /// new one. Called while the choice holds . /// - internal Database OpenForChoice() => _db ??= Database.Open(Config.Db!, allowCreate: SqliteFileMissing); + internal Database OpenForChoice() + { + if (_db is null) + { + _createdByChoice = SqliteFileMissing; + _db = Database.Open(Config.Db!, allowCreate: _createdByChoice); + } + + return _db; + } + + private bool _createdByChoice; + + /// + /// A choice that failed or was cut halfway leaves nothing open that could create the missing file, and what it had + /// begun to write steps aside: moved and not deleted, because in the meantime the true file may have come back. + /// + internal async Task AbandonChoiceAsync() + { + if (!_createdByChoice || _db is null) + { + return; + } + + await _db.DisposeAsync().ConfigureAwait(false); + _db = null; + _createdByChoice = false; + var path = Config.Db!.SqlitePath!; + var aside = path + ".incompleto-" + clock.UtcNow.ToString("yyyyMMdd-HHmmss", System.Globalization.CultureInfo.InvariantCulture); + foreach (var part in new[] { "", "-wal", "-shm" }) + { + try + { + if (File.Exists(path + part)) + { + File.Move(path + part, aside + part, overwrite: true); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + LogStepFailed(logger, ex); + } + } + } + + /// The choice is done: the database it opened is the one in use. + internal void KeepChoice() => _createdByChoice = false; /// Holds the loop still while an error-page choice works on the database. internal async Task ExclusiveAsync(CancellationToken cancellationToken) diff --git a/src/Anubis.Server/Forms.cs b/src/Anubis.Server/Forms.cs index b59f01f..31848ae 100644 --- a/src/Anubis.Server/Forms.cs +++ b/src/Anubis.Server/Forms.cs @@ -1168,6 +1168,7 @@ internal static partial class Forms } var verdict = status.Identity.Verdict; + var done = false; try { switch (choice) @@ -1197,19 +1198,31 @@ internal static partial class Forms break; 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. + // Asked by the user: one more attempt, even after one that failed. + host.MigrationFailed = null; await host.MigrateAsync(new Backups(config.Data, clock), ct).ConfigureAwait(false); await Installation.RenewAsync(host.OpenForChoice(), config.Data, clock, "Database scelto dalla pagina d'errore", ct).ConfigureAwait(false); break; default: return Results.Redirect("/?errore=scelta"); } + + done = true; } catch (Exception ex) when (IsArchiveProblem(ex)) { LogChoiceFailed(logger, ex, choice); return Results.Redirect("/?errore=importazione"); } + finally + { + if (!done) + { + await host.AbandonChoiceAsync().ConfigureAwait(false); + } + } + host.KeepChoice(); LogChoice(logger, choice); // Reset while the loop is still held: released first, it could start the application again before the reset diff --git a/src/Anubis/Data/MarketDataService.cs b/src/Anubis/Data/MarketDataService.cs index 4d487c0..afdfff4 100644 --- a/src/Anubis/Data/MarketDataService.cs +++ b/src/Anubis/Data/MarketDataService.cs @@ -576,7 +576,11 @@ public sealed partial class MarketDataService : IDisposable return; } - var actions = await alpaca.FetchCorporateActionsAsync(universe.Select(m => m.Symbol).ToList(), today.AddDays(-7), today.AddDays(30), cancellationToken) + // Back to a week before the last news: after a long stop or a restore the days in between are missing too. + var last = await _db.ReadAsync(async s => (await s.QueryAsync("SELECT created_at FROM corporate_actions ORDER BY created_at DESC LIMIT 1", r => r.Moment("created_at")) + .ConfigureAwait(false)).Select(m => (DateTimeOffset?)m).FirstOrDefault(), cancellationToken).ConfigureAwait(false); + var from = last is { } known && DateOnly.FromDateTime(known.UtcDateTime) < today ? DateOnly.FromDateTime(known.UtcDateTime) : today; + var actions = await alpaca.FetchCorporateActionsAsync(universe.Select(m => m.Symbol).ToList(), from.AddDays(-7), today.AddDays(30), cancellationToken) .ConfigureAwait(false); await new CorporateActionStore(_db, _clock).UpsertAsync(actions, cancellationToken).ConfigureAwait(false); } diff --git a/src/Anubis/Db/Archive.cs b/src/Anubis/Db/Archive.cs index e9cebb5..29ee101 100644 --- a/src/Anubis/Db/Archive.cs +++ b/src/Anubis/Db/Archive.cs @@ -118,6 +118,12 @@ public static class Archive throw new SchemaException($"L'archivio è alla versione {index.SchemaVersion} dello schema, più recente di questa versione di Anubis."); } + var tables = Schema.Parse(Migrations.All.Take(index.SchemaVersion)); + + // The whole archive is read and checked before the database is even opened: opening a SQLite file that + // is not there creates it. + await VerifyAsync(index, folder, tables, cancellationToken).ConfigureAwait(false); + var status = await Migrations.StatusAsync(db, cancellationToken).ConfigureAwait(false); if (!status.IsEmpty && !await IsEmptyAsync(db, cancellationToken).ConfigureAwait(false)) { @@ -129,10 +135,6 @@ public static class Archive throw new InvalidOperationException("Il database di arrivo ha già uno schema più recente dell'archivio: usa un database vuoto."); } - 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 => diff --git a/src/Anubis/Db/Migrations/0015_rebuild.sql b/src/Anubis/Db/Migrations/0015_rebuild.sql new file mode 100644 index 0000000..e459d50 --- /dev/null +++ b/src/Anubis/Db/Migrations/0015_rebuild.sql @@ -0,0 +1,6 @@ +-- A rebuild from the broker that has begun and is not finished (SPEC 15.1): from when it reads the executions and how +-- many orders it has written so far. Both leave together, in the write that ends it: an interrupted rebuild is taken +-- up again from the same point. +ALTER TABLE account_status ADD COLUMN rebuild_since {timestamp}; + +ALTER TABLE account_status ADD COLUMN rebuild_orders INTEGER; diff --git a/src/Anubis/Platform/Installation.cs b/src/Anubis/Platform/Installation.cs index 88ae990..19b9d3b 100644 --- a/src/Anubis/Platform/Installation.cs +++ b/src/Anubis/Platform/Installation.cs @@ -236,6 +236,17 @@ public static class Installation ("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); + + // A "close all positions" of before the restore may be done already: going on with it would sell what came after. + var bot = await s.FirstOrDefaultAsync("SELECT state FROM risk_state WHERE world = @w", r => r.Json("state").Text, ("w", Trading.RiskEngine.BotRow)).ConfigureAwait(false); + if (bot is not null && JsonSerializer.Deserialize(bot, Trading.RiskEngine.Json) is { CloseAll: true }) + { + await s.ExecuteAsync("UPDATE risk_state SET state = @j, updated_at = @t WHERE world = @w", cancellationToken, + ("j", new DbJson(JsonSerializer.Serialize(new Trading.BotRiskState(), Trading.RiskEngine.Json))), ("t", now), ("w", Trading.RiskEngine.BotRow)).ConfigureAwait(false); + await Trading.Diary.NotifyAsync(s, clock, "close_all_dropped", + "Nel salvataggio c'era una chiusura di tutte le posizioni non ancora finita: non la continuo. Se la vuoi ancora, chiedila di nuovo dalla pagina Rischio.", cancellationToken) + .ConfigureAwait(false); + } } /// Why an order planned before a restore did not leave. diff --git a/src/Anubis/Trading/Ledger.cs b/src/Anubis/Trading/Ledger.cs index 3c60fcd..3049a3e 100644 --- a/src/Anubis/Trading/Ledger.cs +++ b/src/Anubis/Trading/Ledger.cs @@ -1,5 +1,6 @@ using System.Globalization; using Anubis.Core; +using Anubis.Data; using Anubis.Db; namespace Anubis.Trading; @@ -481,13 +482,19 @@ public sealed class Ledger(Database db, IClock clock) db.ReadAsync(async s => { var (baseCurrency, _) = await CurrenciesAsync(s, instrumentId).ConfigureAwait(false); - var rows = await s.QueryAsync("SELECT side, quantity, fee, fee_currency FROM fills WHERE account_id = @a AND instrument_id = @i AND strategy = @s AND executed_at < @at", - r => (Side: Wire.Side(r.Text("side")), Quantity: r.Money("quantity"), Fee: r.Money("fee"), FeeCurrency: r.Text("fee_currency")), + var rows = await s.QueryAsync("SELECT side, quantity, fee, fee_currency, executed_at FROM fills WHERE account_id = @a AND instrument_id = @i AND strategy = @s AND executed_at < @at", + r => (Side: Wire.Side(r.Text("side")), Quantity: r.Money("quantity"), Fee: r.Money("fee"), FeeCurrency: r.Text("fee_currency"), At: r.Moment("executed_at")), ("a", accountId), ("i", instrumentId), ("s", strategy), ("at", at)).ConfigureAwait(false); + + // The shares of before a split count as the new ones they became. + var splits = (await s.QueryAsync("SELECT c.ex_date, c.ratio FROM corporate_actions c JOIN instruments i ON i.symbol = c.symbol WHERE i.id = @i AND c.kind IN (@k1, @k2)", + r => (At: new DateTimeOffset(BarStore.ParseDay(r.Text("ex_date")).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero), Ratio: r.MoneyOrNull("ratio")), + ("i", instrumentId), ("k1", CorporateActionKinds.Split), ("k2", CorporateActionKinds.StockDividend)).ConfigureAwait(false)).Where(x => x.Ratio is > 0m && x.At < at).ToList(); return rows.Sum(r => { var inKind = baseCurrency is not null && r.FeeCurrency == baseCurrency ? r.Fee : 0m; - return r.Side == OrderSide.Buy ? r.Quantity - inKind : -(r.Quantity + inKind); + var ratio = splits.Where(x => x.At > r.At).Aggregate(1m, (all, x) => all * x.Ratio!.Value); + return (r.Side == OrderSide.Buy ? r.Quantity - inKind : -(r.Quantity + inKind)) * ratio; }); }, cancellationToken); diff --git a/src/Anubis/Trading/OrderManager.Protection.cs b/src/Anubis/Trading/OrderManager.Protection.cs index 5760ee2..f4f6a28 100644 --- a/src/Anubis/Trading/OrderManager.Protection.cs +++ b/src/Anubis/Trading/OrderManager.Protection.cs @@ -133,7 +133,7 @@ public sealed partial class OrderManager } } - private async Task ApplySplitCoreAsync(Instrument instrument, CorporateAction split, CancellationToken cancellationToken) + private async Task ApplySplitCoreAsync(Instrument instrument, CorporateAction split, CancellationToken cancellationToken, bool replay = false) { if (!split.ChangesShares) { @@ -154,7 +154,8 @@ public sealed partial class OrderManager await paper.ApplySplitAsync(instrument.Symbol, split.Ratio.Value, oldShares.Value, exDate, cancellationToken).ConfigureAwait(false); } - foreach (var position in (await _ledger.PositionsAsync(_account.AccountId, cancellationToken).ConfigureAwait(false)).Where(p => p.InstrumentId == instrument.Id)) + // Replayed, the split is old news: the stops on the account may be those put after it. + foreach (var position in (await _ledger.PositionsAsync(_account.AccountId, cancellationToken).ConfigureAwait(false)).Where(p => !replay && p.InstrumentId == instrument.Id)) { await CancelStopsOfAsync(instrument.Id, position.Strategy, instrument, cancellationToken).ConfigureAwait(false); } @@ -181,6 +182,11 @@ public sealed partial class OrderManager private async Task AlignPositionAsync(Guid instrumentId, string strategy, Instrument instrument, CancellationToken cancellationToken) { + if (AwaitingRebuild) + { + return; + } + // An execution in progress owns the stops of its position until it ends. Where the broker refuses a purchase // while any sell stop rests on the symbol (Alpaca), a purchase of any strategy holds every stop on it. var sql = "SELECT COUNT(*) FROM executions WHERE account_id = @a AND instrument_id = @i AND status = @w AND (strategy = @s" + diff --git a/src/Anubis/Trading/OrderManager.Rebuild.cs b/src/Anubis/Trading/OrderManager.Rebuild.cs index 33029c8..c566db1 100644 --- a/src/Anubis/Trading/OrderManager.Rebuild.cs +++ b/src/Anubis/Trading/OrderManager.Rebuild.cs @@ -1,4 +1,5 @@ using Anubis.Core; +using Anubis.Data; using Anubis.Db; namespace Anubis.Trading; @@ -30,20 +31,24 @@ public sealed partial class OrderManager /// /// 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. + /// start, before reconciliation: on a database that is up to date it finds nothing and writes nothing. When the + /// account turns out to be ahead of the database, runs before the first row is written. /// - public async Task RebuildAsync(CancellationToken cancellationToken) + public async Task RebuildAsync(CancellationToken cancellationToken, Func? protect = null) { if (_account.Environment == TradingEnvironments.Simulation) { // The internal simulator lives in the database: it went back in time together with the ledger. + AwaitingRebuild = false; return RebuildReport.Nothing; } await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); try { - return await RebuildCoreAsync(cancellationToken).ConfigureAwait(false); + var report = await RebuildCoreAsync(protect, cancellationToken).ConfigureAwait(false); + AwaitingRebuild = false; + return report; } finally { @@ -51,14 +56,16 @@ public sealed partial class OrderManager } } - private async Task RebuildCoreAsync(CancellationToken cancellationToken) + private async Task RebuildCoreAsync(Func? protect, CancellationToken cancellationToken) { - var since = await RebuildSinceAsync(cancellationToken).ConfigureAwait(false); + // A rebuild interrupted halfway goes on from where it started reading, whatever was written since. + var (begun, written) = await _db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT rebuild_since, rebuild_orders FROM account_status WHERE account_id = @a", + r => (Since: r.MomentOrNull("rebuild_since"), Orders: r.IsNull("rebuild_orders") ? 0 : (int)r.Number("rebuild_orders")), ("a", _account.AccountId)), cancellationToken).ConfigureAwait(false); + var since = begun ?? 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; + var unknown = new List<(string ClientId, ClientOrderIdParts Parts, Guid Instrument, List Own, BrokerOrder? Resting)>(); 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) @@ -66,16 +73,28 @@ public sealed partial class OrderManager 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) + if (await InstrumentBySymbolAsync(symbol, cancellationToken).ConfigureAwait(false) is { } instrumentId) + { + unknown.Add((clientId, ClientOrderIds.Parse(clientId)!, instrumentId, own, resting)); + } + else { unclear.Add($"{symbol}: non è nel catalogo, l'ordine {clientId} resta da controllare a mano."); - continue; } + } + var onlyStops = written == 0 && unknown.All(u => u.Parts.Purpose == OrderPurpose.Stop && u.Own.Count == 0); + if (protect is not null && (unclear.Count > 0 || (unknown.Count > 0 && !onlyStops))) + { + await protect(cancellationToken).ConfigureAwait(false); + } + + foreach (var (clientId, parts, instrumentId, own, resting) in unknown) + { + var symbol = own.FirstOrDefault()?.Symbol ?? resting!.Symbol; var remote = resting ?? await _broker.GetOrderAsync(clientId, symbol, cancellationToken).ConfigureAwait(false); if (resting is not null && parts.Purpose != OrderPurpose.Stop) { @@ -84,14 +103,19 @@ public sealed partial class OrderManager 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++; + await InsertRebuiltAsync(clientId, parts, instrumentId, remote, own, since, cancellationToken).ConfigureAwait(false); + written++; } - if (orders > 0) + if (written > 0) { - var recorded = await SyncFillsFromAsync(since, cancellationToken).ConfigureAwait(false); + var recorded = await SyncFillsFromAsync(since, cancellationToken, replay: true).ConfigureAwait(false); + var positions = await _ledger.PositionsAsync(_account.AccountId, cancellationToken).ConfigureAwait(false); + foreach (var instrumentId in positions.Select(p => p.InstrumentId).Distinct()) + { + await ReplaySplitsAsync(instrumentId, _clock.UtcNow, 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)) { @@ -99,10 +123,15 @@ public sealed partial class OrderManager 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." + + var message = $"Conto {_account.Name}: sul conto c'erano {written} 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); + await _db.WriteAsync(async s => + { + await s.ExecuteAsync("UPDATE account_status SET rebuild_since = NULL, rebuild_orders = NULL, updated_at = @now WHERE account_id = @a", cancellationToken, + ("now", _clock.UtcNow), ("a", _account.AccountId)).ConfigureAwait(false); + await Diary.NotifyAsync(s, _clock, "ledger_rebuilt", message, cancellationToken).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); + return new RebuildReport(written, recorded, unclear, onlyStops); } if (unclear.Count > 0) @@ -114,6 +143,22 @@ public sealed partial class OrderManager return new RebuildReport(0, 0, unclear); } + /// The splits with an ex-date up to , in the ledger only: each is applied once. + private async Task ReplaySplitsAsync(Guid instrumentId, DateTimeOffset until, CancellationToken cancellationToken) + { + foreach (var (instrument, split) in await SplitsUntilAsync(instrumentId, until, cancellationToken).ConfigureAwait(false)) + { + await ApplySplitCoreAsync(instrument, split, cancellationToken, replay: true).ConfigureAwait(false); + } + } + + private async Task> SplitsUntilAsync(Guid instrumentId, DateTimeOffset until, CancellationToken cancellationToken) => + Splits is null || await _instruments(instrumentId, cancellationToken).ConfigureAwait(false) is not { IsCrypto: false } instrument + ? [] + : [.. (await Splits(instrument, cancellationToken).ConfigureAwait(false)).Where(s => s.ChangesShares && ExDate(s) <= until).OrderBy(s => s.ExDate).Select(s => (instrument, s))]; + + private static DateTimeOffset ExDate(CorporateAction split) => new(split.ExDate.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero); + 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." : ""; @@ -144,7 +189,8 @@ public sealed partial class OrderManager return id == Guid.Empty ? (Guid?)null : id; }, cancellationToken); - private async Task InsertRebuiltAsync(string clientId, ClientOrderIdParts parts, Guid instrumentId, BrokerOrder? remote, List own, CancellationToken cancellationToken) + private async Task InsertRebuiltAsync(string clientId, ClientOrderIdParts parts, Guid instrumentId, BrokerOrder? remote, List own, DateTimeOffset since, + CancellationToken cancellationToken) { var filled = own.Sum(f => f.Quantity); var side = remote?.Side ?? own[0].Side; @@ -154,6 +200,12 @@ public sealed partial class OrderManager remote?.StopPrice, OrderStatus.Created, 0m, null, remote?.StopPrice ?? remote?.LimitPrice, null, remote?.TimeInForce ?? TimeInForce.Gtc, false, created); await _db.WriteAsync(async s => { + // The mark of a rebuild under way travels with its first row and leaves when everything is done. + var now = _clock.UtcNow; + await s.ExecuteAsync("INSERT INTO account_status (id, account_id, mode, created_at, updated_at) VALUES (@id, @a, @m, @now, @now) ON CONFLICT (account_id) DO NOTHING", + cancellationToken, ("id", Ids.NewId(_clock)), ("a", _account.AccountId), ("m", AccountModes.Normal), ("now", now)).ConfigureAwait(false); + await s.ExecuteAsync("UPDATE account_status SET rebuild_since = @since, rebuild_orders = COALESCE(rebuild_orders, 0) + 1, updated_at = @now WHERE account_id = @a", + cancellationToken, ("since", since), ("now", now), ("a", _account.AccountId)).ConfigureAwait(false); 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); @@ -162,7 +214,7 @@ public sealed partial class OrderManager // 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); + ("a", _account.AccountId), ("x", true), ("now", now), ("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) @@ -187,6 +239,13 @@ public sealed partial class OrderManager } var position = await _ledger.PositionAsync(_account.AccountId, instrumentId, parts.Strategy, cancellationToken).ConfigureAwait(false); + var split = (await SplitsUntilAsync(instrumentId, _clock.UtcNow, cancellationToken).ConfigureAwait(false)).LastOrDefault().Split; + if (split is not null && stop.UpdatedAt < ExDate(split)) + { + // A level of before the split is in old money: the one of the ledger has been divided. + continue; + } + 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 6212d41..d1e9b23 100644 --- a/src/Anubis/Trading/OrderManager.cs +++ b/src/Anubis/Trading/OrderManager.cs @@ -132,6 +132,15 @@ public sealed partial class OrderManager : IDisposable /// A split of the instrument not yet applied, looked for when the price is far below a stop (SPEC 6.10). public Func>? PendingSplit { get; init; } + /// The splits of the instrument up to today, the oldest first, applied or not: a rebuild meets them at their date (SPEC 15.1). + public Func>>? Splits { get; init; } + + /// + /// The account has not been compared with the executions of the broker since the start (SPEC 15.1): until then the + /// ledger may be older than the account, so nothing is written in it, no stop is moved and nothing is sold for it. + /// + public bool AwaitingRebuild { get; set; } + /// Called after new fills are recorded: the equity is photographed at every execution (SPEC 7.5). public Func? AfterFills { get; init; } @@ -723,6 +732,11 @@ public sealed partial class OrderManager : IDisposable private async Task SyncFillsCoreAsync(CancellationToken cancellationToken) { + if (AwaitingRebuild) + { + return 0; + } + var since = await _db.ReadAsync(async s => { var last = (await s.QueryAsync("SELECT executed_at FROM fills WHERE account_id = @a AND execution_id NOT LIKE 'ANU%'", r => r.Moment("executed_at"), ("a", _account.AccountId)) @@ -734,7 +748,11 @@ public sealed partial class OrderManager : IDisposable return await SyncFillsFromAsync(since, cancellationToken).ConfigureAwait(false); } - private async Task SyncFillsFromAsync(DateTimeOffset since, CancellationToken cancellationToken) + /// + /// With the executions are history (SPEC 15.1): they are written with the splits of their + /// time, and nothing is done about them. What to do today is decided afterwards, on the position that results. + /// + private async Task SyncFillsFromAsync(DateTimeOffset since, CancellationToken cancellationToken, bool replay = false) { var fills = await _broker.GetFillsAsync(since, cancellationToken).ConfigureAwait(false); var recorded = 0; @@ -751,6 +769,11 @@ public sealed partial class OrderManager : IDisposable continue; } + if (replay) + { + await ReplaySplitsAsync(row.InstrumentId, fill.ExecutedAt, cancellationToken).ConfigureAwait(false); + } + FillOutcome outcome; try { @@ -795,10 +818,13 @@ public sealed partial class OrderManager : IDisposable await Diary.WriteAsync(s, _clock, DiaryKinds.Orders, "fill", text, new { fill.ExecutionId, row.ClientOrderId, outcome.SlippageBp, outcome.TradeId, Account = _account.Name }, cancellationToken).ConfigureAwait(false); - // Every purchase and sale reaches the phone, with the result when it closes a trade (SPEC 14). - await Notifications.NotificationSender.EnqueueAsync(s, _clock, "fill", _account.Name + ": " + text, cancellationToken).ConfigureAwait(false); + if (!replay) + { + // Every purchase and sale reaches the phone, with the result when it closes a trade (SPEC 14). + await Notifications.NotificationSender.EnqueueAsync(s, _clock, "fill", _account.Name + ": " + text, cancellationToken).ConfigureAwait(false); + } }, cancellationToken).ConfigureAwait(false); - if (row.Purpose == OrderPurpose.Stop && outcome.Quantity > 0m && instrument is not null) + if (!replay && row.Purpose == OrderPurpose.Stop && outcome.Quantity > 0m && instrument is not null) { // A stop that fired only in part, or one of Alpaca's two stops: the rest is sold at once (SPEC 7.2). await ProtectiveSaleAsync(row.InstrumentId, row.Strategy, outcome.Quantity, "stop_partly_triggered", cancellationToken).ConfigureAwait(false); diff --git a/src/Anubis/Trading/Reconciler.cs b/src/Anubis/Trading/Reconciler.cs index 0e2a2b6..4347a70 100644 --- a/src/Anubis/Trading/Reconciler.cs +++ b/src/Anubis/Trading/Reconciler.cs @@ -221,6 +221,11 @@ public sealed class Reconciler(Database db, IClock clock, Ledger ledger) throw new InvalidOperationException("A key that may withdraw is replaced, not aligned."); } + if (manager.AwaitingRebuild) + { + return ReconcileResolution.NotCompared; + } + // Compared again right now: the choice applies to the differences that exist, never to old ones. var report = await ReconcileAsync(manager, cancellationToken).ConfigureAwait(false); if (ReconcileOutcomes.IsDown(report.Outcome)) diff --git a/src/Anubis/Trading/RiskEngine.cs b/src/Anubis/Trading/RiskEngine.cs index a914251..40b2d99 100644 --- a/src/Anubis/Trading/RiskEngine.cs +++ b/src/Anubis/Trading/RiskEngine.cs @@ -40,7 +40,7 @@ public sealed class RiskEngine(Database db, IClock clock, Ledger ledger, StageBo public const string NoRate = "no_fx_rate"; public const int PdtMaxDayTrades = 3; - private static readonly JsonSerializerOptions Json = new() { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower }; + internal static readonly JsonSerializerOptions Json = new() { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower }; private static readonly TimeZoneInfo NewYork = TimeZoneInfo.FindSystemTimeZoneById("America/New_York"); /// The file that stops the bot (SPEC 9.3): /data/STOP in Docker, the data folder on desktop. @@ -345,6 +345,13 @@ public sealed class RiskEngine(Database db, IClock clock, Ledger ledger, StageBo var waiting = 0; foreach (var manager in managers) { + if (manager.AwaitingRebuild) + { + // The ledger may not be the true one yet: it is sold when it is. + waiting++; + continue; + } + foreach (var position in await ledger.PositionsAsync(manager.Account.AccountId, cancellationToken).ConfigureAwait(false)) { if (await instruments(position.InstrumentId, cancellationToken).ConfigureAwait(false) is not { } instrument) diff --git a/src/Anubis/Trading/TradingService.cs b/src/Anubis/Trading/TradingService.cs index dbed9a3..ec0cbf3 100644 --- a/src/Anubis/Trading/TradingService.cs +++ b/src/Anubis/Trading/TradingService.cs @@ -330,6 +330,8 @@ public sealed partial class TradingService : IDisposable ConfirmPrice = Quotes.ConfirmAsync, MarketOpen = MarketOpenAsync, PendingSplit = (instrument, ct) => PendingSplitAsync(account.AccountId, instrument, ct), + Splits = SplitsAsync, + AwaitingRebuild = account.Environment != TradingEnvironments.Simulation, AfterFills = async ct => await Equity.TakeAsync(ct).ConfigureAwait(false), Gate = Risk is null ? null : Risk.GateAsync, LivePermit = Stages.LiveRefusalAsync, @@ -351,7 +353,6 @@ public sealed partial class TradingService : IDisposable await GuardAsync("azioni societarie", () => _market.RefreshCorporateActionsAsync(cancellationToken), cancellationToken).ConfigureAwait(false); } - await GuardAsync("azioni societarie nei registri", () => CorporateActionsAsync(cancellationToken), cancellationToken).ConfigureAwait(false); foreach (var manager in _managers.Values) { await StartAccountAsync(manager, cancellationToken).ConfigureAwait(false); @@ -411,6 +412,7 @@ public sealed partial class TradingService : IDisposable { if (manager.Broker is PaperBroker paper) { + await GuardAsync("azioni societarie nei registri", () => CorporateActionsAsync(manager, cancellationToken), cancellationToken).ConfigureAwait(false); await paper.CatchUpAsync(MinuteBarsAsync, cancellationToken).ConfigureAwait(false); } else @@ -418,6 +420,9 @@ public sealed partial class TradingService : IDisposable await Reconciler.CheckKeyAsync(manager, cancellationToken).ConfigureAwait(false); Guard?.Step("esecuzioni dal broker " + name); await RebuildAsync(manager, cancellationToken).ConfigureAwait(false); + + // After the rebuild: a split or a dividend needs the quantities held at its date (SPEC 15.1). + await GuardAsync("azioni societarie nei registri", () => CorporateActionsAsync(manager, cancellationToken), cancellationToken).ConfigureAwait(false); } Guard?.Step("riconciliazione " + name); @@ -438,14 +443,11 @@ public sealed partial class TradingService : IDisposable /// 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; - } + internal Task RebuildAsync(OrderManager manager, CancellationToken cancellationToken) => + manager.RebuildAsync(cancellationToken, ct => ProtectAsync(manager, ct)); + private async Task ProtectAsync(OrderManager manager, CancellationToken cancellationToken) + { 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\"") @@ -840,7 +842,7 @@ public sealed partial class TradingService : IDisposable public async Task ReconcileAllAsync(CancellationToken cancellationToken) { await RefreshSpecsAsync(cancellationToken).ConfigureAwait(false); - foreach (var manager in _managers.Values) + foreach (var manager in _managers.Values.Where(m => !m.AwaitingRebuild)) { await Reconciler.ReconcileAsync(manager, cancellationToken).ConfigureAwait(false); } @@ -852,6 +854,19 @@ public sealed partial class TradingService : IDisposable /// public async Task CorporateActionsAsync(CancellationToken cancellationToken) { + foreach (var manager in _managers.Values.Where(m => !m.AwaitingRebuild)) + { + await CorporateActionsAsync(manager, cancellationToken).ConfigureAwait(false); + } + } + + private async Task CorporateActionsAsync(OrderManager manager, CancellationToken cancellationToken) + { + if (manager.Account.Broker != Venues.Alpaca) + { + return; + } + var today = DateOnly.FromDateTime(_clock.UtcNow.UtcDateTime); var actions = await _db.ReadAsync(s => s.QueryAsync( "SELECT symbol, kind, ex_date, ratio, cash_amount, currency, new_symbol, source, source_key FROM corporate_actions WHERE ex_date <= @d ORDER BY ex_date", @@ -862,34 +877,37 @@ public sealed partial class TradingService : IDisposable Currency = r.TextOrNull("currency"), NewSymbol = r.TextOrNull("new_symbol"), }, ("d", BarStore.DayText(today))), cancellationToken).ConfigureAwait(false); - foreach (var manager in _managers.Values.Where(m => m.Account.Broker == Venues.Alpaca)) - { - var positions = await Ledger.PositionsAsync(manager.Account.AccountId, cancellationToken).ConfigureAwait(false); - var held = new Dictionary(StringComparer.Ordinal); - foreach (var id in positions.Select(p => p.InstrumentId).Distinct()) - { - if (await _catalog.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } instrument) - { - held[instrument.Symbol] = instrument; - } - } + var positions = await Ledger.PositionsAsync(manager.Account.AccountId, cancellationToken).ConfigureAwait(false); - foreach (var action in actions.Where(a => held.ContainsKey(a.Symbol))) + // What was sold since still owes the dividends of when it was held: a rebuild or a long stop brings them late. + var traded = await _db.ReadAsync(s => s.QueryAsync("SELECT DISTINCT instrument_id FROM fills WHERE account_id = @a AND executed_at >= @at", r => r.Id("instrument_id"), + ("a", manager.Account.AccountId), ("at", _clock.UtcNow - SoldStillOwed)), cancellationToken).ConfigureAwait(false); + var held = new Dictionary(StringComparer.Ordinal); + foreach (var id in positions.Select(p => p.InstrumentId).Concat(traded).Distinct()) + { + if (await _catalog.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } instrument) { - var instrument = held[action.Symbol]; - if (action.ChangesShares) - { - // The ledger and, on the simulator, the broker's book, together and once. - await manager.ApplySplitAsync(instrument, action, cancellationToken).ConfigureAwait(false); - } - else if (action.Kind == CorporateActionKinds.CashDividend && action.CashAmount is > 0m) - { - await PayDividendAsync(manager, instrument, action, cancellationToken).ConfigureAwait(false); - } + held[instrument.Symbol] = instrument; + } + } + + foreach (var action in actions.Where(a => held.ContainsKey(a.Symbol))) + { + var instrument = held[action.Symbol]; + if (action.ChangesShares) + { + // The ledger and, on the simulator, the broker's book, together and once. + await manager.ApplySplitAsync(instrument, action, cancellationToken).ConfigureAwait(false); + } + else if (action.Kind == CorporateActionKinds.CashDividend && action.CashAmount is > 0m) + { + await PayDividendAsync(manager, instrument, action, cancellationToken).ConfigureAwait(false); } } } + private static readonly TimeSpan SoldStillOwed = TimeSpan.FromDays(90); + private async Task PayDividendAsync(OrderManager manager, Instrument instrument, CorporateAction action, CancellationToken cancellationToken) { var key = "div:" + action.SourceKey; @@ -901,8 +919,8 @@ public sealed partial class TradingService : IDisposable var exDate = new DateTimeOffset(action.ExDate.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero); var currency = action.Currency ?? account.Currency; - var strategies = (await Ledger.PositionsAsync(account.AccountId, cancellationToken).ConfigureAwait(false)) - .Where(p => p.InstrumentId == instrument.Id).Select(p => p.Strategy).Distinct(StringComparer.Ordinal).ToList(); + var strategies = await _db.ReadAsync(s => s.QueryAsync("SELECT DISTINCT strategy FROM fills WHERE account_id = @a AND instrument_id = @i", r => r.Text("strategy"), + ("a", account.AccountId), ("i", instrument.Id)), cancellationToken).ConfigureAwait(false); var held = new List<(string Strategy, decimal Quantity)>(); foreach (var strategy in strategies) { @@ -940,13 +958,7 @@ public sealed partial class TradingService : IDisposable private async Task PendingSplitAsync(Guid accountId, Instrument instrument, CancellationToken cancellationToken) { - var today = DateOnly.FromDateTime(_clock.UtcNow.UtcDateTime); - var splits = await _db.ReadAsync(s => s.QueryAsync( - "SELECT kind, ex_date, ratio, source, source_key FROM corporate_actions WHERE symbol = @s AND ex_date <= @d AND kind IN (@k1, @k2) ORDER BY ex_date DESC", - r => new CorporateAction(instrument.Symbol, r.Text("kind"), BarStore.ParseDay(r.Text("ex_date")), r.Text("source"), r.Text("source_key")) { Ratio = r.MoneyOrNull("ratio") }, - ("s", instrument.Symbol), ("d", BarStore.DayText(today)), ("k1", CorporateActionKinds.Split), ("k2", CorporateActionKinds.StockDividend)), cancellationToken) - .ConfigureAwait(false); - foreach (var split in splits.Where(s => s.ChangesShares)) + foreach (var split in (await SplitsAsync(instrument, cancellationToken).ConfigureAwait(false)).Reverse()) { if (!await AppliedAsync(accountId, split.SourceKey, cancellationToken).ConfigureAwait(false)) { @@ -957,6 +969,16 @@ public sealed partial class TradingService : IDisposable return null; } + private Task> SplitsAsync(Instrument instrument, CancellationToken cancellationToken) + { + var today = DateOnly.FromDateTime(_clock.UtcNow.UtcDateTime); + return _db.ReadAsync>(async s => [.. (await s.QueryAsync( + "SELECT kind, ex_date, ratio, source, source_key FROM corporate_actions WHERE symbol = @s AND ex_date <= @d AND kind IN (@k1, @k2) ORDER BY ex_date", + r => new CorporateAction(instrument.Symbol, r.Text("kind"), BarStore.ParseDay(r.Text("ex_date")), r.Text("source"), r.Text("source_key")) { Ratio = r.MoneyOrNull("ratio") }, + ("s", instrument.Symbol), ("d", BarStore.DayText(today)), ("k1", CorporateActionKinds.Split), ("k2", CorporateActionKinds.StockDividend)).ConfigureAwait(false)) + .Where(a => a.ChangesShares)], cancellationToken); + } + private Task MarketOpenAsync(Instrument instrument, CancellationToken cancellationToken) { if (instrument.IsCrypto) diff --git a/tests/Anubis.Tests/RestoreServerTests.cs b/tests/Anubis.Tests/RestoreServerTests.cs index ce3724e..9849940 100644 --- a/tests/Anubis.Tests/RestoreServerTests.cs +++ b/tests/Anubis.Tests/RestoreServerTests.cs @@ -94,6 +94,24 @@ public sealed class RestoreServerTests StringAssert.Contains(ServerHarness.Location(unknown), "errore=scelta"); } + // A damaged archive: refused, and the file is still not there, however many turns the loop makes. + foreach (var damage in new[] { "index.json", "users.jsonl" }) + { + var saved = new Backups(new DataDirectory(data), SystemClock.Instance).List().Single(b => b.Reason == "a-mano"); + var part = Path.Combine(saved.Folder, Backups.ArchiveFolder, damage); + var good = await File.ReadAllTextAsync(part); + await File.WriteAllTextAsync(part, good[..(good.Length / 2)]); + using (var failed = await server.PostFormAsync("/", "/azioni/servizio/ripristina", ("password", ServerHarness.AdminPassword), ("salvataggio", saved.Name))) + { + StringAssert.Contains(ServerHarness.Location(failed), "errore=importazione", damage); + } + + await File.WriteAllTextAsync(part, good); + await Task.Delay(6000); + Assert.IsFalse(File.Exists(file), "Trap 20, after a damaged " + damage); + StringAssert.Contains(await server.TextAsync("/"), "Il file del database non c'è"); + } + Assert.IsFalse(File.Exists(file), "Trap 20: no database by itself."); File.Copy(away, file); await server.WaitForAsync(HostMode.Ready); @@ -260,6 +278,48 @@ public sealed class RestoreServerTests TempFolder.Delete(data); } + [TestMethod] + public async Task AfterAFailedMigrationTheDatabaseCanBeChosenAgain() + { + var (env, postgres) = await ServerHarness.DockerOnEngineAsync(); + await using var engine = postgres; + var data = TempFolder.Create("migration-choice"); + 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)")); + } + + File.Delete(directory.InstallationFile); + await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data, waitReady: false)) + { + await server.WaitForAsync(HostMode.IdentityProblem); + for (var i = 0; i < 2; i++) + { + using var failed = await server.PostFormAsync("/", "/azioni/servizio/usa-questo", ("password", ServerHarness.AdminPassword)); + StringAssert.Contains(ServerHarness.Location(failed), "errore=importazione"); + } + + 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/usa-questo", ("password", ServerHarness.AdminPassword))) + { + Assert.AreEqual("/", ServerHarness.Location(again)); + } + + await server.WaitForAsync(HostMode.Ready); + } + + TempFolder.Delete(data); + } + [TestMethod] public async Task WithAnotherSecretKeyNothingCrashesAndTheAccessIsResetFromTheCommandLine() { diff --git a/tests/Anubis.Tests/RestoreTests.cs b/tests/Anubis.Tests/RestoreTests.cs index 978168f..a447fdb 100644 --- a/tests/Anubis.Tests/RestoreTests.cs +++ b/tests/Anubis.Tests/RestoreTests.cs @@ -262,8 +262,7 @@ public sealed class RestoreTests 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()); + using var service = Service(rig); var manager = rig.Manager(a.Broker, a.Context); await service.RebuildAsync(manager, _none); @@ -300,4 +299,209 @@ public sealed class RestoreTests var open = await a.Paper.GetOpenOrdersAsync(_none); Assert.AreEqual(own.Quantity, open.Sum(o => o.Quantity), "One stop, for the whole quantity."); } + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task ARebuildInterruptedHalfwayIsTakenUpFromTheSamePoint() + { + await using var a = await Account.OpenAsync(); + await a.BuyAsync(a.Btc, 0.01m, 57_000m); + var archive = await a.ArchiveAsync(); + await a.BuyAsync(a.Eth, 0.5m, 1_900m); + a.Rig.Clock.Advance(TimeSpan.FromHours(30)); + await a.Rig.Ledger.SetStopAsync(a.Context.AccountId, a.Btc.Id, StrategyNames.CryptoTrend, 58_500m, _none); + await a.TurnsAsync(a.Manager, 2); + await a.BuyAsync(a.Eth, 1m, 1_900m); + var stops = (await a.Paper.GetOpenOrdersAsync(_none)).Select(o => o.ClientOrderId).Order(StringComparer.Ordinal).ToList(); + + // A copy put back by hand: the bot is active, and the broker stops answering after the orders are written. + var rig = await a.Rig.RestoreAsync(archive); + a.Restored.Add(rig); + var manager = rig.Manager(a.Broker, a.Context); + var settings = new SettingsStore(rig.Db, rig.Clock, new EventBus()); + using var service = Service(rig); + a.Broker.FailFillsAt = 2; + await Assert.ThrowsExactlyAsync(() => service.RebuildAsync(manager, _none)); + Assert.IsNotEmpty(await rig.QueryAsync("SELECT id FROM orders WHERE reason = 'rebuilt from the broker'", r => r.Id("id")), "Interrupted after the orders."); + Assert.AreEqual("stopped", (await settings.GetAsync(SettingsStore.BotState.Key)).Value, "The protection comes before the first row."); + + // The last execution made it into the ledger: what comes before it is still to be read. + var last = (await a.Paper.GetFillsAsync(DateTimeOffset.MinValue, _none)).MaxBy(f => f.ExecutedAt)!; + await rig.Ledger.RecordFillAsync(new LedgerFill(a.Context.AccountId, a.Eth.Id, StrategyNames.CryptoTrend, last.ExecutionId, last.Side, last.Quantity, last.Price, last.Fee, + last.FeeCurrency, last.ExecutedAt), _none); + + // The next attempt knows every order already, and finishes all the same. + await service.RebuildAsync(manager, _none); + await a.SameLedgerAsync(rig, "The ledger is the one that was lost, stops included."); + await new Reconciler(rig.Db, rig.Clock, rig.Ledger).ReconcileAsync(manager, _none); + await manager.AlignStopsAsync(_none); + CollectionAssert.AreEqual(stops, (await a.Paper.GetOpenOrdersAsync(_none)).Select(o => o.ClientOrderId).Order(StringComparer.Ordinal).ToList(), "No stop was touched."); + Assert.HasCount(1, await rig.QueryAsync("SELECT message FROM notifications WHERE kind = 'ledger_rebuilt'", r => r.Text("message"))); + Assert.IsFalse((await manager.RebuildAsync(_none)).FoundAnything); + } + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task AnOldStopReplayedFromTheBrokerSellsNothingToday() + { + // The stop fired in two executions, the strategy bought again later: only the last position counts. + await using var a = await Account.OpenAsync(); + await a.BuyAsync(a.Btc, 0.01m, 57_000m); + var archive = await a.ArchiveAsync(); + a.Broker.SplitStopFills = true; + a.Rig.Clock.Advance(TimeSpan.FromHours(2)); + a.Rig.Quote(a.Btc.Symbol, 56_500m, 56_510m); + await a.TurnsAsync(a.Manager, 4); + a.Rig.Quote(a.Btc.Symbol, 60_000m, 60_010m); + await a.TurnsAsync(a.Manager, 2); + await a.BuyAsync(a.Btc, 0.01m, 57_500m); + + var (rig, manager) = await a.RestoreAsync(archive); + var before = await rig.QueryAsync("SELECT id FROM notifications WHERE kind = 'fill'", r => r.Id("id")); + Assert.IsTrue((await manager.RebuildAsync(_none)).FoundAnything); + Assert.IsEmpty(await rig.QueryAsync("SELECT id FROM executions WHERE purpose = 'protective'", r => r.Id("id")), "Nothing is sold for a stop of the past."); + Assert.HasCount(before.Count, await rig.QueryAsync("SELECT id FROM notifications WHERE kind = 'fill'", r => r.Id("id")), "Old executions do not reach the phone as new."); + await manager.AlignStopsAsync(_none); + await a.TurnsAsync(manager, 3); + Assert.AreEqual(0.01m, (await a.Paper.GetPositionsAsync(_none)).Single(p => p.Symbol == a.Btc.Symbol).Quantity, 0.001m); + Assert.AreEqual(57_500m, (await a.Paper.GetOpenOrdersAsync(_none)).Single().StopPrice); + } + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task UntilItIsRebuiltAnAccountIsNotTouched() + { + await using var a = await Account.OpenAsync(); + await a.BuyAsync(a.Btc, 0.01m, 57_000m); + var archive = await a.ArchiveAsync(); + + // Days later: a trade opened and closed, then the stop the archive knows fires. + a.Rig.Clock.Advance(TimeSpan.FromDays(3)); + await a.BuyAsync(a.Eth, 1m, 1_900m); + await a.SellAsync(a.Eth, 1m); + a.Rig.Clock.Advance(TimeSpan.FromDays(6)); + a.Rig.Quote(a.Btc.Symbol, 56_500m, 56_510m); + await a.TurnsAsync(a.Manager, 3); + + var (rig, manager) = await a.RestoreAsync(archive); + manager.AwaitingRebuild = true; + var count = async () => (await rig.QueryAsync("SELECT id FROM fills", r => r.Id("id"))).Count; + var known = await count(); + Assert.AreEqual(0, await manager.SyncFillsAsync(_none)); + await manager.RefreshAsync(_none); + await manager.AlignStopsAsync(_none); + Assert.AreEqual(ReconcileResolution.NotCompared, await new Reconciler(rig.Db, rig.Clock, rig.Ledger).ResolveAsync(manager, ReconcileChoice.Align, "test", _none)); + Assert.AreEqual(known, await count(), "No execution is written before the rebuild."); + await AskCloseAllAsync(rig); + Assert.AreEqual(0, await CloseAllAsync(rig, manager), "And nothing is sold."); + + Assert.IsTrue((await manager.RebuildAsync(_none)).FoundAnything); + Assert.IsFalse(manager.AwaitingRebuild); + await manager.SyncFillsAsync(_none); + await a.SameLedgerAsync(rig, "The trade of the days in between is there."); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task APendingCloseAllDoesNotSurviveTheRestore() + { + await using var a = await Account.OpenAsync(); + await a.BuyAsync(a.Btc, 0.01m, 57_000m); + await AskCloseAllAsync(a.Rig); + var (rig, manager) = await a.RestoreAsync(await a.ArchiveAsync()); + await manager.RebuildAsync(_none); + Assert.AreEqual(0, await CloseAllAsync(rig, manager), "The command belonged to before the archive."); + Assert.HasCount(1, await rig.QueryAsync("SELECT message FROM notifications WHERE kind = 'close_all_dropped'", r => r.Text("message"))); + } + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task SplitsMeetTheRebuiltExecutionsAtTheirDate() + { + // 10 shares in the archive; then 5 more, a 2-for-1 split, 8 new shares sold, and a stop put after the split. + await using var rig = await TradingRig.CreateAsync(); + var folder = TempFolder.Create("restore-split"); + try + { + await Installation.CheckAsync(rig.Db, new DataDirectory(Path.Combine(folder, "data")), rig.Clock, _none); + var context = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Demo); + var msft = await rig.InstrumentAsync(TradingRig.Stock("MSFT")); + rig.Quote(msft.Symbol, 399.9m, 400m); + var paper = rig.Paper(PaperOptions.Alpaca(), context.AccountId, persist: false); + await paper.DepositAsync(100_000m, "USD", _none); + await rig.Ledger.RecordCapitalAsync(context.AccountId, StrategyNames.EquityMomentum, 100_000m, "USD", "test", _none); + var broker = new FaultyBroker(paper, TradingEnvironments.Demo); + var split = new CorporateAction("MSFT", CorporateActionKinds.Split, new DateOnly(2026, 11, 12), "test", "split-msft") { Ratio = 2m }; + Task> SplitsAsync(Instrument i, CancellationToken ct) => + Task.FromResult>(rig.Clock.UtcNow >= new DateTimeOffset(2026, 11, 12, 0, 0, 0, TimeSpan.Zero) ? [split] : []); + var manager = rig.Manager(broker, context, splits: SplitsAsync); + async Task TradeAsync(OrderSide side, decimal quantity, decimal? stop) + { + rig.Refresh(); + Assert.IsNull((await manager.SubmitAsync(new TradeIntent(msft.Id, StrategyNames.EquityMomentum, side, quantity, side == OrderSide.Buy ? OrderPurpose.Entry : OrderPurpose.Exit, Ids.NewId(rig.Clock)) + { + StopLevel = stop, + StartAggressive = true, + }, _none)).Refusal); + await TurnsAsync(); + } + + async Task TurnsAsync() + { + for (var i = 0; i < 3; i++) + { + rig.Refresh(); + await paper.PumpAsync(_none); + await manager.TickAsync(_none); + rig.Clock.Advance(_minute); + } + } + + await TradeAsync(OrderSide.Buy, 10m, 360m); + var archive = Path.Combine(folder, "archivio"); + await Archive.ExportAsync(rig.Db, archive, rig.Clock, _none); + rig.Clock.Advance(TimeSpan.FromDays(1)); + await TradeAsync(OrderSide.Buy, 5m, 360m); + + rig.Clock.Advance(TimeSpan.FromDays(1)); + rig.Quote(msft.Symbol, 199.9m, 200m); + await paper.ApplySplitAsync("MSFT", 2m, 15m, new DateTimeOffset(2026, 11, 12, 0, 0, 0, TimeSpan.Zero), _none); + await manager.ApplySplitAsync(msft, split, _none); + await TurnsAsync(); + await TradeAsync(OrderSide.Sell, 8m, null); + var lost = (await rig.Ledger.PositionAsync(context.AccountId, msft.Id, StrategyNames.EquityMomentum, _none))!; + Assert.AreEqual((22m, 180m), (lost.Quantity, lost.StopPrice)); + + await using var restored = await rig.RestoreAsync(archive); + await Installation.RenewAsync(restored.Db, new DataDirectory(Path.Combine(folder, "data")), restored.Clock, "Salvataggio ripristinato", _none); + var again = restored.Manager(broker, context, splits: SplitsAsync); + again.StopGeneration = restored.Clock.UtcNow.UtcTicks; + var report = await again.RebuildAsync(_none); + Assert.IsEmpty(report.Unclear, string.Join(" | ", report.Unclear)); + var position = (await restored.Ledger.PositionAsync(context.AccountId, msft.Id, StrategyNames.EquityMomentum, _none))!; + Assert.AreEqual((22m, 180m), (position.Quantity, position.StopPrice)); + Assert.IsEmpty(await restored.QueryAsync("SELECT message FROM notifications WHERE kind = 'ledger_refused_fill'", r => r.Text("message"))); + Assert.HasCount(1, await restored.QueryAsync("SELECT id FROM applied_actions WHERE source_key = 'split-msft'", r => r.Id("id"))); + var reconciled = await new Reconciler(restored.Db, restored.Clock, restored.Ledger).ReconcileAsync(again, _none); + Assert.IsEmpty(reconciled.Differences, string.Join(" | ", reconciled.Differences.Select(d => d.Message))); + } + finally + { + TempFolder.Delete(folder); + } + } + + private static TradingService Service(TradingRig rig) => new(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()); + + private static Task AskCloseAllAsync(TradingRig rig) => rig.Db.WriteAsync(s => s.ExecuteAsync( + "INSERT INTO risk_state (id, world, state, created_at, updated_at) VALUES (@id, 'bot', @j, @t, @t)", _none, + ("id", Ids.NewId(rig.Clock)), ("j", new DbJson("{\"close_all\":true,\"close_all_since\":\"2026-11-07T10:00:00+00:00\"}")), ("t", rig.Clock.UtcNow)), _none); + + private static async Task CloseAllAsync(TradingRig rig, OrderManager manager) + { + var risk = new RiskEngine(rig.Db, rig.Clock, rig.Ledger, new StageBook(rig.Db, rig.Clock, TradingConsent.None, (_, _, _) => Task.FromResult(false)), new SettingsStore(rig.Db, rig.Clock, new EventBus()), new FxStore(rig.Db, rig.Clock), rig.FindAsync, rig.QuoteAsync); + await risk.ContinueCloseAllAsync([manager], _none); + return (await rig.QueryAsync("SELECT id FROM executions WHERE purpose = 'protective'", r => r.Id("id"))).Count; + } } diff --git a/tests/Anubis.Tests/TradingServiceTests.cs b/tests/Anubis.Tests/TradingServiceTests.cs index f0e3049..5c58158 100644 --- a/tests/Anubis.Tests/TradingServiceTests.cs +++ b/tests/Anubis.Tests/TradingServiceTests.cs @@ -72,6 +72,33 @@ public sealed class TradingServiceTests }, (await StrategiesAsync(rig).ConfigureAwait(false)).ToArray(), "A strategy with a history stays where it is."); } + [TestMethod] + [TestCategory(Category.Integration)] + public async Task AnAccountOfTheBrokerWaitsForItsRebuildBeforeAnythingTouchesIt() + { + await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); + var http = new FakeHttp().On(_ => true, _ => FakeHttp.Respond("{}", System.Net.HttpStatusCode.BadRequest)); + using var service = Service(rig, http, new Dictionary { ["ALPACA_API_KEY_DEMO"] = "test-key", ["ALPACA_API_SECRET_DEMO"] = "test-secret" }); + await service.StartAsync(_none).ConfigureAwait(false); + var paper = service.Managers.Single(m => m.Account.Environment == TradingEnvironments.Demo); + Assert.IsTrue(paper.AwaitingRebuild, "The broker answers nothing: the rebuild is still to be done."); + Assert.IsTrue(service.Managers.Where(m => m != paper).All(m => !m.AwaitingRebuild)); + CollectionAssert.Contains(service.AccountsToRebuild.ToList(), paper.Account.Name); + + // A split and a dividend in the table, and the five minutes of the reconciliation: nothing reaches the account. + var msft = await rig.InstrumentAsync(TradingRig.Stock("MSFT")).ConfigureAwait(false); + await service.Ledger.RecordCapitalAsync(paper.Account.AccountId, StrategyNames.EquityMomentum, 5000m, "USD", "test", _none).ConfigureAwait(false); + await service.Ledger.RecordFillAsync(rig.Fill(paper.Account, msft, StrategyNames.EquityMomentum, OrderSide.Buy, 10m, 400m, feeCurrency: "USD"), _none).ConfigureAwait(false); + await rig.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO corporate_actions (id, symbol, kind, ex_date, ratio, source, source_key, created_at) VALUES (@id, 'MSFT', 'split', '2026-11-11', @r, 'test', 'k', @now)", + _none, ("id", Ids.NewId(rig.Clock)), ("r", 2m), ("now", rig.Clock.UtcNow)), _none).ConfigureAwait(false); + rig.Clock.Advance(TimeSpan.FromDays(2)); + var before = http.Requests.Count; + await service.CorporateActionsAsync(_none).ConfigureAwait(false); + await service.ReconcileAllAsync(_none).ConfigureAwait(false); + Assert.AreEqual(10m, (await service.Ledger.PositionAsync(paper.Account.AccountId, msft.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!.Quantity); + Assert.AreEqual(before, http.Requests.Count, "The reconciliation does not ask anything either."); + } + [TestMethod] [TestCategory(Category.Integration)] public async Task TheSimulatorHoldsTheMoneyItsLedgersGive() @@ -121,7 +148,8 @@ public sealed class TradingServiceTests // month is still in the table: it came before the purchase and must change nothing. await rig.Db.WriteAsync(async s => { - foreach (var (kind, day, ratio, cash, key) in new[] { ("cash_dividend", "2026-11-11", (decimal?)null, (decimal?)0.75m, "div-msft"), ("split", "2026-11-12", 2m, null, "split-msft"), ("split", "2026-10-01", 3m, null, "split-msft-old") }) + foreach (var (kind, day, ratio, cash, key) in new[] { ("cash_dividend", "2026-11-11", (decimal?)null, (decimal?)0.75m, "div-msft"), ("split", "2026-11-12", 2m, null, "split-msft"), ("split", "2026-10-01", 3m, null, "split-msft-old"), + ("cash_dividend", "2026-11-14", null, 0.50m, "div-msft-2") }) { await s.ExecuteAsync("INSERT INTO corporate_actions (id, symbol, kind, ex_date, ratio, cash_amount, currency, source, source_key, created_at) " + "VALUES (@id, 'MSFT', @k, @d, @r, @c, 'USD', 'test', @key, @now)", _none, @@ -150,6 +178,12 @@ public sealed class TradingServiceTests Assert.HasCount(1, await rig.QueryAsync("SELECT code FROM journal WHERE code = 'split_applied'", r => r.Text("code")).ConfigureAwait(false)); Assert.IsEmpty(http.Requests); + // A dividend after the split pays the new shares, sold since or not. + rig.Clock.Advance(TimeSpan.FromDays(3)); + await service.Ledger.RecordFillAsync(rig.Fill(account, msft, StrategyNames.EquityMomentum, OrderSide.Sell, 4m, 200m, feeCurrency: "USD"), _none).ConfigureAwait(false); + await service.CorporateActionsAsync(_none).ConfigureAwait(false); + CollectionAssert.AreEquivalent(new[] { 7.5m, 10m }, (await DividendsAsync().ConfigureAwait(false)).ToArray(), "20 new shares at 0,50."); + // Every photograph values the positions at the market, not at their last fill. service.Quotes.Put(new Quote("MSFT", 230m, 230.10m, rig.Clock.UtcNow)); await service.PhotographAsync(_none).ConfigureAwait(false); diff --git a/tests/Anubis.Tests/TradingSupport.cs b/tests/Anubis.Tests/TradingSupport.cs index e6afc7e..e9c953f 100644 --- a/tests/Anubis.Tests/TradingSupport.cs +++ b/tests/Anubis.Tests/TradingSupport.cs @@ -114,7 +114,7 @@ internal sealed class TradingRig : IAsyncDisposable } public OrderManager Manager(IBrokerAccount broker, AccountContext account, Func>? marketOpen = null, - Func>? pendingSplit = null) + Func>? pendingSplit = null, Func>>? splits = null) { var manager = new OrderManager(Db, Clock, Ledger, broker, account, Installation, FindAsync, QuoteAsync) { @@ -122,6 +122,7 @@ internal sealed class TradingRig : IAsyncDisposable ConfirmPrice = QuoteAsync, MarketOpen = marketOpen ?? ((_, _) => Task.FromResult(true)), PendingSplit = pendingSplit, + Splits = splits, }; _owned.Add(manager); return manager; @@ -181,6 +182,12 @@ internal sealed class FaultyBroker(IBrokerAccount inner, string? environment = n /// Every fill is reported twice. public bool DuplicateFills { get; set; } + /// Every execution of a stop is reported in two halves. + public bool SplitStopFills { get; set; } + + /// Which reading of the fills fails, counting from now: 1 the next, 2 the one after it. + public int FailFillsAt { get; set; } + /// Every call fails as if the network were down. public bool Down { get; set; } @@ -246,7 +253,21 @@ internal sealed class FaultyBroker(IBrokerAccount inner, string? environment = n public async Task> GetFillsAsync(DateTimeOffset since, CancellationToken cancellationToken) { + if (FailFillsAt > 0 && --FailFillsAt == 0) + { + throw new BrokerException("risposta interrotta", retryable: true); + } + var fills = await Guard(() => inner.GetFillsAsync(since, cancellationToken)).ConfigureAwait(false); + if (SplitStopFills) + { + fills = [.. fills.SelectMany(f => ClientOrderIds.Parse(f.ClientOrderId)?.Purpose != OrderPurpose.Stop ? [f] : new[] + { + f with { ExecutionId = f.ExecutionId + "a", Quantity = f.Quantity / 2m, Fee = f.Fee / 2m }, + f with { ExecutionId = f.ExecutionId + "b", Quantity = f.Quantity / 2m, Fee = f.Fee / 2m, ExecutedAt = f.ExecutedAt.AddSeconds(1) }, + })]; + } + return DuplicateFills ? [.. fills, .. fills] : fills; }