diff --git a/deploy/docker/publish.sh b/deploy/docker/publish.sh index 1b67eb7..6d10225 100644 --- a/deploy/docker/publish.sh +++ b/deploy/docker/publish.sh @@ -22,6 +22,18 @@ expected=$(sed -n 's:.*\(.*\).*:\1:p' "$root/Directory.Build. [ -n "${REGISTRY_TOKEN:-}" ] || fail "manca il segreto REGISTRY_TOKEN (token Gitea con il permesso write:package)." name="$REGISTRY/balbosoft/anubis" +# The image says what it was made from (its labels): only what comes from the commit of the tag is published as that tag. +# Without the tag here, as in the CI, the commit checked out is the tag's. +commit=$(git -C "$root" rev-parse --verify --quiet "refs/tags/$tag^{commit}" || git -C "$root" rev-parse --verify --quiet HEAD) || fail "non riesco a leggere il commit del tag." +label() { + docker image inspect --format "{{ index .Config.Labels \"org.opencontainers.image.$1\" }}" "$image" +} +built=$(label version) || fail "non trovo l'immagine $image." +# The image built by hand for vX.Y.Z-something says X.Y.Z, the version of Directory.Build.props: the commit tells them apart. +[ "$built" = "$version" ] || [ "$built" = "$expected" ] || fail "l'immagine $image dice di essere la versione '$built', non $version: ricostruiscila." +source=$(label revision) || fail "non trovo l'immagine $image." +[ "$source" = "$commit" ] || fail "l'immagine $image viene dal commit '$source', non da $commit: ricostruiscila dal commit del tag, senza modifiche in sospeso." + # latest moves only for the highest plain version among the tags of the repository. latest="" case "$version" in diff --git a/src/Anubis.Server/AnubisHost.cs b/src/Anubis.Server/AnubisHost.cs index a681eac..c445c13 100644 --- a/src/Anubis.Server/AnubisHost.cs +++ b/src/Anubis.Server/AnubisHost.cs @@ -62,6 +62,7 @@ internal sealed partial class AnubisHost( private readonly AccessGuards _accessGuards = new(clock); private readonly TimeSpan _interval = overrides?.DatabaseCheckInterval ?? TimeSpan.FromSeconds(5); + private readonly TimeSpan _tradingRetry = overrides?.TradingRetry ?? TimeSpan.FromMinutes(1); private readonly Lock _gate = new(); // One step of the loop or one error-page choice at a time: a restore must not race the start that would follow it. @@ -666,7 +667,11 @@ internal sealed partial class AnubisHost( { try { - await trading.StartAsync(cancellationToken).ConfigureAwait(false); + while (!await TryStartAsync(trading, cancellationToken).ConfigureAwait(false)) + { + await Task.Delay(_tradingRetry, cancellationToken).ConfigureAwait(false); + } + await trading.RunAsync(cancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) @@ -678,6 +683,20 @@ internal sealed partial class AnubisHost( } } + private async Task TryStartAsync(TradingService trading, CancellationToken cancellationToken) + { + try + { + await trading.StartAsync(cancellationToken).ConfigureAwait(false); + return true; + } + catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + LogTradingStartFailed(logger, ex, _tradingRetry); + return false; + } + } + // The jobs table keeps the outcome of the last run of each job (Diario e sistema, SPEC 13.6). private async Task RecordJobsAsync(EventSubscription runs, CancellationToken cancellationToken) { @@ -813,6 +832,9 @@ internal sealed partial class AnubisHost( [LoggerMessage(Level = LogLevel.Error, Message = "Trading stopped")] private static partial void LogTradingFailed(ILogger logger, Exception exception); + [LoggerMessage(Level = LogLevel.Error, Message = "Trading could not start: tried again in {Delay}")] + private static partial void LogTradingStartFailed(ILogger logger, Exception exception, TimeSpan delay); + [LoggerMessage(Level = LogLevel.Warning, Message = "Could not record the run of job {Job}")] private static partial void LogJobRecordFailed(ILogger logger, Exception exception, string job); } diff --git a/src/Anubis.Server/Components/Pages/Conti.razor b/src/Anubis.Server/Components/Pages/Conti.razor index bf753ed..d510134 100644 --- a/src/Anubis.Server/Components/Pages/Conti.razor +++ b/src/Anubis.Server/Components/Pages/Conti.razor @@ -130,12 +130,23 @@ else } else if (state.WaitsForUser(Clock.UtcNow, TimeSpan.FromMinutes(15)) && !Shell.IsDemo) { -

Sono passati 15 minuti e la differenza non si è spiegata da sola. Scegli tu:

+ @if (state.Differences.All(d => d.Kind == DifferenceKinds.Stop)) + { +

Manca ancora uno stop, dove avevi lasciato fuori una differenza. Se il conto non lo accetta, allinea il registro:

+ } + else + { +

Sono passati 15 minuti e la differenza non si è spiegata da sola. Scegli tu:

+ }
} + else if (state.ModeReason == Reconciler.StopReason) + { +

Manca ancora uno stop: riprovo a ogni confronto e il conto torna normale da solo quando c'è.

+ } else {

Se entro 15 minuti si spiega da sola il conto torna normale; altrimenti qui potrai scegliere se allineare il registro o lasciare fuori la differenza.

diff --git a/src/Anubis.Server/Components/Pages/Impostazioni.razor b/src/Anubis.Server/Components/Pages/Impostazioni.razor index bfb8b0d..4f4db4b 100644 --- a/src/Anubis.Server/Components/Pages/Impostazioni.razor +++ b/src/Anubis.Server/Components/Pages/Impostazioni.razor @@ -792,7 +792,7 @@ "sola-lettura" => "Questa chiave può solo leggere: per lavorare sul conto di prova serve anche il permesso di fare ordini. Non l'ho salvata.", "importo" => "Scrivi un importo in euro, per esempio 4000 o 1.500,50.", "cambio" => "Manca ancora il cambio euro/dollaro della BCE: lo scarico ogni giorno, riprova più tardi.", - "capitale" => "Una strategia ha investito più di quanto le resterebbe: potrò ridurre il capitale quando avrà venduto.", + "capitale" => "Una strategia ha investito, o sta comprando, più di quanto le resterebbe: potrò ridurre il capitale quando avrà venduto o finito di comprare.", "quote" => "Le quote vanno da 0 a 100 e insieme fanno 100: per esempio 60 e 40. Non ho cambiato nulla.", "limite" => "Un limite non è valido: controlla che ogni valore sia un numero dentro il suo intervallo.", "ordine-limiti" => "Il dimezzamento sul calo dal massimo deve venire prima dell'interruttore, e la perdita di un giorno non può superare quella di una settimana.", diff --git a/src/Anubis.Server/Endpoints.cs b/src/Anubis.Server/Endpoints.cs index fedc91c..179b5f0 100644 --- a/src/Anubis.Server/Endpoints.cs +++ b/src/Anubis.Server/Endpoints.cs @@ -62,7 +62,8 @@ internal static partial class Endpoints checks["scheduler"] = host.SchedulerRunning ? "ok" : "fermo"; healthy &= host.SchedulerRunning; - var (loop, loopOk) = HealthRules.Loop(host.Clock.UtcNow, services.Trading is { IsStarted: true }, services.Trading?.LastTurnAt); + var (loop, loopOk) = HealthRules.Loop(host.Clock.UtcNow, services.Trading is null ? null : status.Since, services.Trading is { IsStarted: true }, + services.Trading is { StartFailed: true }, services.Trading?.LastTurnAt); var (feed, feedOk) = HealthRules.Feed(host.Clock.UtcNow, services.MarketData?.LiveFeed.Since, services.MarketData?.LiveFeed.LastDataAt); checks["motore"] = loop; checks["dati"] = feed; @@ -540,14 +541,19 @@ internal static class HealthRules /// The same silence after which the guard steps in (SPEC 9.3). public static readonly TimeSpan LoopLimit = TimeSpan.FromMinutes(2); + /// A start of the engine this long is stalled, as for the guard (SPEC 9.3). + public static readonly TimeSpan StartLimit = TimeSpan.FromMinutes(10); + /// Longer than the silence that blocks new entries (SPEC 6.5): a line that drops for a moment is not an ill container. public static readonly TimeSpan FeedLimit = TimeSpan.FromMinutes(5); - public static (string Text, bool Ok) Loop(DateTimeOffset now, bool started, DateTimeOffset? lastTurn) => (started, lastTurn) switch + /// The engine's loop; is when the services became ready, null where there is no engine to start. + public static (string Text, bool Ok) Loop(DateTimeOffset now, DateTimeOffset? since, bool started, bool failed, DateTimeOffset? lastTurn) => (since, started, lastTurn) switch { - (false, _) => ("non avviato", true), - (_, null) => ("in avvio", true), - (_, { } at) when now - at > LoopLimit => ("fermo", false), + (null, _, _) => ("non avviato", true), + ({ } from, false, _) when failed || now - from > StartLimit => ("non avviato", false), + (_, false, _) or (_, _, null) => ("in avvio", true), + (_, _, { } at) when now - at > LoopLimit => ("fermo", false), _ => ("ok", true), }; diff --git a/src/Anubis.Server/ServerOptions.cs b/src/Anubis.Server/ServerOptions.cs index a7f3473..a4942ab 100644 --- a/src/Anubis.Server/ServerOptions.cs +++ b/src/Anubis.Server/ServerOptions.cs @@ -81,4 +81,7 @@ internal sealed record ServerOverrides /// True starts the accounts and the order managers in a test; off by default in tests. public bool? Trading { get; init; } + + /// How long after a failed start of the trading engine it is tried again. + public TimeSpan? TradingRetry { get; init; } } diff --git a/src/Anubis/Access/AccessStore.cs b/src/Anubis/Access/AccessStore.cs index 279f4b3..bf136a4 100644 --- a/src/Anubis/Access/AccessStore.cs +++ b/src/Anubis/Access/AccessStore.cs @@ -355,14 +355,23 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets, return (AccessChange.Locked, null); } - var hash = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT password_hash FROM users WHERE id = @id", r => r.Text("password_hash"), ("id", userId)), cancellationToken) - .ConfigureAwait(false); - if (hash is null || !Passwords.Verify(current, hash)) + var user = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT password_hash, totp_secret FROM users WHERE id = @id", + r => (Hash: r.Text("password_hash"), On: !r.IsNull("totp_secret")), ("id", userId)), cancellationToken).ConfigureAwait(false); + if (user == default || !Passwords.Verify(current, user.Hash)) { return (AccessChange.Wrong, null); } - _guards.Fresh.Succeeded(FreshAttempts); + if (user.On) + { + // The password alone is half of it: the wrong codes counted so far stay. + _guards.Fresh.Forgive(FreshAttempts); + } + else + { + _guards.Fresh.Succeeded(FreshAttempts); + } + var replacementHash = Passwords.Hash(replacement, iterations); var now = clock.UtcNow; var token = Ids.NewToken(); @@ -399,7 +408,7 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets, return AccessChange.Wrong; } - _guards.Fresh.Succeeded(FreshAttempts); + _guards.Fresh.Forgive(FreshAttempts); if (user.On) { return AccessChange.AlreadyOn; @@ -410,6 +419,7 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets, return AccessChange.Wrong; } + _guards.Fresh.Succeeded(FreshAttempts); var sealedSecret = secrets.Seal(SecondFactorName(userId), Convert.ToBase64String(secret)); return await db.WriteAsync(async s => { diff --git a/src/Anubis/Trading/Capital.cs b/src/Anubis/Trading/Capital.cs index 0370272..38951a1 100644 --- a/src/Anubis/Trading/Capital.cs +++ b/src/Anubis/Trading/Capital.cs @@ -1,6 +1,7 @@ using Anubis.Core; using Anubis.Data; using Anubis.Db; +using Anubis.Risk; namespace Anubis.Trading; @@ -87,26 +88,33 @@ public sealed class CapitalException : Exception /// /// Capital entrusted to the bot (SPEC 7.1, 8.6): one figure in euro for each broker, set only by the user, split /// between the broker's strategies by their shares. A dollar account converts it at the day's rate and keeps its -/// ledger in dollars from then on. Every change reaches the ledgers as a capital flow, so it is never a result. +/// ledger in dollars from then on. Every change reaches the ledgers as a capital flow, so it is never a result. A +/// change is planned and written in one transaction: the writes are one at a time, so two changes never overlap and +/// none is left halfway. /// -public sealed class Capital(Database db, IClock clock, Ledger ledger, FxStore fx) +public sealed class Capital(Database db, IClock clock, Ledger ledger, FxStore fx, SettingsStore? settings = null) { public Task EntrustedAsync(string broker, CancellationToken cancellationToken) => - db.ReadAsync(s => s.FirstOrDefaultAsync( - "SELECT broker, amount_eur, currency, fx_rate, amount, changed_by, created_at FROM capital_changes WHERE broker = @b ORDER BY created_at DESC, id DESC LIMIT 1", - r => new EntrustedCapital(r.Text("broker"), r.Money("amount_eur"), r.Text("currency"), r.Money("fx_rate"), r.Money("amount"), r.Text("changed_by"), r.Moment("created_at")), - ("b", broker)), cancellationToken); + db.ReadAsync(s => EntrustedAsync(s, broker), cancellationToken); /// The broker's strategies with their share, the capital given so far and their cash, in the account's currency. - public async Task> StrategiesAsync(string broker, CancellationToken cancellationToken) + public Task> StrategiesAsync(string broker, CancellationToken cancellationToken) => + db.ReadAsync(s => StrategiesAsync(s, broker), cancellationToken); + + private static Task EntrustedAsync(DbSession s, string broker) => s.FirstOrDefaultAsync( + "SELECT broker, amount_eur, currency, fx_rate, amount, changed_by, created_at FROM capital_changes WHERE broker = @b ORDER BY created_at DESC, id DESC LIMIT 1", + r => new EntrustedCapital(r.Text("broker"), r.Money("amount_eur"), r.Text("currency"), r.Money("fx_rate"), r.Money("amount"), r.Text("changed_by"), r.Moment("created_at")), + ("b", broker)); + + private static async Task> StrategiesAsync(DbSession s, string broker) { - var rows = await db.ReadAsync(s => s.QueryAsync( + var rows = await s.QueryAsync( "SELECT st.strategy, st.account_id, st.share, a.base_currency FROM strategy_state st JOIN accounts a ON a.id = st.account_id WHERE a.broker = @b ORDER BY st.strategy", - r => (Strategy: r.Text("strategy"), Account: r.Id("account_id"), Share: r.MoneyOrNull("share"), Currency: r.Text("base_currency")), ("b", broker)), cancellationToken) - .ConfigureAwait(false); - var given = await db.ReadAsync(s => s.QueryAsync("SELECT account_id, strategy, amount FROM cash_ledger WHERE kind = @k AND strategy IS NOT NULL", - r => (Account: r.Id("account_id"), Strategy: r.Text("strategy"), Amount: r.Money("amount")), ("k", LedgerKinds.Capital)), cancellationToken).ConfigureAwait(false); - var equities = await ledger.EquitiesAsync(cancellationToken).ConfigureAwait(false); + r => (Strategy: r.Text("strategy"), Account: r.Id("account_id"), Share: r.MoneyOrNull("share"), Currency: r.Text("base_currency")), ("b", broker)).ConfigureAwait(false); + var given = await s.QueryAsync("SELECT account_id, strategy, amount FROM cash_ledger WHERE kind = @k AND strategy IS NOT NULL", + r => (Account: r.Id("account_id"), Strategy: r.Text("strategy"), Amount: r.Money("amount")), ("k", LedgerKinds.Capital)).ConfigureAwait(false); + var equities = await Ledger.EquitiesAsync(s).ConfigureAwait(false); + // A candidate of SPEC 8.4 has no share and no capital: it is no part of any plan. return rows.Where(r => !StrategyNames.IsCandidate(r.Strategy)).Select(r => new StrategyCapital(r.Strategy, r.Account, r.Currency, r.Share ?? StrategyNames.Base.FirstOrDefault(b => b.Name == r.Strategy).Share, @@ -123,35 +131,45 @@ public sealed class Capital(Database db, IClock clock, Ledger ledger, FxStore fx } var currency = StrategyNames.CurrencyOf(broker); - var previous = await EntrustedAsync(broker, cancellationToken).ConfigureAwait(false); - if (previous is not null && previous.AmountEur == amountEur) - { - // The same amount again changes nothing, whatever the exchange rate did meanwhile. - return previous; - } - - var rate = 1m; + decimal? rate = 1m; if (currency != "EUR") { var today = DateOnly.FromDateTime(clock.UtcNow.UtcDateTime); rate = (await fx.RateOnAsync("EUR", currency, today, cancellationToken).ConfigureAwait(false) - ?? await fx.LatestAsync("EUR", currency, cancellationToken).ConfigureAwait(false))?.Rate - ?? throw new CapitalException($"Manca il cambio EUR/{currency}: lo scarico ogni giorno dalla BCE, riprova più tardi."); + ?? await fx.LatestAsync("EUR", currency, cancellationToken).ConfigureAwait(false))?.Rate; } - // Only the change in euro is converted at today's rate: the dollars already given stay as they are, so a - // move of the exchange rate is never booked as a deposit or a withdrawal. The rate kept is the overall one. - var amount = Math.Round((previous?.Amount ?? 0m) + ((amountEur - (previous?.AmountEur ?? 0m)) * rate), 2, MidpointRounding.ToZero); - amount = amountEur == 0m ? 0m : Math.Max(amount, 0m); - var overall = amountEur > 0m && currency != "EUR" ? Math.Round(amount / amountEur, 6) : rate; - var entrusted = new EntrustedCapital(broker, amountEur, currency, overall, amount, changedBy, clock.UtcNow); - var plan = await PlanAsync(broker, entrusted.Amount, null, cancellationToken).ConfigureAwait(false); - await db.WriteAsync(s => s.ExecuteAsync( - "INSERT INTO capital_changes (id, broker, amount_eur, currency, fx_rate, amount, changed_by, created_at) VALUES (@id, @b, @e, @c, @r, @a, @by, @now)", cancellationToken, - ("id", Ids.NewId(clock)), ("b", broker), ("e", amountEur), ("c", currency), ("r", rate), ("a", entrusted.Amount), ("by", changedBy), ("now", entrusted.At)), - cancellationToken).ConfigureAwait(false); - await ApplyAsync(plan, entrusted, cancellationToken).ConfigureAwait(false); - return entrusted; + var highest = await HighestAsync(cancellationToken).ConfigureAwait(false); + return await db.WriteAsync(async s => + { + var previous = await EntrustedAsync(s, broker).ConfigureAwait(false); + if (previous is not null && previous.AmountEur == amountEur) + { + // The same amount again moves nothing, whatever the exchange rate did meanwhile; what an interruption + // left undone is completed. + await ApplyAsync(s, await PlanAsync(s, broker, previous.Amount, null, highest).ConfigureAwait(false), previous, cancellationToken).ConfigureAwait(false); + return previous; + } + + if (rate is not { } today) + { + throw new CapitalException($"Manca il cambio EUR/{currency}: lo scarico ogni giorno dalla BCE, riprova più tardi."); + } + + // Only the change in euro is converted at today's rate: the dollars already given stay as they are, so a + // move of the exchange rate is never booked as a deposit or a withdrawal. The rate kept is the overall one. + var amount = Math.Round((previous?.Amount ?? 0m) + ((amountEur - (previous?.AmountEur ?? 0m)) * today), 2, MidpointRounding.ToZero); + amount = amountEur == 0m ? 0m : Math.Max(amount, 0m); + var overall = amountEur > 0m && currency != "EUR" ? Math.Round(amount / amountEur, 6) : today; + var entrusted = new EntrustedCapital(broker, amountEur, currency, overall, amount, changedBy, clock.UtcNow); + var plan = await PlanAsync(s, broker, entrusted.Amount, null, highest).ConfigureAwait(false); + await s.ExecuteAsync( + "INSERT INTO capital_changes (id, broker, amount_eur, currency, fx_rate, amount, changed_by, created_at) VALUES (@id, @b, @e, @c, @r, @a, @by, @now)", cancellationToken, + ("id", Ids.NewId(clock)), ("b", broker), ("e", amountEur), ("c", currency), ("r", today), ("a", entrusted.Amount), ("by", changedBy), ("now", entrusted.At)) + .ConfigureAwait(false); + await ApplyAsync(s, plan, entrusted, cancellationToken).ConfigureAwait(false); + return entrusted; + }, cancellationToken).ConfigureAwait(false); } /// Changes the shares of a broker's strategies (each between 0 and 1, together exactly 1). Never automatic. @@ -168,22 +186,19 @@ public sealed class Capital(Database db, IClock clock, Ledger ledger, FxStore fx throw new CapitalException("Le quote vanno da 0 a 100% e insieme fanno 100%."); } - var before = await StrategiesAsync(broker, cancellationToken).ConfigureAwait(false); - if (before.Count != shares.Count || before.Any(s => !shares.ContainsKey(s.Strategy))) - { - throw new CapitalException("Serve la quota di ogni strategia del conto, e di nessun'altra."); - } - - var changed = before.Where(s => s.Share != shares[s.Strategy]).ToList(); - if (changed.Count == 0) - { - return; - } - - var entrusted = await EntrustedAsync(broker, cancellationToken).ConfigureAwait(false); - var plan = await PlanAsync(broker, entrusted?.Amount ?? 0m, shares, cancellationToken).ConfigureAwait(false); + var highest = await HighestAsync(cancellationToken).ConfigureAwait(false); await db.WriteAsync(async s => { + var before = await StrategiesAsync(s, broker).ConfigureAwait(false); + if (before.Count != shares.Count || before.Any(b => !shares.ContainsKey(b.Strategy))) + { + throw new CapitalException("Serve la quota di ogni strategia del conto, e di nessun'altra."); + } + + // The same shares again change nothing, but the money an interruption left undone still moves. + var changed = before.Where(b => b.Share != shares[b.Strategy]).ToList(); + var entrusted = await EntrustedAsync(s, broker).ConfigureAwait(false); + var plan = await PlanAsync(s, broker, entrusted?.Amount ?? 0m, shares, highest).ConfigureAwait(false); var now = clock.UtcNow; foreach (var strategy in changed) { @@ -195,36 +210,51 @@ public sealed class Capital(Database db, IClock clock, Ledger ledger, FxStore fx .ConfigureAwait(false); } - await Diary.WriteAsync(s, clock, DiaryKinds.System, "shares_changed", - $"Ripartizione del capitale cambiata da {changedBy}: " + - string.Join(", ", before.Select(b => $"{StrategyNames.Label(b.Strategy, withMarket: true)} {Percent(b.Share)} → {Percent(shares[b.Strategy])}")) + ".", null, cancellationToken) - .ConfigureAwait(false); + if (changed.Count > 0) + { + await Diary.WriteAsync(s, clock, DiaryKinds.System, "shares_changed", + $"Ripartizione del capitale cambiata da {changedBy}: " + + string.Join(", ", before.Select(b => $"{StrategyNames.Label(b.Strategy, withMarket: true)} {Percent(b.Share)} → {Percent(shares[b.Strategy])}")) + ".", null, cancellationToken) + .ConfigureAwait(false); + } + + if (entrusted is not null) + { + await ApplyAsync(s, plan, entrusted, cancellationToken).ConfigureAwait(false); + } }, cancellationToken).ConfigureAwait(false); - if (entrusted is not null) - { - await ApplyAsync(plan, entrusted, cancellationToken).ConfigureAwait(false); - } } private static DbJson Json(decimal share) => new(System.Text.Json.JsonSerializer.Serialize(Percent(share))); private static string Percent(decimal share) => Format.Quantity(share * 100m) + "%"; - // What each strategy should have and what that changes. A reduction that would leave a strategy's cash below - // zero is refused: the money is in positions, and the bot never sells to give capital back. - private async Task> PlanAsync(string broker, decimal amount, IReadOnlyDictionary? shares, - CancellationToken cancellationToken) + private async Task HighestAsync(CancellationToken cancellationToken) => + 1m + (settings is null ? RiskLimits.Default : await RiskSettings.LoadAsync(settings, cancellationToken).ConfigureAwait(false)).MaxPriceGap; + + // What each strategy should have and what that changes. A reduction that would leave a strategy's cash below what + // its purchases under way still have to pay, or below zero, is refused: the bot never sells to give capital back. + private static async Task> PlanAsync(DbSession s, string broker, decimal amount, + IReadOnlyDictionary? shares, decimal highest) { var plan = new List<(StrategyCapital, decimal, decimal)>(); - foreach (var strategy in await StrategiesAsync(broker, cancellationToken).ConfigureAwait(false)) + foreach (var strategy in await StrategiesAsync(s, broker).ConfigureAwait(false)) { var share = shares?.GetValueOrDefault(strategy.Strategy, strategy.Share) ?? strategy.Share; var target = Math.Round(amount * share, 2, MidpointRounding.ToZero); var delta = target - strategy.Capital; - if (strategy.Cash + delta < 0m) + var name = StrategyNames.Label(strategy.Strategy, withMarket: true); + if (delta < 0m && strategy.Cash + delta < 0m) { throw new CapitalException( - $"{StrategyNames.Label(strategy.Strategy, withMarket: true)} ha investito in posizioni più di quanto resterebbe: potrò ridurre il suo capitale quando avrà venduto. Liquidità ora: {Format.Quantity(strategy.Cash)} {strategy.Currency}."); + $"{name} ha investito in posizioni più di quanto resterebbe: potrò ridurre il suo capitale quando avrà venduto. Liquidità ora: {Format.Quantity(strategy.Cash)} {strategy.Currency}."); + } + + var reserved = await RiskEngine.ReservedAsync(s, strategy.AccountId, strategy.Strategy, highest).ConfigureAwait(false); + if (delta < 0m && strategy.Cash - reserved + delta < 0m) + { + throw new CapitalException( + $"{name} ha acquisti in corso che impegnano più di quanto resterebbe: potrò ridurre il suo capitale quando saranno finiti. Liquidità libera ora: {Format.Quantity(Math.Max(0m, strategy.Cash - reserved))} {strategy.Currency}."); } plan.Add((strategy, target, delta)); @@ -233,18 +263,14 @@ public sealed class Capital(Database db, IClock clock, Ledger ledger, FxStore fx return plan; } - private async Task ApplyAsync(List<(StrategyCapital Strategy, decimal Target, decimal Delta)> plan, EntrustedCapital entrusted, CancellationToken cancellationToken) + private async Task ApplyAsync(DbSession s, List<(StrategyCapital Strategy, decimal Target, decimal Delta)> plan, EntrustedCapital entrusted, CancellationToken cancellationToken) { foreach (var (strategy, target, delta) in plan) { - if (delta != 0m) - { - await ledger.RecordCapitalAsync(strategy.AccountId, strategy.Strategy, delta, strategy.Currency, - $"Capitale affidato {Format.Quantity(entrusted.AmountEur)} EUR, quota {Format.Quantity(target)} {strategy.Currency}", cancellationToken).ConfigureAwait(false); - } - - await db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET capital = @c, updated_at = @now WHERE strategy = @s", cancellationToken, - ("c", target), ("now", clock.UtcNow), ("s", strategy.Strategy)), cancellationToken).ConfigureAwait(false); + await ledger.RecordCapitalAsync(s, strategy.AccountId, strategy.Strategy, delta, strategy.Currency, + $"Capitale affidato {Format.Quantity(entrusted.AmountEur)} EUR, quota {Format.Quantity(target)} {strategy.Currency}", cancellationToken).ConfigureAwait(false); + await s.ExecuteAsync("UPDATE strategy_state SET capital = @c, updated_at = @now WHERE strategy = @s", cancellationToken, + ("c", target), ("now", clock.UtcNow), ("s", strategy.Strategy)).ConfigureAwait(false); } } } diff --git a/src/Anubis/Trading/Ledger.cs b/src/Anubis/Trading/Ledger.cs index 3c60fcd..a9b5056 100644 --- a/src/Anubis/Trading/Ledger.cs +++ b/src/Anubis/Trading/Ledger.cs @@ -124,7 +124,10 @@ public sealed class Ledger(Database db, IClock clock) /// Gives (positive) or takes back (negative) capital to a strategy. It counts as a flow, not a result. public Task RecordCapitalAsync(Guid accountId, string strategy, decimal amount, string currency, string note, CancellationToken cancellationToken) => - db.WriteAsync(s => AddCashAsync(s, accountId, strategy, currency, amount, LedgerKinds.Capital, null, note, clock.UtcNow, cancellationToken), cancellationToken); + db.WriteAsync(s => RecordCapitalAsync(s, accountId, strategy, amount, currency, note, cancellationToken), cancellationToken); + + internal Task RecordCapitalAsync(DbSession s, Guid accountId, string strategy, decimal amount, string currency, string note, CancellationToken cancellationToken) => + AddCashAsync(s, accountId, strategy, currency, amount, LedgerKinds.Capital, null, note, clock.UtcNow, cancellationToken); /// /// A correction of a strategy's cash chosen by the user after a reconciliation (SPEC 7.4): a flow, so it changes @@ -447,31 +450,33 @@ public sealed class Ledger(Database db, IClock clock) /// currencies (a fee in a third coin) are kept but not valued. /// public Task> EquitiesAsync(CancellationToken cancellationToken) => - db.ReadAsync>(async s => - { - var accounts = await s.QueryAsync("SELECT id, base_currency FROM accounts", r => (Id: r.Id("id"), Currency: r.Text("base_currency"))).ConfigureAwait(false); - var cash = await s.QueryAsync("SELECT account_id, strategy, currency, kind, amount FROM cash_ledger WHERE strategy IS NOT NULL", - r => (Account: r.Id("account_id"), Strategy: r.Text("strategy"), Currency: r.Text("currency"), Kind: r.Text("kind"), Amount: r.Money("amount"))).ConfigureAwait(false); - var positions = (await s.QueryAsync("SELECT account_id, instrument_id, strategy, quantity, average_price, last_price, stop_price, opened_at FROM positions", - ReadPosition).ConfigureAwait(false)).Where(p => p.Quantity > 0m).ToList(); - var result = new List(); - foreach (var account in accounts) - { - var strategies = cash.Where(c => c.Account == account.Id).Select(c => c.Strategy) - .Concat(positions.Where(p => p.AccountId == account.Id).Select(p => p.Strategy)) - .Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal); - foreach (var strategy in strategies) - { - var rows = cash.Where(c => c.Account == account.Id && c.Strategy == strategy && c.Currency == account.Currency).ToList(); - result.Add(new LedgerEquity(account.Id, strategy, account.Currency, - rows.Sum(r => r.Amount), - positions.Where(p => p.AccountId == account.Id && p.Strategy == strategy).Sum(p => DbValues.Money(p.Value)), - rows.Where(r => LedgerKinds.IsFlow(r.Kind)).Sum(r => r.Amount))); - } - } + db.ReadAsync(EquitiesAsync, cancellationToken); - return result; - }, cancellationToken); + internal static async Task> EquitiesAsync(DbSession s) + { + var accounts = await s.QueryAsync("SELECT id, base_currency FROM accounts", r => (Id: r.Id("id"), Currency: r.Text("base_currency"))).ConfigureAwait(false); + var cash = await s.QueryAsync("SELECT account_id, strategy, currency, kind, amount FROM cash_ledger WHERE strategy IS NOT NULL", + r => (Account: r.Id("account_id"), Strategy: r.Text("strategy"), Currency: r.Text("currency"), Kind: r.Text("kind"), Amount: r.Money("amount"))).ConfigureAwait(false); + var positions = (await s.QueryAsync("SELECT account_id, instrument_id, strategy, quantity, average_price, last_price, stop_price, opened_at FROM positions", + ReadPosition).ConfigureAwait(false)).Where(p => p.Quantity > 0m).ToList(); + var result = new List(); + foreach (var account in accounts) + { + var strategies = cash.Where(c => c.Account == account.Id).Select(c => c.Strategy) + .Concat(positions.Where(p => p.AccountId == account.Id).Select(p => p.Strategy)) + .Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal); + foreach (var strategy in strategies) + { + var rows = cash.Where(c => c.Account == account.Id && c.Strategy == strategy && c.Currency == account.Currency).ToList(); + result.Add(new LedgerEquity(account.Id, strategy, account.Currency, + rows.Sum(r => r.Amount), + positions.Where(p => p.AccountId == account.Id && p.Strategy == strategy).Sum(p => DbValues.Money(p.Value)), + rows.Where(r => LedgerKinds.IsFlow(r.Kind)).Sum(r => r.Amount))); + } + } + + return result; + } /// /// What a strategy held of an instrument just before , from the fills alone: the base of a diff --git a/src/Anubis/Trading/Reconciler.cs b/src/Anubis/Trading/Reconciler.cs index 0e2a2b6..c22ed32 100644 --- a/src/Anubis/Trading/Reconciler.cs +++ b/src/Anubis/Trading/Reconciler.cs @@ -82,7 +82,13 @@ public sealed record AccountState(Guid AccountId, string Mode, DateTimeOffset? M IsPrudent && ModeReason != Reconciler.KeyReason && ModeSince is { } since && now - since >= grace; /// There is something to align or to leave out: a missing stop is neither, it has to be put back. - public bool HasChoices => Differences.Any(d => d.Kind != DifferenceKinds.Stop); + public bool HasChoices => Differences.Any(d => d.Kind != DifferenceKinds.Stop) || ExcludedWithoutStop; + + /// + /// A stop is missing where the user left out a position: the bot asks it for the ledger's quantity, which the account + /// may never take, so the position can be aligned after all. + /// + public bool ExcludedWithoutStop => Differences.Any(d => d.Kind == DifferenceKinds.Stop && Excluded.Any(e => e.StartsWith($"{DifferenceKinds.Position}:{d.Subject}:", StringComparison.Ordinal))); } public enum ReconcileChoice @@ -117,6 +123,9 @@ public sealed class Reconciler(Database db, IClock clock, Ledger ledger) { public const string KeyReason = "key_can_withdraw"; + /// The user has chosen and only a stop is missing: nothing is left to ask, the account returns to normal when it is back. + public const string StopReason = "waiting_for_stop"; + /// How long a difference may take to explain itself before the user is asked. public TimeSpan Grace { get; init; } = TimeSpan.FromMinutes(15); @@ -128,16 +137,17 @@ public sealed class Reconciler(Database db, IClock clock, Ledger ledger) ArgumentNullException.ThrowIfNull(manager); var account = manager.Account; var state = await StateAsync(account.AccountId, cancellationToken).ConfigureAwait(false); + var excluded = state.Excluded.ToHashSet(StringComparer.Ordinal); var healed = new List(); List differences; try { - differences = await CompareAsync(manager, cancellationToken).ConfigureAwait(false); + differences = await CompareAsync(manager, excluded, cancellationToken).ConfigureAwait(false); if (differences.Count > 0) { healed.AddRange(await HealAsync(manager, differences, cancellationToken).ConfigureAwait(false)); var before = differences.Select(d => d.Fingerprint).ToHashSet(StringComparer.Ordinal); - differences = await CompareAsync(manager, cancellationToken).ConfigureAwait(false); + differences = await CompareAsync(manager, excluded, cancellationToken).ConfigureAwait(false); healed.AddRange(before.Except(differences.Select(d => d.Fingerprint), StringComparer.Ordinal)); } } @@ -147,7 +157,6 @@ public sealed class Reconciler(Database db, IClock clock, Ledger ledger) return new ReconcileReport(account.AccountId, down, [], [], state.Mode); } - var excluded = state.Excluded.ToHashSet(StringComparer.Ordinal); differences = differences.Where(d => !excluded.Contains(d.Fingerprint)).ToList(); var outcome = differences.Count > 0 ? ReconcileOutcomes.Different : healed.Count > 0 ? ReconcileOutcomes.Healed : ReconcileOutcomes.Clean; var mode = await RecordAsync(account, state, outcome, differences, healed, cancellationToken).ConfigureAwait(false); @@ -210,7 +219,8 @@ public sealed class Reconciler(Database db, IClock clock, Ledger ledger) /// /// The user's choice after the 15 minutes (SPEC 7.4). Align: positions and cash of the ledger take the account's /// numbers with adjustment rows. Exclude: what differs is left out and no longer reported. Either way the - /// account returns to normal, unless a stop is missing; a later difference starts over. + /// account returns to normal, unless a stop is missing; a later difference starts over. Where a stop is missing, + /// Align takes up again the positions left out before. /// public async Task ResolveAsync(OrderManager manager, ReconcileChoice choice, string by, CancellationToken cancellationToken) { @@ -241,6 +251,22 @@ public sealed class Reconciler(Database db, IClock clock, Ledger ledger) var excluded = state.Excluded.ToList(); if (choice == ReconcileChoice.Align) { + if (state.ExcludedWithoutStop) + { + try + { + var uncovered = stops.Select(d => d.InstrumentId).ToHashSet(); + choices.AddRange((await CompareAsync(manager, excluded.ToHashSet(StringComparer.Ordinal), cancellationToken).ConfigureAwait(false)) + .Where(d => d.Kind == DifferenceKinds.Position && uncovered.Contains(d.InstrumentId) && excluded.Contains(d.Fingerprint))); + } + catch (BrokerException) + { + return ReconcileResolution.NotCompared; + } + + excluded.RemoveAll(e => stops.Any(d => e.StartsWith($"{DifferenceKinds.Position}:{d.Subject}:", StringComparison.Ordinal))); + } + foreach (var difference in choices) { if (!await AlignAsync(account, difference, cancellationToken).ConfigureAwait(false)) @@ -255,10 +281,29 @@ public sealed class Reconciler(Database db, IClock clock, Ledger ledger) excluded.AddRange(choices.Select(d => d.Fingerprint)); } - // With a stop still missing the 15 minutes start again: when the stop is back the account returns to normal by itself. + if (stops.Count > 0 && choices.Count > 0) + { + // What the stops have to cover follows the choice: a position aligned or left out no longer asks for its own. + try + { + if (choice == ReconcileChoice.Align) + { + await manager.AlignStopsAsync(cancellationToken).ConfigureAwait(false); + } + + stops = (await CompareAsync(manager, excluded.ToHashSet(StringComparer.Ordinal), cancellationToken).ConfigureAwait(false)) + .Where(d => d.Kind == DifferenceKinds.Stop).ToList(); + } + catch (BrokerException) + { + // The broker went silent after the choice: the stops stay as they were seen, the next round looks again. + } + } + + // With a stop still missing the account stays prudent, and returns to normal by itself when the stop is back. var now = clock.UtcNow; var outcome = choice == ReconcileChoice.Align ? ReconcileOutcomes.UserAligned : ReconcileOutcomes.UserExcluded; - var (mode, reason) = stops.Count > 0 ? (AccountModes.Prudent, DifferenceKinds.Stop) : (AccountModes.Normal, (string?)null); + var (mode, reason) = stops.Count > 0 ? (AccountModes.Prudent, StopReason) : (AccountModes.Normal, (string?)null); await db.WriteAsync(async s => { await EnsureStatusAsync(s, account.AccountId, now, cancellationToken).ConfigureAwait(false); @@ -291,8 +336,9 @@ public sealed class Reconciler(Database db, IClock clock, Ledger ledger) r.IsNull("key_can_withdraw") ? null : r.Bool("key_can_withdraw"), r.MomentOrNull("key_checked_at")); }, ("a", accountId)).ConfigureAwait(false) ?? AccountState.Initial(accountId), cancellationToken); - /// Every difference between the ledger and the account, before anything is healed. - public async Task> CompareAsync(OrderManager manager, CancellationToken cancellationToken) + // Every difference between the ledger and the account, before anything is healed; those the user left out are among + // them, and what is missing there needs no stop. + private async Task> CompareAsync(OrderManager manager, HashSet excluded, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(manager); var account = manager.Account; @@ -309,34 +355,18 @@ public sealed class Reconciler(Database db, IClock clock, Ledger ledger) var brokerOrders = await manager.Broker.GetOpenOrdersAsync(cancellationToken).ConfigureAwait(false); var ours = brokerOrders.Where(o => ClientOrderIds.IsOurs(o.ClientOrderId, manager.InstallationCode)).ToList(); - differences.AddRange(await StopCoverageAsync(manager, positions, instruments, ours, cancellationToken).ConfigureAwait(false)); - if (account.Environment == TradingEnvironments.Simulation) + + // The internal simulator is the bot's own: there is no other book to compare with (SPEC 7.4). + var simulated = account.Environment == TradingEnvironments.Simulation; + var missing = simulated ? [] : await MissingPositionsAsync(manager, positions, instruments, cancellationToken).ConfigureAwait(false); + var leftOut = missing.Where(d => excluded.Contains(d.Fingerprint)).ToDictionary(d => d.InstrumentId!.Value, d => d.Broker); + differences.AddRange(await StopCoverageAsync(manager, positions, instruments, ours, leftOut, cancellationToken).ConfigureAwait(false)); + if (simulated) { - // The internal simulator is the bot's own: there is no other book to compare with (SPEC 7.4). return differences; } - var held = await manager.Broker.GetPositionsAsync(cancellationToken).ConfigureAwait(false); - foreach (var group in positions.GroupBy(p => p.InstrumentId)) - { - if (!instruments.TryGetValue(group.Key, out var instrument)) - { - continue; - } - - var mine = group.Sum(p => p.Quantity); - var there = held.Where(h => h.Symbol == instrument.Symbol).Sum(h => h.Quantity); - var tolerance = Math.Max(OrderRules.LotOf(instrument.Spec), 0.00000001m); - - // More on the account than in the ledger is the user's own (SPEC 7.1): only less is a difference. - if (there < mine - tolerance) - { - differences.Add(new AccountDifference(DifferenceKinds.Position, instrument.Symbol, mine, there, - $"{instrument.Symbol}: il registro dice {Format.Quantity(mine)}, sul conto ce ne sono {Format.Quantity(there)}.") - { InstrumentId = instrument.Id }); - } - } - + differences.AddRange(missing); var known = await manager.OpenOrdersAsync(cancellationToken).ConfigureAwait(false); var knownIds = known.Select(k => k.ClientOrderId).ToHashSet(StringComparer.Ordinal); foreach (var order in ours.Where(o => !knownIds.Contains(o.ClientOrderId))) @@ -369,6 +399,34 @@ public sealed class Reconciler(Database db, IClock clock, Ledger ledger) return differences; } + private static async Task> MissingPositionsAsync(OrderManager manager, IReadOnlyList positions, Dictionary instruments, + CancellationToken cancellationToken) + { + var differences = new List(); + var held = await manager.Broker.GetPositionsAsync(cancellationToken).ConfigureAwait(false); + foreach (var group in positions.GroupBy(p => p.InstrumentId)) + { + if (!instruments.TryGetValue(group.Key, out var instrument)) + { + continue; + } + + var mine = group.Sum(p => p.Quantity); + var there = held.Where(h => h.Symbol == instrument.Symbol).Sum(h => h.Quantity); + var tolerance = Math.Max(OrderRules.LotOf(instrument.Spec), 0.00000001m); + + // More on the account than in the ledger is the user's own (SPEC 7.1): only less is a difference. + if (there < mine - tolerance) + { + differences.Add(new AccountDifference(DifferenceKinds.Position, instrument.Symbol, mine, there, + $"{instrument.Symbol}: il registro dice {Format.Quantity(mine)}, sul conto ce ne sono {Format.Quantity(there)}.") + { InstrumentId = instrument.Id }); + } + } + + return differences; + } + private async Task> CoherenceAsync(AccountContext account, CancellationToken cancellationToken) { var differences = new List(); @@ -395,7 +453,7 @@ public sealed class Reconciler(Database db, IClock clock, Ledger ledger) } private static async Task> StopCoverageAsync(OrderManager manager, IReadOnlyList positions, Dictionary instruments, - List ours, CancellationToken cancellationToken) + List ours, Dictionary leftOut, CancellationToken cancellationToken) { var differences = new List(); var working = (await manager.WorkingInstrumentsAsync(cancellationToken).ConfigureAwait(false)).ToHashSet(); @@ -408,7 +466,14 @@ public sealed class Reconciler(Database db, IClock clock, Ledger ledger) } var open = manager.MarketOpen is null || await manager.MarketOpen(instrument, cancellationToken).ConfigureAwait(false); - var required = group.Sum(p => manager.DesiredStops(instrument, p.Quantity).Where(d => d.TimeInForce != TimeInForce.Day || open).Sum(d => d.Quantity)); + decimal Covering(decimal quantity) => manager.DesiredStops(instrument, quantity).Where(d => d.TimeInForce != TimeInForce.Day || open).Sum(d => d.Quantity); + var required = group.Sum(p => Covering(p.Quantity)); + if (leftOut.TryGetValue(group.Key, out var there)) + { + // The user left out what is missing here: no stop can cover it, only what is still on the account. + required = Math.Min(required, Covering(there)); + } + var covered = ours.Where(o => o.Symbol == instrument.Symbol && o.Kind == OrderKind.Stop && o.Side == OrderSide.Sell).Sum(o => o.Remaining); if (covered < required - Ledger.Dust) { @@ -525,8 +590,14 @@ public sealed class Reconciler(Database db, IClock clock, Ledger ledger) notify = true; diary = $"Ho messo il conto {account.Name} in modalità prudente: {differences[0].Message} Niente nuovi acquisti finché non si chiarisce; vendite e stop proseguono."; } + else if (reason == StopReason && differences.FirstOrDefault(d => d.Kind != DifferenceKinds.Stop) is { } other) + { + // Something the user has not chosen about: it has its own 15 minutes to explain itself (SPEC 7.4). + since = now; + reason = other.Kind; + } } - else if (mode == AccountModes.Prudent && reason != KeyReason && since is { } start && now - start < Grace) + else if (mode == AccountModes.Prudent && (reason == StopReason || (reason != KeyReason && since is { } start && now - start < Grace))) { mode = AccountModes.Normal; since = now; diff --git a/src/Anubis/Trading/RiskEngine.cs b/src/Anubis/Trading/RiskEngine.cs index a914251..6a79da2 100644 --- a/src/Anubis/Trading/RiskEngine.cs +++ b/src/Anubis/Trading/RiskEngine.cs @@ -197,12 +197,8 @@ public sealed class RiskEngine(Database db, IClock clock, Ledger ledger, StageBo // to (the order-price limit), so several purchases sent together cannot add up to more than the cash. var cash = (await ledger.EquitiesAsync(cancellationToken).ConfigureAwait(false)) .FirstOrDefault(e => e.AccountId == account.AccountId && e.Strategy == intent.Strategy)?.Cash ?? 0m; - var working = await db.ReadAsync(s => s.QueryAsync( - "SELECT quantity, filled, reference_price FROM executions WHERE account_id = @a AND strategy = @s AND side = 'buy' AND status = @w", - r => (r.Money("quantity") - r.Money("filled")) * (r.MoneyOrNull("reference_price") ?? 0m), ("a", account.AccountId), ("s", intent.Strategy), - ("w", ExecutionStates.Working)), cancellationToken).ConfigureAwait(false); var highest = 1m + limits.MaxPriceGap; - var available = cash - (working.Where(v => v > 0m).Sum() * highest); + var available = cash - await db.ReadAsync(s => ReservedAsync(s, account.AccountId, intent.Strategy, highest), cancellationToken).ConfigureAwait(false); data["cash"] = cash; data["reserved"] = cash - available; if (quantity * price * highest > available) @@ -221,6 +217,16 @@ public sealed class RiskEngine(Database db, IClock clock, Ledger ledger, StageBo return (new GateResult(quantity, null, reasons), data); } + /// The cash a strategy's purchases under way still hold: what is left to fill, at the highest price its limit may chase to. + internal static async Task ReservedAsync(DbSession s, Guid accountId, string strategy, decimal highest) + { + var working = await s.QueryAsync( + "SELECT quantity, filled, reference_price FROM executions WHERE account_id = @a AND strategy = @s AND side = 'buy' AND status = @w", + r => (r.Money("quantity") - r.Money("filled")) * (r.MoneyOrNull("reference_price") ?? 0m), ("a", accountId), ("s", strategy), + ("w", ExecutionStates.Working)).ConfigureAwait(false); + return working.Where(v => v > 0m).Sum() * highest; + } + /// /// The world an order counts in (SPEC 7.1, 12.3): real accounts in the real world, the rest in simulation; the /// twin of a strategy with real money follows the blocks of the real strategy. diff --git a/src/Anubis/Trading/TradingService.cs b/src/Anubis/Trading/TradingService.cs index dbed9a3..2b2ce5d 100644 --- a/src/Anubis/Trading/TradingService.cs +++ b/src/Anubis/Trading/TradingService.cs @@ -186,7 +186,7 @@ public sealed partial class TradingService : IDisposable InstallationCode = ClientOrderIds.InstallationCode(installationId); Ledger = new Ledger(db, clock); Reconciler = new Reconciler(db, clock, Ledger); - Capital = new Capital(db, clock, Ledger, fx); + Capital = new Capital(db, clock, Ledger, fx, settings); Equity = new EquityBook(db, clock, Ledger, fx); Quotes = new QuoteBook(clock, FetchQuoteAsync); @@ -226,6 +226,11 @@ public sealed partial class TradingService : IDisposable /// The startup steps of SPEC 9.4 are done and the loop runs. public bool IsStarted => _started; + /// The last attempt of the startup ended with an error: nothing watches the accounts until one succeeds. + public bool StartFailed => _startFailed; + + private volatile bool _startFailed; + /// The live engine (SPEC 5.5, issue #47): the decisions at their times, the planned orders, the recovery. public LiveEngine Engine { get; } @@ -302,9 +307,24 @@ public sealed partial class TradingService : IDisposable /// /// The startup of SPEC 9.4 after the migrations: brokers, clock, corporate actions, then for every account the /// complete reconciliation, the purchases and sales left open canceled (exits restart, entries are proposed again) - /// and every position checked for its stop. Each step is told to the guard. + /// and every position checked for its stop. Each step is told to the guard. After a failure it can be called again: + /// only the steps before the accounts can fail, and those repeat without harm. /// public async Task StartAsync(CancellationToken cancellationToken) + { + try + { + await StartStepsAsync(cancellationToken).ConfigureAwait(false); + _startFailed = false; + } + catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + _startFailed = true; + throw; + } + } + + private async Task StartStepsAsync(CancellationToken cancellationToken) { Guard?.Step("conti e strategie"); var accounts = await PrepareAsync(cancellationToken).ConfigureAwait(false); @@ -312,11 +332,22 @@ public sealed partial class TradingService : IDisposable var okx = await OkxKeysAsync(cancellationToken).ConfigureAwait(false); await RefreshSpecsAsync(cancellationToken).ConfigureAwait(false); await RefreshLimitsAsync(cancellationToken).ConfigureAwait(false); - Guard?.Step("connessione ai broker"); + if (!_startFailed) + { + // A start that fails and is tried again every minute must look still to the guard, not moving between steps. + Guard?.Step("connessione ai broker"); + } + var generation = await StopGenerationAsync(cancellationToken).ConfigureAwait(false); var hang = Fault == GuardChannel.HangMidSale; foreach (var account in accounts) { + if (_managers.ContainsKey(account.AccountId)) + { + // Built by an attempt that failed after it: someone may already be using it. + continue; + } + var broker = Build(account, alpaca, okx); if (broker is null) { @@ -980,7 +1011,9 @@ public sealed partial class TradingService : IDisposable public async Task SetCapitalAsync(string broker, decimal amountEur, string changedBy, CancellationToken cancellationToken) { var entrusted = await Capital.SetAsync(broker, amountEur, changedBy, cancellationToken).ConfigureAwait(false); - await FundSimulatorsAsync(cancellationToken).ConfigureAwait(false); + + // The change is written: whoever asked for it may leave, the simulator still gets its money. + await FundSimulatorsAsync(CancellationToken.None).ConfigureAwait(false); return entrusted; } @@ -988,7 +1021,7 @@ public sealed partial class TradingService : IDisposable public async Task SetSharesAsync(string broker, IReadOnlyDictionary shares, string changedBy, CancellationToken cancellationToken) { await Capital.SetSharesAsync(broker, shares, changedBy, cancellationToken).ConfigureAwait(false); - await FundSimulatorsAsync(cancellationToken).ConfigureAwait(false); + await FundSimulatorsAsync(CancellationToken.None).ConfigureAwait(false); } /// diff --git a/tests/Anubis.Tests/AccountsScreenTests.cs b/tests/Anubis.Tests/AccountsScreenTests.cs index 7d2c1c2..3844fa4 100644 --- a/tests/Anubis.Tests/AccountsScreenTests.cs +++ b/tests/Anubis.Tests/AccountsScreenTests.cs @@ -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 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() diff --git a/tests/Anubis.Tests/DeliveryTests.cs b/tests/Anubis.Tests/DeliveryTests.cs index f9779e4..365de44 100644 --- a/tests/Anubis.Tests/DeliveryTests.cs +++ b/tests/Anubis.Tests/DeliveryTests.cs @@ -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"), "\n 0.9.0\n\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; diff --git a/tests/Anubis.Tests/HealthEndpointTests.cs b/tests/Anubis.Tests/HealthEndpointTests.cs index c3dda93..82c509e 100644 --- a/tests/Anubis.Tests/HealthEndpointTests.cs +++ b/tests/Anubis.Tests/HealthEndpointTests.cs @@ -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 HealthAsync() + { + using var response = await server.GetAsync("/health"); + return (await response.Content.ReadFromJsonAsync())!; + } + + 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); + } } diff --git a/tests/Anubis.Tests/LedgerTests.cs b/tests/Anubis.Tests/LedgerTests.cs index 4b2eba8..975543c 100644 --- a/tests/Anubis.Tests/LedgerTests.cs +++ b/tests/Anubis.Tests/LedgerTests.cs @@ -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 _half = new() { [StrategyNames.EquityMomentum] = 0.5m, [StrategyNames.EquityMeanrev] = 0.5m }; + + /// 6,000 € on Alpaca at 1.10 $/€: 6,600 $, 4,950 to the momentum and 1,650 to the mean reversion. + 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 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 { [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(() => 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(() => 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(() => 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() diff --git a/tests/Anubis.Tests/ReconcilerTests.cs b/tests/Anubis.Tests/ReconcilerTests.cs index 101fced..9a714c0 100644 --- a/tests/Anubis.Tests/ReconcilerTests.cs +++ b/tests/Anubis.Tests/ReconcilerTests.cs @@ -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))); } + /// Coin gone from the account and no stop left: prudent, and past the 15 minutes. + 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() diff --git a/tests/Anubis.Tests/ServerHarness.cs b/tests/Anubis.Tests/ServerHarness.cs index e86e028..071f2d9 100644 --- a/tests/Anubis.Tests/ServerHarness.cs +++ b/tests/Anubis.Tests/ServerHarness.cs @@ -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); diff --git a/tests/Anubis.Tests/StoresTests.cs b/tests/Anubis.Tests/StoresTests.cs index 47e7b82..f7ee5ef 100644 --- a/tests/Anubis.Tests/StoresTests.cs +++ b/tests/Anubis.Tests/StoresTests.cs @@ -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() diff --git a/tools/Anubis.Tasks/Program.cs b/tools/Anubis.Tasks/Program.cs index 1032ca8..3e3df36 100644 --- a/tools/Anubis.Tasks/Program.cs +++ b/tools/Anubis.Tasks/Program.cs @@ -82,25 +82,36 @@ int GuardDrill(string tag) => int BuildImage(string tag) => Step("Costruzione dell'immagine Docker", "docker", - ["build", "-f", "deploy/docker/Dockerfile", "--build-arg", $"ANUBIS_VERSION={tag}", "--build-arg", $"ANUBIS_COMMIT={Commit()}", + ["build", "-f", "deploy/docker/Dockerfile", "--build-arg", $"ANUBIS_VERSION={Version()}", "--build-arg", $"ANUBIS_COMMIT={Commit()}", "-t", $"gitea.encke-hake.ts.net/balbosoft/anubis:{tag}", "."]) ?? 0; -// The commit written in the image, so a diagnostics report says which code it comes from; empty without git. +// The commit written in the image, so a diagnostics report says which code it comes from and only the commit of a tag is +// published as that tag; with something not committed it is marked, and empty without git. string Commit() { - var info = new ProcessStartInfo("git") { WorkingDirectory = root, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; - info.ArgumentList.Add("rev-parse"); - info.ArgumentList.Add("HEAD"); + var commit = Git("rev-parse", "HEAD"); + return commit is null ? "" : Git("status", "--porcelain") is "" ? commit : commit + "-dirty"; +} + +// What a git command answers; null when it fails or git is not there. +string? Git(params string[] arguments) +{ + var info = new ProcessStartInfo("git") { WorkingDirectory = root, UseShellExecute = false, RedirectStandardOutput = true }; + foreach (var argument in arguments) + { + info.ArgumentList.Add(argument); + } + try { using var git = Process.Start(info)!; - var commit = git.StandardOutput.ReadToEnd().Trim(); + var answer = git.StandardOutput.ReadToEnd().Trim(); git.WaitForExit(); - return git.ExitCode == 0 ? commit : ""; + return git.ExitCode == 0 ? answer : null; } catch (System.ComponentModel.Win32Exception) { - return ""; + return null; } }