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
@@ -117,7 +117,7 @@ public sealed class ArchiveTests
|
||||
File.WriteAllLines(cash, lines.Skip(1));
|
||||
await using var target = await TestDb.CreateAsync().ConfigureAwait(false);
|
||||
await Assert.ThrowsAsync<InvalidDataException>(() => Archive.ImportAsync(target.Db, Path.Combine(folder, "a"), _clock)).ConfigureAwait(false);
|
||||
Assert.AreEqual(0L, (await Archive.CountsAsync(target.Db).ConfigureAwait(false))["accounts"], "un'importazione fallita non lascia righe");
|
||||
Assert.IsEmpty(await Archive.CountsAsync(target.Db).ConfigureAwait(false), "un archivio guasto non lascia nemmeno lo schema");
|
||||
|
||||
await Assert.ThrowsAsync<IOException>(() => Archive.ExportAsync(source.Db, Path.Combine(folder, "a"), _clock)).ConfigureAwait(false);
|
||||
}
|
||||
@@ -140,7 +140,7 @@ public sealed class ArchiveTests
|
||||
var backups = new Backups(new DataDirectory(folder), clock);
|
||||
for (var i = 0; i < 16; i++)
|
||||
{
|
||||
await backups.TakeAsync(test.Db, i == 0 ? "prima-della-migrazione" : "notturno").ConfigureAwait(false);
|
||||
await backups.TakeAsync(test.Db, "notturno").ConfigureAwait(false);
|
||||
clock.Advance(TimeSpan.FromDays(1));
|
||||
}
|
||||
|
||||
@@ -180,7 +180,176 @@ public sealed class ArchiveTests
|
||||
await test.Db.WriteAsync(s => s.ExecuteAsync($"DELETE FROM {Migrations.VersionTable} WHERE version = @v", ("v", Migrations.Latest))).ConfigureAwait(false);
|
||||
if (Migrations.Latest > 1)
|
||||
{
|
||||
await Assert.ThrowsAsync<IOException>(() => Migrations.MigrateAsync(test.Db, _clock, _ => throw new IOException("disco pieno"), CancellationToken.None)).ConfigureAwait(false);
|
||||
await Assert.ThrowsAsync<SchemaException>(() => Migrations.MigrateAsync(test.Db, _clock, _ => throw new IOException("disco pieno"), CancellationToken.None)).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task ADamagedArchiveLeavesTheDatabaseUntouchedAndTheGoodOneGoesInAfterwards()
|
||||
{
|
||||
await using var source = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
|
||||
await SeedAsync(source.Db).ConfigureAwait(false);
|
||||
var folder = TempFolder.Create("archive-retry");
|
||||
try
|
||||
{
|
||||
var good = Path.Combine(folder, "a");
|
||||
await Archive.ExportAsync(source.Db, good, _clock).ConfigureAwait(false);
|
||||
await using var target = await TestDb.CreateAsync().ConfigureAwait(false);
|
||||
|
||||
async Task RefusedAsync(string file, Func<string, string> damage)
|
||||
{
|
||||
var path = Path.Combine(good, file);
|
||||
var before = await File.ReadAllTextAsync(path).ConfigureAwait(false);
|
||||
await File.WriteAllTextAsync(path, damage(before)).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await Archive.ImportAsync(target.Db, good, _clock).ConfigureAwait(false);
|
||||
Assert.Fail("Accepted: " + file);
|
||||
}
|
||||
catch (Exception ex) when (Anubis.Server.Forms.IsArchiveProblem(ex))
|
||||
{
|
||||
}
|
||||
|
||||
await File.WriteAllTextAsync(path, before).ConfigureAwait(false);
|
||||
Assert.IsTrue((await Migrations.StatusAsync(target.Db, CancellationToken.None).ConfigureAwait(false)).IsEmpty, "Not even the schema: " + file);
|
||||
}
|
||||
|
||||
// A row less, a number that is not one, a total that changed, a row that is not an object.
|
||||
await RefusedAsync("cash_ledger.jsonl", t => t[(t.IndexOf('\n', StringComparison.Ordinal) + 1)..]).ConfigureAwait(false);
|
||||
await RefusedAsync("fills.jsonl", t => t.Replace("68950", "novanta", StringComparison.Ordinal)).ConfigureAwait(false);
|
||||
await RefusedAsync("fills.jsonl", t => t.Replace("0.0182", "0.0183", StringComparison.Ordinal).Replace("-0.0183", "-0.0182", StringComparison.Ordinal)).ConfigureAwait(false);
|
||||
await RefusedAsync("accounts.jsonl", _ => "[]\n").ConfigureAwait(false);
|
||||
|
||||
// An index that points outside its folder, or names a table twice.
|
||||
await RefusedAsync(Archive.IndexFile, t => t.Replace("\"fills.jsonl\"", "\"../fills.jsonl\"", StringComparison.Ordinal)).ConfigureAwait(false);
|
||||
await RefusedAsync(Archive.IndexFile, t => t.Replace("\"fills\"", "\"accounts\"", StringComparison.Ordinal)).ConfigureAwait(false);
|
||||
|
||||
await Archive.ImportAsync(target.Db, good, _clock).ConfigureAwait(false);
|
||||
Assert.AreEqual(2L, (await Archive.CountsAsync(target.Db).ConfigureAwait(false))["fills"]);
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(folder);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task AnOlderArchiveGoesInAfterAnImportThatStoppedHalfWay()
|
||||
{
|
||||
await using var old = await TestDb.CreateAsync().ConfigureAwait(false);
|
||||
await Migrations.MigrateAsync(old.Db, _clock, null, CancellationToken.None, upTo: 8).ConfigureAwait(false);
|
||||
var folder = TempFolder.Create("archive-old");
|
||||
try
|
||||
{
|
||||
await Archive.ExportAsync(old.Db, Path.Combine(folder, "a"), _clock).ConfigureAwait(false);
|
||||
|
||||
// The first attempt created the schema of the archive and stopped there (power lost).
|
||||
await using var target = await TestDb.CreateAsync().ConfigureAwait(false);
|
||||
await Migrations.MigrateAsync(target.Db, _clock, null, CancellationToken.None, upTo: 5).ConfigureAwait(false);
|
||||
await Archive.ImportAsync(target.Db, Path.Combine(folder, "a"), _clock).ConfigureAwait(false);
|
||||
Assert.AreEqual(Migrations.Latest, (await Migrations.StatusAsync(target.Db, CancellationToken.None).ConfigureAwait(false)).Current);
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(folder);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task AnImportIsSealedUntilTheInstallationIsRenewedAndSoIsTheSqliteCopy()
|
||||
{
|
||||
await using var source = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
|
||||
var folder = TempFolder.Create("seal");
|
||||
try
|
||||
{
|
||||
var data = new DataDirectory(Path.Combine(folder, "data"));
|
||||
await Installation.CheckAsync(source.Db, data, _clock).ConfigureAwait(false);
|
||||
var backup = await new Backups(data, _clock).TakeAsync(source.Db, "a-mano").ConfigureAwait(false);
|
||||
|
||||
// The same fingerprint as installation.json is in the archive: without the seal the import would be accepted as it is.
|
||||
await using var target = await TestDb.CreateAsync().ConfigureAwait(false);
|
||||
await Archive.ImportAsync(target.Db, Path.Combine(backup.Folder, Backups.ArchiveFolder), _clock).ConfigureAwait(false);
|
||||
Assert.AreEqual(IdentityVerdict.StaleDatabase, (await Installation.CheckAsync(target.Db, data, _clock).ConfigureAwait(false)).Verdict);
|
||||
|
||||
if (backup.HasSqliteCopy)
|
||||
{
|
||||
var copy = new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = Path.Combine(backup.Folder, Backups.SqliteCopy) };
|
||||
await using var byHand = Database.Open(copy, allowCreate: false);
|
||||
Assert.AreEqual(IdentityVerdict.StaleDatabase, (await Installation.CheckAsync(byHand, data, _clock).ConfigureAwait(false)).Verdict);
|
||||
Assert.IsTrue((await Installation.ReadRowAsync(byHand).ConfigureAwait(false))!.ProtectedRestart);
|
||||
}
|
||||
|
||||
// Renewed, the new one is accepted and the source becomes the old copy.
|
||||
await Installation.RenewAsync(target.Db, data, _clock, "prova").ConfigureAwait(false);
|
||||
Assert.AreEqual(IdentityVerdict.Match, (await Installation.CheckAsync(target.Db, data, _clock).ConfigureAwait(false)).Verdict);
|
||||
Assert.AreEqual(IdentityVerdict.StaleDatabase, (await Installation.CheckAsync(source.Db, data, _clock).ConfigureAwait(false)).Verdict);
|
||||
Assert.AreEqual(Installation.ReadFile(data)!.InstallationId, (await Installation.ReadRowAsync(source.Db).ConfigureAwait(false))!.Id, "The orders of the ledger keep their installation.");
|
||||
|
||||
// Rows without an installation are never taken for an empty database.
|
||||
await SeedAsync(target.Db).ConfigureAwait(false);
|
||||
await target.Db.WriteAsync(s => s.ExecuteAsync("DELETE FROM installation")).ConfigureAwait(false);
|
||||
Assert.AreEqual(IdentityVerdict.DifferentInstallation, (await Installation.CheckAsync(target.Db, data, _clock).ConfigureAwait(false)).Verdict);
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(folder);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task ASeriesOfBackupsOfOneKindNeverPushesOutTheNightlyOnes()
|
||||
{
|
||||
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
|
||||
var folder = TempFolder.Create("kinds");
|
||||
try
|
||||
{
|
||||
var clock = new ManualClock(_clock.UtcNow);
|
||||
var data = new DataDirectory(folder);
|
||||
var backups = new Backups(data, clock);
|
||||
await backups.TakeAsync(test.Db, "notturno").ConfigureAwait(false);
|
||||
var left = Directory.CreateDirectory(Path.Combine(data.Backups, "20260901-010101-notturno.partial"));
|
||||
left.LastWriteTimeUtc = clock.UtcNow.UtcDateTime.AddDays(-3);
|
||||
for (var i = 0; i < Backups.Keep + 3; i++)
|
||||
{
|
||||
// The same second twice: the second one takes a number.
|
||||
await backups.TakeAsync(test.Db, Backups.BeforeMigration).ConfigureAwait(false);
|
||||
clock.Advance(TimeSpan.FromSeconds(i % 2));
|
||||
}
|
||||
|
||||
Assert.HasCount(1, backups.List().Where(b => b.Reason == "notturno").ToList());
|
||||
Assert.HasCount(Backups.Keep, backups.List().Where(b => b.Reason.StartsWith(Backups.BeforeMigration, StringComparison.Ordinal)).ToList());
|
||||
Assert.IsFalse(Directory.Exists(left.FullName), "What a power failure left is cleaned.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(folder);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task AMigrationThatFailsIsASchemaProblemAndLeavesTheVersionBefore()
|
||||
{
|
||||
await using var test = await TestDb.CreateAsync().ConfigureAwait(false);
|
||||
await Migrations.MigrateAsync(test.Db, _clock, null, CancellationToken.None, upTo: 12).ConfigureAwait(false);
|
||||
await test.Db.WriteAsync(s => s.ExecuteAsync("CREATE TABLE cost_estimates (x INTEGER)")).ConfigureAwait(false);
|
||||
var backups = 0;
|
||||
var error = await Assert.ThrowsExactlyAsync<SchemaException>(() => Migrations.MigrateAsync(test.Db, _clock, _ =>
|
||||
{
|
||||
backups++;
|
||||
return Task.CompletedTask;
|
||||
}, CancellationToken.None)).ConfigureAwait(false);
|
||||
Assert.Contains("0013", error.Message);
|
||||
Assert.AreEqual(1, backups);
|
||||
Assert.AreEqual(12, (await Migrations.StatusAsync(test.Db, CancellationToken.None).ConfigureAwait(false)).Current);
|
||||
|
||||
// Without room for the backup nothing is migrated.
|
||||
var full = await Assert.ThrowsExactlyAsync<SchemaException>(() => Migrations.MigrateAsync(test.Db, _clock, _ => throw new IOException("disco pieno"), CancellationToken.None))
|
||||
.ConfigureAwait(false);
|
||||
Assert.Contains("disco pieno", full.Message);
|
||||
}
|
||||
}
|
||||
@@ -175,4 +175,44 @@ public sealed class LiveEngineTests
|
||||
Assert.IsLessThan(live.Instruments[symbol].Spec.LotSize ?? 0m, Math.Abs(quantity - ledger[symbol]), symbol);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A purchase was working when the process stopped. Normally it is proposed again; after a restore (SPEC 15.1) the
|
||||
/// archive may be older than the account, so nothing is proposed: the strategies decide again.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
[DataRow(false)]
|
||||
[DataRow(true)]
|
||||
public async Task AfterARestoreAnInterruptedPurchaseIsNotProposedAgain(bool restored)
|
||||
{
|
||||
var last = LiveFrom.AddDays(120);
|
||||
await using var live = await LiveRig.CreateAsync(LiveFrom, last).ConfigureAwait(false);
|
||||
var found = false;
|
||||
for (var day = LiveFrom; day <= last && !found; day = day.AddDays(1))
|
||||
{
|
||||
await live.DayAsync(day, async _ =>
|
||||
{
|
||||
if (found || await live.WorkingOrdersAsync().ConfigureAwait(false) == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
found = true;
|
||||
await live.Rig.Db.WriteAsync(async s =>
|
||||
{
|
||||
await s.ExecuteAsync("DELETE FROM installation").ConfigureAwait(false);
|
||||
await s.ExecuteAsync("INSERT INTO installation (id, fingerprint, engine, protected_restart, created_at, renewed_at) VALUES (@id, @f, @e, @p, @now, @now)", CancellationToken.None, ("e", "sqlite"),
|
||||
("id", Guid.NewGuid()), ("f", Guid.NewGuid()), ("p", restored), ("now", live.Rig.Clock.UtcNow)).ConfigureAwait(false);
|
||||
}).ConfigureAwait(false);
|
||||
var again = await live.Engine.ResumeAsync(live.Manager, CancellationToken.None).ConfigureAwait(false);
|
||||
Assert.AreEqual(restored ? 0 : 1, Math.Min(again, 1));
|
||||
Assert.AreEqual(0, await live.WorkingOrdersAsync().ConfigureAwait(false), "What was working is canceled either way.");
|
||||
Assert.HasCount(restored ? 0 : again, await live.Rig.QueryAsync("SELECT id FROM planned_orders WHERE status = @s AND execution_id IS NULL", r => r.Id("id"),
|
||||
("s", PlannedStates.Pending)).ConfigureAwait(false));
|
||||
}).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
Assert.IsTrue(found, "A purchase must have been working.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
using System.Globalization;
|
||||
using Anubis.Brokers;
|
||||
using Anubis.Core;
|
||||
using Anubis.Trading;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>The executions of OKX after a long absence or a restore: recent and history, each counted once (issue #69).</summary>
|
||||
[TestClass]
|
||||
[TestCategory(Category.Unit)]
|
||||
public sealed class OkxHistoryTests
|
||||
{
|
||||
private static readonly DateTimeOffset _now = TradingRig.Start;
|
||||
|
||||
private static string Fill(string trade, DateTimeOffset at, string client = "ANUtrnd00000000aE1") =>
|
||||
"{\"side\":\"buy\",\"fillSz\":\"0.01\",\"fillPx\":\"50000\",\"fee\":\"-0.5\",\"feeCcy\":\"EUR\",\"ordId\":\"1" + trade + "\",\"instId\":\"BTC-EUR\",\"instType\":\"SPOT\",\"clOrdId\":\"" + client +
|
||||
"\",\"billId\":\"b" + trade + "\",\"tradeId\":\"" + trade + "\",\"fillTime\":\"" + Ms(at) + "\",\"ts\":\"" + Ms(at) + "\"}";
|
||||
|
||||
private static string Ms(DateTimeOffset at) => at.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
private static string Envelope(IEnumerable<string> items) => "{\"code\":\"0\",\"msg\":\"\",\"data\":[" + string.Join(',', items) + "]}";
|
||||
|
||||
private static OkxTrading Adapter(FakeHttp http) =>
|
||||
new(http.Client(), new ManualClock(_now), new OkxCredentials("doc-key", "doc-secret", "doc-pass"), new OkxTradingOptions { Environment = TradingEnvironments.Demo },
|
||||
TradingConsent.None);
|
||||
|
||||
private static FakeHttp Http(IReadOnlyList<string> history, IReadOnlyList<string> recent) => new FakeHttp()
|
||||
.On(u => u.AbsolutePath == "/api/v5/trade/fills-history", r => FakeHttp.Respond(Envelope(
|
||||
r.RequestUri!.Query.Contains("after=", StringComparison.Ordinal) ? history.Skip(100) : history.Take(100))))
|
||||
.On(u => u.AbsolutePath == "/api/v5/trade/fills", _ => FakeHttp.Respond(Envelope(recent)))
|
||||
.On(u => u.AbsolutePath == "/api/v5/trade/order", _ => FakeHttp.Respond("{\"code\":\"51603\",\"msg\":\"Order does not exist\",\"data\":[]}"));
|
||||
|
||||
[TestMethod]
|
||||
public async Task AfterALongAbsenceTheHistoryIsReadTooAndEachExecutionCountsOnce()
|
||||
{
|
||||
var since = _now.AddDays(-20);
|
||||
string[] history = [.. Enumerable.Range(0, 150).Select(i => Fill((1000 + i).ToString(CultureInfo.InvariantCulture), _now.AddDays(-5).AddMinutes(-i)))];
|
||||
var http = Http(history, [Fill("2000", _now.AddHours(-1)), Fill("1000", _now.AddDays(-5))]);
|
||||
var fills = await Adapter(http).GetFillsAsync(since, CancellationToken.None);
|
||||
|
||||
Assert.HasCount(151, fills);
|
||||
Assert.HasCount(151, fills.Select(f => f.ExecutionId).Distinct().ToList());
|
||||
var asked = http.Urls.Where(u => u.AbsolutePath.EndsWith("/fills-history", StringComparison.Ordinal)).ToList();
|
||||
Assert.HasCount(2, asked, "Two pages of history.");
|
||||
StringAssert.Contains(asked[0].Query, "instType=SPOT");
|
||||
StringAssert.Contains(asked[0].Query, "begin=" + Ms(since));
|
||||
StringAssert.Contains(asked[1].Query, "after=b1099");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheRecentOnesAloneAreEnoughForTheEverydayReading()
|
||||
{
|
||||
var http = Http([], [Fill("2000", _now.AddHours(-1))]);
|
||||
Assert.HasCount(1, await Adapter(http).GetFillsAsync(_now.AddHours(-48), CancellationToken.None));
|
||||
Assert.IsTrue(http.Urls.All(u => u.AbsolutePath == "/api/v5/trade/fills"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheHistoryIsAskedOnlyAsFarAsOkxKeepsIt()
|
||||
{
|
||||
var http = Http([], []);
|
||||
var adapter = Adapter(http);
|
||||
await adapter.GetFillsAsync(_now.AddDays(-400), CancellationToken.None);
|
||||
StringAssert.Contains(http.Urls.First().Query, "begin=" + Ms(_now - OkxTrading.HistoryReach));
|
||||
Assert.AreEqual(OkxTrading.HistoryReach, adapter.FillHistory);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AnOldExecutionWhoseOrderOkxForgotIsReadWithoutAName()
|
||||
{
|
||||
var http = Http([Fill("1000", _now.AddDays(-10), client: "")], []);
|
||||
Assert.AreEqual("", (await Adapter(http).GetFillsAsync(_now.AddDays(-20), CancellationToken.None)).Single().ClientOrderId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
using System.Net;
|
||||
using Anubis.Access;
|
||||
using Anubis.Core;
|
||||
using Anubis.Db;
|
||||
using Anubis.Platform;
|
||||
using Anubis.Server;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>Restore, old copies, failed migrations and a changed secret key as the user meets them (issue #69, SPEC 9.4, 15.1).</summary>
|
||||
[TestClass]
|
||||
[TestCategory(Category.Integration)]
|
||||
public sealed class RestoreServerTests
|
||||
{
|
||||
/// <summary>The database of the data folder is set aside and an empty one takes its place; the answer is how to put it back.</summary>
|
||||
private static async Task<(Func<Task> PutBack, Func<Task> PutNew, TestDb? Empty)> EmptyDatabaseAsync(Dictionary<string, string?> env, string data, TestDb? postgres)
|
||||
{
|
||||
if (postgres is not null)
|
||||
{
|
||||
var empty = await TestDb.CreateAsync(DbEngine.Postgres);
|
||||
ServerHarness.UsePostgres(env, empty);
|
||||
return (() =>
|
||||
{
|
||||
ServerHarness.UsePostgres(env, postgres);
|
||||
return Task.CompletedTask;
|
||||
}, () =>
|
||||
{
|
||||
ServerHarness.UsePostgres(env, empty);
|
||||
return Task.CompletedTask;
|
||||
}, empty);
|
||||
}
|
||||
|
||||
var file = new DataDirectory(data).SqliteFile;
|
||||
var old = data + "-vecchio.sqlite3";
|
||||
var fresh = data + "-nuovo.sqlite3";
|
||||
void Take(string from, string to)
|
||||
{
|
||||
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
|
||||
File.Copy(from, to, overwrite: true);
|
||||
foreach (var f in Directory.EnumerateFiles(Path.GetDirectoryName(file)!).Where(f => f.StartsWith(file, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
File.Delete(f);
|
||||
}
|
||||
}
|
||||
|
||||
Take(file, old);
|
||||
await File.WriteAllBytesAsync(file, []);
|
||||
return (() =>
|
||||
{
|
||||
Take(file, fresh);
|
||||
File.Copy(old, file);
|
||||
return Task.CompletedTask;
|
||||
}, () =>
|
||||
{
|
||||
Take(file, old);
|
||||
File.Copy(fresh, file);
|
||||
return Task.CompletedTask;
|
||||
}, null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AfterARestoreTheOldDatabaseIsRefusedAndTheNewOneWaitsForTheUser()
|
||||
{
|
||||
var (env, postgres) = await ServerHarness.DockerOnEngineAsync();
|
||||
await using var engine = postgres;
|
||||
var data = TempFolder.Create("protected");
|
||||
string password;
|
||||
await using (var first = await ServerHarness.StartAsync("docker", env, dataDir: data))
|
||||
{
|
||||
password = await first.SignInFirstTimeAsync();
|
||||
using var saved = await first.PostFormAsync("/impostazioni", "/azioni/salvataggio");
|
||||
}
|
||||
|
||||
var backup = new Backups(new DataDirectory(data), SystemClock.Instance).List().Single(b => b.Reason == "a-mano");
|
||||
var (putBack, putNew, empty) = await EmptyDatabaseAsync(env, data, postgres);
|
||||
await using var second = empty;
|
||||
await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data, waitReady: false))
|
||||
{
|
||||
await server.WaitForAsync(HostMode.IdentityProblem);
|
||||
using (var restore = await server.PostFormAsync("/", "/azioni/servizio/ripristina", ("password", ServerHarness.AdminPassword), ("salvataggio", backup.Name)))
|
||||
{
|
||||
Assert.AreEqual("/", ServerHarness.Location(restore));
|
||||
}
|
||||
|
||||
// Without the trading engine nothing can be rebuilt: the restart waits.
|
||||
await server.WaitForAsync(HostMode.Ready);
|
||||
using (var signIn = await server.PostFormAsync("/accesso", "/azioni/accesso", ("password", password)))
|
||||
{
|
||||
Assert.AreEqual("/", ServerHarness.Location(signIn));
|
||||
}
|
||||
|
||||
StringAssert.Contains(await server.TextAsync("/"), "Ripartenza protetta");
|
||||
using (var early = await server.PostFormAsync("/rischio", "/azioni/bot/riattiva"))
|
||||
{
|
||||
Assert.AreEqual("stopped", (await server.Host.Services!.Settings.GetAsync(SettingsStore.BotState.Key)).Value);
|
||||
}
|
||||
|
||||
Assert.HasCount(1, await server.Host.Services!.Db.ReadAsync(s => s.QueryAsync("SELECT message FROM journal WHERE code = 'protected_restart'", r => r.Text("message"))));
|
||||
}
|
||||
|
||||
// The database of before the restore comes back, by mistake: same installation, older fingerprint, engine off.
|
||||
await putBack();
|
||||
await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data, waitReady: false))
|
||||
{
|
||||
await server.WaitForAsync(HostMode.IdentityProblem);
|
||||
Assert.AreEqual(IdentityVerdict.StaleDatabase, server.Host.Status.Identity!.Verdict);
|
||||
StringAssert.Contains(await server.TextAsync("/"), "una copia più vecchia");
|
||||
using var health = await server.GetAsync("/health");
|
||||
Assert.AreEqual(HttpStatusCode.ServiceUnavailable, health.StatusCode);
|
||||
Assert.IsNull(server.Host.Services);
|
||||
}
|
||||
|
||||
// The right one: protected until the user confirms, then as before.
|
||||
await putNew();
|
||||
await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data, trading: true))
|
||||
{
|
||||
using (var signIn = await server.PostFormAsync("/accesso", "/azioni/accesso", ("password", password)))
|
||||
{
|
||||
Assert.AreEqual("/", ServerHarness.Location(signIn));
|
||||
}
|
||||
|
||||
for (var i = 0; i < 300 && server.Host.Services!.Trading is not { Started: true }; i++)
|
||||
{
|
||||
await Task.Delay(100);
|
||||
}
|
||||
|
||||
StringAssert.Contains(await server.TextAsync("/rischio"), "Sui conti non c'era niente che il database non conoscesse già");
|
||||
using (var go = await server.PostFormAsync("/rischio", "/azioni/bot/riattiva"))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.Redirect, go.StatusCode);
|
||||
}
|
||||
|
||||
Assert.AreEqual("active", (await server.Host.Services!.Settings.GetAsync(SettingsStore.BotState.Key)).Value);
|
||||
Assert.IsFalse((await Installation.ReadRowAsync(server.Host.Services.Db))!.ProtectedRestart);
|
||||
Assert.IsFalse((await server.TextAsync("/rischio")).Contains("Ripartenza protetta", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
TempFolder.Delete(data);
|
||||
foreach (var left in new[] { data + "-vecchio.sqlite3", data + "-nuovo.sqlite3" })
|
||||
{
|
||||
File.Delete(left);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AFailedMigrationKeepsTheEngineOffAndTakesOneBackup()
|
||||
{
|
||||
var (env, postgres) = await ServerHarness.DockerOnEngineAsync();
|
||||
await using var engine = postgres;
|
||||
var data = TempFolder.Create("migration");
|
||||
var directory = new DataDirectory(data);
|
||||
directory.Ensure();
|
||||
var settings = postgres?.Settings ?? new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = directory.SqliteFile };
|
||||
await using (var db = Database.Open(settings))
|
||||
{
|
||||
await Migrations.MigrateAsync(db, SystemClock.Instance, null, CancellationToken.None, upTo: 12);
|
||||
await Installation.CheckAsync(db, directory, SystemClock.Instance);
|
||||
await db.WriteAsync(s => s.ExecuteAsync("CREATE TABLE cost_estimates (x INTEGER)"));
|
||||
}
|
||||
|
||||
await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data, waitReady: false))
|
||||
{
|
||||
await server.WaitForAsync(HostMode.SchemaProblem);
|
||||
await Task.Delay(1000);
|
||||
Assert.HasCount(1, new Backups(directory, SystemClock.Instance).List(), "One backup, however long the page stays open.");
|
||||
var html = await server.TextAsync("/");
|
||||
StringAssert.Contains(html, "0013");
|
||||
StringAssert.Contains(html, "prima-della-migrazione");
|
||||
|
||||
using (var wrong = await server.PostFormAsync("/", "/azioni/servizio/riprova", ("password", "wrong-password-123")))
|
||||
{
|
||||
StringAssert.Contains(ServerHarness.Location(wrong), "errore=password");
|
||||
}
|
||||
|
||||
await using (var db = Database.Open(settings))
|
||||
{
|
||||
await db.WriteAsync(s => s.ExecuteAsync("DROP TABLE cost_estimates"));
|
||||
}
|
||||
|
||||
using (var again = await server.PostFormAsync("/", "/azioni/servizio/riprova", ("password", ServerHarness.AdminPassword)))
|
||||
{
|
||||
Assert.AreEqual("/", ServerHarness.Location(again));
|
||||
}
|
||||
|
||||
await server.WaitForAsync(HostMode.Ready);
|
||||
}
|
||||
|
||||
TempFolder.Delete(data);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task WithAnotherSecretKeyNothingCrashesAndTheAccessIsResetFromTheCommandLine()
|
||||
{
|
||||
var (env, postgres) = await ServerHarness.DockerOnEngineAsync();
|
||||
await using var engine = postgres;
|
||||
var data = TempFolder.Create("key");
|
||||
string password;
|
||||
await using (var first = await ServerHarness.StartAsync("docker", env, dataDir: data))
|
||||
{
|
||||
password = await first.SignInFirstTimeAsync();
|
||||
var services = first.Host.Services!;
|
||||
var secret = Totp.NewSecret();
|
||||
var user = (await services.Access.GetUserAsync())!;
|
||||
Assert.IsTrue(await services.Access.EnableSecondFactorAsync(user.Id, secret, Totp.Compute(secret, DateTimeOffset.UtcNow)));
|
||||
await services.Secrets.SetAsync("FINNHUB_API_KEY", "chiave-di-prova-1", "test");
|
||||
}
|
||||
|
||||
env["ANUBIS_SECRET_KEY"] = "another-secret-key-0123456789-abcdefghij";
|
||||
await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data))
|
||||
{
|
||||
using (var refused = await server.PostFormAsync("/accesso", "/azioni/accesso", ("password", password), ("codice", "123456")))
|
||||
{
|
||||
Assert.AreEqual("/accesso?errore=chiave", ServerHarness.Location(refused));
|
||||
}
|
||||
|
||||
StringAssert.Contains(await server.TextAsync("/accesso?errore=chiave"), "ANUBIS_SECRET_KEY");
|
||||
using var output = new StringWriter();
|
||||
Assert.AreEqual(0, await AccessCommand.RunAsync(["reset", "--platform", "docker", "--data-dir", data], output, env, iterations: 1000), output.ToString());
|
||||
var temporary = output.ToString().Split("Password provvisoria: ")[1].Split('\n')[0].Trim();
|
||||
using (var signIn = await server.PostFormAsync("/accesso", "/azioni/accesso", ("password", temporary)))
|
||||
{
|
||||
Assert.AreEqual("/", ServerHarness.Location(signIn));
|
||||
}
|
||||
|
||||
const string chosen = "chosen-test-pass-3";
|
||||
using (var change = await server.PostFormAsync("/primo-accesso", "/azioni/primo-accesso", ("attuale", temporary), ("nuova", chosen), ("conferma", chosen)))
|
||||
{
|
||||
Assert.AreEqual("/?ok=password", ServerHarness.Location(change));
|
||||
}
|
||||
|
||||
StringAssert.Contains(await server.TextAsync("/impostazioni"), "Non si legge più: la chiave dei segreti è cambiata");
|
||||
}
|
||||
|
||||
TempFolder.Delete(data);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheCommandLineImportsIntoANewSqliteFileOfTheSameFolder()
|
||||
{
|
||||
var data = TempFolder.Create("cli-same");
|
||||
var env = ServerHarness.DockerSqlite();
|
||||
await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data))
|
||||
{
|
||||
await server.SignInFirstTimeAsync();
|
||||
}
|
||||
|
||||
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
|
||||
var root = TempFolder.Create("cli-same-archive");
|
||||
var archive = Path.Combine(root, "archivio");
|
||||
using var output = new StringWriter();
|
||||
Assert.AreEqual(0, await DatabaseCommand.RunAsync(["export", archive, "--platform", "docker", "--data-dir", data], output, env), output.ToString());
|
||||
var directory = new DataDirectory(data);
|
||||
foreach (var f in Directory.EnumerateFiles(Path.GetDirectoryName(directory.SqliteFile)!))
|
||||
{
|
||||
File.Delete(f);
|
||||
}
|
||||
|
||||
// A wrong folder creates nothing.
|
||||
Assert.AreEqual(1, await DatabaseCommand.RunAsync(["import", root, "--platform", "docker", "--data-dir", data], output, env));
|
||||
Assert.IsFalse(File.Exists(directory.SqliteFile));
|
||||
|
||||
Assert.AreEqual(0, await DatabaseCommand.RunAsync(["import", archive, "--platform", "docker", "--data-dir", data], output, env), output.ToString());
|
||||
await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data))
|
||||
{
|
||||
Assert.IsTrue((await Installation.ReadRowAsync(server.Host.Services!.Db))!.ProtectedRestart);
|
||||
}
|
||||
|
||||
TempFolder.Delete(data);
|
||||
TempFolder.Delete(root);
|
||||
}
|
||||
}
|
||||
@@ -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.");
|
||||
}
|
||||
}
|
||||
@@ -480,6 +480,61 @@ public sealed class RiskEngineTests
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Simulation)]
|
||||
public async Task AfterARestoreRealMoneyWaitsForThePasswordOfTheUser()
|
||||
{
|
||||
await using var s = await CreateAsync(Consent());
|
||||
var live = await FakeRealAccountAsync(s);
|
||||
await s.Rig.Ledger.RecordCapitalAsync(live.Account.AccountId, StrategyNames.CryptoTrend, 2_500m, "EUR", "test", _none);
|
||||
await RequirementsMetAsync(s);
|
||||
await s.Stages.ConfirmLiveAsync(new LiveConfirmation(StrategyNames.CryptoTrend, live.Account.AccountId,
|
||||
StageBook.Phrase(StrategyNames.CryptoTrend, StrategyStages.Reduced), Password, null, "utente"), _none);
|
||||
var before = (await s.Stages.GetAsync(StrategyNames.CryptoTrend, _none))!;
|
||||
Assert.AreEqual("stage", (await Assert.ThrowsExactlyAsync<LiveConfirmationException>(() => s.Stages.ReconfirmAsync(StrategyNames.CryptoTrend, Password, null, "utente", _none))).Code,
|
||||
"nothing to confirm before a restore");
|
||||
s.Rig.Refresh();
|
||||
await live.Manager.SubmitAsync(Buy(s, 0.002m) with { StartAggressive = true }, _none);
|
||||
await s.Rig.TurnsAsync(live.Manager, 3, _minute);
|
||||
var planned = Ids.NewId(s.Rig.Clock);
|
||||
await s.Rig.Db.WriteAsync(x => x.ExecuteAsync(
|
||||
"INSERT INTO planned_orders (id, decision_id, strategy, account_id, instrument_id, side, purpose, quantity, exit_all, reference_price, reason, due_at, valid_until, status, created_at, updated_at) " +
|
||||
"VALUES (@id, @id, 'crypto_trend', @a, @i, 'buy', 'entry', 0.001, @no, 60000, 'trend_entry', @t, @t, 'pending', @t, @t)", _none,
|
||||
("id", planned), ("a", live.Account.AccountId), ("i", s.Btc.Id), ("no", false), ("t", s.Rig.Clock.UtcNow)), _none);
|
||||
|
||||
await Installation.CheckAsync(s.Rig.Db, new DataDirectory(TempFolder.Create("reconfirm")), s.Rig.Clock, _none);
|
||||
await Installation.ProtectAsync(s.Rig.Db, s.Rig.Clock, _none);
|
||||
|
||||
// Stopped, exit only, with its counts untouched; what was planned does not leave; the stop stays.
|
||||
Assert.AreEqual("stopped", (await s.Settings.GetAsync(SettingsStore.BotState.Key)).Value);
|
||||
var waiting = (await s.Stages.GetAsync(StrategyNames.CryptoTrend, _none))!;
|
||||
Assert.AreEqual((StrategyStages.Reduced, true, true, before.StageSince), (waiting.Stage, waiting.ExitOnly, waiting.WaitsForReconfirmation, waiting.StageSince));
|
||||
Assert.AreEqual("dropped/protected_restart", (await s.Rig.QueryAsync("SELECT status, outcome FROM planned_orders WHERE id = @id",
|
||||
r => r.Text("status") + "/" + r.TextOrNull("outcome"), ("id", planned))).Single());
|
||||
Assert.HasCount(1, await s.Rig.QueryAsync("SELECT reason FROM strategy_stage_history WHERE reason = 'exit_only_after_restore'", r => r.Text("reason")));
|
||||
Assert.HasCount(1, await live.Paper.GetOpenOrdersAsync(_none), "the stop on the real account");
|
||||
|
||||
// The bot restarted: still no purchase with real money, while a sale goes; holding nothing does not free it.
|
||||
await s.Risk.RestartAsync("utente", _none);
|
||||
Assert.AreEqual(RiskReasons.ExitOnly, (await live.Manager.SubmitAsync(Buy(s, 0.001m), _none)).Refusal);
|
||||
var held = (await s.Rig.Ledger.PositionAsync(live.Account.AccountId, s.Btc.Id, StrategyNames.CryptoTrend, _none))!.Quantity;
|
||||
Assert.IsNull((await live.Manager.SubmitAsync(Sell(s, held) with { StartAggressive = true }, _none)).Refusal);
|
||||
await s.Rig.TurnsAsync(live.Manager, 3, _minute);
|
||||
Assert.AreEqual(0m, (await s.Rig.Ledger.PositionAsync(live.Account.AccountId, s.Btc.Id, StrategyNames.CryptoTrend, _none))?.Quantity ?? 0m);
|
||||
await s.Stages.ReleaseExitOnlyAsync(s.Rig.Ledger, _none);
|
||||
Assert.IsTrue((await s.Stages.GetAsync(StrategyNames.CryptoTrend, _none))!.WaitsForReconfirmation, "only the user takes it out");
|
||||
|
||||
Assert.AreEqual("password", (await Assert.ThrowsExactlyAsync<LiveConfirmationException>(() => s.Stages.ReconfirmAsync(StrategyNames.CryptoTrend, "sbagliata", null, "utente", _none))).Code);
|
||||
var closed = new StageBook(s.Rig.Db, s.Rig.Clock, TradingConsent.None, (_, _, _) => Task.FromResult(true));
|
||||
Assert.AreEqual(RiskReasons.NoConsent, (await Assert.ThrowsExactlyAsync<LiveConfirmationException>(() => closed.ReconfirmAsync(StrategyNames.CryptoTrend, Password, null, "utente", _none))).Code);
|
||||
await s.Stages.ReconfirmAsync(StrategyNames.CryptoTrend, Password, null, "utente", _none);
|
||||
var back = (await s.Stages.GetAsync(StrategyNames.CryptoTrend, _none))!;
|
||||
Assert.AreEqual((StrategyStages.Reduced, false, before.StageSince), (back.Stage, back.ExitOnly, back.StageSince));
|
||||
s.Rig.Refresh();
|
||||
Assert.IsNull((await live.Manager.SubmitAsync(Buy(s, 0.001m), _none)).Refusal);
|
||||
Assert.HasCount(2, await s.Rig.QueryAsync("SELECT key FROM config_history WHERE key = @k", r => r.Text("key"), ("k", "strategy.crypto_trend.stage")));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Simulation)]
|
||||
public async Task ADemotedStrategyKeepsManagingItsRealPositionsDownToZero()
|
||||
|
||||
@@ -27,12 +27,15 @@ public sealed class StoresTests
|
||||
Assert.IsTrue(File.Exists(data.InstallationFile));
|
||||
Assert.AreEqual(IdentityVerdict.Match, (await Installation.CheckAsync(test.Db, data, clock).ConfigureAwait(false)).Verdict);
|
||||
|
||||
// Data folder lost: rewritten from the database.
|
||||
// The file of the data folder is lost: nobody can tell this database from an old copy, so the engine does not start.
|
||||
var before = Installation.ReadFile(data)!;
|
||||
File.Delete(data.InstallationFile);
|
||||
Assert.AreEqual(IdentityVerdict.FileRestored, (await Installation.CheckAsync(test.Db, data, clock).ConfigureAwait(false)).Verdict);
|
||||
var missing = await Installation.CheckAsync(test.Db, data, clock).ConfigureAwait(false);
|
||||
Assert.AreEqual(IdentityVerdict.MissingFile, missing.Verdict);
|
||||
Assert.IsFalse(missing.CanStart);
|
||||
Assert.IsFalse(File.Exists(data.InstallationFile));
|
||||
|
||||
// A stale copy of the database: same installation, older fingerprint.
|
||||
var before = Installation.ReadFile(data)!;
|
||||
Installation.WriteFile(data, before with { Fingerprint = "newer" });
|
||||
var stale = await Installation.CheckAsync(test.Db, data, clock).ConfigureAwait(false);
|
||||
Assert.AreEqual(IdentityVerdict.StaleDatabase, stale.Verdict);
|
||||
@@ -43,7 +46,7 @@ public sealed class StoresTests
|
||||
Assert.AreEqual(IdentityVerdict.DifferentInstallation, (await Installation.CheckAsync(test.Db, data, clock).ConfigureAwait(false)).Verdict);
|
||||
|
||||
// The user adopts this database: new fingerprint on both sides, protected restart on.
|
||||
var renewed = await Installation.RenewAsync(test.Db, data, clock, adoptDatabaseIdentity: true).ConfigureAwait(false);
|
||||
var renewed = await Installation.RenewAsync(test.Db, data, clock, "prova").ConfigureAwait(false);
|
||||
Assert.AreEqual(before.InstallationId, renewed.InstallationId);
|
||||
Assert.AreNotEqual(before.Fingerprint, renewed.Fingerprint);
|
||||
var row = await Installation.ReadRowAsync(test.Db).ConfigureAwait(false);
|
||||
@@ -124,10 +127,11 @@ public sealed class StoresTests
|
||||
Assert.IsTrue((await secrets.StatusAsync("OKX_API_KEY_DEMO").ConfigureAwait(false)).FromEnvironment);
|
||||
await Assert.ThrowsAsync<ReadOnlySettingException>(() => secrets.SetAsync("OKX_API_KEY_DEMO", "x-123456789", "admin")).ConfigureAwait(false);
|
||||
|
||||
// With another key the value cannot be read: the error says to enter it again.
|
||||
// With another key the value cannot be read: whoever asks goes on without it, and the status says it must be entered again.
|
||||
var otherKey = new SecretStore(test.Db, clock, Enumerable.Repeat((byte)7, 32).ToArray());
|
||||
var error = await Assert.ThrowsAsync<System.Security.Cryptography.CryptographicException>(() => otherKey.RevealAsync("ALPACA_API_SECRET_DEMO")).ConfigureAwait(false);
|
||||
Assert.Contains("Reinserisci", error.Message);
|
||||
Assert.IsNull(await otherKey.RevealAsync("ALPACA_API_SECRET_DEMO").ConfigureAwait(false));
|
||||
Assert.IsTrue((await otherKey.StatusAsync("ALPACA_API_SECRET_DEMO").ConfigureAwait(false)).Unreadable);
|
||||
Assert.IsFalse((await secrets.StatusAsync("ALPACA_API_SECRET_DEMO").ConfigureAwait(false)).Unreadable);
|
||||
|
||||
// A value sealed under one name does not open under another.
|
||||
var sealedValue = secrets.Seal("A", "x");
|
||||
|
||||
@@ -29,6 +29,26 @@ internal sealed class TradingRig : IAsyncDisposable
|
||||
Catalog = new InstrumentCatalog(test.Db, Clock);
|
||||
}
|
||||
|
||||
// The same market and the same clock on another database: the account goes on while the ledger went back (SPEC 15.1).
|
||||
private TradingRig(TestDb test, TradingRig before)
|
||||
{
|
||||
Test = test;
|
||||
Clock = before.Clock;
|
||||
Ledger = new Ledger(test.Db, Clock);
|
||||
Catalog = new InstrumentCatalog(test.Db, Clock);
|
||||
_quotes = before._quotes;
|
||||
_specs = before._specs;
|
||||
_instruments = before._instruments;
|
||||
}
|
||||
|
||||
/// <summary>An archive of this rig loaded in a new database of <paramref name="engine"/> (that of the run when null).</summary>
|
||||
public async Task<TradingRig> RestoreAsync(string archive, Anubis.Platform.DbEngine? engine = null)
|
||||
{
|
||||
var test = engine is { } e ? await TestDb.CreateAsync(e).ConfigureAwait(false) : await TestDb.CreateAsync().ConfigureAwait(false);
|
||||
await Archive.ImportAsync(test.Db, archive, Clock).ConfigureAwait(false);
|
||||
return new TradingRig(test, this);
|
||||
}
|
||||
|
||||
public TestDb Test { get; }
|
||||
|
||||
public Database Db => Test.Db;
|
||||
|
||||
Reference in new issue
Block a user