Files
Anubis/src/Anubis.Server/Components/Pages/Strategie.razor
T
Alby96andClaude Opus 5.5 13f9c42f61 Add the Operazioni, Strategie and Rischio screens (refs #45)
The three screens follow mockups 03, 04 and 07.

Operazioni shows the balance of the closed trades, filters, a CSV export,
and for each trade why it was bought and sold. The reasons come from the
decision codes through fixed Italian templates.

Strategie shows the four stages towards real money, a card per strategy
with its requirements, the procedure of SPEC 12.4, and why each strategy in
observation waits. A strategy that failed its backtest cannot be moved into
the simulation.

Rischio shows the emergency switch, the automatic blocks, the use of each
limit, the fall from the peak, the scenarios and the risk events. Stop,
close and restart now go through the risk engine. A restart is refused
while the STOP file exists.

Impostazioni gains the limits, the day-trade guard and the scenarios.
Lowering a limit is always allowed. Raising a limit or the entrusted capital
while a strategy uses real money needs the phrase and the password.

The demo now holds the decisions behind its trades, the 58 days of
simulation and the indices of its curves, so it matches the mockups.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 16:14:44 +01:00

235 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>
</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" : ""). 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),
(_, "frase") => ("La frase non corrisponde: scrivila esattamente come è mostrata.", false),
(_, "password") => ("Password o codice non corretti.", 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);
}