Merge branch 'fase9-fix-conti' into fase-9
This commit is contained in:
commit
e58a26e8fa
20 files changed
+814
-174
No files matched your search
@@ -147,6 +147,48 @@ public sealed class AccountsScreenTests
|
||||
StringAssert.Contains(await server.TextAsync("/impostazioni"), "Trend crypto: quota 100%");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task AMissingStopWhereAPositionWasLeftOutOffersBothChoicesAgain()
|
||||
{
|
||||
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite());
|
||||
await server.SignInFirstTimeAsync();
|
||||
var db = server.Host.Services!.Db;
|
||||
var account = Guid.NewGuid();
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
async Task<string> PageAsync(string reason, DateTimeOffset since, params string[] excluded)
|
||||
{
|
||||
var differences = System.Text.Json.JsonSerializer.Serialize(new
|
||||
{
|
||||
Current = new[] { new AccountDifference(DifferenceKinds.Stop, "BTC-EUR", 0.00598m, 0m, "BTC-EUR: gli stop coprono 0 su 0,00598.") },
|
||||
Excluded = excluded,
|
||||
});
|
||||
await db.WriteAsync(async s =>
|
||||
{
|
||||
await s.ExecuteAsync("DELETE FROM account_status");
|
||||
await s.ExecuteAsync("INSERT INTO account_status (id, account_id, mode, mode_since, mode_reason, differences, last_reconciled_at, last_outcome, created_at, updated_at) " +
|
||||
"VALUES (@id, @a, 'prudent', @since, @r, @d, @now, 'different', @now, @now)",
|
||||
("id", Guid.NewGuid()), ("a", account), ("since", since), ("r", reason), ("d", new DbJson(differences)), ("now", now));
|
||||
});
|
||||
return await server.TextAsync("/conti");
|
||||
}
|
||||
|
||||
await db.WriteAsync(s => s.ExecuteAsync("INSERT INTO accounts (id, name, broker, environment, base_currency, created_at) VALUES (@id, 'OKX demo', 'okx', 'demo', 'EUR', @t)",
|
||||
("id", account), ("t", now)));
|
||||
var both = await PageAsync(Reconciler.StopReason, now.AddMinutes(-20), "position:BTC-EUR:0.00998:0.00598");
|
||||
StringAssert.Contains(both, "Allinea il registro al conto");
|
||||
StringAssert.Contains(both, "Lascia fuori ciò che non è del bot");
|
||||
StringAssert.Contains(both, "dove avevi lasciato fuori una differenza");
|
||||
|
||||
// Another instrument's exclusion has nothing to do with it, and after a choice nobody is told to choose again.
|
||||
var again = await PageAsync(Reconciler.StopReason, now.AddMinutes(-20), "position:ETH-EUR:1:0");
|
||||
StringAssert.Contains(again, "Ricontrolla adesso");
|
||||
Assert.DoesNotContain("Allinea il registro al conto", again);
|
||||
var waiting = await PageAsync(Reconciler.StopReason, now.AddMinutes(-2), "position:BTC-EUR:0.00998:0.00598");
|
||||
StringAssert.Contains(waiting, "torna normale da solo quando c'è");
|
||||
StringAssert.Contains(await PageAsync(DifferenceKinds.Stop, now.AddMinutes(-2)), "Se entro 15 minuti si spiega da sola");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task TheUserSplitsTheCapitalAndWithRealMoneyOnlyThroughTheProcedure()
|
||||
|
||||
@@ -193,10 +193,14 @@ public sealed partial class DeliveryTests
|
||||
{
|
||||
var now = new DateTimeOffset(2026, 12, 1, 9, 0, 0, TimeSpan.Zero);
|
||||
DateTimeOffset? Ago(double minutes) => now.AddMinutes(-minutes);
|
||||
Assert.IsTrue(HealthRules.Loop(now, false, Ago(60)).Ok, "Not started, as on the error page or without keys.");
|
||||
Assert.IsTrue(HealthRules.Loop(now, true, null).Ok);
|
||||
Assert.IsTrue(HealthRules.Loop(now, true, Ago(1.9)).Ok);
|
||||
Assert.AreEqual(("fermo", false), HealthRules.Loop(now, true, Ago(2.1)));
|
||||
Assert.AreEqual(("non avviato", true), HealthRules.Loop(now, null, false, false, null), "No engine to start, as in the demo. Without keys the simulators start as the others.");
|
||||
Assert.AreEqual(("in avvio", true), HealthRules.Loop(now, Ago(9.9), false, false, null));
|
||||
Assert.AreEqual(("non avviato", false), HealthRules.Loop(now, Ago(10.1), false, false, null), "Stalled.");
|
||||
Assert.AreEqual(("non avviato", false), HealthRules.Loop(now, Ago(0.1), false, true, null), "Failed: known at once.");
|
||||
Assert.AreEqual(new GuardOptions().StalledStart, HealthRules.StartLimit);
|
||||
Assert.AreEqual(("in avvio", true), HealthRules.Loop(now, Ago(60), true, false, null));
|
||||
Assert.AreEqual(("ok", true), HealthRules.Loop(now, Ago(60), true, false, Ago(1.9)));
|
||||
Assert.AreEqual(("fermo", false), HealthRules.Loop(now, Ago(60), true, false, Ago(2.1)));
|
||||
Assert.AreEqual(new GuardOptions().Silence, HealthRules.LoopLimit);
|
||||
|
||||
Assert.IsTrue(HealthRules.Feed(now, null, null).Ok, "No instrument to follow yet.");
|
||||
@@ -311,6 +315,23 @@ public sealed partial class DeliveryTests
|
||||
Assert.IsTrue(docker.All(r => r.Contains("\"$IMAGE\"", StringComparison.Ordinal)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheImageSaysTheVersionAndTheCommitItIsMadeFrom()
|
||||
{
|
||||
// The image of the manual publication comes from the tasks, that of a tag from the workflow: both say what they are.
|
||||
var tasks = Text("tools/Anubis.Tasks/Program.cs");
|
||||
StringAssert.Contains(tasks, "$\"ANUBIS_VERSION={Version()}\"");
|
||||
StringAssert.Contains(tasks, "$\"ANUBIS_COMMIT={Commit()}\"");
|
||||
StringAssert.Contains(tasks, "\"-dirty\"");
|
||||
var build = (string)Steps("image").Single(s => ((string)s["run"]).Contains("docker build", StringComparison.Ordinal))["run"];
|
||||
StringAssert.Contains(build, "version=${REF_NAME#v}");
|
||||
StringAssert.Contains(build, "\"ANUBIS_VERSION=$version\"");
|
||||
StringAssert.Contains(build, "\"ANUBIS_COMMIT=$(git rev-parse HEAD)\"");
|
||||
var publish = Text("deploy/docker/publish.sh");
|
||||
Assert.IsLessThan(publish.IndexOf("docker login", StringComparison.Ordinal), publish.IndexOf("docker image inspect", StringComparison.Ordinal), "Checked before anything leaves the house.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheYamlReaderRefusesWhatItDoesNotKnow()
|
||||
@@ -381,22 +402,66 @@ public sealed partial class DeliveryTests
|
||||
Assert.IsEmpty(offline.Pushed());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
[OSCondition(OperatingSystems.Linux)]
|
||||
[DataRow("v0.9.0", "ci", PublishRun.Commit, false)]
|
||||
[DataRow("v0.9.0", "0.8.0", PublishRun.Commit, false)]
|
||||
[DataRow("v0.9.0", "0.9.0-rc.1", PublishRun.Commit, false)]
|
||||
[DataRow("v0.9.0", "0.9.0", PublishRun.Commit + "-dirty", false)]
|
||||
[DataRow("v0.9.0", "0.9.0", "fedcba9876543210fedcba9876543210fedcba98", false)]
|
||||
[DataRow("v0.9.0", "0.9.0", "", false)]
|
||||
[DataRow("v0.9.0", "0.9.0", PublishRun.Commit, true)]
|
||||
public async Task TheScriptRefusesAnImageThatIsNotTheOneOfTheTag(string tag, string version, string revision, bool tagged)
|
||||
{
|
||||
using var run = new PublishRun("v0.7.0", version: version, revision: revision, tagged: tagged);
|
||||
var (code, output) = await run.RunAsync(tag, PublishRun.Token);
|
||||
Assert.AreEqual(1, code, output);
|
||||
StringAssert.Contains(output, "Pubblicazione non riuscita: l'immagine");
|
||||
Assert.IsEmpty(run.Pushed());
|
||||
Assert.AreEqual("", run.Input, "Not even the login.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
[OSCondition(OperatingSystems.Linux)]
|
||||
[DataRow("v0.9.0", PublishRun.TagCommit, true)]
|
||||
[DataRow("v0.9.0-rc.1", PublishRun.TagCommit, true)]
|
||||
[DataRow("v0.9.0-rc.1", PublishRun.Commit, false)]
|
||||
public async Task TheScriptTakesTheImageOfTheTasksAtTheCommitOfTheTag(string tag, string revision, bool tagged)
|
||||
{
|
||||
// The commit of the tag when the tag is here, otherwise the one checked out: in the workflow they are the same.
|
||||
using var run = new PublishRun("v0.7.0", version: "0.9.0", revision: revision, tagged: tagged);
|
||||
var (code, output) = await run.RunAsync(tag, PublishRun.Token);
|
||||
Assert.AreEqual(0, code, output);
|
||||
Assert.IsNotEmpty(run.Pushed());
|
||||
}
|
||||
|
||||
private sealed class PublishRun : IDisposable
|
||||
{
|
||||
public const string Token = "a-token-only-for-the-test";
|
||||
public const string Commit = "0123456789abcdef0123456789abcdef01234567";
|
||||
public const string TagCommit = "89abcdef0123456789abcdef0123456789abcdef";
|
||||
|
||||
private readonly string _root = Path.Combine(Path.GetTempPath(), "anubis-publish-" + Guid.NewGuid().ToString("N"));
|
||||
|
||||
public PublishRun(string others, bool gitFails = false)
|
||||
public PublishRun(string others, bool gitFails = false, string? version = null, string revision = Commit, bool tagged = false)
|
||||
{
|
||||
Directory.CreateDirectory(Path.Combine(_root, "deploy", "docker"));
|
||||
Directory.CreateDirectory(Path.Combine(_root, "bin"));
|
||||
File.WriteAllText(Path.Combine(_root, "deploy", "docker", "publish.sh"), Text("deploy/docker/publish.sh"));
|
||||
File.WriteAllText(Path.Combine(_root, "Directory.Build.props"), "<Project>\n <Version>0.9.0</Version>\n</Project>\n");
|
||||
Tool("docker", "printf '%s\\n' \"$*\" >> \"$RECORD/calls\"\nif [ \"$1\" = login ]; then cat > \"$RECORD/input\"; printf '%s' \"$DOCKER_CONFIG\" > \"$RECORD/config\"; fi\n");
|
||||
Tool("git", gitFails ? "exit 128\n" : string.Concat(others.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(o => $"printf 'abc\\trefs/tags/{o}\\n'\n")));
|
||||
_version = version;
|
||||
Tool("docker", "printf '%s\\n' \"$*\" >> \"$RECORD/calls\"\nif [ \"$1\" = login ]; then cat > \"$RECORD/input\"; printf '%s' \"$DOCKER_CONFIG\" > \"$RECORD/config\"; fi\n" +
|
||||
$"case \"$*\" in *image.version*) printf '%s\\n' \"$VERSION\" ;; *image.revision*) printf '%s\\n' '{revision}' ;; esac\n");
|
||||
var tagCommit = tagged ? $"printf '%s\\n' {TagCommit}; exit 0" : "exit 1";
|
||||
Tool("git", $"case \"$*\" in *rev-parse*refs/tags/*) {tagCommit} ;; *rev-parse*HEAD*) printf '%s\\n' {Commit}; exit 0 ;; esac\n" +
|
||||
(gitFails ? "exit 128\n" : string.Concat(others.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(o => $"printf 'abc\\trefs/tags/{o}\\n'\n"))));
|
||||
}
|
||||
|
||||
// What the image says of itself when the test says nothing: the version of the tag.
|
||||
private readonly string? _version;
|
||||
|
||||
public string Calls => Recorded("calls");
|
||||
|
||||
public string Input => Recorded("input");
|
||||
@@ -413,6 +478,7 @@ public sealed partial class DeliveryTests
|
||||
info.ArgumentList.Add(tag);
|
||||
info.Environment["PATH"] = Path.Combine(_root, "bin") + ":" + Environment.GetEnvironmentVariable("PATH");
|
||||
info.Environment["RECORD"] = _root;
|
||||
info.Environment["VERSION"] = _version ?? tag[1..];
|
||||
info.Environment["REGISTRY"] = "registry.test";
|
||||
info.Environment["REGISTRY_USER"] = "someone";
|
||||
info.Environment["REGISTRY_TOKEN"] = token;
|
||||
|
||||
@@ -23,4 +23,49 @@ public sealed class HealthEndpointTests
|
||||
Assert.AreEqual(AnubisInfo.Name, body.Name);
|
||||
Assert.AreEqual(AnubisInfo.Version, body.Version);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task AnEngineThatCouldNotStartIsNotHealthyAndIsTriedAgain()
|
||||
{
|
||||
var (env, postgres) = await ServerHarness.DockerOnEngineAsync();
|
||||
await using var engine = postgres;
|
||||
await using var server = await ServerHarness.StartAsync("docker", env, trading: true);
|
||||
async Task<HealthResponse> HealthAsync()
|
||||
{
|
||||
using var response = await server.GetAsync("/health");
|
||||
return (await response.Content.ReadFromJsonAsync<HealthResponse>())!;
|
||||
}
|
||||
|
||||
async Task UntilAsync(string status, string loop)
|
||||
{
|
||||
HealthResponse? last = null;
|
||||
for (var i = 0; i < 100; i++)
|
||||
{
|
||||
last = await HealthAsync();
|
||||
if (last.Status == status && last.Checks!.GetValueOrDefault("motore") == loop)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await Task.Delay(100);
|
||||
}
|
||||
|
||||
Assert.Fail($"{last!.Status}, {string.Join(", ", last.Checks!)}");
|
||||
}
|
||||
|
||||
await UntilAsync("ok", "ok");
|
||||
|
||||
// The services start again and the engine's startup fails at its first steps: ready, but nothing watches the stops.
|
||||
var db = server.Host.Services!.Db;
|
||||
await db.WriteAsync(s => s.ExecuteAsync("ALTER TABLE instruments RENAME TO instruments_away"));
|
||||
await server.Host.RestartServicesAsync(CancellationToken.None);
|
||||
await server.WaitForAsync(HostMode.Ready);
|
||||
await UntilAsync("unavailable", "non avviato");
|
||||
|
||||
// The cause goes away: the start is tried again by itself.
|
||||
await server.Host.Services!.Db.WriteAsync(s => s.ExecuteAsync("ALTER TABLE instruments_away RENAME TO instruments"));
|
||||
await UntilAsync("ok", "ok");
|
||||
Assert.IsTrue(server.Host.Services!.Trading!.IsStarted);
|
||||
}
|
||||
}
|
||||
@@ -202,6 +202,133 @@ public sealed class LedgerTests
|
||||
Assert.AreEqual(realized + positions.Sum(p => p.Unrealized), equity.Result, 0.0001m, $"passo {step}: risultato = realizzato + non realizzato");
|
||||
}
|
||||
|
||||
private static readonly Dictionary<string, decimal> _half = new() { [StrategyNames.EquityMomentum] = 0.5m, [StrategyNames.EquityMeanrev] = 0.5m };
|
||||
|
||||
/// <summary>6,000 € on Alpaca at 1.10 $/€: 6,600 $, 4,950 to the momentum and 1,650 to the mean reversion.</summary>
|
||||
private static async Task<(TradingRig Rig, AccountContext Account, Capital Capital)> EntrustedAsync()
|
||||
{
|
||||
var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
|
||||
var fx = new FxStore(rig.Db, rig.Clock);
|
||||
await fx.UpsertAsync([new FxRate("EUR", "USD", new DateOnly(2026, 11, 9), 1.10m, "ecb")], _none).ConfigureAwait(false);
|
||||
var alpaca = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Demo).ConfigureAwait(false);
|
||||
await rig.Db.WriteAsync(async s =>
|
||||
{
|
||||
foreach (var (strategy, share) in new[] { (StrategyNames.EquityMomentum, 0.75m), (StrategyNames.EquityMeanrev, 0.25m) })
|
||||
{
|
||||
await s.ExecuteAsync("INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at, share) VALUES (@id, @s, @a, 'observation', 0, @j, @now, @now, @sh)",
|
||||
_none, ("id", Ids.NewId(rig.Clock)), ("s", strategy), ("a", alpaca.AccountId), ("j", new Anubis.Db.DbJson("{}")), ("now", rig.Clock.UtcNow), ("sh", share))
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
}, _none).ConfigureAwait(false);
|
||||
var capital = new Capital(rig.Db, rig.Clock, rig.Ledger, fx);
|
||||
await capital.SetAsync(Venues.Alpaca, 6000m, "test", _none).ConfigureAwait(false);
|
||||
return (rig, alpaca, capital);
|
||||
}
|
||||
|
||||
private static async Task SharesAsync(Capital capital, TradingRig rig, decimal momentum, decimal meanrev)
|
||||
{
|
||||
var strategies = (await capital.StrategiesAsync(Venues.Alpaca, _none).ConfigureAwait(false)).ToDictionary(s => s.Strategy);
|
||||
Assert.AreEqual((momentum, meanrev), (strategies[StrategyNames.EquityMomentum].Capital, strategies[StrategyNames.EquityMeanrev].Capital));
|
||||
var stored = await rig.QueryAsync("SELECT capital FROM strategy_state ORDER BY strategy DESC", r => r.Money("capital")).ConfigureAwait(false);
|
||||
CollectionAssert.AreEqual(new[] { momentum, meanrev }, stored.ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task SharesWrittenWithoutTheirMoneyAreCompletedByTheSameSplit()
|
||||
{
|
||||
var (rig, _, capital) = await EntrustedAsync().ConfigureAwait(false);
|
||||
await using var owned = rig;
|
||||
|
||||
// What an interruption between the two writes left behind: the new shares without the capital flows.
|
||||
await rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET share = 0.5", _none), _none).ConfigureAwait(false);
|
||||
await capital.SetSharesAsync(Venues.Alpaca, _half, "test", _none).ConfigureAwait(false);
|
||||
await SharesAsync(capital, rig, 3300m, 3300m).ConfigureAwait(false);
|
||||
Assert.IsEmpty(await rig.QueryAsync("SELECT id FROM config_history WHERE key LIKE 'strategy.%'", r => r.Id("id")).ConfigureAwait(false), "No share changed.");
|
||||
|
||||
// Complete: the same split again writes nothing.
|
||||
async Task<int> RowsAsync() => (await rig.QueryAsync("SELECT id FROM cash_ledger", r => r.Id("id")).ConfigureAwait(false)).Count + (await rig.QueryAsync("SELECT id FROM journal", r => r.Id("id")).ConfigureAwait(false)).Count;
|
||||
var rows = await RowsAsync().ConfigureAwait(false);
|
||||
await capital.SetSharesAsync(Venues.Alpaca, _half, "test", _none).ConfigureAwait(false);
|
||||
Assert.AreEqual(rows, await RowsAsync().ConfigureAwait(false));
|
||||
|
||||
// The same for the capital: the figure was written, the flows were not.
|
||||
await rig.Db.WriteAsync(s => s.ExecuteAsync(
|
||||
"INSERT INTO capital_changes (id, broker, amount_eur, currency, fx_rate, amount, changed_by, created_at) VALUES (@id, 'alpaca', 8000, 'USD', 1.1, 8800, 'test', @now)", _none,
|
||||
("id", Ids.NewId(rig.Clock)), ("now", rig.Clock.UtcNow.AddSeconds(1))), _none).ConfigureAwait(false);
|
||||
await capital.SetAsync(Venues.Alpaca, 8000m, "test", _none).ConfigureAwait(false);
|
||||
await SharesAsync(capital, rig, 4400m, 4400m).ConfigureAwait(false);
|
||||
Assert.HasCount(2, await rig.QueryAsync("SELECT id FROM capital_changes", r => r.Id("id")).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task OverlappingChangesMoveTheMoneyOnce()
|
||||
{
|
||||
var (rig, _, capital) = await EntrustedAsync().ConfigureAwait(false);
|
||||
await using var owned = rig;
|
||||
var original = new Dictionary<string, decimal> { [StrategyNames.EquityMomentum] = 0.75m, [StrategyNames.EquityMeanrev] = 0.25m };
|
||||
for (var round = 0; round < 10; round++)
|
||||
{
|
||||
var split = round % 2 == 0 ? _half : original;
|
||||
using var together = new Barrier(4);
|
||||
await Task.WhenAll(Enumerable.Range(0, 4).Select(_ => Task.Factory.StartNew(() =>
|
||||
{
|
||||
together.SignalAndWait();
|
||||
return capital.SetSharesAsync(Venues.Alpaca, split, "test", _none);
|
||||
}, _none, TaskCreationOptions.LongRunning, TaskScheduler.Default).Unwrap())).ConfigureAwait(false);
|
||||
await SharesAsync(capital, rig, 6600m * split[StrategyNames.EquityMomentum], 6600m * split[StrategyNames.EquityMeanrev]).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
Assert.HasCount(10, await rig.QueryAsync("SELECT id FROM journal WHERE code = 'shares_changed'", r => r.Id("id")).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task ASplitThatFailsHalfwayLeavesEverythingAsItWas()
|
||||
{
|
||||
var (rig, _, capital) = await EntrustedAsync().ConfigureAwait(false);
|
||||
await using var owned = rig;
|
||||
|
||||
// The flows cannot be written: the shares must not move either.
|
||||
await rig.Db.WriteAsync(s => s.ExecuteAsync("ALTER TABLE cash_ledger RENAME COLUMN note TO note_away", _none), _none).ConfigureAwait(false);
|
||||
await Assert.ThrowsAsync<System.Data.Common.DbException>(() => capital.SetSharesAsync(Venues.Alpaca, _half, "test", _none)).ConfigureAwait(false);
|
||||
await rig.Db.WriteAsync(s => s.ExecuteAsync("ALTER TABLE cash_ledger RENAME COLUMN note_away TO note", _none), _none).ConfigureAwait(false);
|
||||
CollectionAssert.AreEqual(new[] { 0.75m, 0.25m }, (await rig.QueryAsync("SELECT share FROM strategy_state ORDER BY strategy DESC", r => r.Money("share")).ConfigureAwait(false)).ToArray());
|
||||
await SharesAsync(capital, rig, 4950m, 1650m).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task MoneyHeldByAPurchaseUnderWayIsNotGivenAway()
|
||||
{
|
||||
var (rig, account, capital) = await EntrustedAsync().ConfigureAwait(false);
|
||||
await using var owned = rig;
|
||||
var msft = await rig.InstrumentAsync(TradingRig.Stock("MSFT")).ConfigureAwait(false);
|
||||
|
||||
// 11 shares at 400 $, 2 of them filled: 9 still to pay, at most 1% dearer, hold 3,636 $ of the 4,950.
|
||||
await rig.Db.WriteAsync(x => x.ExecuteAsync(
|
||||
"INSERT INTO executions (id, account_id, instrument_id, strategy, side, purpose, quantity, filled, order_key, sequence, step, reference_price, status, started_at, created_at, updated_at) " +
|
||||
"VALUES (@id, @a, @i, @s, 'buy', 'entry', 11, 2, 'K1', 1, 0, 400, @w, @t, @t, @t)", _none,
|
||||
("id", Ids.NewId(rig.Clock)), ("a", account.AccountId), ("i", msft.Id), ("s", StrategyNames.EquityMomentum), ("w", ExecutionStates.Working), ("t", rig.Clock.UtcNow)), _none)
|
||||
.ConfigureAwait(false);
|
||||
var error = await Assert.ThrowsExactlyAsync<CapitalException>(() => capital.SetSharesAsync(Venues.Alpaca, _half, "test", _none)).ConfigureAwait(false);
|
||||
Assert.Contains("Momentum azioni", error.Message);
|
||||
Assert.Contains("acquisti in corso", error.Message);
|
||||
await Assert.ThrowsExactlyAsync<CapitalException>(() => capital.SetAsync(Venues.Alpaca, 2000m, "test", _none)).ConfigureAwait(false);
|
||||
await SharesAsync(capital, rig, 4950m, 1650m).ConfigureAwait(false);
|
||||
|
||||
// 1,314 $ are free: giving the strategy more, or taking no more than that, is fine.
|
||||
await capital.SetAsync(Venues.Alpaca, 7000m, "test", _none).ConfigureAwait(false);
|
||||
await capital.SetAsync(Venues.Alpaca, 6000m, "test", _none).ConfigureAwait(false);
|
||||
await SharesAsync(capital, rig, 4950m, 1650m).ConfigureAwait(false);
|
||||
|
||||
// The purchase is over: the money is free again.
|
||||
await rig.Db.WriteAsync(x => x.ExecuteAsync("UPDATE executions SET status = 'canceled'", _none), _none).ConfigureAwait(false);
|
||||
await capital.SetSharesAsync(Venues.Alpaca, _half, "test", _none).ConfigureAwait(false);
|
||||
await SharesAsync(capital, rig, 3300m, 3300m).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task EquityPhotographsSeparateWorldsAndCorrectForCapitalChanges()
|
||||
|
||||
@@ -217,7 +217,7 @@ public sealed class ReconcilerTests
|
||||
{
|
||||
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.AreEqual((AccountModes.Prudent, Reconciler.StopReason), (state.Mode, state.ModeReason));
|
||||
Assert.IsFalse(state.Excluded.Any(e => e.StartsWith(DifferenceKinds.Stop, StringComparison.Ordinal)), string.Join("; ", state.Excluded));
|
||||
}
|
||||
|
||||
@@ -228,6 +228,112 @@ public sealed class ReconcilerTests
|
||||
Assert.AreEqual(AccountModes.Normal, report.Mode, string.Join("; ", report.Differences.Select(d => d.Message)));
|
||||
}
|
||||
|
||||
/// <summary>Coin gone from the account and no stop left: prudent, and past the 15 minutes.</summary>
|
||||
private static async Task GoneWithItsStopAsync(Setup s, decimal missing)
|
||||
{
|
||||
s.Broker.Missing["BTC-EUR"] = missing;
|
||||
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);
|
||||
CollectionAssert.AreEquivalent(new[] { DifferenceKinds.Position, DifferenceKinds.Stop }, report.Differences.Select(d => d.Kind).ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Simulation)]
|
||||
[DataRow(ReconcileChoice.Align)]
|
||||
[DataRow(ReconcileChoice.Exclude)]
|
||||
public async Task APositionThatLeftWithItsStopDoesNotKeepTheAccountPrudentAfterTheChoice(ReconcileChoice choice)
|
||||
{
|
||||
await using var s = await HoldingAsync().ConfigureAwait(false);
|
||||
await GoneWithItsStopAsync(s, 0.00998m).ConfigureAwait(false);
|
||||
|
||||
// No stop can cover what is not there: whatever the user chooses, none is waited for.
|
||||
Assert.AreEqual(ReconcileResolution.Normal, 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.Normal, state.Mode);
|
||||
Assert.IsEmpty(state.Differences);
|
||||
s.Rig.Clock.Advance(TimeSpan.FromMinutes(5));
|
||||
var report = await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false);
|
||||
Assert.AreEqual((ReconcileOutcomes.Clean, AccountModes.Normal), (report.Outcome, report.Mode), string.Join("; ", report.Differences.Select(d => d.Message)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Simulation)]
|
||||
public async Task AStopMissingOnWhatIsLeftStaysAndAlignTakesUpTheExcludedPosition()
|
||||
{
|
||||
await using var s = await HoldingAsync().ConfigureAwait(false);
|
||||
await GoneWithItsStopAsync(s, 0.004m).ConfigureAwait(false);
|
||||
|
||||
// 0.00598 are still on the account without their stop: that is not left out, and only for that quantity.
|
||||
Assert.AreEqual(ReconcileResolution.StopsMissing, await s.Reconciler.ResolveAsync(s.Manager, ReconcileChoice.Exclude, "test", _none).ConfigureAwait(false));
|
||||
var state = await s.Reconciler.StateAsync(s.Account.AccountId, _none).ConfigureAwait(false);
|
||||
Assert.AreEqual((DifferenceKinds.Stop, 0.00598m, 0m), (state.Differences.Single().Kind, state.Differences.Single().Ledger, state.Differences.Single().Broker));
|
||||
|
||||
// The stop asked for what the ledger says never goes through: the way out is to take the account's number.
|
||||
s.Rig.Clock.Advance(TimeSpan.FromMinutes(16));
|
||||
await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false);
|
||||
state = await s.Reconciler.StateAsync(s.Account.AccountId, _none).ConfigureAwait(false);
|
||||
Assert.IsTrue(state.WaitsForUser(s.Rig.Clock.UtcNow, s.Reconciler.Grace));
|
||||
Assert.IsTrue(state.HasChoices, "The position left out can still be aligned.");
|
||||
Assert.AreEqual(ReconcileResolution.StopsMissing, 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);
|
||||
state = await s.Reconciler.StateAsync(s.Account.AccountId, _none).ConfigureAwait(false);
|
||||
Assert.IsEmpty(state.Excluded);
|
||||
Assert.IsFalse(state.HasChoices);
|
||||
|
||||
s.Broker.RefuseStops = false;
|
||||
Assert.AreEqual(AccountModes.Normal, (await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false)).Mode);
|
||||
Assert.AreEqual(0.00598m, (await s.Paper.GetOpenOrdersAsync(_none).ConfigureAwait(false)).Single().Quantity);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Simulation)]
|
||||
public async Task AfterTheChoiceTheAccountReturnsToNormalWheneverTheStopIsBack()
|
||||
{
|
||||
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));
|
||||
Assert.AreEqual(ReconcileResolution.StopsMissing, await s.Reconciler.ResolveAsync(s.Manager, ReconcileChoice.Align, "test", _none).ConfigureAwait(false));
|
||||
|
||||
// Much later than 15 minutes: the user has already chosen, nothing is left to ask.
|
||||
s.Rig.Clock.Advance(TimeSpan.FromHours(3));
|
||||
Assert.AreEqual(AccountModes.Prudent, (await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false)).Mode);
|
||||
s.Broker.RefuseStops = false;
|
||||
Assert.AreEqual(AccountModes.Normal, (await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false)).Mode);
|
||||
Assert.HasCount(1, await CodesAsync(s.Rig, "account_normal").ConfigureAwait(false));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Simulation)]
|
||||
public async Task ANewDifferenceWhileAStopIsAwaitedHasItsOwnFifteenMinutes()
|
||||
{
|
||||
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));
|
||||
await s.Reconciler.ResolveAsync(s.Manager, ReconcileChoice.Align, "test", _none).ConfigureAwait(false);
|
||||
|
||||
// Coin leaves the account while the stop is awaited: past its 15 minutes that one waits for the user (SPEC 7.4).
|
||||
s.Rig.Clock.Advance(TimeSpan.FromMinutes(30));
|
||||
s.Broker.Missing["BTC-EUR"] = 0.004m;
|
||||
await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false);
|
||||
var state = await s.Reconciler.StateAsync(s.Account.AccountId, _none).ConfigureAwait(false);
|
||||
Assert.IsFalse(state.WaitsForUser(s.Rig.Clock.UtcNow, s.Reconciler.Grace), "It may still explain itself.");
|
||||
s.Rig.Clock.Advance(TimeSpan.FromMinutes(16));
|
||||
s.Broker.Missing.Clear();
|
||||
s.Broker.RefuseStops = false;
|
||||
Assert.AreEqual(AccountModes.Prudent, (await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false)).Mode);
|
||||
Assert.AreEqual(ReconcileResolution.Normal, await s.Reconciler.ResolveAsync(s.Manager, ReconcileChoice.Align, "test", _none).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Simulation)]
|
||||
public async Task AKeyThatMayWithdrawStopsPurchasesUntilItIsReplaced()
|
||||
|
||||
@@ -101,6 +101,7 @@ internal sealed partial class ServerHarness : IAsyncDisposable
|
||||
MarketHttp = marketHttp,
|
||||
MarketSockets = marketHttp is null ? null : () => new FakeSocket(),
|
||||
Trading = trading,
|
||||
TradingRetry = TimeSpan.FromMilliseconds(200),
|
||||
TelegramHttp = telegramHttp,
|
||||
});
|
||||
await app.StartAsync().ConfigureAwait(false);
|
||||
|
||||
@@ -359,6 +359,43 @@ public sealed class AccessTests
|
||||
Assert.IsFalse(await Started().ReauthenticateAsync("password-giusta", code).ConfigureAwait(false), "A code used once stays used after the services start again.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task ThePasswordAloneDoesNotClearTheWrongCodes()
|
||||
{
|
||||
var clock = new ManualClock(new DateTimeOffset(2026, 11, 30, 9, 0, 0, TimeSpan.Zero));
|
||||
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
|
||||
var access = new AccessStore(test.Db, clock, new SecretStore(test.Db, clock, new byte[32]), iterations: 1000);
|
||||
Assert.IsTrue(await access.EnsureUserAsync("password-giusta", mustChange: false).ConfigureAwait(false));
|
||||
var user = (await access.GetUserAsync().ConfigureAwait(false))!.Id;
|
||||
var secret = Totp.NewSecret();
|
||||
Assert.AreEqual(AccessChange.Done, await access.EnableSecondFactorAsync(user, secret, "password-giusta", Totp.Compute(secret, clock.UtcNow), Guid.Empty).ConfigureAwait(false));
|
||||
clock.Advance(TimeSpan.FromMinutes(1));
|
||||
var wrong = Totp.Compute(secret, clock.UtcNow.AddHours(1));
|
||||
|
||||
// Whoever knows the password and not the code: neither form gives back the attempts.
|
||||
for (var i = 0; i < LoginLimiter.PerAddress - 1; i++)
|
||||
{
|
||||
Assert.IsFalse(await access.ReauthenticateAsync("password-giusta", wrong).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
Assert.AreEqual(AccessChange.Done, (await access.ChangePasswordAsync(user, "password-giusta", "una password nuova", Guid.Empty).ConfigureAwait(false)).Outcome, "It takes back its own attempt only.");
|
||||
Assert.AreEqual(AccessChange.AlreadyOn, await access.EnableSecondFactorAsync(user, Totp.NewSecret(), "una password nuova", "000000", Guid.Empty).ConfigureAwait(false));
|
||||
Assert.IsFalse(await access.ReauthenticateAsync("una password nuova", wrong).ConfigureAwait(false));
|
||||
Assert.IsFalse(await access.ReauthenticateAsync("una password nuova", Totp.Compute(secret, clock.UtcNow)).ConfigureAwait(false), "Locked: even the right code waits.");
|
||||
clock.Advance(LoginLimiter.Window);
|
||||
|
||||
// Both right: the count starts over.
|
||||
Assert.IsFalse(await access.ReauthenticateAsync("una password nuova", wrong).ConfigureAwait(false));
|
||||
Assert.IsTrue(await access.ReauthenticateAsync("una password nuova", Totp.Compute(secret, clock.UtcNow)).ConfigureAwait(false));
|
||||
for (var i = 0; i < LoginLimiter.PerAddress; i++)
|
||||
{
|
||||
Assert.AreEqual(AccessChange.Wrong, (await access.ChangePasswordAsync(user, "sbagliata", "una password nuova", Guid.Empty).ConfigureAwait(false)).Outcome);
|
||||
}
|
||||
|
||||
Assert.AreEqual(AccessChange.Locked, (await access.ChangePasswordAsync(user, "una password nuova", "un'altra ancora", Guid.Empty).ConfigureAwait(false)).Outcome);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task EndedSessionsAreRemovedAtTheNextSignIn()
|
||||
|
||||
Reference in new issue
Block a user