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
@@ -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.
|
||||
@@ -712,7 +713,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)
|
||||
@@ -724,6 +729,20 @@ internal sealed partial class AnubisHost(
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<bool> 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<JobRun> runs, CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -859,6 +878,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);
|
||||
}
|
||||
@@ -130,12 +130,23 @@ else
|
||||
}
|
||||
else if (state.WaitsForUser(Clock.UtcNow, TimeSpan.FromMinutes(15)) && !Shell.IsDemo)
|
||||
{
|
||||
<p>Sono passati 15 minuti e la differenza non si è spiegata da sola. Scegli tu:</p>
|
||||
@if (state.Differences.All(d => d.Kind == DifferenceKinds.Stop))
|
||||
{
|
||||
<p>Manca ancora uno stop, dove avevi lasciato fuori una differenza. Se il conto non lo accetta, allinea il registro:</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p>Sono passati 15 minuti e la differenza non si è spiegata da sola. Scegli tu:</p>
|
||||
}
|
||||
<div class="choices">
|
||||
<form method="post" action="/azioni/conti/@a.Id/allinea"><AntiforgeryToken /><button class="btn btn-small" type="submit" data-confirm="Il registro prende i numeri del conto, con una riga di rettifica che resta nel diario. Confermi?">Allinea il registro al conto</button></form>
|
||||
<form method="post" action="/azioni/conti/@a.Id/escludi"><AntiforgeryToken /><button class="btn btn-small" type="submit">Lascia fuori ciò che non è del bot</button></form>
|
||||
</div>
|
||||
}
|
||||
else if (state.ModeReason == Reconciler.StopReason)
|
||||
{
|
||||
<p class="note">Manca ancora uno stop: riprovo a ogni confronto e il conto torna normale da solo quando c'è.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p class="note">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.</p>
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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
|
||||
/// <summary>The same silence after which the guard steps in (SPEC 9.3).</summary>
|
||||
public static readonly TimeSpan LoopLimit = TimeSpan.FromMinutes(2);
|
||||
|
||||
/// <summary>A start of the engine this long is stalled, as for the guard (SPEC 9.3).</summary>
|
||||
public static readonly TimeSpan StartLimit = TimeSpan.FromMinutes(10);
|
||||
|
||||
/// <summary>Longer than the silence that blocks new entries (SPEC 6.5): a line that drops for a moment is not an ill container.</summary>
|
||||
public static readonly TimeSpan FeedLimit = TimeSpan.FromMinutes(5);
|
||||
|
||||
public static (string Text, bool Ok) Loop(DateTimeOffset now, bool started, DateTimeOffset? lastTurn) => (started, lastTurn) switch
|
||||
/// <summary>The engine's loop; <paramref name="since"/> is when the services became ready, null where there is no engine to start.</summary>
|
||||
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),
|
||||
};
|
||||
|
||||
|
||||
@@ -81,4 +81,7 @@ internal sealed record ServerOverrides
|
||||
|
||||
/// <summary>True starts the accounts and the order managers in a test; off by default in tests.</summary>
|
||||
public bool? Trading { get; init; }
|
||||
|
||||
/// <summary>How long after a failed start of the trading engine it is tried again.</summary>
|
||||
public TimeSpan? TradingRetry { get; init; }
|
||||
}
|
||||
@@ -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 =>
|
||||
{
|
||||
|
||||
+100
-74
@@ -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
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<EntrustedCapital?> 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);
|
||||
|
||||
/// <summary>The broker's strategies with their share, the capital given so far and their cash, in the account's currency.</summary>
|
||||
public async Task<IReadOnlyList<StrategyCapital>> StrategiesAsync(string broker, CancellationToken cancellationToken)
|
||||
public Task<IReadOnlyList<StrategyCapital>> StrategiesAsync(string broker, CancellationToken cancellationToken) =>
|
||||
db.ReadAsync(s => StrategiesAsync(s, broker), cancellationToken);
|
||||
|
||||
private static Task<EntrustedCapital?> 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<IReadOnlyList<StrategyCapital>> 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);
|
||||
}
|
||||
|
||||
/// <summary>Changes the shares of a broker's strategies (each between 0 and 1, together exactly 1). Never automatic.</summary>
|
||||
@@ -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<List<(StrategyCapital Strategy, decimal Target, decimal Delta)>> PlanAsync(string broker, decimal amount, IReadOnlyDictionary<string, decimal>? shares,
|
||||
CancellationToken cancellationToken)
|
||||
private async Task<decimal> 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<List<(StrategyCapital Strategy, decimal Target, decimal Delta)>> PlanAsync(DbSession s, string broker, decimal amount,
|
||||
IReadOnlyDictionary<string, decimal>? 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -125,7 +125,10 @@ public sealed class Ledger(Database db, IClock clock)
|
||||
|
||||
/// <summary>Gives (positive) or takes back (negative) capital to a strategy. It counts as a flow, not a result.</summary>
|
||||
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);
|
||||
|
||||
/// <summary>
|
||||
/// A correction of a strategy's cash chosen by the user after a reconciliation (SPEC 7.4): a flow, so it changes
|
||||
@@ -448,31 +451,33 @@ public sealed class Ledger(Database db, IClock clock)
|
||||
/// currencies (a fee in a third coin) are kept but not valued.
|
||||
/// </summary>
|
||||
public Task<IReadOnlyList<LedgerEquity>> EquitiesAsync(CancellationToken cancellationToken) =>
|
||||
db.ReadAsync<IReadOnlyList<LedgerEquity>>(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<LedgerEquity>();
|
||||
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<IReadOnlyList<LedgerEquity>> 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<LedgerEquity>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What a strategy held of an instrument just before <paramref name="at"/>, from the fills alone: the base of a
|
||||
|
||||
@@ -82,7 +82,13 @@ public sealed record AccountState(Guid AccountId, string Mode, DateTimeOffset? M
|
||||
IsPrudent && ModeReason != Reconciler.KeyReason && ModeSince is { } since && now - since >= grace;
|
||||
|
||||
/// <summary>There is something to align or to leave out: a missing stop is neither, it has to be put back.</summary>
|
||||
public bool HasChoices => Differences.Any(d => d.Kind != DifferenceKinds.Stop);
|
||||
public bool HasChoices => Differences.Any(d => d.Kind != DifferenceKinds.Stop) || ExcludedWithoutStop;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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";
|
||||
|
||||
/// <summary>The user has chosen and only a stop is missing: nothing is left to ask, the account returns to normal when it is back.</summary>
|
||||
public const string StopReason = "waiting_for_stop";
|
||||
|
||||
/// <summary>How long a difference may take to explain itself before the user is asked.</summary>
|
||||
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<string>();
|
||||
List<AccountDifference> 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)
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public async Task<ReconcileResolution> ResolveAsync(OrderManager manager, ReconcileChoice choice, string by, CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -246,6 +256,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))
|
||||
@@ -260,10 +286,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);
|
||||
@@ -296,8 +341,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);
|
||||
|
||||
/// <summary>Every difference between the ledger and the account, before anything is healed.</summary>
|
||||
public async Task<List<AccountDifference>> 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<List<AccountDifference>> CompareAsync(OrderManager manager, HashSet<string> excluded, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(manager);
|
||||
var account = manager.Account;
|
||||
@@ -314,34 +360,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)))
|
||||
@@ -374,6 +404,34 @@ public sealed class Reconciler(Database db, IClock clock, Ledger ledger)
|
||||
return differences;
|
||||
}
|
||||
|
||||
private static async Task<List<AccountDifference>> MissingPositionsAsync(OrderManager manager, IReadOnlyList<LedgerPosition> positions, Dictionary<Guid, Instrument> instruments,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var differences = new List<AccountDifference>();
|
||||
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<List<AccountDifference>> CoherenceAsync(AccountContext account, CancellationToken cancellationToken)
|
||||
{
|
||||
var differences = new List<AccountDifference>();
|
||||
@@ -400,7 +458,7 @@ public sealed class Reconciler(Database db, IClock clock, Ledger ledger)
|
||||
}
|
||||
|
||||
private static async Task<List<AccountDifference>> StopCoverageAsync(OrderManager manager, IReadOnlyList<LedgerPosition> positions, Dictionary<Guid, Instrument> instruments,
|
||||
List<BrokerOrder> ours, CancellationToken cancellationToken)
|
||||
List<BrokerOrder> ours, Dictionary<Guid, decimal> leftOut, CancellationToken cancellationToken)
|
||||
{
|
||||
var differences = new List<AccountDifference>();
|
||||
var working = (await manager.WorkingInstrumentsAsync(cancellationToken).ConfigureAwait(false)).ToHashSet();
|
||||
@@ -413,7 +471,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)
|
||||
{
|
||||
@@ -530,8 +595,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;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
/// <summary>The cash a strategy's purchases under way still hold: what is left to fill, at the highest price its limit may chase to.</summary>
|
||||
internal static async Task<decimal> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
|
||||
@@ -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
|
||||
/// <summary>The startup steps of SPEC 9.4 are done and the loop runs.</summary>
|
||||
public bool IsStarted => _started;
|
||||
|
||||
/// <summary>The last attempt of the startup ended with an error: nothing watches the accounts until one succeeds.</summary>
|
||||
public bool StartFailed => _startFailed;
|
||||
|
||||
private volatile bool _startFailed;
|
||||
|
||||
/// <summary>The live engine (SPEC 5.5, issue #47): the decisions at their times, the planned orders, the recovery.</summary>
|
||||
public LiveEngine Engine { get; }
|
||||
|
||||
@@ -302,9 +307,24 @@ public sealed partial class TradingService : IDisposable
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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)
|
||||
{
|
||||
@@ -1002,7 +1033,9 @@ public sealed partial class TradingService : IDisposable
|
||||
public async Task<EntrustedCapital> 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;
|
||||
}
|
||||
|
||||
@@ -1010,7 +1043,7 @@ public sealed partial class TradingService : IDisposable
|
||||
public async Task SetSharesAsync(string broker, IReadOnlyDictionary<string, decimal> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
Reference in new issue
Block a user