Files
Anubis/src/Anubis.Server/Components/Pages/Strategie.razor
T
Alby96andClaude Opus 5.5 9ac159a7db
ci / test (postgres) (push) Successful in 3m52s
ci / test (sqlite) (push) Failing after 2m41s
ci / image (push) Skipped
Fix the defects of the Phase 5 review (refs #41 #42 #43 #44 #45 #46)
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>
2026-11-11 16:48:41 +01:00

247 lines
13 KiB
Plaintext

@inherits LoadedComponent
@page "/strategie"
@inject AnubisHost Host
@inject ShellData Shell
@inject IClock Clock
@using Anubis.Trading
<PageTitle>Strategie · Anubis</PageTitle>
@{
var v = _view;
var c = _currency;
var working = v.Cards.Where(x => x.Stage.Stage != StrategyStages.Observation).ToList();
var watching = v.Cards.Where(x => x.Stage.Stage == StrategyStages.Observation).ToList();
}
@if (_message is { } message)
{
<p class="notice @(_ok ? "notice-gain" : "notice-loss")" role="status"><Icon Name="@(_ok ? "check" : "alert")" Size="16" />@message</p>
}
<section class="panel" aria-labelledby="percorso">
<h2 id="percorso">Il percorso verso i soldi veri <span class="note">Una strategia avanza solo se supera tutti i requisiti e se lo confermi tu. Se peggiora, torna indietro da sola.</span></h2>
<ol class="stages">
@foreach (var (stage, i) in new[] { StrategyStages.Observation, StrategyStages.Simulation, StrategyStages.Reduced, StrategyStages.Real }.Select((s, i) => (s, i)))
{
var here = v.Cards.Where(x => x.Stage.Stage == stage).ToList();
<li class="@(here.Count > 0 ? "here" : null)">
<span class="step">@(i + 1)</span>
<strong>@Capital(StrategyStages.Label(stage))</strong>
<p>@StageText(stage)</p>
<p class="stage-count">
@if (here.Count == 0)
{
<span class="muted">Nessuna strategia</span>
}
else
{
@foreach (var x in here)
{
<span class="swatch round" style="background: @x.Color"></span>
}
<strong>@(here.Count == 1 ? "1 strategia" : $"{here.Count} strategie")</strong>
}
</p>
</li>
}
</ol>
</section>
@foreach (var s in working)
{
var up = s.ResultEur >= 0;
<section class="panel strategy" aria-label="@s.Name">
<div class="strategy-about">
<h2><span class="swatch round" style="background: @s.Color"></span>@s.Name <span class="tag">@(s.Stage.ExitOnly ? "Sola uscita" : "In " + StrategyStages.Label(s.Stage.Stage).ToLower(CultureInfo.GetCultureInfo("it-IT")))</span></h2>
<p>@s.Description</p>
<ul>
@foreach (var rule in s.Rules)
{
<li>@rule</li>
}
</ul>
<p class="note">Conto @s.Account. Capitale assegnato: @Shell.Money(s.CapitalEur, c, decimals: 0).</p>
</div>
<div class="strategy-result">
<p class="strategy-number">@Shell.Money(s.ResultEur, c, withSign: true) <span class="cell-change @(up ? "gain" : "loss")"><Arrow Up="up" />@Format.Percent(s.ResultPercent, 2, withSign: true)</span></p>
@if (s.Curve.Count > 1)
{
var min = s.Curve.Min(p => p.Index);
var max = s.Curve.Max(p => p.Index);
var range = Math.Max(0.0001m, max - min);
var points = string.Join(' ', s.Curve.Select((p, i) => Css(i * 300m / (s.Curve.Count - 1)) + "," + Css(70m - (p.Index - min) / range * 60m)));
<svg class="spark" viewBox="0 0 300 80" role="img" aria-label="Andamento della strategia"><polyline points="@points" style="stroke: @s.Color" /></svg>
}
<dl class="account-lines">
<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">
<h3>Requisiti per @(s.Stage.Stage == StrategyStages.Reduced ? "il reale pieno" : StrategyStages.IsLive(s.Stage.Stage) ? "restare con soldi veri" : "usare soldi veri")</h3>
<ul class="checks">
@foreach (var r in s.Requirements)
{
<li class="@(r.Met ? "ok" : StrategiesView.IsPending(r) ? "wait" : "warn")">
<Icon Name="@(r.Met ? "tick" : StrategiesView.IsPending(r) ? "clock" : "alert")" Size="16" />
<span><strong>@r.Label</strong>: @r.Value <span class="muted">(@r.Target)</span></span>
</li>
}
</ul>
@if (s.Stage.ExitOnly)
{
<p class="notice notice-attention"><Icon Name="alert" Size="16" />Tornata indietro con posizioni vere ancora aperte: le gestisce fino a zero, con i loro stop, senza nuovi acquisti.</p>
}
@if (StrategyStages.IsLive(s.Stage.Stage) && !Shell.IsDemo)
{
<form method="post" action="/azioni/strategie/@s.Stage.Strategy/osservazione" class="form-inline">
<AntiforgeryToken />
<button class="btn btn-danger" type="submit" data-confirm="Togli i soldi veri a questa strategia: torna in simulazione e le posizioni vere restano in sola uscita fino a zero. Confermi?">Togli i soldi veri</button>
</form>
}
@if (s.Stage.Stage is StrategyStages.Simulation or StrategyStages.Reduced)
{
var target = s.Stage.Stage == StrategyStages.Reduced ? "Passa al reale" : "Passa al reale ridotto";
var broker = StrategyNames.BrokerOf(s.Stage.Strategy);
var accounts = v.LiveAccounts.Where(a => a.Broker == broker).ToList();
if (!s.AllMet)
{
<p class="form-inline"><button class="btn" type="button" disabled>@target</button> <span class="note">@(s.DaysToGo is { } d ? $"Disponibile tra {d} {(d == 1 ? "giorno" : "giorni")}, se gli altri requisiti reggono" : "Non ancora: mancano dei requisiti")</span></p>
@if (s.Requirements.Any(r => !r.Met && !StrategiesView.IsPending(r)))
{
<p class="notice notice-attention"><Icon Name="alert" Size="16" />Per ora non merita soldi veri. Resta in simulazione finché non migliora.</p>
}
}
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>
}
else
{
<details class="confirm-live">
<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" : ""). 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)
{
<option value="@a.Id">@a.Name</option>
}
</select>
</label>
<label>Scrivi: <code>@s.Phrase</code><input name="frase" required autocomplete="off" /></label>
<label>Password<input name="password" type="password" required autocomplete="current-password" /></label>
<label>Codice a sei cifre (se attivo)<input name="codice" inputmode="numeric" autocomplete="one-time-code" /></label>
<button class="btn btn-danger" type="submit">Conferma soldi veri</button>
</form>
</details>
}
}
@if (s.Stage.Stage == StrategyStages.Simulation && !Shell.IsDemo)
{
<form method="post" action="/azioni/strategie/@s.Stage.Strategy/osservazione" class="form-inline">
<AntiforgeryToken />
<button class="btn btn-small" type="submit" data-confirm="Riporta la strategia in osservazione: smette di operare nel simulatore. Confermi?">Riporta in osservazione</button>
</form>
}
</div>
</section>
}
<section class="plain" aria-labelledby="osservazione">
<div class="panel-head">
<h2 id="osservazione">In osservazione</h2>
<a href="/laboratorio">Prova una nuova strategia nel laboratorio</a>
</div>
@if (watching.Count == 0)
{
<p class="note">Nessuna strategia di base in osservazione.</p>
}
else
{
<dl class="observing">
@foreach (var s in watching)
{
var report = StrategiesView.ReportOf(s.Stage);
var passed = s.Stage.Qualification?.Passed == true;
<dt>@s.Name</dt>
<dd>
<span>@StrategiesView.ObservationReason(s.Stage)@if (report is not null) {<text> Rapporto: </text><code>@report</code>}</span>
@if (passed && !Shell.IsDemo)
{
<form method="post" action="/azioni/strategie/@s.Stage.Strategy/simulazione"><AntiforgeryToken /><button class="btn btn-small" type="submit">Porta in simulazione</button></form>
}
else if (!passed)
{
<span class="attention nowrap"><Icon Name="alert" Size="16" />@(s.Stage.Qualification?.Verdict.Contains("Alpaca", StringComparison.Ordinal) == true ? "In attesa dei dati" : "Non supera i test")</span>
}
</dd>
}
</dl>
}
</section>
@code {
private StrategiesView _view = null!;
private string _currency = "EUR";
private string? _message;
private bool _ok;
[CascadingParameter]
public HttpContext? HttpContext { get; set; }
[SupplyParameterFromQuery(Name = "ok")]
public string? Ok { get; set; }
[SupplyParameterFromQuery(Name = "errore")]
public string? Errore { get; set; }
protected override async Task LoadAsync()
{
var ct = HttpContext?.RequestAborted ?? CancellationToken.None;
var services = Host.Services!;
_currency = Shell.Effective((await services.Settings.GetAsync(SettingsStore.Currency.Key, ct)).Value);
_view = await StrategiesView.LoadAsync(services, Clock, TradingConsent.From(Host.Config).AllowLive, ct);
(_message, _ok) = (Ok, Errore) switch
{
("simulazione", _) => ("Fatto: la strategia è in simulazione, con ordini finti su prezzi veri.", true),
("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. 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),
(_, { }) => ("Non è stato possibile completare la scelta: riprova.", false),
_ => (null, false),
};
}
private static string StageText(string stage) => stage switch
{
StrategyStages.Observation => "Produce solo segnali, nessun ordine.",
StrategyStages.Simulation => $"Ordini finti su prezzi veri, per almeno {StageBook.SimulationDays} giorni.",
StrategyStages.Reduced => "Soldi veri, con un quarto del capitale.",
_ => "Soldi veri, rischio pieno.",
};
private static string Capital(string text) => text.Length == 0 ? text : char.ToUpper(text[0], CultureInfo.GetCultureInfo("it-IT")) + text[1..];
private static string Css(decimal value) => value.ToString("0.##", CultureInfo.InvariantCulture);
}