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>
219 lines
12 KiB
C#
219 lines
12 KiB
C#
using System.Net;
|
|
using Anubis.Db;
|
|
using Anubis.Server;
|
|
using Anubis.Trading;
|
|
|
|
namespace Anubis.Tests;
|
|
|
|
/// <summary>The Conti e posizioni screen and the accounts part of Impostazioni (issue #32).</summary>
|
|
[TestClass]
|
|
public sealed class AccountsScreenTests
|
|
{
|
|
[TestMethod]
|
|
[TestCategory(Category.Integration)]
|
|
public async Task TheDemoShowsTheFiguresOfTheMockup()
|
|
{
|
|
var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]);
|
|
var demoRoot = server.Host.Config.Data.Root;
|
|
try
|
|
{
|
|
var page = await server.TextAsync("/conti");
|
|
|
|
// Mockup 02: totals, the two cards, the stops. The ledger computes them from the seeded rows.
|
|
foreach (var figure in new[]
|
|
{
|
|
"10.412,46", "6.671,13", "3.741,33", "4.231,60", "1.905,10", "2.326,50", "+163,45", "+68,15", "14,49",
|
|
"6.180,86", "7.170,41", "1.836,23", "2.130,21", "4.344,63", "5.040,20", "+75,83", "+105,03", "0,33",
|
|
"+231,60", "+5,79%", "+180,86", "+3,01%", "22,3%", "37,5%", "4,3%", "35,9%", "59,4%", "40,6%",
|
|
})
|
|
{
|
|
StringAssert.Contains(page, figure, $"Missing {figure} on the Conti page.");
|
|
}
|
|
|
|
StringAssert.Contains(page, "Attivo, aggiornato oggi alle 02:06");
|
|
StringAssert.Contains(page, "Attivo dal 7 ottobre");
|
|
StringAssert.Contains(page, "5 stop permanenti");
|
|
StringAssert.Contains(page, "6 stop giornalieri");
|
|
StringAssert.Contains(page, "In coda per l'apertura delle 15:30");
|
|
StringAssert.Contains(page, "Registro interno coerente (controllo delle 08:20)");
|
|
StringAssert.Contains(page, "i prelievi sono disattivati");
|
|
StringAssert.Contains(page, "circa 309");
|
|
Assert.IsLessThan(page.IndexOf("Vendi 0,262", StringComparison.Ordinal), page.IndexOf("Vendi 0,0182", StringComparison.Ordinal), "The largest stop comes first.");
|
|
|
|
// The filter keeps one account; the CSV has one row per position, for a spreadsheet.
|
|
var okx = await server.TextAsync("/conti?conto=okx");
|
|
Assert.IsFalse(okx.Contains("NVDA", StringComparison.Ordinal));
|
|
using var csv = await server.GetAsync("/api/conti/posizioni.csv");
|
|
Assert.AreEqual(HttpStatusCode.OK, csv.StatusCode);
|
|
Assert.AreEqual("text/csv", csv.Content.Headers.ContentType?.MediaType);
|
|
var bytes = await csv.Content.ReadAsByteArrayAsync();
|
|
CollectionAssert.AreEqual(new byte[] { 0xEF, 0xBB, 0xBF }, bytes[..3], "Excel reads the accents only with the BOM.");
|
|
var lines = System.Text.Encoding.UTF8.GetString(bytes[3..]).Split('\n', StringSplitOptions.RemoveEmptyEntries);
|
|
Assert.HasCount(11, lines);
|
|
StringAssert.StartsWith(lines[1], "BTC/EUR;Bitcoin;okx;crypto_trend;0,0182;68950;71420;EUR;1299,84;44,95;66180;", lines[1]);
|
|
|
|
var settings = await server.TextAsync("/impostazioni");
|
|
StringAssert.Contains(settings, "Conti e chiavi");
|
|
StringAssert.Contains(settings, "Nella modalità dimostrativa chiavi e capitale non si cambiano.");
|
|
Assert.IsFalse(settings.Contains("/azioni/capitale/", StringComparison.Ordinal), "No capital form in the demo.");
|
|
}
|
|
finally
|
|
{
|
|
// The server first: on Windows a database still open cannot be deleted.
|
|
await server.DisposeAsync();
|
|
TempFolder.Delete(demoRoot);
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
[TestCategory(Category.Integration)]
|
|
public async Task KeysAreAskedToTheBrokerBeforeTheyAreKept()
|
|
{
|
|
var network = new FakeHttp()
|
|
.On(u => u.AbsolutePath == "/api/v5/account/config", _ => FakeHttp.Respond(Fixture.Text("okx-trading/account-config.json")))
|
|
.On(u => u.AbsolutePath == "/v2/account", _ => FakeHttp.Respond(Fixture.Text("alpaca-trading/account.json")))
|
|
.On(_ => true, _ => FakeHttp.Respond("not here", HttpStatusCode.NotFound));
|
|
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), marketHttp: network, trading: true);
|
|
await server.SignInFirstTimeAsync();
|
|
var secrets = server.Host.Services!.Secrets;
|
|
|
|
// The documentation's OKX key may withdraw: refused, nothing saved.
|
|
using (var okx = await server.PostFormAsync("/impostazioni", "/azioni/chiavi/okx",
|
|
("OKX_API_KEY_DEMO", "test-okx-key"), ("OKX_API_SECRET_DEMO", "test-okx-secret"), ("OKX_API_PASSPHRASE_DEMO", "test-okx-pass")))
|
|
{
|
|
Assert.AreEqual("/impostazioni?errore=prelievo#conti", ServerHarness.Location(okx));
|
|
}
|
|
|
|
Assert.IsFalse((await secrets.StatusAsync("OKX_API_KEY_DEMO")).IsSet);
|
|
|
|
// A missing field never reaches the broker.
|
|
using (var empty = await server.PostFormAsync("/impostazioni", "/azioni/chiavi/alpaca", ("ALPACA_API_KEY_DEMO", "test-alpaca-key"), ("ALPACA_API_SECRET_DEMO", " ")))
|
|
{
|
|
Assert.AreEqual("/impostazioni?errore=chiavi-vuote#conti", ServerHarness.Location(empty));
|
|
}
|
|
|
|
// Alpaca keys never withdraw and this account may trade: kept, encrypted, never shown again; the engine restarts with them.
|
|
using (var alpaca = await server.PostFormAsync("/impostazioni", "/azioni/chiavi/alpaca", ("ALPACA_API_KEY_DEMO", "test-alpaca-key"), ("ALPACA_API_SECRET_DEMO", "test-alpaca-secret")))
|
|
{
|
|
Assert.AreEqual("/impostazioni?ok=chiavi#conti", ServerHarness.Location(alpaca));
|
|
}
|
|
|
|
await server.WaitForAsync(HostMode.Ready);
|
|
secrets = server.Host.Services!.Secrets;
|
|
Assert.IsTrue((await secrets.StatusAsync("ALPACA_API_SECRET_DEMO")).IsSet);
|
|
var settings = await server.TextAsync("/impostazioni");
|
|
Assert.IsFalse(settings.Contains("test-alpaca-secret", StringComparison.Ordinal), "A saved key is never shown again.");
|
|
StringAssert.Contains(settings, "Impostata");
|
|
|
|
// Every form needs its antiforgery token, also the ones that send no field.
|
|
foreach (var path in new[] { "/azioni/chiavi/alpaca/togli", "/azioni/conti/" + Guid.NewGuid() + "/allinea" })
|
|
{
|
|
using var forged = await server.Http.PostAsync(new Uri(path, UriKind.Relative), new FormUrlEncodedContent([]));
|
|
Assert.AreEqual(HttpStatusCode.BadRequest, forged.StatusCode, path);
|
|
}
|
|
|
|
Assert.IsTrue((await secrets.StatusAsync("ALPACA_API_SECRET_DEMO")).IsSet, "A forged request removes nothing.");
|
|
// The engine starts in the background after "ready": the paper account appears within moments.
|
|
var accounts = new List<string>();
|
|
for (var i = 0; i < 100 && accounts.Count == 0; i++)
|
|
{
|
|
accounts = [.. await server.Host.Services.Db.ReadAsync(s => s.QueryAsync("SELECT name FROM accounts WHERE environment = 'demo'", r => r.Text("name")))];
|
|
if (accounts.Count == 0)
|
|
{
|
|
await Task.Delay(100);
|
|
}
|
|
}
|
|
|
|
CollectionAssert.AreEqual(new[] { "Alpaca paper" }, accounts.ToArray());
|
|
|
|
// Capital in euro, as people type it; dollars need the ECB rate first.
|
|
using (var capital = await server.PostFormAsync("/impostazioni", "/azioni/capitale/okx", ("euro", "1.500,50")))
|
|
{
|
|
Assert.AreEqual("/impostazioni?ok=capitale#conti", ServerHarness.Location(capital));
|
|
}
|
|
|
|
using (var usd = await server.PostFormAsync("/impostazioni", "/azioni/capitale/alpaca", ("euro", "2000")))
|
|
{
|
|
Assert.AreEqual("/impostazioni?errore=cambio#conti", ServerHarness.Location(usd));
|
|
}
|
|
|
|
using (var bad = await server.PostFormAsync("/impostazioni", "/azioni/capitale/okx", ("euro", "molto")))
|
|
{
|
|
Assert.AreEqual("/impostazioni?errore=importo#conti", ServerHarness.Location(bad));
|
|
}
|
|
|
|
var changes = await server.Host.Services.Db.ReadAsync(s => s.QueryAsync("SELECT broker, amount_eur FROM capital_changes", r => (r.Text("broker"), r.Money("amount_eur"))));
|
|
CollectionAssert.AreEqual(new[] { ("okx", 1500.50m) }, changes.ToArray());
|
|
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")]
|
|
[DataRow("1.500", "1500")]
|
|
[DataRow("1.500,50", "1500.50")]
|
|
[DataRow("1500,5", "1500.5")]
|
|
[DataRow("1500.50", "1500.50")]
|
|
[DataRow(" 2 000 € ", "2000")]
|
|
[DataRow("10,999", "10.99")]
|
|
[DataRow("-5", null)]
|
|
[DataRow("abc", null)]
|
|
[DataRow("", null)]
|
|
public void AmountsAreReadAsPeopleTypeThem(string text, string? expected) =>
|
|
Assert.AreEqual(expected is null ? null : decimal.Parse(expected, System.Globalization.CultureInfo.InvariantCulture), Forms.ParseEuro(text));
|
|
}
|