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>
This commit is contained in:
1 parent
7041533ce2
commit
13f9c42f61
16 files changed
+2085
-34
No files matched your search
@@ -80,6 +80,15 @@
|
||||
case "lock":
|
||||
<rect x="5" y="10.5" width="14" height="10" rx="2.2" /><path d="M8.5 10.5V7.8a3.5 3.5 0 0 1 7 0v2.7" />
|
||||
break;
|
||||
case "search":
|
||||
<circle cx="11" cy="11" r="6.5" /><path d="m16 16 4 4" />
|
||||
break;
|
||||
case "ban":
|
||||
<circle cx="12" cy="12" r="8.5" /><path d="m6 6 12 12" />
|
||||
break;
|
||||
case "tick":
|
||||
<path d="m5 12.5 4.5 4.5L19 7.5" />
|
||||
break;
|
||||
case "logout":
|
||||
<path d="M14 4h4.5A1.5 1.5 0 0 1 20 5.5v13a1.5 1.5 0 0 1-1.5 1.5H14M10 16l-4-4 4-4M6 12h10" />
|
||||
break;
|
||||
|
||||
@@ -21,6 +21,9 @@
|
||||
"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.",
|
||||
"limiti" => "Limiti di rischio salvati.",
|
||||
"rischio" => "Impostazione del rischio salvata.",
|
||||
|
||||
_ => "Fatto.",
|
||||
})</p>
|
||||
}
|
||||
@@ -30,7 +33,7 @@
|
||||
}
|
||||
|
||||
<nav class="tabs" aria-label="Sezioni delle impostazioni">
|
||||
<a href="#aspetto">Aspetto</a><a href="#conti">Conti</a><a href="#dati">Dati</a><a href="#sicurezza">Sicurezza</a><a href="#sistema">Sistema</a><a href="#modifiche">Modifiche</a>
|
||||
<a href="#aspetto">Aspetto</a><a href="#conti">Conti</a><a href="#rischio">Rischio</a><a href="#dati">Dati</a><a href="#sicurezza">Sicurezza</a><a href="#sistema">Sistema</a><a href="#modifiche">Modifiche</a>
|
||||
</nav>
|
||||
|
||||
<section class="panel" id="aspetto">
|
||||
@@ -135,7 +138,56 @@
|
||||
}
|
||||
</section>
|
||||
|
||||
<section class="panel" id="rischio">
|
||||
<h2>Rischio</h2>
|
||||
<p class="note">I limiti valgono per tutte le strategie insieme. Abbassarli è sempre possibile. @(_anyLive ? "Una strategia usa soldi veri: per alzarne uno servono la frase e la password." : "Finché nessuna strategia usa soldi veri, puoi anche alzarli.")</p>
|
||||
@if (!Shell.IsDemo)
|
||||
{
|
||||
<form method="post" action="/azioni/rischio/limiti" class="form-grid limits-form">
|
||||
<AntiforgeryToken />
|
||||
@foreach (var l in _limits)
|
||||
{
|
||||
<label>@l.Label<input name="@l.Key" value="@l.Value" inputmode="decimal" autocomplete="off" readonly="@l.ReadOnly" /></label>
|
||||
}
|
||||
@if (_anyLive)
|
||||
{
|
||||
<label>Per alzare un limite scrivi: <code>@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>
|
||||
}
|
||||
<button class="btn" type="submit">Salva i limiti</button>
|
||||
</form>
|
||||
<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>
|
||||
<select id="pdt" name="valore" data-autosubmit>
|
||||
<option value="off" selected="@(_pdt == "off")">Spenta</option>
|
||||
<option value="on" selected="@(_pdt == "on")">Accesa</option>
|
||||
</select>
|
||||
<noscript><button class="btn btn-small" type="submit">Salva</button></noscript>
|
||||
</form>
|
||||
<h3>Scenari «Se succedesse domani»</h3>
|
||||
<form method="post" action="/azioni/rischio/@Anubis.Risk.Scenarios.Setting.Key" class="form">
|
||||
<AntiforgeryToken />
|
||||
<label for="scenari">Uno per riga: descrizione; variazione delle crypto %; delle azioni USA %; del dollaro sull'euro %. Per esempio «Le crypto perdono il 20% in un giorno; -20; 0; 0».</label>
|
||||
<textarea id="scenari" name="valore" rows="5" spellcheck="false">@_scenarios</textarea>
|
||||
<button class="btn" type="submit">Salva gli scenari</button>
|
||||
</form>
|
||||
}
|
||||
else
|
||||
{
|
||||
<dl class="facts">
|
||||
@foreach (var l in _limits)
|
||||
{
|
||||
<dt>@l.Label</dt><dd>@l.Value</dd>
|
||||
}
|
||||
</dl>
|
||||
}
|
||||
</section>
|
||||
|
||||
<section class="panel" id="dati">
|
||||
|
||||
<h2>Dati</h2>
|
||||
@if (Host.Services!.MarketData is not { } market)
|
||||
{
|
||||
@@ -302,7 +354,13 @@
|
||||
|
||||
private sealed record BrokerSetup(string Broker, string Title, string Short, IReadOnlyList<BrokerKey> Keys, AccountState? State, EntrustedCapital? Entrusted,
|
||||
IReadOnlyList<StrategyCapital> Strategies);
|
||||
private sealed record LimitField(string Key, string Label, string Value, bool ReadOnly);
|
||||
private readonly List<LimitField> _limits = [];
|
||||
private bool _anyLive;
|
||||
private string _pdt = "off";
|
||||
private string _scenarios = "";
|
||||
private IReadOnlyList<Anubis.Data.SourceState> _sources = [];
|
||||
|
||||
private SettingValue _meetings = new(SettingsStore.CentralBankMeetings.Key, "", false, null);
|
||||
private List<SettingChange> _history = [];
|
||||
private IReadOnlyList<BackupInfo> _backups = [];
|
||||
@@ -328,6 +386,16 @@
|
||||
_history = await services.Settings.HistoryAsync(null, 50, ct);
|
||||
_meetings = await services.Settings.GetAsync(SettingsStore.CentralBankMeetings.Key, ct);
|
||||
_sources = await new Anubis.Data.SourceStateStore(services.Db, Clock).ListAsync(ct);
|
||||
foreach (var definition in Anubis.Risk.RiskSettings.Limits)
|
||||
{
|
||||
var value = await services.Settings.GetAsync(definition.Key, ct);
|
||||
_limits.Add(new LimitField(definition.Key, definition.Label, value.Value, value.ReadOnly));
|
||||
}
|
||||
|
||||
_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);
|
||||
|
||||
_backups = services.Backups.List();
|
||||
var ledger = new Ledger(services.Db, Clock);
|
||||
var capital = new Capital(services.Db, Clock, ledger, new FxStore(services.Db, Clock));
|
||||
@@ -372,6 +440,12 @@
|
||||
"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.",
|
||||
"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.",
|
||||
"scenari" => "Gli scenari non sono validi: una riga ciascuno, con descrizione e tre percentuali separate da punto e virgola.",
|
||||
|
||||
_ => PasswordMessages.For(Errore),
|
||||
};
|
||||
|
||||
|
||||
@@ -1,5 +1,233 @@
|
||||
@inherits LoadedComponent
|
||||
@page "/operazioni"
|
||||
@inject AnubisHost Host
|
||||
@inject ShellData Shell
|
||||
@inject IClock Clock
|
||||
@using Anubis.Trading
|
||||
|
||||
<PageTitle>Operazioni · Anubis</PageTitle>
|
||||
|
||||
<Pending Title="Ancora nessuna operazione chiusa.">Quando il bot comincerà a lavorare, qui troverai ogni operazione con il suo risultato e il perché di ogni ingresso e uscita.</Pending>
|
||||
@{
|
||||
var v = _view;
|
||||
var c = _currency;
|
||||
var f = _filter;
|
||||
}
|
||||
@if (v.Total == 0)
|
||||
{
|
||||
<Pending Title="Ancora nessuna operazione chiusa.">Qui compare ogni operazione quando si chiude: quanto ha reso, quanto è durata e perché il bot ha comprato e venduto. Le strategie in osservazione non operano: le vedi in <a href="/strategie">Strategie</a>.</Pending>
|
||||
}
|
||||
else
|
||||
{
|
||||
<section class="panel head-block trades-head" aria-label="Il bilancio delle operazioni">
|
||||
<div class="half">
|
||||
<p class="lead">Per ogni euro perso ne ha guadagnati</p>
|
||||
<p class="big-number">@(v.PerEuroLost is { } per ? Shell.Money(per, c) : "—")</p>
|
||||
<p class="note">Guadagni incassati finora: <strong class="@(v.Net >= 0 ? "gain" : "loss")">@Shell.Money(v.Net, c, withSign: true)</strong>@(f.Period == "avvio" && f.Strategy is null && f.Account is null ? "" : " con i filtri scelti")</p>
|
||||
<dl class="cells">
|
||||
<div><dt>In guadagno</dt><dd><strong>@v.Winners su @v.Matching</strong><span>@Format.Percent(v.Matching == 0 ? 0 : (decimal)v.Winners / v.Matching * 100m)</span></dd></div>
|
||||
<div><dt>Guadagno medio</dt><dd><strong>@(v.Winners == 0 ? "—" : Shell.Money(v.Gains / v.Winners, c, withSign: true))</strong><span>su @v.Winners @(v.Winners == 1 ? "operazione" : "operazioni")</span></dd></div>
|
||||
<div><dt>Perdita media</dt><dd><strong>@(v.Losers == 0 ? "—" : Shell.Money(v.Losses / v.Losers, c, withSign: true))</strong><span>su @v.Losers @(v.Losers == 1 ? "operazione" : "operazioni")</span></dd></div>
|
||||
<div><dt>Commissioni</dt><dd><strong>@Shell.Money(v.Fees, c)</strong><span>già tolte</span></dd></div>
|
||||
</dl>
|
||||
</div>
|
||||
<div class="half">
|
||||
<h2>Risultato di ogni operazione <span class="note">dalla prima all'ultima; in alto i guadagni, in basso le perdite</span></h2>
|
||||
@if (v.Bars.Count > 0)
|
||||
{
|
||||
var max = Math.Max(1m, v.Bars.Max(b => Math.Abs(b.Eur)));
|
||||
var width = 600m / v.Bars.Count;
|
||||
var best = v.Bars.MaxBy(b => b.Eur);
|
||||
var worst = v.Bars.MinBy(b => b.Eur);
|
||||
<svg class="result-bars" viewBox="0 0 600 180" preserveAspectRatio="none" role="img" aria-label="Risultato di ogni operazione: la migliore @Shell.Money(best.Eur, c, withSign: true) su @best.Symbol, la peggiore @Shell.Money(worst.Eur, c, withSign: true) su @worst.Symbol">
|
||||
<line x1="0" x2="600" y1="90" y2="90" class="axis" />
|
||||
@for (var i = 0; i < v.Bars.Count; i++)
|
||||
{
|
||||
var b = v.Bars[i];
|
||||
var h = Math.Abs(b.Eur) / max * 70m;
|
||||
<rect x="@Css(i * width + width * 0.15m)" y="@Css(b.Eur >= 0 ? 90 - h : 90)" width="@Css(width * 0.7m)" height="@Css(Math.Max(h, 0.5m))" class="@(b.Eur >= 0 ? "gain" : "loss")" />
|
||||
}
|
||||
</svg>
|
||||
<p class="note bars-scale"><span>@Day(v.Bars[0].At)</span><span>@Day(v.Bars[^1].At)</span></p>
|
||||
<p class="note">La migliore <strong class="gain">@Shell.Money(best.Eur, c, withSign: true)</strong> su @best.Symbol, la peggiore <strong class="loss">@Shell.Money(worst.Eur, c, withSign: true)</strong> su @worst.Symbol.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p class="note">Nessuna operazione con questi filtri.</p>
|
||||
}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel" aria-labelledby="elenco">
|
||||
<h2 id="elenco" class="visually-hidden">Operazioni chiuse</h2>
|
||||
<form class="filters" method="get" action="/operazioni">
|
||||
<label class="search"><Icon Name="search" Size="16" /><span class="visually-hidden">Cerca uno strumento</span><input type="search" name="cerca" value="@f.Search" placeholder="Cerca uno strumento" /></label>
|
||||
<label><span class="visually-hidden">Conto</span>
|
||||
<select name="conto" data-autosubmit>
|
||||
<option value="">Tutti i conti</option>
|
||||
@foreach (var (id, name) in v.Accounts)
|
||||
{
|
||||
<option value="@id" selected="@(f.Account == id)">@name</option>
|
||||
}
|
||||
</select>
|
||||
</label>
|
||||
<label><span class="visually-hidden">Strategia</span>
|
||||
<select name="strategia" data-autosubmit>
|
||||
<option value="">Tutte le strategie</option>
|
||||
@foreach (var s in v.Strategies)
|
||||
{
|
||||
<option value="@s" selected="@(f.Strategy == s)">@StrategyNames.Label(s)</option>
|
||||
}
|
||||
</select>
|
||||
</label>
|
||||
<label><span class="visually-hidden">Esito</span>
|
||||
<select name="esito" data-autosubmit>
|
||||
@foreach (var (key, label) in TradeFilter.Results)
|
||||
{
|
||||
<option value="@key" selected="@((f.Result ?? "") == key)">@label</option>
|
||||
}
|
||||
</select>
|
||||
</label>
|
||||
<label><span class="visually-hidden">Periodo</span>
|
||||
<select name="periodo" data-autosubmit>
|
||||
@foreach (var (key, label) in TradeFilter.Periods)
|
||||
{
|
||||
<option value="@key" selected="@(f.Period == key)">@label</option>
|
||||
}
|
||||
</select>
|
||||
</label>
|
||||
<noscript><button class="btn" type="submit">Filtra</button></noscript>
|
||||
<a class="btn" href="/api/operazioni.csv@(f.Query(1))" download><Icon Name="download" Size="18" />Esporta CSV</a>
|
||||
</form>
|
||||
|
||||
@if (v.Rows.Count == 0)
|
||||
{
|
||||
<p class="note">Nessuna operazione con questi filtri.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="trades" role="list">
|
||||
<div class="trade-row trade-header" aria-hidden="true">
|
||||
<span>Chiusa</span><span>Strumento</span><span class="wide">Strategia</span><span class="wide">Durata</span><span class="num wide">Entrata e uscita</span><span class="num">Risultato</span><span class="wide">Perché è stata chiusa</span>
|
||||
</div>
|
||||
@foreach (var t in v.Rows)
|
||||
{
|
||||
var gain = t.RealizedEur >= 0;
|
||||
<details class="trade" role="listitem">
|
||||
<summary class="trade-row">
|
||||
<span class="nowrap">@When(t.ClosedAt)</span>
|
||||
<span><strong>@t.Symbol</strong> <span class="muted">@t.Name</span></span>
|
||||
<span class="wide nowrap"><span class="swatch round" style="background: var(--s-@t.Strategy.Replace('_', '-'))"></span>@StrategyNames.Label(t.Strategy)</span>
|
||||
<span class="wide">@Duration(t)</span>
|
||||
<span class="num wide nowrap">@Format.Money(t.EntryPrice, t.Currency, decimals: t.EntryPrice >= 1m ? 2 : 4) → @Format.Money(t.ExitPrice, t.Currency, decimals: t.ExitPrice >= 1m ? 2 : 4)</span>
|
||||
<span class="num nowrap @(gain ? "gain" : "loss")"><strong>@Shell.Money(t.RealizedEur, c, withSign: true)</strong> <span class="cell-extra">(@Format.Percent(t.Percent, 2, withSign: true))</span></span>
|
||||
<span class="wide">@t.ExitReason</span>
|
||||
</summary>
|
||||
<div class="why">
|
||||
<div class="why-card">
|
||||
<h3>Perché l'ho comprata</h3>
|
||||
@if (t.Bought.Count == 0)
|
||||
{
|
||||
<p class="note">Per questa operazione non c'è la traccia della decisione d'acquisto: è precedente al registro delle decisioni o è stata aperta senza strategia.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<ul class="checks">
|
||||
@foreach (var line in t.Bought)
|
||||
{
|
||||
<li class="@(line.Good ? "ok" : "warn")"><Icon Name="@(line.Good ? "check" : "alert")" Size="16" />@line.Text</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
</div>
|
||||
<div class="why-card">
|
||||
<h3>Perché l'ho venduta</h3>
|
||||
@if (t.Sold.Count == 0)
|
||||
{
|
||||
<p>@t.ExitReason.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<ul class="checks">
|
||||
@foreach (var line in t.Sold)
|
||||
{
|
||||
<li class="@(line.Good ? "ok" : "warn")"><Icon Name="@(line.Good ? "check" : "alert")" Size="16" />@line.Text</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
<dl class="account-lines">
|
||||
<dt>Comprata @Long(t.OpenedAt)</dt><dd><strong>@Format.Quantity(t.Quantity) a @Format.Money(t.EntryPrice, t.Currency, decimals: t.EntryPrice >= 1m ? 2 : 4)</strong></dd>
|
||||
<dt>Venduta @Long(t.ClosedAt)</dt><dd><strong>a @Format.Money(t.ExitPrice, t.Currency, decimals: t.ExitPrice >= 1m ? 2 : 4)</strong></dd>
|
||||
<dt>Differenza dal prezzo atteso</dt><dd><strong>@Slip(t.EntrySlipBp) e @Slip(t.ExitSlipBp)</strong></dd>
|
||||
<dt>Commissioni</dt><dd><strong>@Format.Money(t.Fees, t.Currency)</strong></dd>
|
||||
<dt>Conto</dt><dd>@t.Account</dd>
|
||||
</dl>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
</div>
|
||||
var pages = (v.Matching + TradeFilter.PageSize - 1) / TradeFilter.PageSize;
|
||||
<div class="pager">
|
||||
<span class="note">Mostrate @v.Rows.Count di @v.Matching</span>
|
||||
@if (f.Page > 1)
|
||||
{
|
||||
<a class="btn" href="/operazioni@(f.Query(f.Page - 1))">Più recenti</a>
|
||||
}
|
||||
@if (f.Page < pages)
|
||||
{
|
||||
<a class="btn" href="/operazioni@(f.Query(f.Page + 1))">Più vecchie</a>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
|
||||
@code {
|
||||
private TradesView _view = null!;
|
||||
private TradeFilter _filter = null!;
|
||||
private string _currency = "EUR";
|
||||
|
||||
[CascadingParameter]
|
||||
public HttpContext? HttpContext { get; set; }
|
||||
|
||||
[SupplyParameterFromQuery(Name = "cerca")] public string? Cerca { get; set; }
|
||||
[SupplyParameterFromQuery(Name = "conto")] public string? Conto { get; set; }
|
||||
[SupplyParameterFromQuery(Name = "strategia")] public string? Strategia { get; set; }
|
||||
[SupplyParameterFromQuery(Name = "esito")] public string? Esito { get; set; }
|
||||
[SupplyParameterFromQuery(Name = "periodo")] public string? Periodo { get; set; }
|
||||
[SupplyParameterFromQuery(Name = "pagina")] public string? Pagina { 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);
|
||||
_filter = TradeFilter.Parse(Cerca, Conto, Strategia, Esito, Periodo, Pagina);
|
||||
_view = await TradesView.LoadAsync(services, Clock, _filter, null, ct);
|
||||
}
|
||||
|
||||
private static string Css(decimal value) => value.ToString("0.##", CultureInfo.InvariantCulture);
|
||||
|
||||
private string Local(DateTimeOffset at, string format) => TimeZoneInfo.ConvertTime(at, Shell.Zone).ToString(format, CultureInfo.GetCultureInfo("it-IT"));
|
||||
|
||||
private string When(DateTimeOffset at) => Capital(Local(at, "ddd d MMM, HH:mm"));
|
||||
|
||||
private string Day(DateTimeOffset at) => Local(at, "d MMM");
|
||||
|
||||
private string Long(DateTimeOffset at) => Local(at, "dddd d MMMM, HH:mm");
|
||||
|
||||
private static string Capital(string text) => text.Length == 0 ? text : char.ToUpper(text[0], CultureInfo.GetCultureInfo("it-IT")) + text[1..];
|
||||
|
||||
private static string Duration(TradeRow t)
|
||||
{
|
||||
var days = (int)Math.Round((t.ClosedAt - t.OpenedAt).TotalDays);
|
||||
return days switch
|
||||
{
|
||||
< 1 => "in giornata",
|
||||
1 => "1 giorno",
|
||||
_ => $"{days} giorni",
|
||||
};
|
||||
}
|
||||
|
||||
private static string Slip(decimal? bp) => bp is { } b ? Format.Percent(b / 100m, 2) : "—";
|
||||
}
|
||||
@@ -1,30 +1,298 @@
|
||||
@inherits LoadedComponent
|
||||
@page "/rischio"
|
||||
@inject AnubisHost Host
|
||||
@inject ShellData Shell
|
||||
@inject IClock Clock
|
||||
@using Anubis.Trading
|
||||
@using Anubis.Risk
|
||||
|
||||
<PageTitle>Rischio · Anubis</PageTitle>
|
||||
|
||||
<section class="panel">
|
||||
<h2><Icon Name="shield" Size="18" />Interruttore</h2>
|
||||
@if (_bot == "stopped")
|
||||
{
|
||||
<p class="notice notice-attention" role="status"><Icon Name="alert" Size="16" />"Ferma tutto" è acceso: il bot non apre e non gestisce operazioni finché non lo riattivi.</p>
|
||||
<form method="post" action="/azioni/bot/riattiva" class="form-inline">
|
||||
<AntiforgeryToken />
|
||||
<input type="hidden" name="ritorno" value="/rischio" />
|
||||
<button class="btn" type="submit" data-confirm="Riattivare il bot?">Riattiva il bot</button>
|
||||
</form>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p>"Ferma tutto", in alto, blocca il bot. Dopo averlo usato il bot si riattiva solo da qui, mai da solo e mai da Telegram.</p>
|
||||
}
|
||||
@{
|
||||
var v = _view;
|
||||
var c = _currency;
|
||||
}
|
||||
@if (_message is { } message)
|
||||
{
|
||||
<p class="notice notice-loss" role="status"><Icon Name="alert" Size="16" />@message</p>
|
||||
}
|
||||
<div class="risk-top">
|
||||
<section class="panel" aria-labelledby="interruttore">
|
||||
<div class="panel-head">
|
||||
<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")
|
||||
{
|
||||
<p class="notice notice-attention" role="status"><Icon Name="alert" Size="16" /><span>
|
||||
@if (v.Risk.State.Tripped)
|
||||
{
|
||||
<text>L'interruttore è scattato: il calo dal massimo ha superato il @Format.Percent(v.Limits.DrawdownStop * 100m, 0). </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>
|
||||
}
|
||||
</span></p>
|
||||
@if (v.StopFile)
|
||||
{
|
||||
<p class="note">C'è il file <code>STOP</code> nella cartella dei dati: toglilo, poi conferma qui la ripartenza.</p>
|
||||
}
|
||||
@if (!Shell.IsDemo)
|
||||
{
|
||||
<form method="post" action="/azioni/bot/riattiva" class="form-inline">
|
||||
<AntiforgeryToken />
|
||||
<input type="hidden" name="ritorno" value="/rischio" />
|
||||
<button class="btn" type="submit" disabled="@v.StopFile" data-confirm="@RestartText(v)">Riparti</button>
|
||||
</form>
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
<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)
|
||||
{
|
||||
<div class="choices">
|
||||
<form method="post" action="/azioni/bot/ferma"><AntiforgeryToken /><input type="hidden" name="ritorno" value="/rischio" /><button class="btn btn-danger-solid" type="submit" data-confirm="Ferma tutto: annullo gli ordini in attesa e non apro posizioni finché non riparti da qui. Gli stop restano. Confermi?"><Icon Name="stop" Size="18" />Ferma tutto</button></form>
|
||||
<form method="post" action="/azioni/bot/chiudi"><AntiforgeryToken /><input type="hidden" name="ritorno" value="/rischio" /><button class="btn btn-danger" type="submit" data-confirm="Ferma e chiudi: fermo tutto e vendo a mercato ogni posizione del bot. Ciò che è su un mercato chiuso parte all'apertura e intanto tiene il suo stop. Non si annulla. Confermi?">Ferma e chiudi tutte le posizioni</button></form>
|
||||
</div>
|
||||
}
|
||||
<p class="note">Anche un file chiamato <code>STOP</code> nella cartella dei dati ferma tutto entro un minuto.</p>
|
||||
}
|
||||
</section>
|
||||
<section class="panel" aria-labelledby="blocchi">
|
||||
<h2 id="blocchi">Blocchi automatici</h2>
|
||||
@if (!v.AnyBlock)
|
||||
{
|
||||
<p class="gain status-line"><Icon Name="check" Size="16" />Nessun blocco attivo</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<ul class="blocks">
|
||||
@if (v.Risk.State.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>
|
||||
}
|
||||
@if (v.Risk.State.DailyBlockUntil is { } until && until > Clock.UtcNow)
|
||||
{
|
||||
<li><Icon Name="clock" Size="16" />Perdita del giorno oltre il limite: niente nuovi ingressi fino a @Moment(until).</li>
|
||||
}
|
||||
@if (v.Risk.State.WeeklyHalvingUntil is { } half && half > Clock.UtcNow)
|
||||
{
|
||||
<li><Icon Name="clock" Size="16" />Perdita della settimana oltre il limite: rischio dimezzato fino a @Moment(half).</li>
|
||||
}
|
||||
@if (v.Risk.Measures.Drawdown <= -v.Limits.DrawdownHalf && !v.Risk.State.Tripped)
|
||||
{
|
||||
<li><Icon Name="alert" Size="16" />Calo dal massimo oltre il @Format.Percent(v.Limits.DrawdownHalf * 100m, 0): rischio dimezzato.</li>
|
||||
}
|
||||
@if (v.BotState == "paused")
|
||||
{
|
||||
<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)
|
||||
{
|
||||
<li class="loss"><Icon Name="stop" Size="16" />Ferma tutto acceso.</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
<dl class="block-list">
|
||||
<dt>Prossimo blocco in programma</dt>
|
||||
@if (v.NextCalendarBlock is { } next)
|
||||
{
|
||||
<dd><strong>@Capital(Local(next.From, "dddd d MMMM")), dalle @Local(next.From, "HH:mm") alle @Local(next.To, "HH:mm")</strong><span>@next.Title: in quell'ora non apro posizioni.</span></dd>
|
||||
}
|
||||
else
|
||||
{
|
||||
<dd><span>Nessun dato economico importante nei prossimi 14 giorni.</span></dd>
|
||||
}
|
||||
<dt>Ultimo blocco scattato</dt>
|
||||
@if (v.LastCalendarBlock is { } last)
|
||||
{
|
||||
<dd><strong>@Capital(Local(last.From, "dddd d MMMM")), dalle @Local(last.From, "HH:mm") alle @Local(last.To, "HH:mm")</strong><span>@last.Title.</span></dd>
|
||||
}
|
||||
else
|
||||
{
|
||||
<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>
|
||||
</dl>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section class="panel" aria-labelledby="limiti">
|
||||
<div class="panel-head">
|
||||
<h2 id="limiti">I limiti <span class="note">Valgono per tutte le strategie insieme@(v.World == Worlds.Real ? ", sui conti veri" : ", nel mondo simulato"). Si cambiano dalle <a href="/impostazioni#rischio">impostazioni</a>, mai da soli.</span></h2>
|
||||
</div>
|
||||
<div class="table-wrap">
|
||||
<table class="table limits">
|
||||
<thead>
|
||||
<tr><th scope="col">Limite</th><th scope="col" class="num">Adesso</th><th scope="col" class="wide">Quanto ne sto usando</th><th scope="col" class="num">Soglia</th><th scope="col" class="wide">Se lo supero</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var row in v.Rows)
|
||||
{
|
||||
<tr>
|
||||
<th scope="row">@row.Label</th>
|
||||
<td class="num nowrap">@row.Now@if (row.Detail is { } d) {<text> </text><span class="muted">(@d)</span>}</td>
|
||||
<td class="wide">
|
||||
@if (row.Usage is { } u)
|
||||
{
|
||||
<span class="usage @(u >= 0.8m ? "high" : null)" role="img" aria-label="@Format.Percent(u * 100m, 0) del limite"><span style="width: @Css(u * 100m)%"></span></span>
|
||||
}
|
||||
</td>
|
||||
<td class="num nowrap">@row.Threshold</td>
|
||||
<td class="wide">@row.Beyond</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
<Pending Title="Limiti e scenari non sono ancora attivi.">Limiti di perdita, calo dal massimo, esposizione e scenari arrivano con le strategie e il controllo del rischio.</Pending>
|
||||
|
||||
<div class="columns">
|
||||
<section class="panel" aria-labelledby="calo">
|
||||
<h2 id="calo">Quanto è sceso dal massimo</h2>
|
||||
<p class="note">Ogni fotografia del patrimonio@(v.Risk.State.PeakFrom is { } from ? " dal " + Local(from, "d MMMM") : " dall'avvio"). A zero vuol dire che il portafoglio era al suo punto più alto.</p>
|
||||
@if (v.Drawdown.Count < 2)
|
||||
{
|
||||
<p class="note">Ancora troppo poche fotografie per disegnare la curva.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
var worst = v.Drawdown.MinBy(p => p.Drawdown)!;
|
||||
var floor = Math.Min(-0.01m, worst.Drawdown * 1.2m);
|
||||
var first = v.Drawdown[0].At;
|
||||
var span = Math.Max(1d, (v.Drawdown[^1].At - first).TotalSeconds);
|
||||
string X(DateTimeOffset at) => Css((decimal)((at - first).TotalSeconds / span) * 560m + 30m);
|
||||
string Y(decimal d) => Css(10m + d / floor * 150m);
|
||||
var points = string.Join(' ', v.Drawdown.Select(p => X(p.At) + "," + Y(p.Drawdown)));
|
||||
<svg class="drawdown" viewBox="0 0 600 190" role="img" aria-label="Calo dal massimo: il peggiore @Format.Percent(worst.Drawdown * 100m, 2) il @Local(worst.At, "d MMMM")">
|
||||
<line x1="30" x2="590" y1="10" y2="10" class="axis" />
|
||||
<text x="0" y="14" class="tick">0%</text>
|
||||
<text x="0" y="164" class="tick">@Format.Percent(floor * 100m, 1)</text>
|
||||
<polygon points="30,10 @points @X(v.Drawdown[^1].At),10" class="area" />
|
||||
<polyline points="@points" class="line" />
|
||||
<circle cx="@X(worst.At)" cy="@Y(worst.Drawdown)" r="4" class="dot" />
|
||||
<text x="@X(worst.At)" y="@(Css(Math.Min(180m, 26m + worst.Drawdown / floor * 150m)))" text-anchor="middle" class="label">@Format.Percent(worst.Drawdown * 100m, 2) il @Local(worst.At, "d MMM")</text>
|
||||
</svg>
|
||||
<p class="note">
|
||||
@if (-worst.Drawdown < v.Limits.DrawdownHalf / 5m)
|
||||
{
|
||||
<text>Le soglie del @Format.Percent(v.Limits.DrawdownHalf * 100m, 0) e del @Format.Percent(v.Limits.DrawdownStop * 100m, 0) sono fuori scala: il calo peggiore è rimasto sotto un quinto del limite.</text>
|
||||
}
|
||||
else
|
||||
{
|
||||
<text>A @Format.Percent(-v.Limits.DrawdownHalf * 100m, 0) il rischio si dimezza, a @Format.Percent(-v.Limits.DrawdownStop * 100m, 0) il bot si ferma e aspetta te.</text>
|
||||
}
|
||||
</p>
|
||||
}
|
||||
</section>
|
||||
<section class="panel" aria-labelledby="scenari">
|
||||
<h2 id="scenari">Se succedesse domani</h2>
|
||||
<p class="note">Quanto perderei con le posizioni di adesso. Gli scenari si cambiano in <a href="/impostazioni#rischio">Impostazioni</a>.</p>
|
||||
@if (!v.HasPositions)
|
||||
{
|
||||
<p class="note">Nessuna posizione aperta: oggi nessuno scenario costerebbe nulla.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="table-wrap">
|
||||
<table class="table">
|
||||
<thead><tr><th scope="col">Scenario</th><th scope="col" class="num">Senza stop</th><th scope="col" class="num">Con gli stop</th></tr></thead>
|
||||
<tbody>
|
||||
@foreach (var s in v.Scenarios)
|
||||
{
|
||||
<tr>
|
||||
<th scope="row">@s.Scenario.Label</th>
|
||||
<td class="num nowrap"><strong>@Shell.Money(s.WithoutStops, c, decimals: 0)</strong> <span class="muted">(@Format.Percent(s.WithoutStopsShare * 100m, 1, withSign: true))</span></td>
|
||||
<td class="num nowrap muted">@(s.SameWithStops ? "uguale" : "circa " + Shell.Money(s.WithStops ?? 0m, c, decimals: 0))</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p class="notice notice-attention"><Icon Name="alert" Size="16" />Gli stop non sono una garanzia: in un crollo improvviso il prezzo può saltarli. E nessuno stop protegge dal cambio.</p>
|
||||
}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div class="columns">
|
||||
<section aria-labelledby="mai" class="plain">
|
||||
<h2 id="mai">Cosa il bot non può fare, mai</h2>
|
||||
<ul class="never">
|
||||
<li><Icon Name="ban" Size="16" />Usare soldi presi in prestito o vendere allo scoperto</li>
|
||||
<li><Icon Name="ban" Size="16" />Prelevare o spostare denaro: le chiavi dei conti non lo permettono</li>
|
||||
<li><Icon Name="ban" Size="16" />Toccare posizioni che non ha aperto lui</li>
|
||||
<li><Icon Name="ban" Size="16" />Passare ai soldi veri senza la tua conferma</li>
|
||||
<li><Icon Name="ban" Size="16" />Rischiare di più per recuperare una perdita</li>
|
||||
<li><Icon Name="ban" Size="16" />Comprare di più perché lo suggerisce una notizia o il modello</li>
|
||||
</ul>
|
||||
</section>
|
||||
<section aria-labelledby="eventi" class="plain">
|
||||
<div class="panel-head">
|
||||
<h2 id="eventi">Eventi di rischio</h2>
|
||||
@if (v.Events.Count == 0)
|
||||
{
|
||||
<span class="note">Nessun limite superato dall'avvio</span>
|
||||
}
|
||||
</div>
|
||||
@if (v.Events.Count > 0)
|
||||
{
|
||||
<dl class="events">
|
||||
@foreach (var e in v.Events)
|
||||
{
|
||||
<dt>@Local(e.At, "d MMMM")</dt>
|
||||
<dd class="@(e.Severity is RiskSeverities.Critical or RiskSeverities.High ? "loss" : null)">@e.Message</dd>
|
||||
}
|
||||
</dl>
|
||||
<a href="/diario">Vedi tutto nel diario</a>
|
||||
}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
private string _bot = "active";
|
||||
private RiskView _view = null!;
|
||||
private string _currency = "EUR";
|
||||
private string? _message;
|
||||
|
||||
protected override async Task LoadAsync() =>
|
||||
_bot = (await Host.Services!.Settings.GetAsync(SettingsStore.BotState.Key)).Value;
|
||||
[CascadingParameter]
|
||||
public HttpContext? HttpContext { 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 RiskView.LoadAsync(services, Clock, Shell.Zone, ct);
|
||||
_message = Errore switch
|
||||
{
|
||||
"file-stop" => "Il file STOP è ancora nella cartella dei dati: toglilo prima di ripartire.",
|
||||
"bot" => "Comando non ammesso nello stato attuale del bot.",
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
private static string BotText(string state) => state switch
|
||||
{
|
||||
"active" => "Il bot sta operando",
|
||||
"paused" => "In pausa",
|
||||
_ => "Fermo",
|
||||
};
|
||||
|
||||
private static string RestartText(RiskView v) => v.Risk.State.Tripped
|
||||
? "Riparti: il massimo di riferimento riparte dal patrimonio di adesso e il bot torna a operare. Confermi?"
|
||||
: "Riparti: il bot torna a operare. Confermi?";
|
||||
|
||||
private static string Css(decimal value) => value.ToString("0.##", CultureInfo.InvariantCulture);
|
||||
|
||||
private string Local(DateTimeOffset at, string format) => TimeZoneInfo.ConvertTime(at, Shell.Zone).ToString(format, CultureInfo.GetCultureInfo("it-IT"));
|
||||
|
||||
private string Moment(DateTimeOffset at) => Local(at, "d MMMM 'alle' HH:mm");
|
||||
|
||||
private static string Capital(string text) => text.Length == 0 ? text : char.ToUpper(text[0], CultureInfo.GetCultureInfo("it-IT")) + text[1..];
|
||||
}
|
||||
@@ -1,5 +1,234 @@
|
||||
@inherits LoadedComponent
|
||||
@page "/strategie"
|
||||
@inject AnubisHost Host
|
||||
@inject ShellData Shell
|
||||
@inject IClock Clock
|
||||
@using Anubis.Trading
|
||||
|
||||
<PageTitle>Strategie · Anubis</PageTitle>
|
||||
|
||||
<Pending Title="Le strategie non sono ancora attive.">Arrivano dopo il laboratorio: ognuna con la sua descrizione, i requisiti per passare allo stadio successivo e i risultati.</Pending>
|
||||
@{
|
||||
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);
|
||||
}
|
||||
Reference in new issue
Block a user