Write the manuals and fix what following them found
The manual, the runbook and the go-live list are written and checked claim by claim against the code, and the installation is done from zero by following them on both engines. That found real defects, now fixed: - with SQLite a missing database file left no way to restore a backup: the choices appear, and the file is created only by the user's choice; - an account whose difference vanished after the 15 minutes stayed prudent with no button, a missing stop could be left out for good, and a choice made while the broker was silent used old numbers; - after "Ferma tutto" the positions could not be closed without restarting; - a refused key looked like a silent broker: it has its own notice now; - the split of the capital between the strategies of a broker (SPEC 13.5) could not be changed from the interface. refs #72 #68 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2257c3e16c
commit
24e20584d4
28 files changed
+1147
-57
No files matched your search
@@ -128,6 +128,16 @@ internal sealed partial class AnubisHost(
|
||||
/// <summary>The database even when not ready (error-page choices need it to restore or import).</summary>
|
||||
internal Database? Database => _db;
|
||||
|
||||
/// <summary>SQLite, and the file of an installation that exists is not in its place.</summary>
|
||||
internal bool SqliteFileMissing =>
|
||||
Config.Db is { Engine: DbEngine.Sqlite, SqlitePath: { } path } && !File.Exists(path) && File.Exists(Config.Data.InstallationFile);
|
||||
|
||||
/// <summary>
|
||||
/// For an error-page choice that writes into a missing SQLite file: the only place where a known installation gets a
|
||||
/// new one. Called while the choice holds <see cref="ExclusiveAsync"/>.
|
||||
/// </summary>
|
||||
internal Database OpenForChoice() => _db ??= Database.Open(Config.Db!, allowCreate: SqliteFileMissing);
|
||||
|
||||
/// <summary>Holds the loop still while an error-page choice works on the database.</summary>
|
||||
internal async Task<IDisposable> ExclusiveAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -250,7 +260,6 @@ internal sealed partial class AnubisHost(
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
SetStatus(HostMode.DatabaseUnavailable, Redactor.Redact(ex.Message));
|
||||
if (Config.Db!.Engine == DbEngine.Sqlite)
|
||||
{
|
||||
// Reopen next time: the file may come back, or the folder may be released.
|
||||
@@ -258,6 +267,15 @@ internal sealed partial class AnubisHost(
|
||||
_db = null;
|
||||
}
|
||||
|
||||
if (SqliteFileMissing)
|
||||
{
|
||||
// SPEC 15.1: without the file the user may restore, import or start over, as with an empty database. The
|
||||
// file is created only by that choice, and a file that comes back meanwhile is used without one.
|
||||
SetStatus(HostMode.IdentityProblem, Redactor.Redact(ex.Message), new IdentityCheck(IdentityVerdict.EmptyDatabase, Installation.ReadFile(Config.Data), null));
|
||||
return;
|
||||
}
|
||||
|
||||
SetStatus(HostMode.DatabaseUnavailable, Redactor.Redact(ex.Message));
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,9 @@
|
||||
|
||||
@switch (verdict)
|
||||
{
|
||||
case IdentityVerdict.EmptyDatabase when Host.SqliteFileMissing:
|
||||
<p>Il file del database non c'è, ma la cartella dei dati appartiene a un'installazione che esiste già. Il motore resta spento e non ne creo un altro da solo. Se l'hai spostato, o il disco era scollegato, rimettilo al suo posto: riparto da solo.</p>
|
||||
break;
|
||||
case IdentityVerdict.EmptyDatabase:
|
||||
<p>Il database è vuoto, ma la cartella dei dati appartiene a un'installazione che esiste già. Il motore resta spento: se partisse, comincerebbe da zero e i conti risulterebbero diversi dal registro.</p>
|
||||
break;
|
||||
|
||||
@@ -79,7 +79,7 @@ else
|
||||
<section class="panel account" aria-label="@a.Name">
|
||||
<div class="account-head">
|
||||
<h2>@a.Name <span class="tag">@a.Kind</span></h2>
|
||||
<span class="link-state @(state.LastOutcome == ReconcileOutcomes.Unreachable ? "down" : null)"><span class="dot"></span>@Connection(a)</span>
|
||||
<span class="link-state @(ReconcileOutcomes.IsDown(state.LastOutcome) ? "down" : null)"><span class="dot"></span>@Connection(a)</span>
|
||||
</div>
|
||||
<div class="account-value">
|
||||
<span class="account-equity">@Shell.Money(a.Eur(a.Equity), c)</span>
|
||||
@@ -119,7 +119,16 @@ else
|
||||
<li>@d.Message</li>
|
||||
}
|
||||
</ul>
|
||||
@if (state.WaitsForUser(Clock.UtcNow, TimeSpan.FromMinutes(15)) && !Shell.IsDemo)
|
||||
@if (state.WaitsForUser(Clock.UtcNow, TimeSpan.FromMinutes(15)) && !state.HasChoices && !Shell.IsDemo)
|
||||
{
|
||||
<p>@(state.Differences.Count == 0
|
||||
? "La differenza non c'è più, ma si è spiegata dopo i 15 minuti: il conto torna normale quando lo dici tu."
|
||||
: "Manca ancora uno stop: riprovo a ogni confronto. Se nel frattempo è tornato al suo posto, ricontrolla adesso.")</p>
|
||||
<div class="choices">
|
||||
<form method="post" action="/azioni/conti/@a.Id/allinea"><AntiforgeryToken /><button class="btn btn-small" type="submit">Ricontrolla adesso</button></form>
|
||||
</div>
|
||||
}
|
||||
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>
|
||||
<div class="choices">
|
||||
@@ -166,7 +175,11 @@ else
|
||||
}
|
||||
else if (state.LastOutcome is ReconcileOutcomes.Unreachable)
|
||||
{
|
||||
<li class="attention"><Icon Name="alert" Size="16" />Il broker non risponde: riprovo ogni 5 minuti (ultimo tentativo alle @Time(state.LastReconciledAt))</li>
|
||||
<li class="attention"><Icon Name="alert" Size="16" />Il broker non risponde: riprovo ogni 5 minuti (ultimo controllo riuscito alle @Time(state.LastReconciledAt))</li>
|
||||
}
|
||||
else if (state.LastOutcome is ReconcileOutcomes.KeyRefused)
|
||||
{
|
||||
<li class="attention"><Icon Name="alert" Size="16" /><span>Il broker non accetta più la chiave: inseriscine una nuova in <a href="/impostazioni#conti">Impostazioni</a></span></li>
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -353,6 +366,9 @@ else
|
||||
{
|
||||
("allinea", _) => ("Fatto: il registro ha preso i numeri del conto e il conto è tornato normale.", true),
|
||||
("escludi", _) => ("Fatto: la differenza resta fuori dal registro e il conto è tornato normale.", true),
|
||||
("ricontrollo", _) => ("Fatto: ho ricontrollato e il conto è tornato normale.", true),
|
||||
(_, "broker") => ("Il broker non risponde: non ho potuto confrontare il conto e non ho cambiato niente. Riprova tra poco.", false),
|
||||
(_, "stop") => ("Il conto resta prudente: manca ancora uno stop. Riprovo a metterlo e torna normale da solo quando c'è.", false),
|
||||
(_, "motore") => ("Il motore di trading non è attivo: riprova tra poco.", false),
|
||||
(_, "chiave") => ("Una chiave che permette i prelievi non si allinea: va sostituita in Impostazioni.", false),
|
||||
(_, "presto") => ("La scelta si fa dopo 15 minuti di modalità prudente: prima la differenza può ancora spiegarsi da sola.", false),
|
||||
@@ -374,6 +390,11 @@ else
|
||||
return "Il broker non risponde";
|
||||
}
|
||||
|
||||
if (a.State.LastOutcome == ReconcileOutcomes.KeyRefused)
|
||||
{
|
||||
return "Chiave non accettata";
|
||||
}
|
||||
|
||||
if (_latency?.GetValueOrDefault(a.Id) is > 0 and var ms)
|
||||
{
|
||||
return $"Connesso, risposta in {ms} ms";
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
"chiavi" => "Chiavi verificate e salvate: possono fare ordini e non possono prelevare. Il motore è ripartito e le usa.",
|
||||
"chiavi-tolte" => "Chiavi tolte: quel conto torna al simulatore interno per le strategie che non hanno ancora storia sul conto di prova.",
|
||||
"capitale" => "Capitale affidato aggiornato e diviso tra le strategie.",
|
||||
"quote" => "Ripartizione del capitale salvata.",
|
||||
"limiti" => "Limiti di rischio salvati.",
|
||||
"rischio" => "Impostazione del rischio salvata.",
|
||||
"telegram" => "Telegram funziona: ti ho mandato un messaggio di prova e ho salvato token e chat.",
|
||||
@@ -76,7 +77,7 @@
|
||||
|
||||
<section class="panel" id="conti">
|
||||
<h2>Conti e chiavi</h2>
|
||||
<p class="hint">In questa fase uso solo denaro finto: il simulatore interno è sempre acceso e, con le chiavi dei conti di prova, le strategie passano ai conti di prova dei broker. Le chiavi di conti veri non servono e non vanno inserite.</p>
|
||||
<p class="hint">Questa versione usa solo denaro finto: il simulatore interno è sempre acceso. Con le chiavi di prova di Alpaca le strategie azionarie che non hanno ancora movimenti passano al conto di prova; le crypto restano nel simulatore interno. Le chiavi di conti veri non servono e non vanno inserite.</p>
|
||||
@foreach (var b in _brokers)
|
||||
{
|
||||
<h3>@b.Title</h3>
|
||||
@@ -141,9 +142,30 @@
|
||||
<AntiforgeryToken />
|
||||
<label for="euro-@b.Broker">Nuovo importo in euro</label>
|
||||
<input id="euro-@b.Broker" name="euro" inputmode="decimal" autocomplete="off" value="@(b.Entrusted is { } cur ? Format.Quantity(cur.AmountEur) : "")" required />
|
||||
@if (b.Live)
|
||||
{
|
||||
<RaiseFields />
|
||||
}
|
||||
<button class="btn btn-small" type="submit">Salva</button>
|
||||
</form>
|
||||
<p class="hint">Si divide tra le strategie del conto secondo le quote@(b.Broker == Venues.Alpaca ? ", in dollari al cambio BCE del giorno" : ""). Ridurlo non vende nulla: se una strategia ha investito più di quanto le resterebbe, aspetto che venda.</p>
|
||||
@if (b.Strategies.Count > 1)
|
||||
{
|
||||
<h4>Ripartizione tra le strategie di @b.Short</h4>
|
||||
<form method="post" action="/azioni/quote/@b.Broker" class="form-grid">
|
||||
<AntiforgeryToken />
|
||||
@foreach (var s in b.Strategies)
|
||||
{
|
||||
<label>@StrategyNames.Label(s.Strategy, withMarket: true) (%)<input name="quota-@s.Strategy" inputmode="decimal" autocomplete="off" value="@Format.Quantity(s.Share * 100m)" required /></label>
|
||||
}
|
||||
@if (b.Live)
|
||||
{
|
||||
<RaiseFields />
|
||||
}
|
||||
<button class="btn btn-small" type="submit">Salva la ripartizione</button>
|
||||
</form>
|
||||
<p class="hint">Insieme devono fare 100. La quota cambia la dimensione delle prossime operazioni: non vende quello che è già comprato. I parametri delle strategie invece non si toccano da qui: sono quelli provati nel test, e un cambio passa da una nuova prova in Laboratorio.</p>
|
||||
}
|
||||
}
|
||||
}
|
||||
</section>
|
||||
@@ -170,7 +192,7 @@
|
||||
<h3>Protezione day trade</h3>
|
||||
<form method="post" action="/azioni/rischio/@Anubis.Risk.RiskSettings.PdtGuard.Key" class="form-inline">
|
||||
<AntiforgeryToken />
|
||||
<label for="pdt">Per un conto Alpaca sotto i 25.000 $: al massimo 3 operazioni aperte e chiuse in giornata ogni 5 sedute.</label>
|
||||
<label for="pdt">Se Alpaca applica ancora al tuo conto la regola sulle operazioni in giornata (PDT): al massimo 3 operazioni aperte e chiuse in giornata ogni 5 sedute.</label>
|
||||
<select id="pdt" name="valore" data-autosubmit>
|
||||
<option value="off" selected="@(_pdt == "off")">Spenta</option>
|
||||
<option value="on" selected="@(_pdt == "on")">Accesa</option>
|
||||
@@ -641,7 +663,7 @@
|
||||
private sealed record BrokerKey(string Name, string Label, SecretStatus Status);
|
||||
|
||||
private sealed record BrokerSetup(string Broker, string Title, string Short, IReadOnlyList<BrokerKey> Keys, AccountState? State, EntrustedCapital? Entrusted,
|
||||
IReadOnlyList<StrategyCapital> Strategies);
|
||||
IReadOnlyList<StrategyCapital> Strategies, bool Live);
|
||||
private sealed record LimitField(string Key, string Label, string Value, bool ReadOnly);
|
||||
private readonly List<LimitField> _limits = [];
|
||||
private SettingValue _taxMethod = new(Anubis.Trading.TaxExport.MethodSetting.Key, "lifo", false, null);
|
||||
@@ -717,7 +739,8 @@
|
||||
|
||||
_pdt = (await services.Settings.GetAsync(Anubis.Risk.RiskSettings.PdtGuard.Key, ct)).Value;
|
||||
_scenarios = (await services.Settings.GetAsync(Anubis.Risk.Scenarios.Setting.Key, ct)).Value;
|
||||
_anyLive = await (services.Trading?.Stages ?? new StageBook(services.Db, Clock, TradingConsent.None, (_, _, _) => Task.FromResult(false))).AnyLiveAsync(null, ct);
|
||||
var stages = services.Trading?.Stages ?? new StageBook(services.Db, Clock, TradingConsent.None, (_, _, _) => Task.FromResult(false));
|
||||
_anyLive = await stages.AnyLiveAsync(null, ct);
|
||||
|
||||
_backups = services.Backups.List();
|
||||
_telegramToken = await services.Secrets.StatusAsync(Anubis.Notifications.TelegramSettings.TokenSecret, ct);
|
||||
@@ -738,7 +761,7 @@
|
||||
|
||||
var demoAccount = await services.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT id FROM accounts WHERE broker = @b AND environment = 'demo'", r => (Guid?)r.Id("id"), ("b", broker)), ct);
|
||||
var state = demoAccount is { } id ? await reconciler.StateAsync(id, ct) : null;
|
||||
_brokers.Add(new BrokerSetup(broker, title, name, keys, state, await capital.EntrustedAsync(broker, ct), await capital.StrategiesAsync(broker, ct)));
|
||||
_brokers.Add(new BrokerSetup(broker, title, name, keys, state, await capital.EntrustedAsync(broker, ct), await capital.StrategiesAsync(broker, ct), await stages.AnyLiveAsync(broker, ct)));
|
||||
}
|
||||
var user = HttpContext!.User;
|
||||
_hasSecondFactor = CurrentUser.HasSecondFactor(user);
|
||||
@@ -770,6 +793,7 @@
|
||||
"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.",
|
||||
"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.",
|
||||
"frase-rischio" => $"Una strategia usa soldi veri: per aggiungere rischio scrivi la frase «{StageBook.RaisePhrase}». Non ho cambiato nulla.",
|
||||
|
||||
@@ -149,7 +149,7 @@
|
||||
<section class="panel overview-account desk-only" aria-label="@a.Name">
|
||||
<div class="account-head">
|
||||
<h2>@a.Name <span class="tag">@a.Kind</span></h2>
|
||||
<span class="link-state @(Down(a) ? "down" : null)"><span class="dot"></span>@(Down(a) ? "Non risponde" : "Connesso")</span>
|
||||
<span class="link-state @(Down(a) ? "down" : null)"><span class="dot"></span>@(KeyRefused(a) ? "Chiave non accettata" : Down(a) ? "Non risponde" : "Connesso")</span>
|
||||
</div>
|
||||
<div class="account-value">
|
||||
<span class="account-equity">@Shell.Money(a.Eur(a.Equity), c)</span>
|
||||
@@ -225,7 +225,7 @@
|
||||
{
|
||||
var up = a.Result >= 0;
|
||||
<li>
|
||||
<span><strong>@a.Name</strong><span class="sub"><span class="dot @(Down(a) ? "down" : null)"></span>@a.Kind, @(Down(a) ? "non risponde" : "connesso")</span></span>
|
||||
<span><strong>@a.Name</strong><span class="sub"><span class="dot @(Down(a) ? "down" : null)"></span>@a.Kind, @(KeyRefused(a) ? "chiave non accettata" : Down(a) ? "non risponde" : "connesso")</span></span>
|
||||
<span class="num"><strong>@Shell.Money(a.Eur(a.Equity), c)</strong><span class="sub @(up ? "gain" : "loss")"><Arrow Up="up" /><strong>@Shell.Money(a.Eur(a.Result), c, withSign: true)</strong></span></span>
|
||||
</li>
|
||||
}
|
||||
@@ -446,7 +446,9 @@
|
||||
return o.Positions == 1 ? $"Sorveglio una posizione, {stops}. {orders}" : $"Sorveglio {o.Positions} posizioni, {stops}. {orders}";
|
||||
}
|
||||
|
||||
private static bool Down(AccountCard a) => a.State.LastOutcome == ReconcileOutcomes.Unreachable;
|
||||
private static bool KeyRefused(AccountCard a) => a.State.LastOutcome == ReconcileOutcomes.KeyRefused;
|
||||
|
||||
private static bool Down(AccountCard a) => ReconcileOutcomes.IsDown(a.State.LastOutcome);
|
||||
|
||||
private string AccountNote(AccountCard a, IReadOnlyList<PositionRow> held)
|
||||
{
|
||||
|
||||
@@ -81,6 +81,11 @@
|
||||
<input type="hidden" name="ritorno" value="/rischio" />
|
||||
<button class="btn" type="submit" disabled="@(v.StopFile || v.ProtectedRestart is { CanRestart: false })" data-confirm="@RestartText(v)">Riparti</button>
|
||||
</form>
|
||||
@if (v.BotState == "stopped" && !v.CloseAllPending && v.ProtectedRestart is not { CanRestart: false })
|
||||
{
|
||||
<p class="note">Se preferisci uscire da tutto, puoi vendere le posizioni adesso, senza ripartire.</p>
|
||||
<form method="post" action="/azioni/bot/chiudi"><AntiforgeryToken /><input type="hidden" name="ritorno" value="/rischio" /><button class="btn btn-danger" type="submit" data-confirm="Vendo a mercato ogni posizione del bot, che resta fermo. Ciò che è su un mercato chiuso parte all'apertura e intanto tiene il suo stop. Non si annulla. Confermi?">Chiudi tutte le posizioni</button></form>
|
||||
}
|
||||
}
|
||||
}
|
||||
@if (v.BotState != "stopped")
|
||||
@@ -151,7 +156,7 @@
|
||||
<dd><span>Nessuno negli ultimi 14 giorni.</span></dd>
|
||||
}
|
||||
<dt>Protezione day trade (azioni)</dt>
|
||||
<dd><span>@(v.PdtGuard ? "Accesa: al massimo 3 operazioni in giornata ogni 5 sedute." : "Spenta. Si accende in Impostazioni se il conto Alpaca vale meno di 25.000 $.")</span></dd>
|
||||
<dd><span>@(v.PdtGuard ? "Accesa: al massimo 3 operazioni in giornata ogni 5 sedute." : "Spenta. Si accende in Impostazioni se Alpaca applica ancora al tuo conto la regola sulle operazioni in giornata.")</span></dd>
|
||||
</dl>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@@ -143,7 +143,7 @@
|
||||
}
|
||||
else if (!v.LiveAllowed || accounts.Count == 0 || Shell.IsDemo)
|
||||
{
|
||||
<p class="form-inline"><button class="btn" type="button" disabled>@target</button> <span class="note">@(v.LiveAllowed ? "Serve un conto reale di " + (broker == "okx" ? "OKX" : "Alpaca") + " nelle Impostazioni." : "La configurazione d'avvio non consente i soldi veri.")</span></p>
|
||||
<p class="form-inline"><button class="btn" type="button" disabled>@target</button> <span class="note">@(v.LiveAllowed ? "Manca un conto reale di " + (broker == "okx" ? "OKX" : "Alpaca") + ": questa versione non permette ancora di collegarne uno." : "La configurazione d'avvio non consente i soldi veri.")</span></p>
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
@* The fields of the procedure of SPEC 12.4, for a change that adds risk while a strategy uses real money. *@
|
||||
<p class="note">Una strategia di questo conto usa soldi veri: per aggiungere rischio servono la frase e la password.</p>
|
||||
<label>Scrivi: <code>@Anubis.Trading.StageBook.RaisePhrase</code><input name="frase" autocomplete="off" /></label>
|
||||
<label>Password<input name="password" type="password" autocomplete="current-password" /></label>
|
||||
<label>Codice a sei cifre (se attivo)<input name="codice" inputmode="numeric" autocomplete="one-time-code" /></label>
|
||||
@@ -368,9 +368,10 @@ internal static partial class Endpoints
|
||||
: "Comando non ammesso nello stato attuale del bot.");
|
||||
}
|
||||
|
||||
var restart = command is "restart" or "riattiva"
|
||||
&& await Platform.Installation.ReadRowAsync(host.Services.Db, ct).ConfigureAwait(false) is { ProtectedRestart: true };
|
||||
if (restart && (host.Services.Trading is not { Risk: not null, Started: true } engineOn || engineOn.AccountsToRebuild.Count > 0))
|
||||
var protectedRestart = await Platform.Installation.ReadRowAsync(host.Services.Db, ct).ConfigureAwait(false) is { ProtectedRestart: true };
|
||||
var restart = protectedRestart && command is "restart" or "riattiva";
|
||||
if (protectedRestart && command is "restart" or "riattiva" or "close" or "chiudi"
|
||||
&& (host.Services.Trading is not { Risk: not null, Started: true } engineOn || engineOn.AccountsToRebuild.Count > 0))
|
||||
{
|
||||
// SPEC 15.1: first the executions after the archive, then the user's confirmation.
|
||||
var waiting = host.Services.Trading?.AccountsToRebuild ?? [];
|
||||
|
||||
@@ -34,6 +34,7 @@ internal static partial class Forms
|
||||
signed.MapPost("/chiavi/{broker}", SaveKeysAsync);
|
||||
signed.MapPost("/chiavi/{broker}/togli", RemoveKeysAsync);
|
||||
signed.MapPost("/capitale/{broker}", SetCapitalAsync);
|
||||
signed.MapPost("/quote/{broker}", SetSharesAsync);
|
||||
signed.MapPost("/telegram", SaveTelegramAsync);
|
||||
signed.MapPost("/telegram/prova", TestTelegramAsync);
|
||||
signed.MapPost("/telegram/togli", RemoveTelegramAsync);
|
||||
@@ -361,9 +362,15 @@ internal static partial class Forms
|
||||
return Results.Redirect("/conti?errore=presto");
|
||||
}
|
||||
|
||||
await trading.Reconciler.ResolveAsync(manager, choice == "allinea" ? Anubis.Trading.ReconcileChoice.Align : Anubis.Trading.ReconcileChoice.Exclude,
|
||||
var resolution = await trading.Reconciler.ResolveAsync(manager, choice == "allinea" ? Anubis.Trading.ReconcileChoice.Align : Anubis.Trading.ReconcileChoice.Exclude,
|
||||
context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
|
||||
return Results.Redirect("/conti?ok=" + choice);
|
||||
return Results.Redirect(resolution switch
|
||||
{
|
||||
Anubis.Trading.ReconcileResolution.NotCompared => "/conti?errore=broker",
|
||||
Anubis.Trading.ReconcileResolution.StopsMissing => "/conti?errore=stop",
|
||||
_ when !state.HasChoices => "/conti?ok=ricontrollo",
|
||||
_ => "/conti?ok=" + choice,
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -590,6 +597,54 @@ internal static partial class Forms
|
||||
return Results.Redirect(back + "?ok=capitale#conti");
|
||||
}
|
||||
|
||||
/// <summary>How the capital of a broker is split between its strategies, in percent (SPEC 13.5): only the user changes it.</summary>
|
||||
private static async Task<IResult> SetSharesAsync(string broker, IFormCollection form, AnubisHost host, IClock clock, HttpContext context, CancellationToken ct)
|
||||
{
|
||||
const string back = "/impostazioni";
|
||||
if (broker is not (Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca))
|
||||
{
|
||||
return Results.Redirect(back + "?errore=conto#conti");
|
||||
}
|
||||
|
||||
if (host.IsDemo || host.Services?.Trading is not { } trading)
|
||||
{
|
||||
return Results.Redirect(back + "?errore=motore#conti");
|
||||
}
|
||||
|
||||
var shares = new Dictionary<string, decimal>(StringComparer.Ordinal);
|
||||
foreach (var strategy in await trading.Capital.StrategiesAsync(broker, ct).ConfigureAwait(false))
|
||||
{
|
||||
if (ParseEuro(form["quota-" + strategy.Strategy].ToString().Replace("%", "", StringComparison.Ordinal)) is not { } percent)
|
||||
{
|
||||
return Results.Redirect(back + "?errore=quote#conti");
|
||||
}
|
||||
|
||||
shares[strategy.Strategy] = percent / 100m;
|
||||
}
|
||||
|
||||
if (shares.Count == 0 || shares.Values.Any(s => s is < 0m or > 1m) || shares.Values.Sum() != 1m)
|
||||
{
|
||||
return Results.Redirect(back + "?errore=quote#conti");
|
||||
}
|
||||
|
||||
// Moving capital between strategies gives some of them more: with real money on this broker it is more risk (SPEC 12.4).
|
||||
if (await RaiseRefusalAsync(host.Services!, clock, broker, form, ct).ConfigureAwait(false) is { } refusal)
|
||||
{
|
||||
return Results.Redirect(back + "?errore=" + refusal + "#conti");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await trading.SetSharesAsync(broker, shares, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Anubis.Trading.CapitalException)
|
||||
{
|
||||
return Results.Redirect(back + "?errore=capitale#conti");
|
||||
}
|
||||
|
||||
return Results.Redirect(back + "?ok=quote#conti");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The user's choices on the Strategie screen (SPEC 12.3, 12.4): observation and simulation from a button, real
|
||||
/// money only through the procedure, with the phrase, the password and the second factor checked by the stage book.
|
||||
@@ -1097,7 +1152,6 @@ internal static partial class Forms
|
||||
// The startup loop stays still until the choice is done and the installation renewed.
|
||||
using var exclusive = await host.ExclusiveAsync(ct).ConfigureAwait(false);
|
||||
var status = host.Status;
|
||||
var db = host.Database;
|
||||
if (choice == "riprova" && status.Mode == HostMode.SchemaProblem)
|
||||
{
|
||||
host.MigrationFailed = null;
|
||||
@@ -1106,8 +1160,10 @@ internal static partial class Forms
|
||||
return Results.Redirect("/");
|
||||
}
|
||||
|
||||
if (status.Mode != HostMode.IdentityProblem || status.Identity is null || db is null)
|
||||
// Without a database the choices stand only while the SQLite file is missing: one that came back is used as it is.
|
||||
if (status.Mode != HostMode.IdentityProblem || status.Identity is null || (host.Database is null && !host.SqliteFileMissing))
|
||||
{
|
||||
host.Wake();
|
||||
return Results.Redirect("/");
|
||||
}
|
||||
|
||||
@@ -1123,8 +1179,8 @@ internal static partial class Forms
|
||||
return Results.Redirect("/?errore=scelta");
|
||||
}
|
||||
|
||||
await Archive.ImportAsync(db, Path.Combine(backup.Folder, Backups.ArchiveFolder), clock, ct).ConfigureAwait(false);
|
||||
await Installation.RenewAsync(db, config.Data, clock, "Salvataggio ripristinato", ct).ConfigureAwait(false);
|
||||
await Archive.ImportAsync(host.OpenForChoice(), Path.Combine(backup.Folder, Backups.ArchiveFolder), clock, ct).ConfigureAwait(false);
|
||||
await Installation.RenewAsync(host.OpenForChoice(), config.Data, clock, "Salvataggio ripristinato", ct).ConfigureAwait(false);
|
||||
break;
|
||||
case "importa" when verdict == IdentityVerdict.EmptyDatabase:
|
||||
var folder = ServiceChoices.ImportFolders(config.Data).FirstOrDefault(f => Path.GetFileName(f) == form["archivio"].ToString());
|
||||
@@ -1133,8 +1189,8 @@ internal static partial class Forms
|
||||
return Results.Redirect("/?errore=scelta");
|
||||
}
|
||||
|
||||
await Archive.ImportAsync(db, folder, clock, ct).ConfigureAwait(false);
|
||||
await Installation.RenewAsync(db, config.Data, clock, "Archivio importato", ct).ConfigureAwait(false);
|
||||
await Archive.ImportAsync(host.OpenForChoice(), folder, clock, ct).ConfigureAwait(false);
|
||||
await Installation.RenewAsync(host.OpenForChoice(), config.Data, clock, "Archivio importato", ct).ConfigureAwait(false);
|
||||
break;
|
||||
case "da-capo" when verdict == IdentityVerdict.EmptyDatabase:
|
||||
Installation.StartOver(config.Data, clock);
|
||||
@@ -1142,7 +1198,7 @@ internal static partial class Forms
|
||||
case "usa-questo" when verdict is IdentityVerdict.DifferentInstallation or IdentityVerdict.StaleDatabase or IdentityVerdict.MissingFile:
|
||||
// An old copy may have an old schema: it is brought up to date, after its own backup, before it is protected.
|
||||
await host.MigrateAsync(new Backups(config.Data, clock), ct).ConfigureAwait(false);
|
||||
await Installation.RenewAsync(db, config.Data, clock, "Database scelto dalla pagina d'errore", ct).ConfigureAwait(false);
|
||||
await Installation.RenewAsync(host.OpenForChoice(), config.Data, clock, "Database scelto dalla pagina d'errore", ct).ConfigureAwait(false);
|
||||
break;
|
||||
default:
|
||||
return Results.Redirect("/?errore=scelta");
|
||||
|
||||
@@ -27,7 +27,7 @@ internal sealed record ProtectedRestartView(DateTimeOffset Since, bool Working,
|
||||
var rebuilt = await services.Db.ReadAsync(s => s.QueryAsync("SELECT message FROM journal WHERE code = 'ledger_rebuilt' AND occurred_at >= @f ORDER BY occurred_at, id",
|
||||
r => r.Text("message"), ("f", row.RenewedAt)), cancellationToken).ConfigureAwait(false);
|
||||
var stages = services.Trading is { } trading ? await trading.Stages.AllAsync(cancellationToken).ConfigureAwait(false) : [];
|
||||
return new ProtectedRestartView(row.RenewedAt, services.Trading is { Started: false }, services.Trading?.AccountsToRebuild ?? [], rebuilt,
|
||||
return new ProtectedRestartView(row.RenewedAt, services.Trading is not { Started: true }, services.Trading?.AccountsToRebuild ?? [], rebuilt,
|
||||
[.. stages.Where(s => s.WaitsForReconfirmation).Select(s => StrategyNames.Label(s.Strategy, withMarket: true))]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,6 +82,9 @@ public sealed class Database : IAsyncDisposable
|
||||
pg.Timeout = settings.ConnectTimeoutSeconds;
|
||||
pg.CommandTimeout = 60;
|
||||
pg.ApplicationName = "anubis";
|
||||
|
||||
// The password is the only way in: otherwise every process tries Kerberos first and complains about a missing library.
|
||||
pg.GssEncryptionMode = GssEncryptionMode.Disable;
|
||||
var dataSource = new NpgsqlDataSourceBuilder(pg.ToString()).Build();
|
||||
return new Database(DbEngine.Postgres, pg.ToString(), dataSource, settings.Describe());
|
||||
}
|
||||
|
||||
@@ -214,6 +214,7 @@ public static class SoakReporter
|
||||
ReconcileOutcomes.Healed => "sistemate da sole",
|
||||
ReconcileOutcomes.Different => "con differenze",
|
||||
ReconcileOutcomes.Unreachable => "conto non raggiungibile",
|
||||
ReconcileOutcomes.KeyRefused => "chiave non accettata",
|
||||
_ => outcome,
|
||||
};
|
||||
|
||||
|
||||
@@ -168,18 +168,36 @@ 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);
|
||||
await db.WriteAsync(async s =>
|
||||
{
|
||||
foreach (var (strategy, share) in shares)
|
||||
var now = clock.UtcNow;
|
||||
foreach (var strategy in changed)
|
||||
{
|
||||
var share = shares[strategy.Strategy];
|
||||
await s.ExecuteAsync("UPDATE strategy_state SET share = @sh, updated_at = @now WHERE strategy = @s", cancellationToken,
|
||||
("sh", share), ("now", clock.UtcNow), ("s", strategy)).ConfigureAwait(false);
|
||||
("sh", share), ("now", now), ("s", strategy.Strategy)).ConfigureAwait(false);
|
||||
await s.ExecuteAsync("INSERT INTO config_history (id, key, old_value, new_value, changed_by, created_at) VALUES (@id, @k, @o, @n, @by, @t)", cancellationToken,
|
||||
("id", Ids.NewId(clock)), ("k", "strategy." + strategy.Strategy + ".share"), ("o", Json(strategy.Share)), ("n", Json(share)), ("by", changedBy), ("t", now))
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await Diary.WriteAsync(s, clock, DiaryKinds.System, "shares_changed",
|
||||
$"Quote di {broker} cambiate da {changedBy}: " + string.Join(", ", shares.Select(p => $"{p.Key} {Format.Quantity(p.Value * 100m)}%")) + ".", null, cancellationToken)
|
||||
$"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);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
if (entrusted is not null)
|
||||
@@ -188,6 +206,10 @@ public sealed class Capital(Database db, IClock clock, Ledger ledger, FxStore fx
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -202,7 +224,7 @@ public sealed class Capital(Database db, IClock clock, Ledger ledger, FxStore fx
|
||||
if (strategy.Cash + delta < 0m)
|
||||
{
|
||||
throw new CapitalException(
|
||||
$"{strategy.Strategy} ha investito in posizioni più di quanto resterebbe: potrò ridurre il suo capitale quando avrà venduto. Liquidità ora: {Format.Quantity(strategy.Cash)} {strategy.Currency}.");
|
||||
$"{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}.");
|
||||
}
|
||||
|
||||
plan.Add((strategy, target, delta));
|
||||
|
||||
@@ -300,6 +300,9 @@ public class BrokerException : Exception
|
||||
}
|
||||
|
||||
public bool Retryable { get; }
|
||||
|
||||
/// <summary>The broker does not accept the key: expired, revoked, or not allowed from this address. Waiting does not help.</summary>
|
||||
public bool KeyRefused { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>The broker refused the order: it does not exist on the broker and will not be resent as it is.</summary>
|
||||
|
||||
@@ -27,6 +27,12 @@ public static class ReconcileOutcomes
|
||||
/// <summary>The broker could not be reached: nothing is concluded.</summary>
|
||||
public const string Unreachable = "unreachable";
|
||||
|
||||
/// <summary>The broker answers but no longer accepts the key: only the user can replace it.</summary>
|
||||
public const string KeyRefused = "key_refused";
|
||||
|
||||
/// <summary>The account could not be read, for one reason or the other.</summary>
|
||||
public static bool IsDown(string? outcome) => outcome is Unreachable or KeyRefused;
|
||||
|
||||
public const string UserAligned = "user_aligned";
|
||||
public const string UserExcluded = "user_excluded";
|
||||
}
|
||||
@@ -71,9 +77,12 @@ public sealed record AccountState(Guid AccountId, string Mode, DateTimeOffset? M
|
||||
|
||||
public bool IsPrudent => Mode == AccountModes.Prudent;
|
||||
|
||||
/// <summary>The 15 minutes have passed and the difference is still there: only the user can close it (SPEC 7.4).</summary>
|
||||
/// <summary>The 15 minutes have passed: only the user can close it (SPEC 7.4), also when the difference is gone meanwhile.</summary>
|
||||
public bool WaitsForUser(DateTimeOffset now, TimeSpan grace) =>
|
||||
IsPrudent && ModeReason != Reconciler.KeyReason && Differences.Count > 0 && ModeSince is { } since && now - since >= grace;
|
||||
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 enum ReconcileChoice
|
||||
@@ -85,6 +94,19 @@ public enum ReconcileChoice
|
||||
Exclude,
|
||||
}
|
||||
|
||||
/// <summary>How the user's choice ended.</summary>
|
||||
public enum ReconcileResolution
|
||||
{
|
||||
/// <summary>The account is normal again.</summary>
|
||||
Normal,
|
||||
|
||||
/// <summary>The broker did not answer: nothing was compared, so nothing was changed.</summary>
|
||||
NotCompared,
|
||||
|
||||
/// <summary>A stop is still missing: the account stays prudent, and returns to normal by itself when it is back.</summary>
|
||||
StopsMissing,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reconciliation (SPEC 7.4), at start and every 5 minutes. What is compared depends on the environment: in the
|
||||
/// internal simulator the ledger's own coherence; on demo accounts positions, orders and stops; on real accounts
|
||||
@@ -121,8 +143,8 @@ public sealed class Reconciler(Database db, IClock clock, Ledger ledger)
|
||||
}
|
||||
catch (BrokerException ex)
|
||||
{
|
||||
await RecordUnreachableAsync(account, state, ex.Message, cancellationToken).ConfigureAwait(false);
|
||||
return new ReconcileReport(account.AccountId, ReconcileOutcomes.Unreachable, [], [], state.Mode);
|
||||
var down = await RecordDownAsync(account, state, ex, cancellationToken).ConfigureAwait(false);
|
||||
return new ReconcileReport(account.AccountId, down, [], [], state.Mode);
|
||||
}
|
||||
|
||||
var excluded = state.Excluded.ToHashSet(StringComparer.Ordinal);
|
||||
@@ -145,8 +167,13 @@ public sealed class Reconciler(Database db, IClock clock, Ledger ledger)
|
||||
{
|
||||
permissions = await manager.Broker.GetKeyPermissionsAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (BrokerException)
|
||||
catch (BrokerException ex)
|
||||
{
|
||||
if (ex.KeyRefused)
|
||||
{
|
||||
await RecordDownAsync(account, await StateAsync(account.AccountId, cancellationToken).ConfigureAwait(false), ex, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -183,9 +210,9 @@ 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; a later difference starts over.
|
||||
/// account returns to normal, unless a stop is missing; a later difference starts over.
|
||||
/// </summary>
|
||||
public async Task ResolveAsync(OrderManager manager, ReconcileChoice choice, string by, CancellationToken cancellationToken)
|
||||
public async Task<ReconcileResolution> ResolveAsync(OrderManager manager, ReconcileChoice choice, string by, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(manager);
|
||||
var account = manager.Account;
|
||||
@@ -195,17 +222,26 @@ public sealed class Reconciler(Database db, IClock clock, Ledger ledger)
|
||||
}
|
||||
|
||||
// Compared again right now: the choice applies to the differences that exist, never to old ones.
|
||||
await ReconcileAsync(manager, cancellationToken).ConfigureAwait(false);
|
||||
var report = await ReconcileAsync(manager, cancellationToken).ConfigureAwait(false);
|
||||
if (ReconcileOutcomes.IsDown(report.Outcome))
|
||||
{
|
||||
return ReconcileResolution.NotCompared;
|
||||
}
|
||||
|
||||
var state = await StateAsync(account.AccountId, cancellationToken).ConfigureAwait(false);
|
||||
if (state.Mode != AccountModes.Prudent || state.ModeReason == KeyReason)
|
||||
{
|
||||
return;
|
||||
return ReconcileResolution.Normal;
|
||||
}
|
||||
|
||||
// A position without its stop is never "left out": nothing would put the user back on it.
|
||||
var stops = state.Differences.Where(d => d.Kind == DifferenceKinds.Stop).ToList();
|
||||
var choices = state.Differences.Except(stops).ToList();
|
||||
|
||||
var excluded = state.Excluded.ToList();
|
||||
if (choice == ReconcileChoice.Align)
|
||||
{
|
||||
foreach (var difference in state.Differences)
|
||||
foreach (var difference in choices)
|
||||
{
|
||||
if (!await AlignAsync(account, difference, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
@@ -216,24 +252,32 @@ public sealed class Reconciler(Database db, IClock clock, Ledger ledger)
|
||||
}
|
||||
else
|
||||
{
|
||||
excluded.AddRange(state.Differences.Select(d => d.Fingerprint));
|
||||
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.
|
||||
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);
|
||||
await db.WriteAsync(async s =>
|
||||
{
|
||||
await EnsureStatusAsync(s, account.AccountId, now, cancellationToken).ConfigureAwait(false);
|
||||
await s.ExecuteAsync("UPDATE account_status SET mode = @m, mode_since = @now, mode_reason = NULL, differences = @d, last_outcome = @o, updated_at = @now WHERE account_id = @a",
|
||||
cancellationToken, ("m", AccountModes.Normal), ("now", now), ("d", Stored([], excluded.Distinct(StringComparer.Ordinal).ToList())), ("o", outcome),
|
||||
await s.ExecuteAsync("UPDATE account_status SET mode = @m, mode_since = @now, mode_reason = @r, differences = @d, last_outcome = @o, updated_at = @now WHERE account_id = @a",
|
||||
cancellationToken, ("m", mode), ("r", reason), ("now", now), ("d", Stored(stops, excluded.Distinct(StringComparer.Ordinal).ToList())), ("o", outcome),
|
||||
("a", account.AccountId)).ConfigureAwait(false);
|
||||
await s.ExecuteAsync("INSERT INTO reconciliations (id, account_id, outcome, details, occurred_at, created_at) VALUES (@id, @a, @o, @d, @now, @now)", cancellationToken,
|
||||
("id", Ids.NewId(clock)), ("a", account.AccountId), ("o", outcome), ("d", new DbJson(JsonSerializer.Serialize(new { by, differences = state.Differences }))),
|
||||
("now", now)).ConfigureAwait(false);
|
||||
var what = choice == ReconcileChoice.Align ? "ho allineato il registro al conto" : "ho lasciato fuori dal registro ciò che non è mio";
|
||||
await Diary.WriteAsync(s, clock, DiaryKinds.System, "account_resolved", $"Conto {account.Name}: {what}, come hai scelto. Il conto torna normale.",
|
||||
null, cancellationToken).ConfigureAwait(false);
|
||||
var what = (choices.Count, choice) switch
|
||||
{
|
||||
(0, _) => "ho ricontrollato, come hai chiesto",
|
||||
(_, ReconcileChoice.Align) => "ho allineato il registro al conto, come hai scelto",
|
||||
_ => "ho lasciato fuori dal registro ciò che non è mio, come hai scelto",
|
||||
};
|
||||
var then = stops.Count > 0 ? "Resta prudente: " + string.Join(" ", stops.Select(d => d.Message)) : "Il conto torna normale.";
|
||||
await Diary.WriteAsync(s, clock, DiaryKinds.System, "account_resolved", $"Conto {account.Name}: {what}. {then}", null, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
return stops.Count > 0 ? ReconcileResolution.StopsMissing : ReconcileResolution.Normal;
|
||||
}
|
||||
|
||||
public Task<AccountState> StateAsync(Guid accountId, CancellationToken cancellationToken) =>
|
||||
@@ -532,21 +576,34 @@ public sealed class Reconciler(Database db, IClock clock, Ledger ledger)
|
||||
return mode;
|
||||
}
|
||||
|
||||
private async Task RecordUnreachableAsync(AccountContext account, AccountState state, string message, CancellationToken cancellationToken)
|
||||
private async Task<string> RecordDownAsync(AccountContext account, AccountState state, BrokerException failure, CancellationToken cancellationToken)
|
||||
{
|
||||
var now = clock.UtcNow;
|
||||
var outcome = failure.KeyRefused ? ReconcileOutcomes.KeyRefused : ReconcileOutcomes.Unreachable;
|
||||
await db.WriteAsync(async s =>
|
||||
{
|
||||
await EnsureStatusAsync(s, account.AccountId, now, cancellationToken).ConfigureAwait(false);
|
||||
await s.ExecuteAsync("UPDATE account_status SET last_outcome = @o, updated_at = @now WHERE account_id = @a", cancellationToken,
|
||||
("o", ReconcileOutcomes.Unreachable), ("now", now), ("a", account.AccountId)).ConfigureAwait(false);
|
||||
if (state.LastOutcome != ReconcileOutcomes.Unreachable)
|
||||
("o", outcome), ("now", now), ("a", account.AccountId)).ConfigureAwait(false);
|
||||
if (state.LastOutcome == outcome)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (failure.KeyRefused)
|
||||
{
|
||||
await Diary.NotifyAsync(s, clock, "key_refused",
|
||||
$"Il broker non accetta più la chiave del conto {account.Name}: scaduta, revocata o non ammessa da questo indirizzo. Finché non ne inserisci una nuova " +
|
||||
"in Impostazioni, Conti e chiavi, lì non compro, non vendo e non sposto gli stop; quelli già sul conto restano.", cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await Diary.WriteAsync(s, clock, DiaryKinds.System, "reconcile_unreachable",
|
||||
$"Non riesco a riconciliare il conto {account.Name}: il broker non risponde. Riprovo tra 5 minuti.", new { message = Redactor.Redact(message) }, cancellationToken)
|
||||
$"Non riesco a riconciliare il conto {account.Name}: il broker non risponde. Riprovo tra 5 minuti.", new { message = Redactor.Redact(failure.Message) }, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
return outcome;
|
||||
}
|
||||
|
||||
private async Task EnsureStatusAsync(DbSession s, Guid accountId, DateTimeOffset now, CancellationToken cancellationToken) =>
|
||||
|
||||
@@ -118,7 +118,12 @@ public sealed class TradingHttp(HttpClient http, IClock clock, string sourceName
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(answer);
|
||||
var text = answer.Body.Length <= 300 ? answer.Body : answer.Body[..300] + "…";
|
||||
return new BrokerException($"{SourceName}: risposta {(int)answer.Status} da {ApiHttp.Describe(url)}: {Redactor.Redact(text)}", retryable: false);
|
||||
return new BrokerException($"{SourceName}: risposta {(int)answer.Status} da {ApiHttp.Describe(url)}: {Redactor.Redact(text)}", retryable: false)
|
||||
{
|
||||
// OKX answers 401 also to a request signed with a wrong clock (50102, 50112): that is not the key.
|
||||
KeyRefused = answer.Status is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden &&
|
||||
!answer.Body.Contains("\"50102\"", StringComparison.Ordinal) && !answer.Body.Contains("\"50112\"", StringComparison.Ordinal),
|
||||
};
|
||||
}
|
||||
|
||||
private Task WaitAsync(int attempt, CancellationToken cancellationToken) =>
|
||||
|
||||
@@ -984,6 +984,13 @@ public sealed partial class TradingService : IDisposable
|
||||
return entrusted;
|
||||
}
|
||||
|
||||
/// <summary>Changes the shares of a broker's strategies and gives the internal simulator the money its ledgers now hold.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The internal simulator's book holds at least the cash its ledgers give the bot: the simulator has no money of
|
||||
/// its own, it plays the broker for the ledger (SPEC 7.3).
|
||||
|
||||
Reference in new issue
Block a user