An independent review found these, now fixed and tested: - Risk limits could be raised through PUT /api/settings without the phrase and the password. The API now refuses risk keys. - The reference equity counted results twice after reduced to real and after a demotion. Each ledger now keeps a baseline, and carried results stay in the ledger's currency until the reference is computed. - An instrument could be bought by a second strategy in the same account (SPEC 8.6), and purchases under way did not hold their cash, so several purchases sent together could exceed it. Both are refused or shrunk now. - After an automatic trip of the switch there was no way to restart from the interface. Rischio now shows the trip of both worlds and the restart. - The fresh password of SPEC 12.4 could be tried without limit. Five wrong attempts in 15 minutes now lock it. - Observation to simulation skipped the 90 days of live signals. - A new build changed the qualification of a strategy with real money, "Ferma tutto" counted as a critical incident, raising risk ignored demotion conditions in progress, and weekends counted as stock sessions. - The 12.4 confirmation now summarises capital, first purchases and limits, and live strategies show the gap with their simulated twin. The backtest converts each bar with the rate fixed before it opens, the day before, and the report now counts how often correctives and risk changed a decision. crypto_trend is still not passed: the broad universe now falls 32.8%. The outcome file also keeps the qualified parameters. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
17d6b8db38
commit
9ac159a7db
27 files changed
+1015
-532
No files matched your search
@@ -472,6 +472,7 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we
|
||||
.confirm-live summary { list-style: none; align-self: flex-start; display: inline-flex; }
|
||||
.confirm-live summary::-webkit-details-marker { display: none; }
|
||||
.confirm-live[open] summary { margin-bottom: 12px; }
|
||||
.confirm-summary { margin: 0; padding-left: 20px; display: grid; gap: 4px; }
|
||||
.form-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 12px 16px; align-items: end; }
|
||||
.form-grid > p { grid-column: 1 / -1; }
|
||||
.form-grid label { display: flex; flex-direction: column; gap: 6px; font-weight: 550; }
|
||||
|
||||
@@ -443,7 +443,8 @@
|
||||
"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.",
|
||||
"password-rischio" => "Password o codice non corretti. Non ho cambiato nulla.",
|
||||
"password-rischio" => "Password o codice non corretti. Dopo cinque tentativi sbagliati devi aspettare 15 minuti. Non ho cambiato nulla.",
|
||||
"retrocessione-rischio" => "Una strategia con soldi veri ha una condizione di retrocessione in corso: finché dura non si aggiunge rischio. Non ho cambiato nulla.",
|
||||
"scenari" => "Gli scenari non sono validi: una riga ciascuno, con descrizione e tre percentuali separate da punto e virgola.",
|
||||
|
||||
_ => PasswordMessages.For(Errore),
|
||||
|
||||
@@ -254,7 +254,7 @@
|
||||
</ul>
|
||||
@if (r.Notes.Count > 0)
|
||||
{
|
||||
<h3>Ordini non eseguiti come chiesto</h3>
|
||||
<h3>Decisioni e ordini non eseguiti come chiesto</h3>
|
||||
<ul>
|
||||
@foreach (var (reason, count) in r.Notes.OrderByDescending(n => n.Value))
|
||||
{
|
||||
|
||||
@@ -22,14 +22,21 @@
|
||||
<h2 id="interruttore">Interruttore d'emergenza</h2>
|
||||
<span class="link-state @(v.BotState == "active" ? null : "down")"><span class="dot"></span>@BotText(v.BotState)</span>
|
||||
</div>
|
||||
@if (v.BotState == "stopped")
|
||||
@if (v.WaitsForRestart)
|
||||
{
|
||||
<p class="notice notice-attention" role="status"><Icon Name="alert" Size="16" /><span>
|
||||
@if (v.Risk.State.Tripped)
|
||||
@if (v.Tripped.Count > 0)
|
||||
{
|
||||
<text>L'interruttore è scattato: il calo dal massimo ha superato il @Format.Percent(v.Limits.DrawdownStop * 100m, 0). </text>
|
||||
<text>L'interruttore è scattato @string.Join(" e ", v.Tripped.Select(t => Where(t.World))): il calo dal massimo ha superato il @Format.Percent(v.Limits.DrawdownStop * 100m, 0). </text>
|
||||
}
|
||||
@if (v.BotState == "stopped")
|
||||
{
|
||||
<text>Il bot non apre posizioni e non vende per le strategie; gli stop di protezione restano attivi.</text>
|
||||
}
|
||||
else
|
||||
{
|
||||
<text>Lì non apro posizioni e non vendo per le strategie; gli stop di protezione restano attivi. Il resto continua a lavorare.</text>
|
||||
}
|
||||
Il bot non apre posizioni e non vende per le strategie; gli stop di protezione restano attivi.
|
||||
@if (v.CloseAllPending)
|
||||
{
|
||||
<text> Sta vendendo tutte le posizioni: ciò che è su un mercato chiuso parte all'apertura.</text>
|
||||
@@ -48,7 +55,7 @@
|
||||
</form>
|
||||
}
|
||||
}
|
||||
else
|
||||
@if (v.BotState != "stopped")
|
||||
{
|
||||
<p>Con <strong>Ferma tutto</strong> annullo gli ordini in attesa e non apro nuove posizioni. Gli stop di protezione restano attivi, così quello che è aperto non rimane scoperto. Per ripartire serve la tua conferma, da qui.</p>
|
||||
@if (!Shell.IsDemo)
|
||||
@@ -70,9 +77,9 @@
|
||||
else
|
||||
{
|
||||
<ul class="blocks">
|
||||
@if (v.Risk.State.Tripped)
|
||||
@foreach (var t in v.Tripped)
|
||||
{
|
||||
<li class="loss"><Icon Name="alert" Size="16" />Interruttore scattato @(v.Risk.State.TrippedAt is { } at ? "il " + Moment(at) : ""): aspetta la tua conferma.</li>
|
||||
<li class="loss"><Icon Name="alert" Size="16" />Interruttore scattato @Where(t.World) @(t.State.TrippedAt is { } at ? "il " + Moment(at) : ""): aspetta la tua conferma.</li>
|
||||
}
|
||||
@if (v.Risk.State.DailyBlockUntil is { } until && until > Clock.UtcNow)
|
||||
{
|
||||
@@ -90,7 +97,7 @@
|
||||
{
|
||||
<li><Icon Name="pause" Size="16" />Bot in pausa: niente nuovi ingressi, stop e uscite proseguono.</li>
|
||||
}
|
||||
@if (v.BotState == "stopped" && !v.Risk.State.Tripped)
|
||||
@if (v.BotState == "stopped" && v.Tripped.Count == 0)
|
||||
{
|
||||
<li class="loss"><Icon Name="stop" Size="16" />Ferma tutto acceso.</li>
|
||||
}
|
||||
@@ -284,7 +291,9 @@
|
||||
_ => "Fermo",
|
||||
};
|
||||
|
||||
private static string RestartText(RiskView v) => v.Risk.State.Tripped
|
||||
private static string Where(string world) => world == Worlds.Real ? "sui conti veri" : "nel mondo simulato";
|
||||
|
||||
private static string RestartText(RiskView v) => v.Tripped.Count > 0
|
||||
? "Riparti: il massimo di riferimento riparte dal patrimonio di adesso e il bot torna a operare. Confermi?"
|
||||
: "Riparti: il bot torna a operare. Confermi?";
|
||||
|
||||
|
||||
@@ -75,6 +75,10 @@
|
||||
<dt>Calo peggiore</dt><dd><strong>@Format.Percent(s.WorstFall * 100m, 1)</strong></dd>
|
||||
<dt>Operazioni chiuse</dt><dd><strong>@s.Closed@(s.Closed > 0 ? $", di cui {s.Winners} in guadagno" : "")</strong></dd>
|
||||
<dt>Posizioni aperte</dt><dd><strong>@(s.Open.Count == 0 ? "nessuna" : string.Join(", ", s.Open.Distinct()))</strong></dd>
|
||||
@if (s.TwinGap is { } gap)
|
||||
{
|
||||
<dt>Rispetto al gemello simulato</dt><dd><strong>@Format.Percent(gap, 2, withSign: true)</strong> <span class="muted">del capitale usato</span></dd>
|
||||
}
|
||||
</dl>
|
||||
</div>
|
||||
<div class="strategy-steps">
|
||||
@@ -122,7 +126,14 @@
|
||||
<summary class="btn">@target</summary>
|
||||
<form method="post" action="/azioni/strategie/@s.Stage.Strategy/reale" class="form-grid">
|
||||
<AntiforgeryToken />
|
||||
<p>Stai per affidare soldi veri a <strong>@s.Name</strong>@(s.Stage.Stage == StrategyStages.Simulation ? ", con un quarto del capitale" : ""). Per confermare scrivi la frase qui sotto e la tua password.</p>
|
||||
<p>Stai per affidare soldi veri a <strong>@s.Name</strong>@(s.Stage.Stage == StrategyStages.Simulation ? ", con un quarto del capitale" : ""). Ecco cosa cambia:</p>
|
||||
<ul class="confirm-summary">
|
||||
@foreach (var line in s.Summary)
|
||||
{
|
||||
<li>@line</li>
|
||||
}
|
||||
</ul>
|
||||
<p>Per confermare scrivi la frase qui sotto e la tua password.</p>
|
||||
<label>Conto reale
|
||||
<select name="conto" required>
|
||||
@foreach (var a in accounts)
|
||||
@@ -210,8 +221,9 @@
|
||||
("osservazione", _) => ("Fatto: la strategia è in osservazione.", true),
|
||||
("reale", _) => ("Fatto: la strategia usa soldi veri da adesso. Se peggiora torna indietro da sola.", true),
|
||||
(_, "backtest") => ("Solo una strategia che ha superato il backtest può andare in simulazione.", false),
|
||||
(_, "osservazione-giorni") => ($"Prima della simulazione servono almeno {StageBook.ObservationDays} giorni di segnali raccolti dal vivo in osservazione.", false),
|
||||
(_, "frase") => ("La frase non corrisponde: scrivila esattamente come è mostrata.", false),
|
||||
(_, "password") => ("Password o codice non corretti.", false),
|
||||
(_, "password") => ("Password o codice non corretti. Dopo cinque tentativi sbagliati devi aspettare 15 minuti.", false),
|
||||
(_, "requisiti") => ("Non tutti i requisiti sono soddisfatti.", false),
|
||||
(_, "conto") => ("Il conto scelto non è il conto reale del broker di questa strategia.", false),
|
||||
(_, "consenso") => ("La configurazione d'avvio non consente i soldi veri.", false),
|
||||
|
||||
@@ -133,6 +133,13 @@ internal static partial class Endpoints
|
||||
return Error(StatusCodes.Status400BadRequest, "usa_i_comandi", "Lo stato del bot si cambia con pausa, ripresa e Ferma tutto.");
|
||||
}
|
||||
|
||||
// Risk limits go only through the settings page, which checks their order and asks for the confirmation of
|
||||
// SPEC 12.4 when a limit goes up while a strategy uses real money: the check holds on the API too.
|
||||
if (Anubis.Risk.RiskSettings.All.Any(d => d.Key == key))
|
||||
{
|
||||
return Error(StatusCodes.Status400BadRequest, "usa_le_impostazioni", "I limiti di rischio si cambiano da Impostazioni, con la conferma quando servono soldi veri.");
|
||||
}
|
||||
|
||||
return await SetSettingAsync(host, key, body.Value, context, ct).ConfigureAwait(false);
|
||||
});
|
||||
|
||||
@@ -252,6 +259,10 @@ internal static partial class Endpoints
|
||||
{
|
||||
var settings = host.Services!.Settings;
|
||||
var current = (await settings.GetAsync(SettingsStore.BotState.Key, ct).ConfigureAwait(false)).Value;
|
||||
|
||||
// A switch tripped by the fall from the high stops only its world and leaves the bot "active": the restart is
|
||||
// the user's confirmation for that world too (SPEC 9.2, 9.3).
|
||||
var tripped = host.Services.Trading?.Risk is { } engine && await engine.AnyTrippedAsync(ct).ConfigureAwait(false);
|
||||
var target = command switch
|
||||
{
|
||||
"pause" or "pausa" when current == "active" => "paused",
|
||||
@@ -259,6 +270,7 @@ internal static partial class Endpoints
|
||||
"stop" or "ferma" => "stopped",
|
||||
"close" or "chiudi" => "stopped",
|
||||
"restart" or "riattiva" when current == "stopped" => "active",
|
||||
"restart" or "riattiva" when tripped => current,
|
||||
_ => null,
|
||||
};
|
||||
if (target is null)
|
||||
|
||||
@@ -294,7 +294,7 @@ internal static partial class Forms
|
||||
}
|
||||
|
||||
/// <summary>The capital entrusted to a broker, in euro (SPEC 7.1, 8.6): only the user sets it.</summary>
|
||||
private static async Task<IResult> SetCapitalAsync(string broker, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
||||
private static async Task<IResult> SetCapitalAsync(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))
|
||||
@@ -314,7 +314,7 @@ internal static partial class Forms
|
||||
|
||||
// More capital while a strategy of this broker has real money is more risk: it needs the procedure (SPEC 12.4).
|
||||
if ((await trading.Capital.EntrustedAsync(broker, ct).ConfigureAwait(false))?.AmountEur is { } before && amount > before &&
|
||||
await RaiseRefusalAsync(host.Services!, broker, form, ct).ConfigureAwait(false) is { } refusal)
|
||||
await RaiseRefusalAsync(host.Services!, clock, broker, form, ct).ConfigureAwait(false) is { } refusal)
|
||||
{
|
||||
return Results.Redirect(back + "?errore=" + refusal + "#conti");
|
||||
}
|
||||
@@ -392,6 +392,8 @@ internal static partial class Forms
|
||||
"phrase" => "frase",
|
||||
"password" => "password",
|
||||
"requirements" => "requisiti",
|
||||
"backtest" => "backtest",
|
||||
"observation" => "osservazione-giorni",
|
||||
"account" => "conto",
|
||||
Anubis.Risk.RiskReasons.NoConsent => "consenso",
|
||||
_ => "scelta",
|
||||
@@ -404,7 +406,7 @@ internal static partial class Forms
|
||||
/// The risk limits (SPEC 9.2, 13.5), all at once. Lowering is always allowed; raising any of them while a strategy
|
||||
/// has real money needs the phrase, the password and the second factor (SPEC 12.4).
|
||||
/// </summary>
|
||||
private static async Task<IResult> SetLimitsAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
||||
private static async Task<IResult> SetLimitsAsync(IFormCollection form, AnubisHost host, IClock clock, HttpContext context, CancellationToken ct)
|
||||
{
|
||||
const string back = "/impostazioni";
|
||||
if (host.IsDemo || host.Services is not { } services)
|
||||
@@ -440,7 +442,7 @@ internal static partial class Forms
|
||||
|
||||
if (Anubis.Risk.RiskSettings.From(k => current[k]).RaisedBy(limits))
|
||||
{
|
||||
if (await RaiseRefusalAsync(services, null, form, ct).ConfigureAwait(false) is { } refusal)
|
||||
if (await RaiseRefusalAsync(services, clock, null, form, ct).ConfigureAwait(false) is { } refusal)
|
||||
{
|
||||
return Results.Redirect(back + "?errore=" + refusal + "#rischio");
|
||||
}
|
||||
@@ -469,9 +471,10 @@ internal static partial class Forms
|
||||
}
|
||||
|
||||
/// <summary>Null when more risk may go ahead; otherwise the error code for the page.</summary>
|
||||
private static async Task<string?> RaiseRefusalAsync(AppServices services, string? broker, IFormCollection form, CancellationToken ct)
|
||||
private static async Task<string?> RaiseRefusalAsync(AppServices services, IClock clock, string? broker, IFormCollection form, CancellationToken ct)
|
||||
{
|
||||
var stages = services.Trading?.Stages ?? new Anubis.Trading.StageBook(services.Db, new SystemClock(), Anubis.Trading.TradingConsent.None, (_, _, _) => Task.FromResult(false));
|
||||
// Without the trading engine no strategy can hold real money, so the stage book only has to say so.
|
||||
var stages = services.Trading?.Stages ?? new Anubis.Trading.StageBook(services.Db, clock, Anubis.Trading.TradingConsent.None, (_, _, _) => Task.FromResult(false));
|
||||
try
|
||||
{
|
||||
var code = form["codice"].ToString();
|
||||
@@ -480,7 +483,12 @@ internal static partial class Forms
|
||||
}
|
||||
catch (Anubis.Trading.LiveConfirmationException ex)
|
||||
{
|
||||
return ex.Code == "phrase" ? "frase-rischio" : "password-rischio";
|
||||
return ex.Code switch
|
||||
{
|
||||
"phrase" => "frase-rischio",
|
||||
"demotion" => "retrocessione-rischio",
|
||||
_ => "password-rischio",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -83,6 +83,8 @@ internal static class LabText
|
||||
BacktestReasons.NoShortSelling => "Vendite allo scoperto rifiutate",
|
||||
BacktestReasons.WrittenOff => "Residui sotto il minimo lasciati dopo un'uscita",
|
||||
BacktestReasons.Dividend => "Dividendi incassati",
|
||||
_ when reason.StartsWith(BacktestReasons.AdjustedPrefix, StringComparison.Ordinal) =>
|
||||
"Decisioni cambiate da correttivi e rischio (" + ReasonTexts.Text(reason[BacktestReasons.AdjustedPrefix.Length..]).TrimEnd('.') + ")",
|
||||
_ => "Ordini sotto il minimo dello strumento, non inviati",
|
||||
};
|
||||
}
|
||||
@@ -30,9 +30,13 @@ internal sealed record RiskView(
|
||||
(DateTimeOffset From, DateTimeOffset To, string Title)? NextCalendarBlock,
|
||||
(DateTimeOffset From, DateTimeOffset To, string Title)? LastCalendarBlock,
|
||||
bool PdtGuard,
|
||||
bool HasPositions)
|
||||
bool HasPositions,
|
||||
IReadOnlyList<WorldRisk> Tripped)
|
||||
{
|
||||
public bool AnyBlock => Risk.State.Tripped || Risk.EntriesBlocked || Risk.Multiplier < 1m || BotState != "active";
|
||||
public bool AnyBlock => Tripped.Count > 0 || Risk.EntriesBlocked || Risk.Multiplier < 1m || BotState != "active";
|
||||
|
||||
/// <summary>The switch tripped by itself in a world (SPEC 9.2): it waits for the user's restart, like "Ferma tutto".</summary>
|
||||
public bool WaitsForRestart => BotState == "stopped" || Tripped.Count > 0;
|
||||
|
||||
public static async Task<RiskView> LoadAsync(AppServices services, IClock clock, TimeZoneInfo zone, CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -44,6 +48,20 @@ internal sealed record RiskView(
|
||||
var accounts = await AccountsView.LoadAsync(services, clock, zone, cancellationToken).ConfigureAwait(false);
|
||||
var world = accounts.Accounts.Any(a => TradingEnvironments.World(a.Environment) == Worlds.Real) ? Worlds.Real : Worlds.Simulated;
|
||||
var risk = await engine.WorldAsync(world, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// Both worlds: a switch tripped in the simulation must show even when the page measures the real one.
|
||||
var tripped = new List<WorldRisk>();
|
||||
foreach (var w in new[] { Worlds.Real, Worlds.Simulated })
|
||||
{
|
||||
var each = w == world ? risk : await engine.WorldAsync(w, cancellationToken).ConfigureAwait(false);
|
||||
if (each.State.Tripped)
|
||||
{
|
||||
tripped.Add(each);
|
||||
}
|
||||
}
|
||||
|
||||
// Weights, crypto and the risk of a trade are measured on the reference equity, as the risk engine does (SPEC 9.2).
|
||||
var reference = await engine.ReferenceAsync(cancellationToken).ConfigureAwait(false);
|
||||
var bot = (await services.Settings.GetAsync(SettingsStore.BotState.Key, cancellationToken).ConfigureAwait(false)).Value;
|
||||
var now = clock.UtcNow;
|
||||
|
||||
@@ -80,13 +98,13 @@ internal sealed record RiskView(
|
||||
$"A {Pct(-limits.DrawdownHalf, 0)} dimezzo il rischio. A {Pct(-limits.DrawdownStop, 0)} fermo tutto e aspetto te", RiskSettings.DrawdownStop.Key),
|
||||
new("Capitale investito", equity > 0m ? Pct(accounts.InvestedEur / equity, 1) : "—", null, equity > 0m ? Use(accounts.InvestedEur / equity, limits.MaxInvested) : null,
|
||||
Pct(limits.MaxInvested, 0), "Non compro altro: non uso mai soldi presi in prestito", RiskSettings.MaxInvested.Key),
|
||||
new("Peso di una sola posizione", biggest is null || equity <= 0m ? "—" : Pct(biggest.ValueEur / equity, 1), biggest?.Symbol,
|
||||
biggest is null || equity <= 0m ? 0m : Use(biggest.ValueEur / equity, limits.MaxPosition), Pct(limits.MaxPosition, 0), "Riduco la posizione fino alla soglia",
|
||||
new("Peso di una sola posizione", biggest is null || reference <= 0m ? "—" : Pct(biggest.ValueEur / reference, 1), biggest?.Symbol,
|
||||
biggest is null || reference <= 0m ? 0m : Use(biggest.ValueEur / reference, limits.MaxPosition), Pct(limits.MaxPosition, 0), "Riduco la posizione fino alla soglia",
|
||||
RiskSettings.MaxPosition.Key),
|
||||
new("Crypto sul totale", equity > 0m ? Pct(crypto / equity, 1) : "—", null, equity > 0m ? Use(crypto / equity, limits.MaxCrypto) : null, Pct(limits.MaxCrypto, 0),
|
||||
new("Crypto sul totale", reference > 0m ? Pct(crypto / reference, 1) : "—", null, reference > 0m ? Use(crypto / reference, limits.MaxCrypto) : null, Pct(limits.MaxCrypto, 0),
|
||||
"Niente nuovi acquisti di crypto", RiskSettings.MaxCrypto.Key),
|
||||
new("Rischio di una singola operazione", atRisk.Count == 0 || equity <= 0m ? "—" : Pct(atRisk.Average() / equity), atRisk.Count == 0 ? null : "in media, fino allo stop",
|
||||
atRisk.Count == 0 || equity <= 0m ? 0m : Use(atRisk.Average() / equity, limits.MaxTradeRisk), Pct(limits.MaxTradeRisk), "Rimpicciolisco l'ordine prima di inviarlo",
|
||||
new("Rischio di una singola operazione", atRisk.Count == 0 || reference <= 0m ? "—" : Pct(atRisk.Average() / reference), atRisk.Count == 0 ? null : "in media, oggi fino allo stop",
|
||||
atRisk.Count == 0 || reference <= 0m ? 0m : Use(atRisk.Average() / reference, limits.MaxTradeRisk), Pct(limits.MaxTradeRisk), "All'acquisto rimpicciolisco l'ordine prima di inviarlo",
|
||||
RiskSettings.MaxTradeRisk.Key),
|
||||
new("Ordini al minuto", perMinute.ToString(System.Globalization.CultureInfo.InvariantCulture), null, Use(perMinute, limits.OrdersPerMinute),
|
||||
limits.OrdersPerMinute.ToString(System.Globalization.CultureInfo.InvariantCulture), "Mi fermo e ti avviso: può essere un guasto", RiskSettings.OrdersPerMinute.Key),
|
||||
@@ -115,7 +133,7 @@ internal sealed record RiskView(
|
||||
|
||||
return new RiskView(bot, engine.StopRequested, (await engine.BotAsync(cancellationToken).ConfigureAwait(false)).CloseAll, world, risk, limits, rows, drawdown, scenarios,
|
||||
await engine.EventsAsync(8, cancellationToken).ConfigureAwait(false), next, last, await RiskSettings.PdtGuardAsync(services.Settings, cancellationToken).ConfigureAwait(false),
|
||||
positions.Count > 0);
|
||||
positions.Count > 0, tripped);
|
||||
}
|
||||
|
||||
private static decimal? Worst(IReadOnlyList<IndexPoint> index, DateTimeOffset? from)
|
||||
|
||||
@@ -24,7 +24,9 @@ internal sealed record StrategyCard(
|
||||
IReadOnlyList<(DateTimeOffset At, decimal Index)> Curve,
|
||||
IReadOnlyList<Requirement> Requirements,
|
||||
string Phrase,
|
||||
int? DaysToGo)
|
||||
int? DaysToGo,
|
||||
IReadOnlyList<string> Summary,
|
||||
decimal? TwinGap)
|
||||
{
|
||||
public string Color => "var(--s-" + Stage.Strategy.Replace('_', '-') + ")";
|
||||
|
||||
@@ -74,6 +76,11 @@ internal sealed record StrategiesView(IReadOnlyList<StrategyCard> Cards, bool Li
|
||||
.ConfigureAwait(false);
|
||||
var equities = await ledger.EquitiesAsync(cancellationToken).ConfigureAwait(false);
|
||||
var positions = await ledger.PositionsAsync(null, cancellationToken).ConfigureAwait(false);
|
||||
var limits = await Anubis.Risk.RiskSettings.LoadAsync(services.Settings, cancellationToken).ConfigureAwait(false);
|
||||
decimal? reference = services.Trading?.Risk is { } risk ? await risk.ReferenceAsync(cancellationToken).ConfigureAwait(false) : null;
|
||||
async Task<string> SymbolAsync(Guid instrument) =>
|
||||
await services.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT symbol FROM instruments WHERE id = @id", r => r.Text("symbol"), ("id", instrument)), cancellationToken)
|
||||
.ConfigureAwait(false) ?? "?";
|
||||
var cards = new List<StrategyCard>();
|
||||
foreach (var stage in await stages.AllAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
@@ -112,8 +119,45 @@ internal sealed record StrategiesView(IReadOnlyList<StrategyCard> Cards, bool Li
|
||||
var symbols = new List<string>();
|
||||
foreach (var p in positions.Where(p => p.AccountId == ledgerAccount && p.Strategy == stage.Strategy))
|
||||
{
|
||||
symbols.Add(await services.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT symbol FROM instruments WHERE id = @id", r => r.Text("symbol"), ("id", p.InstrumentId)),
|
||||
cancellationToken).ConfigureAwait(false) ?? "?");
|
||||
symbols.Add(await SymbolAsync(p.InstrumentId).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
// What the confirmation of SPEC 12.4 changes: the capital used, the purchases of the first cycle (estimated
|
||||
// from what the simulation holds today) and the limits with their base.
|
||||
var summary = new List<string>();
|
||||
if (stage.Stage is StrategyStages.Simulation or StrategyStages.Reduced)
|
||||
{
|
||||
var toReduced = stage.Stage == StrategyStages.Simulation;
|
||||
var factor = toReduced ? StrategyStages.ReducedShare : 1m;
|
||||
var simEquity = equities.FirstOrDefault(e => e.AccountId == stage.AccountId && e.Strategy == stage.Strategy);
|
||||
var simUsd = accounts.FirstOrDefault(a => a.Id == stage.AccountId).Currency == "USD";
|
||||
decimal SimEur(decimal amount) => simUsd ? (rate > 0m ? amount / rate : 0m) : amount;
|
||||
summary.Add(toReduced
|
||||
? $"Capitale usato: un quarto di quello assegnato, {Format.Money(SimEur(simEquity?.Flows ?? 0m) * factor, decimals: 0)}."
|
||||
: $"Capitale usato: tutto quello assegnato, {Format.Money(SimEur(simEquity?.Flows ?? 0m), decimals: 0)}.");
|
||||
var buys = new List<string>();
|
||||
foreach (var p in positions.Where(p => p.AccountId == stage.AccountId && p.Strategy == stage.Strategy && p.Quantity > 0m))
|
||||
{
|
||||
buys.Add($"{await SymbolAsync(p.InstrumentId).ConfigureAwait(false)} per circa {Format.Money(SimEur(p.Value) * factor, decimals: 0)}");
|
||||
}
|
||||
|
||||
summary.Add(buys.Count == 0
|
||||
? "Acquisti al primo ciclo: nessuno per ora, la simulazione non tiene posizioni."
|
||||
: (toReduced ? "Acquisti al primo ciclo, stimati da ciò che la simulazione tiene oggi: " : "Al primo ciclo le posizioni vere crescono fino alla misura piena: ") +
|
||||
string.Join(", ", buys) + ".");
|
||||
summary.Add("Limiti che valgono: perdita in un giorno " + Format.Percent(limits.DailyLoss * 100m, 1) + ", calo dal massimo " +
|
||||
Format.Percent(limits.DrawdownHalf * 100m, 0) + " e " + Format.Percent(limits.DrawdownStop * 100m, 0) + ", una posizione " +
|
||||
Format.Percent(limits.MaxPosition * 100m, 0) + ", rischio di un'operazione " + Format.Percent(limits.MaxTradeRisk * 100m, 1) +
|
||||
", misurati sul patrimonio di riferimento" + (reference is { } r ? $" (oggi {Format.Money(r, decimals: 0)})" : "") +
|
||||
(toReduced ? ", e in reale ridotto su un quarto di esso." : "."));
|
||||
}
|
||||
|
||||
// The simulated twin against the real account (SPEC 12.3): the gap of results, as a share of the capital used.
|
||||
decimal? twinGap = null;
|
||||
if (stage.HasTwin && stage.AccountId is { } twinAccount &&
|
||||
equities.FirstOrDefault(e => e.AccountId == twinAccount && e.Strategy == stage.Strategy) is { Flows: > 0m } twin && equity is { Flows: > 0m } real)
|
||||
{
|
||||
twinGap = ((real.Equity - real.Flows) / real.Flows * 100m) - ((twin.Equity - twin.Flows) / twin.Flows * 100m);
|
||||
}
|
||||
|
||||
var requirements = await stages.RequirementsAsync(stage.Strategy, cancellationToken).ConfigureAwait(false);
|
||||
@@ -126,7 +170,7 @@ internal sealed record StrategiesView(IReadOnlyList<StrategyCard> Cards, bool Li
|
||||
cards.Add(new StrategyCard(stage, StrategyNames.Label(stage.Strategy, withMarket: true) + (stage.Strategy == StrategyNames.CryptoTrend ? "" : " USA"),
|
||||
family?.Description ?? "", Rules.GetValueOrDefault(stage.Strategy) ?? [], account.Name ?? "—", account.Currency ?? "EUR", Eur(flows), Eur(result),
|
||||
flows > 0m ? result / flows * 100m : 0m, worst, trades.Count, trades.Count(r => r >= 0m), symbols, [.. curve.Where(p => p.At >= since || stage.StageSince is null)],
|
||||
requirements, StageBook.Phrase(stage.Strategy, next), toGo));
|
||||
requirements, StageBook.Phrase(stage.Strategy, next), toGo, summary, twinGap));
|
||||
}
|
||||
|
||||
var live = accounts.Where(a => a.Environment == TradingEnvironments.Live).Select(a => (a.Id, a.Name, a.Broker)).ToList();
|
||||
|
||||
Reference in new issue
Block a user