Rebuild the state from the brokers after a restore and refuse an older copy
A restore, an import or an adopted database restarts protected: the engine stays stopped, reads from the broker what the archive does not know (orders, stops, executions, also from the OKX history up to 89 days), cancels orders left working, protects what it finds and waits for the user. Strategies with real money stay exit only until confirmed again. The database of before the restore, put back by mistake, is refused by its fingerprint. A failed migration leaves the engine off with one backup and a way to try again; an archive is checked whole before the database is touched; a changed secret key no longer crashes anything, and "anubis access reset" gives the access back to whoever holds the computer. The image runs the db and access commands without the guard. refs #69 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3da9b00f44
commit
4897594b87
40 files changed
+1871
-90
No files matched your search
@@ -0,0 +1,303 @@
|
||||
using Anubis.Core;
|
||||
using Anubis.Data;
|
||||
using Anubis.Db;
|
||||
using Anubis.Platform;
|
||||
using Anubis.Trading;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class RestoreTests
|
||||
{
|
||||
private static readonly CancellationToken _none = CancellationToken.None;
|
||||
private static readonly TimeSpan _minute = TimeSpan.FromSeconds(60);
|
||||
|
||||
/// <summary>A demo account: a simulator whose book lives outside the database, as a broker's does.</summary>
|
||||
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<TradingRig> Restored { get; } = [];
|
||||
|
||||
public static async Task<Account> 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<string> 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<List<string>> 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<List<string>> FillsAsync(TradingRig rig) => [.. (await rig.QueryAsync("SELECT execution_id, side, quantity, price, fee FROM fills",
|
||||
r => $"{r.Text("execution_id")} {r.Text("side")} {r.Money("quantity")} {r.Money("price")} {r.Money("fee")}")).Order(StringComparer.Ordinal)];
|
||||
|
||||
CollectionAssert.AreEqual(await PositionsAsync(Rig), await PositionsAsync(restored), message);
|
||||
CollectionAssert.AreEqual(await FillsAsync(Rig), await FillsAsync(restored), message);
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
foreach (var rig in Restored)
|
||||
{
|
||||
await rig.DisposeAsync();
|
||||
}
|
||||
|
||||
await Rig.DisposeAsync();
|
||||
TempFolder.Delete(Folder);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Simulation)]
|
||||
public async Task WhatTheAccountDidAfterTheArchiveIsRebuiltFromTheBroker()
|
||||
{
|
||||
await using var a = await Account.OpenAsync();
|
||||
await a.BuyAsync(a.Btc, 0.01m, 57_000m);
|
||||
var archive = await a.ArchiveAsync();
|
||||
|
||||
// After the archive: the BTC stop rises, part is sold, ETH is bought, and one purchase is still working.
|
||||
a.Rig.Clock.Advance(TimeSpan.FromHours(5));
|
||||
await a.Rig.Ledger.SetStopAsync(a.Context.AccountId, a.Btc.Id, StrategyNames.CryptoTrend, 58_500m, _none);
|
||||
await a.TurnsAsync(a.Manager, 2);
|
||||
await a.SellAsync(a.Btc, 0.004m);
|
||||
await a.BuyAsync(a.Eth, 1m, 1_900m);
|
||||
var stops = (await a.Paper.GetOpenOrdersAsync(_none)).Where(o => o.Kind == OrderKind.Stop).Select(o => o.ClientOrderId).ToList();
|
||||
Assert.HasCount(2, stops);
|
||||
a.Rig.Refresh();
|
||||
Assert.IsNull((await a.Manager.SubmitAsync(new TradeIntent(a.Eth.Id, StrategyNames.CryptoTrend, OrderSide.Buy, 0.5m, OrderPurpose.Entry, Ids.NewId(a.Rig.Clock)) { StopLevel = 1_900m }, _none)).Refusal);
|
||||
await a.TurnsAsync(a.Manager, 1);
|
||||
Assert.HasCount(1, (await a.Paper.GetOpenOrdersAsync(_none)).Where(o => o.Side == OrderSide.Buy).ToList());
|
||||
|
||||
// The broker repeats its fills, as brokers do.
|
||||
a.Broker.DuplicateFills = true;
|
||||
var (rig, manager) = await a.RestoreAsync(archive);
|
||||
var report = await manager.RebuildAsync(_none);
|
||||
Assert.IsTrue(report.FoundAnything);
|
||||
Assert.IsEmpty(report.Unclear, string.Join(" | ", report.Unclear));
|
||||
Assert.IsEmpty((await a.Paper.GetOpenOrdersAsync(_none)).Where(o => o.Side == OrderSide.Buy).ToList(), "The purchase nobody follows any more is canceled.");
|
||||
await a.SameLedgerAsync(rig, "The rebuilt ledger is the one that was lost.");
|
||||
Assert.AreEqual(58_500m, (await rig.Ledger.PositionAsync(a.Context.AccountId, a.Btc.Id, StrategyNames.CryptoTrend, _none))!.StopPrice,
|
||||
"A stop raised after the archive never goes back down.");
|
||||
|
||||
// A second pass finds nothing, reconciliation agrees, and the stops on the account are exactly those needed.
|
||||
var second = await manager.RebuildAsync(_none);
|
||||
Assert.AreEqual((0, 0, false), (second.Orders, second.Fills, second.FoundAnything));
|
||||
var reconciled = await new Reconciler(rig.Db, rig.Clock, rig.Ledger).ReconcileAsync(manager, _none);
|
||||
Assert.IsEmpty(reconciled.Differences, string.Join(" | ", reconciled.Differences.Select(d => d.Message)));
|
||||
await manager.AlignStopsAsync(_none);
|
||||
await a.TurnsAsync(manager, 3);
|
||||
var open = await a.Paper.GetOpenOrdersAsync(_none);
|
||||
Assert.IsTrue(open.All(o => o.Kind == OrderKind.Stop), "Only stops.");
|
||||
foreach (var position in (await rig.Ledger.PositionsAsync(a.Context.AccountId, _none)).Where(p => p.Quantity > 0m))
|
||||
{
|
||||
var symbol = position.InstrumentId == a.Btc.Id ? a.Btc.Symbol : a.Eth.Symbol;
|
||||
Assert.AreEqual(position.Quantity, open.Where(o => o.Symbol == symbol).Sum(o => o.Quantity), symbol);
|
||||
}
|
||||
|
||||
// A stop moved now takes a name of its own: the names used after the archive are gone from the ledger, not from the account.
|
||||
await rig.Ledger.SetStopAsync(a.Context.AccountId, a.Btc.Id, StrategyNames.CryptoTrend, 59_000m, _none);
|
||||
await a.TurnsAsync(manager, 2);
|
||||
var moved = (await a.Paper.GetOpenOrdersAsync(_none)).Single(o => o.Symbol == a.Btc.Symbol);
|
||||
Assert.AreEqual(59_000m, moved.StopPrice);
|
||||
Assert.DoesNotContain(moved.ClientOrderId, stops);
|
||||
Assert.HasCount(1, await rig.QueryAsync("SELECT message FROM journal WHERE code = 'ledger_rebuilt'", r => r.Text("message")));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Simulation)]
|
||||
public async Task AStopThatFiredAfterTheArchiveClosesThePosition()
|
||||
{
|
||||
await using var a = await Account.OpenAsync();
|
||||
await a.BuyAsync(a.Btc, 0.01m, 57_000m);
|
||||
var archive = await a.ArchiveAsync();
|
||||
a.Rig.Clock.Advance(TimeSpan.FromHours(2));
|
||||
a.Rig.Quote(a.Btc.Symbol, 56_500m, 56_510m);
|
||||
await a.TurnsAsync(a.Manager, 3);
|
||||
Assert.AreEqual(0m, (await a.Rig.Ledger.PositionAsync(a.Context.AccountId, a.Btc.Id, StrategyNames.CryptoTrend, _none))?.Quantity ?? 0m);
|
||||
|
||||
var (rig, manager) = await a.RestoreAsync(archive);
|
||||
await manager.RebuildAsync(_none);
|
||||
await new Reconciler(rig.Db, rig.Clock, rig.Ledger).ReconcileAsync(manager, _none);
|
||||
Assert.AreEqual(0m, (await rig.Ledger.PositionAsync(a.Context.AccountId, a.Btc.Id, StrategyNames.CryptoTrend, _none))?.Quantity ?? 0m);
|
||||
await a.SameLedgerAsync(rig, "The sale made by the stop is in the rebuilt ledger.");
|
||||
await a.TurnsAsync(manager, 2);
|
||||
Assert.IsEmpty(await a.Paper.GetOpenOrdersAsync(_none), "Nothing is put back for a position that is gone.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Simulation)]
|
||||
public async Task OrdersOfAnotherInstallationAreNotTakenAndAnUpToDateLedgerFindsNothing()
|
||||
{
|
||||
await using var a = await Account.OpenAsync();
|
||||
var foreign = new[]
|
||||
{
|
||||
ClientOrderIds.Build("OTHR", TradingEnvironments.Demo, StrategyNames.CryptoTrend, OrderPurpose.Entry, "AAAAAAAA", 1),
|
||||
ClientOrderIds.Build(TradingRig.Installation, TradingEnvironments.Live, StrategyNames.CryptoTrend, OrderPurpose.Entry, "BBBBBBBB", 1),
|
||||
"un-ordine-a-mano",
|
||||
};
|
||||
foreach (var id in foreign)
|
||||
{
|
||||
await a.Paper.SubmitOrderAsync(new OrderRequest(id, a.Btc.Symbol, OrderSide.Buy, OrderKind.Limit, 0.001m, TimeInForce.Gtc) { LimitPrice = 50_000m }, _none);
|
||||
}
|
||||
|
||||
await a.BuyAsync(a.Btc, 0.01m, 57_000m);
|
||||
Assert.IsFalse((await a.Manager.RebuildAsync(_none)).FoundAnything);
|
||||
Assert.HasCount(0, await a.Rig.QueryAsync("SELECT client_order_id FROM orders WHERE client_order_id IN (@a, @b, @c)", r => r.Text("client_order_id"),
|
||||
("a", foreign[0]), ("b", foreign[1]), ("c", foreign[2])));
|
||||
Assert.HasCount(3, (await a.Paper.GetOpenOrdersAsync(_none)).Where(o => foreign.Contains(o.ClientOrderId)).ToList(), "Not ours, not touched.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Simulation)]
|
||||
public async Task ARestoreFromOneEngineToTheOtherRebuildsTheSame()
|
||||
{
|
||||
if (!await TestDb.PostgresAvailableAsync())
|
||||
{
|
||||
Assert.Inconclusive("PostgreSQL per i test non raggiungibile: la prova tra motori gira in CI e con `tasks ci`.");
|
||||
}
|
||||
|
||||
await using var a = await Account.OpenAsync();
|
||||
await a.BuyAsync(a.Btc, 0.01m, 57_000m);
|
||||
var archive = await a.ArchiveAsync();
|
||||
await a.SellAsync(a.Btc, 0.003m);
|
||||
var (rig, manager) = await a.RestoreAsync(archive, a.Rig.Db.Engine == DbEngine.Sqlite ? DbEngine.Postgres : DbEngine.Sqlite);
|
||||
Assert.IsTrue((await manager.RebuildAsync(_none)).FoundAnything);
|
||||
await a.SameLedgerAsync(rig, "The other engine gets the same ledger.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Simulation)]
|
||||
public async Task AnOldCopyPutBackByHandIsRecognisedOnTheAccountAndStopsTheBot()
|
||||
{
|
||||
await using var a = await Account.OpenAsync();
|
||||
await a.BuyAsync(a.Btc, 0.01m, 57_000m);
|
||||
var archive = await a.ArchiveAsync();
|
||||
await a.SellAsync(a.Btc, 0.003m);
|
||||
|
||||
// A database dump put back with the fingerprint it had: nothing says it is old, except the account.
|
||||
var rig = await a.Rig.RestoreAsync(archive);
|
||||
a.Restored.Add(rig);
|
||||
await rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE installation SET protected_restart = @no", _none, ("no", false)), _none);
|
||||
using var service = new TradingService(rig.Db, rig.Clock, new EventBus(), new SecretStore(rig.Db, rig.Clock, new byte[32]), null, new FxStore(rig.Db, rig.Clock),
|
||||
TradingConsent.None, new Guid("0193a7c0-0000-7000-8000-0000000000aa"), new FakeHttp());
|
||||
var manager = rig.Manager(a.Broker, a.Context);
|
||||
await service.RebuildAsync(manager, _none);
|
||||
|
||||
var settings = new SettingsStore(rig.Db, rig.Clock, new EventBus());
|
||||
Assert.AreEqual("stopped", (await settings.GetAsync(SettingsStore.BotState.Key)).Value);
|
||||
Assert.IsTrue((await Installation.ReadRowAsync(rig.Db, _none))!.ProtectedRestart);
|
||||
Assert.HasCount(1, await rig.QueryAsync("SELECT message FROM notifications WHERE kind = 'protected_restart'", r => r.Text("message")));
|
||||
await a.SameLedgerAsync(rig, "And the ledger is rebuilt all the same.");
|
||||
|
||||
// Confirmed by the user, a start that finds nothing new leaves the bot as it is.
|
||||
await settings.SetAsync(SettingsStore.BotState.Key, "active", "test");
|
||||
await Installation.ClearProtectedRestartAsync(rig.Db, _none);
|
||||
await service.RebuildAsync(manager, _none);
|
||||
Assert.AreEqual("active", (await settings.GetAsync(SettingsStore.BotState.Key)).Value);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Simulation)]
|
||||
public async Task AStopTheDatabaseDoesNotKnowIsAdoptedWithoutStoppingTheBot()
|
||||
{
|
||||
// The guard put a stop while the engine was off, and its note got lost.
|
||||
await using var a = await Account.OpenAsync();
|
||||
await a.BuyAsync(a.Btc, 0.01m, 57_000m);
|
||||
var own = (await a.Paper.GetOpenOrdersAsync(_none)).Single();
|
||||
await a.Paper.CancelOrderAsync(own.ClientOrderId, own.Symbol, _none);
|
||||
var guard = ClientOrderIds.Build(TradingRig.Installation, TradingEnvironments.Demo, StrategyNames.CryptoTrend, OrderPurpose.Stop, "GGGGGGGG", 1);
|
||||
await a.Paper.SubmitOrderAsync(new OrderRequest(guard, a.Btc.Symbol, OrderSide.Sell, OrderKind.Stop, own.Quantity, TimeInForce.Gtc) { StopPrice = 57_000m }, _none);
|
||||
|
||||
var report = await a.Manager.RebuildAsync(_none);
|
||||
Assert.AreEqual((1, false), (report.Orders, report.FoundAnything));
|
||||
await new Reconciler(a.Rig.Db, a.Rig.Clock, a.Rig.Ledger).ReconcileAsync(a.Manager, _none);
|
||||
await a.Manager.AlignStopsAsync(_none);
|
||||
await a.TurnsAsync(a.Manager, 2);
|
||||
var open = await a.Paper.GetOpenOrdersAsync(_none);
|
||||
Assert.AreEqual(own.Quantity, open.Sum(o => o.Quantity), "One stop, for the whole quantity.");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user