Write the manuals and fix what following them found
The manual, the runbook and the go-live list are written and checked claim by claim against the code, and the installation is done from zero by following them on both engines. That found real defects, now fixed: - with SQLite a missing database file left no way to restore a backup: the choices appear, and the file is created only by the user's choice; - an account whose difference vanished after the 15 minutes stayed prudent with no button, a missing stop could be left out for good, and a choice made while the broker was silent used old numbers; - after "Ferma tutto" the positions could not be closed without restarting; - a refused key looked like a silent broker: it has its own notice now; - the split of the capital between the strategies of a broker (SPEC 13.5) could not be changed from the interface. refs #72 #68 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2257c3e16c
commit
24e20584d4
28 files changed
+1147
-57
No files matched your search
@@ -1,6 +1,7 @@
|
||||
using System.Net;
|
||||
using Anubis.Db;
|
||||
using Anubis.Server;
|
||||
using Anubis.Trading;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
@@ -146,6 +147,60 @@ public sealed class AccountsScreenTests
|
||||
StringAssert.Contains(await server.TextAsync("/impostazioni"), "Trend crypto: quota 100%");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task TheUserSplitsTheCapitalAndWithRealMoneyOnlyThroughTheProcedure()
|
||||
{
|
||||
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), trading: true);
|
||||
var password = await server.SignInFirstTimeAsync();
|
||||
var db = server.Host.Services!.Db;
|
||||
async Task<string> SplitAsync(string momentum, string meanrev, params (string, string)[] more)
|
||||
{
|
||||
using var answer = await server.PostFormAsync("/impostazioni", "/azioni/quote/alpaca",
|
||||
[("quota-" + StrategyNames.EquityMomentum, momentum), ("quota-" + StrategyNames.EquityMeanrev, meanrev), .. more]);
|
||||
return ServerHarness.Location(answer);
|
||||
}
|
||||
|
||||
Task<List<decimal?>> SharesAsync() => db.ReadAsync(s => s.QueryAsync("SELECT share FROM strategy_state WHERE strategy IN (@m, @r) ORDER BY strategy DESC",
|
||||
r => r.MoneyOrNull("share"), ("m", StrategyNames.EquityMomentum), ("r", StrategyNames.EquityMeanrev)));
|
||||
|
||||
var page = await server.TextAsync("/impostazioni");
|
||||
StringAssert.Contains(page, "Ripartizione tra le strategie di Alpaca");
|
||||
Assert.DoesNotContain("Ripartizione tra le strategie di OKX", page, "A single strategy has nothing to split.");
|
||||
|
||||
Assert.AreEqual("/impostazioni?ok=quote#conti", await SplitAsync("62,5%", "37,5"));
|
||||
CollectionAssert.AreEqual(new decimal?[] { 0.625m, 0.375m }, (await SharesAsync()).ToArray());
|
||||
foreach (var (momentum, meanrev) in new[] { ("60", "30"), ("110", "-10"), ("molto", "40"), ("", "") })
|
||||
{
|
||||
Assert.AreEqual("/impostazioni?errore=quote#conti", await SplitAsync(momentum, meanrev), momentum + "/" + meanrev);
|
||||
}
|
||||
|
||||
using (var unknown = await server.PostFormAsync("/impostazioni", "/azioni/quote/binance", ("quota-x", "100")))
|
||||
{
|
||||
Assert.AreEqual("/impostazioni?errore=conto#conti", ServerHarness.Location(unknown));
|
||||
}
|
||||
|
||||
// The old and the new value stay, in the changes and in the diary; the same split again adds nothing.
|
||||
Assert.AreEqual("/impostazioni?ok=quote#conti", await SplitAsync("62,5", "37,5"));
|
||||
var log = await db.ReadAsync(s => s.QueryAsync("SELECT old_value, new_value FROM config_history WHERE key = @k", r => (r.Text("old_value"), r.Text("new_value")),
|
||||
("k", "strategy." + StrategyNames.EquityMomentum + ".share")));
|
||||
Assert.HasCount(1, log);
|
||||
StringAssert.Contains(log[0].Item2, "62,5%");
|
||||
var diary = await db.ReadAsync(s => s.QueryAsync("SELECT message FROM journal WHERE code = 'shares_changed'", r => r.Text("message")));
|
||||
Assert.HasCount(1, diary);
|
||||
StringAssert.Contains(diary[0], "→ 62,5%");
|
||||
Assert.DoesNotContain(StrategyNames.EquityMomentum, diary[0]);
|
||||
|
||||
// Real money on the account: any new split needs the phrase and the password.
|
||||
await db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET stage = 'reduced' WHERE strategy = @s", ("s", StrategyNames.EquityMomentum)));
|
||||
StringAssert.Contains(await server.TextAsync("/impostazioni"), "Una strategia di questo conto usa soldi veri");
|
||||
Assert.AreEqual("/impostazioni?errore=frase-rischio#conti", await SplitAsync("50", "50"));
|
||||
Assert.AreEqual("/impostazioni?errore=password-rischio#conti", await SplitAsync("50", "50", ("frase", StageBook.RaisePhrase), ("password", "sbagliata")));
|
||||
CollectionAssert.AreEqual(new decimal?[] { 0.625m, 0.375m }, (await SharesAsync()).ToArray());
|
||||
Assert.AreEqual("/impostazioni?ok=quote#conti", await SplitAsync("50", "50", ("frase", StageBook.RaisePhrase), ("password", password)));
|
||||
CollectionAssert.AreEqual(new decimal?[] { 0.5m, 0.5m }, (await SharesAsync()).ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
[DataRow("4000", "4000")]
|
||||
|
||||
@@ -258,7 +258,7 @@ public sealed class LedgerTests
|
||||
|
||||
// Reducing capital below what is invested is refused: the bot never sells to give money back.
|
||||
var error = await Assert.ThrowsExactlyAsync<CapitalException>(() => capital.SetAsync(Venues.Okx, 0m, "test", _none)).ConfigureAwait(false);
|
||||
Assert.Contains("crypto_trend", error.Message);
|
||||
Assert.Contains("Trend crypto", error.Message);
|
||||
await Assert.ThrowsExactlyAsync<CapitalException>(() =>
|
||||
capital.SetSharesAsync(Venues.Alpaca, new Dictionary<string, decimal> { [StrategyNames.EquityMomentum] = 0.8m, [StrategyNames.EquityMeanrev] = 0.3m }, "test", _none)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
@@ -127,9 +127,18 @@ public sealed class ReconcilerTests
|
||||
// otherwise copy numbers that are no longer true. The choice compares again before it acts.
|
||||
s.Broker.Missing.Clear();
|
||||
Assert.AreEqual(AccountModes.Prudent, (await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false)).Mode);
|
||||
Assert.IsEmpty((await s.Reconciler.StateAsync(s.Account.AccountId, _none).ConfigureAwait(false)).Differences);
|
||||
state = await s.Reconciler.StateAsync(s.Account.AccountId, _none).ConfigureAwait(false);
|
||||
Assert.IsEmpty(state.Differences);
|
||||
Assert.IsTrue(state.WaitsForUser(s.Rig.Clock.UtcNow, s.Reconciler.Grace), "Also with nothing left to align: otherwise it would stay prudent forever.");
|
||||
Assert.IsFalse(state.HasChoices);
|
||||
s.Broker.Missing["BTC-EUR"] = 0.004m;
|
||||
|
||||
// With the broker silent nothing is compared, so the choice changes nothing.
|
||||
s.Broker.Down = true;
|
||||
Assert.AreEqual(ReconcileResolution.NotCompared, await s.Reconciler.ResolveAsync(s.Manager, ReconcileChoice.Align, "test", _none).ConfigureAwait(false));
|
||||
Assert.AreEqual(AccountModes.Prudent, (await s.Reconciler.StateAsync(s.Account.AccountId, _none).ConfigureAwait(false)).Mode);
|
||||
s.Broker.Down = false;
|
||||
|
||||
// Align: the ledger takes the account's number with an adjustment, and the account is normal again.
|
||||
await s.Reconciler.ResolveAsync(s.Manager, ReconcileChoice.Align, "test", _none).ConfigureAwait(false);
|
||||
Assert.AreEqual(0.00598m, (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, StrategyNames.CryptoTrend, _none).ConfigureAwait(false))!.Quantity);
|
||||
@@ -192,6 +201,33 @@ public sealed class ReconcilerTests
|
||||
Assert.AreEqual(AccountModes.Prudent, report.Mode);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Simulation)]
|
||||
public async Task AMissingStopIsNeverLeftOutByTheUsersChoice()
|
||||
{
|
||||
await using var s = await HoldingAsync().ConfigureAwait(false);
|
||||
var stop = (await s.Paper.GetOpenOrdersAsync(_none).ConfigureAwait(false)).Single();
|
||||
await s.Paper.CancelOrderAsync(stop.ClientOrderId, stop.Symbol, _none).ConfigureAwait(false);
|
||||
s.Broker.RefuseStops = true;
|
||||
await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false);
|
||||
s.Rig.Clock.Advance(TimeSpan.FromMinutes(16));
|
||||
var report = await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false);
|
||||
Assert.IsTrue(report.Differences.Any(d => d.Kind == DifferenceKinds.Stop), string.Join("; ", report.Differences.Select(d => d.Message)));
|
||||
foreach (var choice in new[] { ReconcileChoice.Align, ReconcileChoice.Exclude })
|
||||
{
|
||||
Assert.AreEqual(ReconcileResolution.StopsMissing, await s.Reconciler.ResolveAsync(s.Manager, choice, "test", _none).ConfigureAwait(false));
|
||||
var state = await s.Reconciler.StateAsync(s.Account.AccountId, _none).ConfigureAwait(false);
|
||||
Assert.AreEqual((AccountModes.Prudent, DifferenceKinds.Stop), (state.Mode, state.ModeReason));
|
||||
Assert.IsFalse(state.Excluded.Any(e => e.StartsWith(DifferenceKinds.Stop, StringComparison.Ordinal)), string.Join("; ", state.Excluded));
|
||||
}
|
||||
|
||||
// The stop is back within the new 15 minutes: normal by itself.
|
||||
s.Broker.RefuseStops = false;
|
||||
s.Rig.Clock.Advance(TimeSpan.FromMinutes(5));
|
||||
report = await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false);
|
||||
Assert.AreEqual(AccountModes.Normal, report.Mode, string.Join("; ", report.Differences.Select(d => d.Message)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Simulation)]
|
||||
public async Task AKeyThatMayWithdrawStopsPurchasesUntilItIsReplaced()
|
||||
@@ -230,4 +266,39 @@ public sealed class ReconcilerTests
|
||||
Assert.HasCount(1, await CodesAsync(s.Rig, "reconcile_unreachable").ConfigureAwait(false));
|
||||
Assert.AreEqual(AccountModes.Normal, (await s.Reconciler.StateAsync(s.Account.AccountId, _none).ConfigureAwait(false)).Mode, "Silence is not a difference.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Simulation)]
|
||||
public async Task AKeyTheBrokerNoLongerAcceptsIsSaidToTheUserOnce()
|
||||
{
|
||||
await using var s = await HoldingAsync().ConfigureAwait(false);
|
||||
s.Broker.Down = true;
|
||||
await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false);
|
||||
s.Broker.KeyRefused = true;
|
||||
|
||||
// At the start the key is read first, and the account may never get to its reconciliation.
|
||||
Assert.IsNull(await s.Reconciler.CheckKeyAsync(s.Manager, _none).ConfigureAwait(false));
|
||||
Assert.AreEqual(ReconcileOutcomes.KeyRefused, (await s.Reconciler.StateAsync(s.Account.AccountId, _none).ConfigureAwait(false)).LastOutcome);
|
||||
Assert.AreEqual(ReconcileOutcomes.KeyRefused, (await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false)).Outcome);
|
||||
Assert.HasCount(1, await CodesAsync(s.Rig, "key_refused").ConfigureAwait(false));
|
||||
var sent = await s.Rig.Db.ReadAsync(r => r.CountAsync("SELECT COUNT(*) FROM notifications WHERE message LIKE @b", ("b", "%non accetta più la chiave%")), _none).ConfigureAwait(false);
|
||||
Assert.AreEqual(1, sent, "It reaches the phone too.");
|
||||
|
||||
s.Broker.Down = false;
|
||||
Assert.AreEqual(ReconcileOutcomes.Clean, (await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false)).Outcome);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
[DataRow(401, """{"code":"50111","msg":"Invalid OK-ACCESS-KEY","data":[]}""", true)]
|
||||
[DataRow(401, """{"code":"50110","msg":"Your IP is not included in your API key's IP whitelist.","data":[]}""", true)]
|
||||
[DataRow(401, """{"code":"50102","msg":"Timestamp request expired","data":[]}""", false)]
|
||||
[DataRow(403, """{"message":"forbidden."}""", true)]
|
||||
[DataRow(404, """{"message":"position does not exist"}""", false)]
|
||||
public void ARefusedKeyIsToldFromOtherAnswers(int status, string body, bool refused)
|
||||
{
|
||||
using var client = new HttpClient();
|
||||
var http = new TradingHttp(client, new SystemClock(), "broker", (_, _) => true);
|
||||
Assert.AreEqual(refused, http.Failure(new Uri("https://broker.example/v2/positions"), new HttpAnswer((System.Net.HttpStatusCode)status, body)).KeyRefused);
|
||||
}
|
||||
}
|
||||
@@ -58,6 +58,71 @@ public sealed class RestoreServerTests
|
||||
}, null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AMissingSqliteFileOffersTheRestoreAndNeverCreatesADatabaseByItself()
|
||||
{
|
||||
var data = TempFolder.Create("missing-file");
|
||||
var file = new DataDirectory(data).SqliteFile;
|
||||
await using (var first = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), dataDir: data))
|
||||
{
|
||||
await first.SignInFirstTimeAsync();
|
||||
using var saved = await first.PostFormAsync("/impostazioni", "/azioni/salvataggio");
|
||||
}
|
||||
|
||||
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
|
||||
var away = data + "-altrove.sqlite3";
|
||||
File.Copy(file, away, overwrite: true);
|
||||
foreach (var f in Directory.EnumerateFiles(Path.GetDirectoryName(file)!))
|
||||
{
|
||||
File.Delete(f);
|
||||
}
|
||||
|
||||
// The file comes back while the page waits: it is used, with no choice to make.
|
||||
await using (var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), dataDir: data, waitReady: false))
|
||||
{
|
||||
await server.WaitForAsync(HostMode.IdentityProblem);
|
||||
StringAssert.Contains(await server.TextAsync("/"), "Il file del database non c'è");
|
||||
using var health = await server.GetAsync("/health");
|
||||
Assert.AreEqual(HttpStatusCode.ServiceUnavailable, health.StatusCode);
|
||||
using (var wrong = await server.PostFormAsync("/", "/azioni/servizio/da-capo", ("password", "wrong-password-123")))
|
||||
{
|
||||
StringAssert.Contains(ServerHarness.Location(wrong), "errore=password");
|
||||
}
|
||||
|
||||
using (var unknown = await server.PostFormAsync("/", "/azioni/servizio/ripristina", ("password", ServerHarness.AdminPassword), ("salvataggio", "inesistente")))
|
||||
{
|
||||
StringAssert.Contains(ServerHarness.Location(unknown), "errore=scelta");
|
||||
}
|
||||
|
||||
Assert.IsFalse(File.Exists(file), "Trap 20: no database by itself.");
|
||||
File.Copy(away, file);
|
||||
await server.WaitForAsync(HostMode.Ready);
|
||||
}
|
||||
|
||||
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
|
||||
foreach (var f in Directory.EnumerateFiles(Path.GetDirectoryName(file)!))
|
||||
{
|
||||
File.Delete(f);
|
||||
}
|
||||
|
||||
await using (var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), dataDir: data, waitReady: false))
|
||||
{
|
||||
await server.WaitForAsync(HostMode.IdentityProblem);
|
||||
var backup = new Backups(new DataDirectory(data), SystemClock.Instance).List().Single(b => b.Reason == "a-mano");
|
||||
using (var restore = await server.PostFormAsync("/", "/azioni/servizio/ripristina", ("password", ServerHarness.AdminPassword), ("salvataggio", backup.Name)))
|
||||
{
|
||||
Assert.AreEqual("/", ServerHarness.Location(restore));
|
||||
}
|
||||
|
||||
await server.WaitForAsync(HostMode.Ready);
|
||||
Assert.IsTrue((await Installation.ReadRowAsync(server.Host.Services!.Db))!.ProtectedRestart);
|
||||
Assert.AreEqual("stopped", (await server.Host.Services.Settings.GetAsync(SettingsStore.BotState.Key)).Value);
|
||||
}
|
||||
|
||||
File.Delete(away);
|
||||
TempFolder.Delete(data);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AfterARestoreTheOldDatabaseIsRefusedAndTheNewOneWaitsForTheUser()
|
||||
{
|
||||
@@ -95,6 +160,13 @@ public sealed class RestoreServerTests
|
||||
Assert.AreEqual("stopped", (await server.Host.Services!.Settings.GetAsync(SettingsStore.BotState.Key)).Value);
|
||||
}
|
||||
|
||||
// Nor is anything sold from a ledger that has not read the accounts yet.
|
||||
Assert.IsFalse((await server.TextAsync("/rischio")).Contains("Chiudi tutte le posizioni", StringComparison.Ordinal));
|
||||
using (var close = await server.PostFormAsync("/rischio", "/azioni/bot/chiudi"))
|
||||
{
|
||||
StringAssert.Contains(ServerHarness.Location(close), "errore");
|
||||
}
|
||||
|
||||
Assert.HasCount(1, await server.Host.Services!.Db.ReadAsync(s => s.QueryAsync("SELECT message FROM journal WHERE code = 'protected_restart'", r => r.Text("message"))));
|
||||
}
|
||||
|
||||
|
||||
@@ -196,7 +196,9 @@ public sealed class StrategyScreensTests
|
||||
}
|
||||
|
||||
Assert.AreEqual("stopped", await StateAsync());
|
||||
StringAssert.Contains(await server.TextAsync("/rischio"), "Riparti");
|
||||
var stopped = await server.TextAsync("/rischio");
|
||||
StringAssert.Contains(stopped, "Riparti");
|
||||
StringAssert.Contains(stopped, "Chiudi tutte le posizioni", "Selling everything does not need a restart first.");
|
||||
|
||||
// With the STOP file in the data folder the restart is refused.
|
||||
var stopFile = services.Trading!.Risk!.StopFile!;
|
||||
|
||||
@@ -175,12 +175,18 @@ internal sealed class FaultyBroker(IBrokerAccount inner, string? environment = n
|
||||
/// <summary>The next order is refused with this code.</summary>
|
||||
public string? RejectNext { get; set; }
|
||||
|
||||
/// <summary>Stop orders are refused, everything else is taken.</summary>
|
||||
public bool RefuseStops { get; set; }
|
||||
|
||||
/// <summary>Every fill is reported twice.</summary>
|
||||
public bool DuplicateFills { get; set; }
|
||||
|
||||
/// <summary>Every call fails as if the network were down.</summary>
|
||||
public bool Down { get; set; }
|
||||
|
||||
/// <summary>With <see cref="Down"/>: the broker answers, but does not accept the key.</summary>
|
||||
public bool KeyRefused { get; set; }
|
||||
|
||||
public List<OrderRequest> Sent { get; } = [];
|
||||
|
||||
public string Venue => inner.Venue;
|
||||
@@ -214,6 +220,11 @@ internal sealed class FaultyBroker(IBrokerAccount inner, string? environment = n
|
||||
throw new OrderRejectedException("rifiutato", code);
|
||||
}
|
||||
|
||||
if (RefuseStops && request.Kind == OrderKind.Stop)
|
||||
{
|
||||
throw new OrderRejectedException("rifiutato", "stop");
|
||||
}
|
||||
|
||||
Sent.Add(request);
|
||||
var answer = await inner.SubmitOrderAsync(request, cancellationToken).ConfigureAwait(false);
|
||||
if (LoseNextAnswer)
|
||||
@@ -246,5 +257,5 @@ internal sealed class FaultyBroker(IBrokerAccount inner, string? environment = n
|
||||
|
||||
public IAsyncEnumerable<OrderUpdate> StreamOrderUpdatesAsync(CancellationToken cancellationToken) => inner.StreamOrderUpdatesAsync(cancellationToken);
|
||||
|
||||
private Task<T> Guard<T>(Func<Task<T>> call) => Down ? throw new BrokerException("rete giù", retryable: true) : call();
|
||||
private Task<T> Guard<T>(Func<Task<T>> call) => Down ? throw new BrokerException(KeyRefused ? "chiave" : "rete giù", retryable: !KeyRefused) { KeyRefused = KeyRefused } : call();
|
||||
}
|
||||
Reference in new issue
Block a user