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.");
// 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;
}
}