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 = Service(rig); 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."); } [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."); // One of them was cut right after its row: it still has no state. await rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE orders SET status = 'created', filled_quantity = 0 WHERE reason = 'rebuilt from the broker' AND purpose <> 'stop'", _none), _none); // 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."); Assert.IsEmpty(await rig.QueryAsync("SELECT id FROM orders WHERE status = 'created'", r => r.Id("id")), "Every rebuilt order has the state the broker says."); 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 asked = new List<(string Symbols, DateOnly Since)>(); var photographs = new List(); var down = true; var again = restored.Manager(broker, context, splits: async (i, ct) => down ? [] : await SplitsAsync(i, ct), refreshSplits: (symbols, since, _) => { asked.Add((string.Join(',', symbols), since)); return down ? throw new MarketDataException("rete giù") : Task.CompletedTask; }, afterFills: async ct => photographs.Add((await restored.Ledger.PositionAsync(context.AccountId, msft.Id, StrategyNames.EquityMomentum, ct))!.Quantity)); again.AwaitingRebuild = true; again.StopGeneration = restored.Clock.UtcNow.UtcTicks; var known = await restored.QueryAsync("SELECT id FROM fills", r => r.Id("id")); await Assert.ThrowsExactlyAsync(() => again.RebuildAsync(_none)); Assert.IsTrue(again.AwaitingRebuild, "Without the splits nothing is replayed."); Assert.HasCount(known.Count, await restored.QueryAsync("SELECT id FROM fills", r => r.Id("id"))); down = false; var report = await again.RebuildAsync(_none); Assert.AreEqual(2, asked.Count(a => a == ("MSFT", new DateOnly(2026, 11, 9))), "Back to a day before the last execution of the archive."); CollectionAssert.AreEqual(new[] { 22m }, photographs, "One photograph, when every split is in its place."); 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"))); await again.RebuildAsync(_none); Assert.HasCount(2, asked, "Nothing new to write: no need to ask."); 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); } } [TestMethod] [TestCategory(Category.Simulation)] public async Task StoppingAnAccountNotRebuiltYetKeepsTheStopOfAPurchase() { // The purchase filled and the engine died before reading it; "Ferma tutto" comes while the account waits. await using var a = await Account.OpenAsync(); a.Rig.Refresh(); await a.Manager.SubmitAsync(new TradeIntent(a.Btc.Id, StrategyNames.CryptoTrend, OrderSide.Buy, 0.01m, OrderPurpose.Entry, Ids.NewId(a.Rig.Clock)) { StopLevel = 57_000m, StartAggressive = true }, _none); a.Broker.FailFillsAt = 2; await Assert.ThrowsExactlyAsync(() => a.Manager.TickAsync(_none)); a.Rig.Refresh(); await a.Paper.PumpAsync(_none); var manager = a.Rig.Manager(a.Broker, a.Context); manager.AwaitingRebuild = true; Assert.IsEmpty(await manager.CancelWorkingAsync("manual_stop")); await manager.RebuildAsync(_none); Assert.HasCount(1, await manager.CancelWorkingAsync(LiveReasons.Restart)); Assert.AreEqual(57_000m, (await a.Rig.Ledger.PositionAsync(a.Context.AccountId, a.Btc.Id, StrategyNames.CryptoTrend, _none))!.StopPrice); Assert.AreEqual(57_000m, (await a.Paper.GetOpenOrdersAsync(_none)).Single().StopPrice); } [TestMethod] [TestCategory(Category.Simulation)] public async Task ExecutionsOfWhileTheBotWasOffComeBeforeTheSplitsAndTheDividends() { await using var rig = await TradingRig.CreateAsync(); var context = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Demo); var msft = await rig.InstrumentAsync(TradingRig.Stock("MSFT")); var nvda = await rig.InstrumentAsync(TradingRig.Stock("NVDA")); 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); using var service = Service(rig); Task> SplitsAsync(Instrument i, CancellationToken ct) => rig.Db.ReadAsync>(async s => [.. await s.QueryAsync("SELECT source_key FROM corporate_actions WHERE symbol = @s AND kind = 'split'", r => new CorporateAction(i.Symbol, "split", new DateOnly(2026, 11, 12), "test", r.Text("source_key")) { Ratio = 10m }, ("s", i.Symbol))], ct); OrderManager Manager() => rig.Manager(broker, context, splits: SplitsAsync); async Task TurnsAsync(OrderManager manager) { for (var i = 0; i < 3; i++) { rig.Refresh(); await paper.PumpAsync(_none); await manager.TickAsync(_none); rig.Clock.Advance(_minute); } } Task<(Guid?, string?)> BuyAsync(OrderManager manager, Instrument instrument, decimal quantity) => manager.SubmitAsync( new TradeIntent(instrument.Id, StrategyNames.EquityMomentum, OrderSide.Buy, quantity, OrderPurpose.Entry, Ids.NewId(rig.Clock)) { StopLevel = 360m, StartAggressive = true }, _none); // 10 MSFT with their stop; NVDA bought and sold before, then bought again: filled, and the engine dies before reading it. rig.Quote("MSFT", 399.9m, 400m); rig.Quote("NVDA", 399.9m, 400m); var first = Manager(); await BuyAsync(first, msft, 10m); await TurnsAsync(first); await rig.Ledger.RecordFillAsync(rig.Fill(context, nvda, StrategyNames.EquityMomentum, OrderSide.Buy, 1m, 400m, feeCurrency: "USD"), _none); await rig.Ledger.RecordFillAsync(rig.Fill(context, nvda, StrategyNames.EquityMomentum, OrderSide.Sell, 1m, 400m, feeCurrency: "USD"), _none); rig.Clock.Advance(_minute); await BuyAsync(first, nvda, 10m); broker.FailFillsAt = 2; await Assert.ThrowsExactlyAsync(() => first.TickAsync(_none)); rig.Refresh(); await paper.PumpAsync(_none); // Off: the stop of MSFT fires on Wednesday; Thursday, 10-for-1 for both and a dividend of MSFT. rig.Clock.Advance(TimeSpan.FromDays(1)); rig.Quote("MSFT", 350m, 350.1m); await paper.PumpAsync(_none); rig.Clock.Advance(TimeSpan.FromDays(1)); rig.Quote("MSFT", 35m, 35.01m); rig.Quote("NVDA", 40m, 40.01m); await rig.Db.WriteAsync(async s => { foreach (var (symbol, kind, ratio, cash) in new[] { ("MSFT", "split", (decimal?)10m, (decimal?)null), ("NVDA", "split", 10m, null), ("MSFT", "cash_dividend", null, 1m) }) { await s.ExecuteAsync("INSERT INTO corporate_actions (id, symbol, kind, ex_date, ratio, cash_amount, currency, source, source_key, created_at) VALUES (@id, @s, @k, '2026-11-12', @r, @c, 'USD', 'test', @key, @now)", _none, ("id", Ids.NewId(rig.Clock)), ("s", symbol), ("k", kind), ("r", ratio), ("c", cash), ("key", kind + symbol), ("now", rig.Clock.UtcNow)); } }, _none); var second = Manager(); second.AwaitingRebuild = true; var report = await second.RebuildAsync(_none); Assert.AreEqual(0, report.Orders); await service.CorporateActionsAsync(second, _none); Assert.AreEqual(0m, (await rig.Ledger.PositionAsync(context.AccountId, msft.Id, StrategyNames.EquityMomentum, _none))?.Quantity ?? 0m, "The stop sold the 10 old shares."); Assert.AreEqual(100m, (await rig.Ledger.PositionAsync(context.AccountId, nvda.Id, StrategyNames.EquityMomentum, _none))!.Quantity, "The purchase finds its split."); Assert.IsEmpty(await rig.QueryAsync("SELECT id FROM cash_ledger WHERE kind = 'dividend'", r => r.Id("id")), "Sold before the ex-date: nothing is owed."); Assert.IsEmpty(await rig.QueryAsync("SELECT id FROM executions WHERE purpose = 'protective'", r => r.Id("id"))); Assert.IsNotEmpty(await rig.QueryAsync("SELECT id FROM notifications WHERE kind = 'fill' AND message LIKE '%Vend%MSFT%'", r => r.Id("id")), "The sale of the stop reaches the phone."); } [TestMethod] [TestCategory(Category.Simulation)] public async Task TheRestOfAStopThatFiredInPartWhileOffIsSold() { await using var rig = await TradingRig.CreateAsync(); var context = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Demo); var msft = await rig.InstrumentAsync(TradingRig.Stock("MSFT")); 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 first = rig.Manager(broker, context); rig.Quote("MSFT", 399.9m, 400m); await first.SubmitAsync(new TradeIntent(msft.Id, StrategyNames.EquityMomentum, OrderSide.Buy, 1.5m, OrderPurpose.Entry, Ids.NewId(rig.Clock)) { StopLevel = 360m, StartAggressive = true }, _none); for (var i = 0; i < 3; i++) { rig.Refresh(); await paper.PumpAsync(_none); await first.TickAsync(_none); rig.Clock.Advance(_minute); } // The stop of the fraction is a day order and is over; that of the whole share fires while the bot is off. var stops = await paper.GetOpenOrdersAsync(_none); Assert.HasCount(2, stops); await paper.CancelOrderAsync(stops.Single(o => o.Quantity == 0.5m).ClientOrderId, "MSFT", _none); rig.Clock.Advance(TimeSpan.FromHours(1)); rig.Quote("MSFT", 350m, 350.1m); await paper.PumpAsync(_none); var second = rig.Manager(broker, context); second.AwaitingRebuild = true; await second.RebuildAsync(_none); Assert.AreEqual(0.5m, (await rig.QueryAsync("SELECT quantity FROM executions WHERE purpose = 'protective' AND status = 'working'", r => r.Money("quantity"))).Single()); } [TestMethod] [TestCategory(Category.Simulation)] public async Task TheProtectiveSalesOfTheArchiveAreNotContinued() { await using var a = await Account.OpenAsync(); await a.BuyAsync(a.Btc, 0.01m, 57_000m); await a.Manager.SubmitAsync(new TradeIntent(a.Btc.Id, StrategyNames.CryptoTrend, OrderSide.Sell, 0.01m, OrderPurpose.Protective, Ids.NewId(a.Rig.Clock)), _none); var simulated = await a.Rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation); await a.Rig.Manager(a.Rig.Paper(PaperOptions.Okx(), simulated.AccountId, persist: false), simulated) .SubmitAsync(new TradeIntent(a.Btc.Id, StrategyNames.CryptoTrend, OrderSide.Sell, 0.01m, OrderPurpose.Protective, Ids.NewId(a.Rig.Clock)), _none); var (rig, _) = await a.RestoreAsync(await a.ArchiveAsync()); async Task StatusAsync(Guid account) => (await rig.QueryAsync("SELECT status FROM executions WHERE account_id = @a AND purpose = 'protective'", r => r.Text("status"), ("a", account))).Single(); Assert.AreEqual(ExecutionStates.Canceled, await StatusAsync(a.Context.AccountId)); Assert.AreEqual(ExecutionStates.Working, await StatusAsync(simulated.AccountId), "The simulator went back in time with its sales."); // One of an execution that is over, still open on the account, is canceled there too. a.Rig.Refresh(); await a.Manager.CancelWorkingAsync("prova"); await a.Rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE executions SET status = 'canceled' WHERE status = 'working'", _none), _none); await a.Manager.SubmitAsync(new TradeIntent(a.Btc.Id, StrategyNames.CryptoTrend, OrderSide.Sell, 0.004m, OrderPurpose.Exit, Ids.NewId(a.Rig.Clock)), _none); await a.Manager.TickAsync(_none); Assert.HasCount(1, (await a.Paper.GetOpenOrdersAsync(_none)).Where(o => o.Kind == OrderKind.Limit).ToList()); await a.Rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE executions SET status = 'canceled' WHERE status = 'working'", _none), _none); await a.Rig.Manager(a.Broker, a.Context).RebuildAsync(_none); Assert.IsEmpty((await a.Paper.GetOpenOrdersAsync(_none)).Where(o => o.Kind == OrderKind.Limit).ToList()); } [TestMethod] [TestCategory(Category.Simulation)] public async Task ProtectionFromTheLoopStopsTheOtherAccountsAndKeepsWhatIsOfToday() { 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); foreach (var (asked, kept) in new[] { ("2026-11-07T10:00:00+00:00", false), ("2026-12-31T10:00:00+00:00", true) }) { 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 = Service(rig); await service.StartAsync(_none); var simulator = service.Managers.Single(m => m.Account.Broker == Venues.Okx); rig.Clock.Advance(_minute); var (buy, _) = await simulator.SubmitAsync(new TradeIntent(a.Btc.Id, StrategyNames.CryptoTrend, OrderSide.Buy, 0.001m, OrderPurpose.Entry, Ids.NewId(rig.Clock)), _none); await AskCloseAllAsync(rig, asked); var manager = rig.Manager(a.Broker, a.Context); await service.RebuildAsync(manager, _none); Assert.AreEqual(ExecutionStates.Canceled, (await rig.QueryAsync("SELECT status FROM executions WHERE id = @id", r => r.Text("status"), ("id", buy))).Single()); var state = (await rig.QueryAsync("SELECT state FROM risk_state WHERE world = 'bot'", r => r.Json("state").Text)).Single(); Assert.AreEqual(kept, System.Text.Json.JsonDocument.Parse(state).RootElement.GetProperty("close_all").GetBoolean(), asked); Assert.HasCount(1, await rig.QueryAsync("SELECT message FROM notifications WHERE kind = 'protected_restart'", r => r.Text("message"))); } } [TestMethod] [TestCategory(Category.Simulation)] public async Task AnAttemptCutRightAfterTheProtectionStillNamesTheStopsAnew() { 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 = await a.Rig.RestoreAsync(archive); a.Restored.Add(rig); await Installation.ProtectAsync(rig.Db, rig.Clock, rig.Clock.UtcNow, "prova", _none); using var service = Service(rig); var manager = rig.Manager(a.Broker, a.Context); await service.RebuildAsync(manager, _none); Assert.AreEqual((await Installation.ReadRowAsync(rig.Db, _none))!.RenewedAt.UtcTicks, manager.StopGeneration); } [TestMethod] [TestCategory(Category.Simulation)] public async Task AResumedRebuildOfTheGuardsStopsDoesNotStopTheBot() { 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); Task PlaceAsync(int sequence) => a.Paper.SubmitOrderAsync(new OrderRequest(ClientOrderIds.Build(TradingRig.Installation, TradingEnvironments.Demo, StrategyNames.CryptoTrend, OrderPurpose.Stop, "GGGGGGGG", sequence), a.Btc.Symbol, OrderSide.Sell, OrderKind.Stop, own.Quantity / 2m, TimeInForce.Gtc) { StopPrice = 57_000m }, _none); using var service = Service(a.Rig); await PlaceAsync(1); a.Broker.FailFillsAt = 2; await Assert.ThrowsExactlyAsync(() => service.RebuildAsync(a.Manager, _none)); await PlaceAsync(2); await service.RebuildAsync(a.Manager, _none); Assert.IsFalse((await Installation.ReadRowAsync(a.Rig.Db, _none))!.ProtectedRestart); Assert.IsEmpty(await a.Rig.QueryAsync("SELECT message FROM notifications WHERE kind = 'protected_restart'", r => r.Text("message"))); } [TestMethod] [TestCategory(Category.Simulation)] public async Task TheGuardCountsFromTheMomentTheFiguresOfTheAccountWereRead() { await using var a = await Account.OpenAsync(); await a.BuyAsync(a.Btc, 0.01m, 57_000m); var known = await a.Manager.GuardAccountAsync(_none); var read = a.Rig.Clock.UtcNow; a.Rig.Clock.Advance(_minute); await a.SellAsync(a.Btc, 0.004m); var held = (await a.Rig.Ledger.PositionAsync(a.Context.AccountId, a.Btc.Id, StrategyNames.CryptoTrend, _none))!.Quantity; await a.Paper.SubmitOrderAsync(new OrderRequest("a-mano", a.Btc.Symbol, OrderSide.Buy, OrderKind.Market, 0.5m, TimeInForce.Gtc), _none); await a.TurnsAsync(a.Manager, 2); foreach (var stop in await a.Paper.GetOpenOrdersAsync(_none)) { await a.Paper.CancelOrderAsync(stop.ClientOrderId, stop.Symbol, _none); } var state = new Anubis.Supervision.GuardState(a.Rig.Clock.UtcNow, TradingRig.Installation, [known with { WrittenAt = read }]); var outcome = await Anubis.Supervision.GuardRepair.RunAsync(state, state.Accounts[0], a.Broker, a.Rig.Clock, _none); Assert.AreEqual(held, outcome.Placed.Single().Quantity, "What was sold after the figures, not what the user holds."); } 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, string since = "2026-11-07T10:00:00+00:00") => 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\":\"{since}\"}}")), ("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; } }