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:
Alby96andClaude Opus 5.5 committed 2026-11-11 16:14:44 +01:00
1 parent 7041533ce2
commit 13f9c42f61
16 files changed
+2085 -34

No files matched your search

+151
View File
@@ -224,6 +224,7 @@ textarea {
.panel > h2 { display: flex; align-items: center; gap: 10px; margin-bottom: 12px; }
.panel > h3, .panel h3 { margin: 20px 0 8px; }
.note { color: var(--text-3); font-size: 13px; line-height: 18px; }
h2 .note, h3 .note { font-weight: 400; letter-spacing: 0; }
.hint { color: var(--text-3); font-size: 13px; line-height: 18px; }
.empty { display: flex; flex-direction: column; gap: 8px; color: var(--text-2); max-width: 70ch; }
.empty-title { color: var(--text); font-weight: 600; font-size: 15px; }
@@ -389,6 +390,137 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we
.currency-lines dd { margin: 0; text-align: right; }
.fx-warning { margin-top: 16px; }
/* ---- Operazioni ---- */
.visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
.trades-head .lead { margin-top: 0; }
.trades-head .big-number { margin-top: 8px; }
.trades-head .note { margin-top: 10px; }
.trades-head h2 { display: flex; align-items: baseline; gap: 12px; flex-wrap: wrap; }
.cells { margin-bottom: 0; }
.cells > div { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
.cells dt { color: var(--text-3); font-size: 13px; }
.cells dd { margin: 0; display: flex; flex-direction: column; gap: 2px; }
.cells dd strong { font-size: 18px; line-height: 24px; font-weight: 650; letter-spacing: -0.015em; font-variant-numeric: tabular-nums; }
.cells dd span { color: var(--text-3); font-size: 13px; }
.result-bars { display: block; width: 100%; height: 170px; margin-top: 16px; }
.result-bars .axis { stroke: var(--rule); stroke-width: 1; vector-effect: non-scaling-stroke; }
.result-bars rect.gain { fill: var(--gain); }
.result-bars rect.loss { fill: var(--loss); }
.bars-scale { display: flex; justify-content: space-between; gap: 12px; flex-wrap: wrap; }
.filters { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin-bottom: 16px; }
.filters .btn:last-child { margin-left: auto; }
.search { position: relative; flex: 1 1 240px; display: flex; align-items: center; }
.search .icon { position: absolute; left: 14px; color: var(--text-3); pointer-events: none; }
.search input { width: 100%; padding-left: 40px !important; }
.trades { display: flex; flex-direction: column; margin: 0 -22px; }
.trade-row {
display: grid; grid-template-columns: 116px minmax(0, 1fr) 128px 70px 176px 146px minmax(0, 1.7fr) 20px;
gap: 12px; align-items: center; padding: 14px 22px; border-bottom: 1px solid var(--rule-inner); font-variant-numeric: tabular-nums;
}
.trade-header { color: var(--text-3); font-size: 13px; padding-top: 4px; padding-bottom: 8px; border-bottom: 1px solid var(--rule); }
.trade-header::after { content: ""; }
.trade-row .num { text-align: right; }
.trade summary { list-style: none; cursor: pointer; }
.trade summary::-webkit-details-marker { display: none; }
.trade summary::after {
content: ""; justify-self: end; width: 8px; height: 8px; margin-right: 4px;
border-right: 2px solid var(--text-2); border-bottom: 2px solid var(--text-2); transform: rotate(45deg) translateY(-3px);
}
.trade[open] summary::after { transform: rotate(-135deg) translateY(-3px); }
.trade summary:hover { background: var(--surface-2); }
.trade[open] { background: var(--surface-2); }
.trade[open] summary { border-bottom: 0; }
.why { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 20px; padding: 4px 22px 22px; border-bottom: 1px solid var(--rule-inner); }
.why-card { background: var(--surface); border: 1px solid var(--rule); border-radius: 12px; padding: 18px 20px; display: flex; flex-direction: column; gap: 10px; }
.why-card h3 { margin: 0 !important; }
.why-card .account-lines { margin-top: 4px; }
.checks { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; }
.checks li { display: flex; align-items: flex-start; gap: 10px; }
.checks .icon { margin-top: 2px; }
.checks .ok .icon { color: var(--gain); }
.checks .warn { color: var(--attention); }
.checks .wait .icon { color: var(--text-2); }
.pager { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; padding-top: 18px; }
.pager .note { margin-right: auto; }
/* ---- Strategie ---- */
.stages { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 16px; }
.stages li { border: 1px solid var(--rule); border-radius: 12px; padding: 16px 18px; display: flex; flex-direction: column; gap: 6px; }
.stages li > strong { font-size: 15px; }
.stages li > p { color: var(--text-2); font-size: 13.5px; }
.stages li.here { border: 2px solid var(--text); background: var(--surface-2); padding: 15px 17px; }
.stages .step { border: 1.5px solid var(--text); background: transparent; width: 24px; height: 24px; font-size: 13px; font-weight: 650; }
.stages .here .step { background: var(--text); color: var(--surface); }
.stage-count { display: flex; align-items: center; gap: 4px; margin-top: auto; padding-top: 6px; color: var(--text) !important; }
.stage-count .swatch { margin-right: 0; }
.stage-count strong { margin-left: 4px; }
.strategy { display: grid; grid-template-columns: minmax(0, 1.3fr) minmax(0, 1fr) minmax(0, 1.15fr); padding: 0; }
.strategy > div { padding: 24px 26px; min-width: 0; display: flex; flex-direction: column; gap: 12px; }
.strategy > div + div { border-left: 1px solid var(--rule); }
.strategy-about h2 { display: flex; align-items: center; gap: 4px; flex-wrap: wrap; font-size: 20px; line-height: 28px; }
.strategy-about h2 .tag { margin-left: 10px; background: var(--info-bg); color: var(--link); }
.strategy-about > p:first-of-type { font-size: 15px; line-height: 22px; }
.strategy-about ul { margin: 0; padding-left: 20px; color: var(--text-2); display: flex; flex-direction: column; gap: 4px; }
.strategy-about .note { margin-top: auto; }
.strategy-number { display: flex; align-items: center; gap: 14px; font-size: 30px; line-height: 36px; font-weight: 650; letter-spacing: -0.02em; font-variant-numeric: tabular-nums; }
.spark { display: block; width: 100%; height: 80px; }
.strategy-result .account-lines { grid-template-columns: max-content minmax(0, 1fr); column-gap: 16px; }
.strategy-result .account-lines dd { overflow-wrap: anywhere; }
.spark polyline { fill: none; stroke-width: 2; stroke-linejoin: round; }
.strategy-steps h3 { margin: 0 !important; }
.strategy-steps form { margin: 0; }
.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; }
.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; }
.form-grid .btn { justify-self: start; }
.confirm-live .form-grid { grid-template-columns: 1fr; }
.plain { border-top: 2px solid var(--text); padding-top: 18px; }
.plain > h2 { margin-bottom: 8px; }
.observing { display: grid; grid-template-columns: minmax(180px, max-content) minmax(0, 1fr); margin: 0; }
.observing dt, .observing dd { margin: 0; padding: 14px 0; border-bottom: 1px solid var(--rule-inner); }
.observing dt { font-weight: 650; padding-right: 32px; }
.observing dd { display: flex; align-items: center; justify-content: space-between; gap: 16px; color: var(--text-2); }
.observing form { margin: 0; flex: none; }
.attention { display: inline-flex; align-items: center; gap: 6px; }
/* ---- Rischio ---- */
.risk-top { display: grid; grid-template-columns: minmax(0, 1.6fr) minmax(0, 1fr); gap: 20px; align-items: stretch; }
.risk-top .panel { display: flex; flex-direction: column; gap: 12px; }
.risk-top .panel-head { margin-bottom: 0; }
.risk-top p { color: var(--text-2); }
.btn-danger-solid { background: var(--loss); border-color: var(--loss); color: var(--surface); }
.btn-danger-solid:hover { background: var(--loss); opacity: .9; }
.status-line.gain { display: flex; align-items: center; gap: 8px; color: var(--gain); font-weight: 600; font-size: 14px; white-space: normal; }
.blocks { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }
.blocks li { display: flex; align-items: flex-start; gap: 10px; }
.blocks .icon { margin-top: 2px; }
.block-list { margin: 0; display: flex; flex-direction: column; }
.block-list dt { color: var(--text-3); font-size: 13px; padding-top: 12px; border-top: 1px solid var(--rule-inner); }
.block-list dd { margin: 0 0 12px; display: flex; flex-direction: column; gap: 2px; }
.block-list dd span { color: var(--text-2); font-size: 13.5px; }
.limits td.wide { width: 24%; vertical-align: middle; }
.usage { display: block; position: relative; height: 6px; border-radius: 3px; background: var(--track); overflow: hidden; }
.usage span { display: block; height: 100%; border-radius: 3px; background: var(--text-2); min-width: 2px; }
.usage.high span { background: var(--attention); }
.drawdown { display: block; width: 100%; height: auto; margin-top: 12px; overflow: visible; }
.drawdown .axis { stroke: var(--rule); stroke-width: 1; }
.drawdown .tick { fill: var(--text-3); font-size: 12px; }
.drawdown .area { fill: var(--loss); opacity: .1; }
.drawdown .line { fill: none; stroke: var(--loss); stroke-width: 2; stroke-linejoin: round; }
.drawdown .dot { fill: var(--loss); }
.drawdown .label { fill: var(--text); font-size: 12.5px; font-weight: 650; }
.columns .panel .notice { margin-top: 12px; }
.never { list-style: none; margin: 0; padding: 0; }
.never li { display: flex; align-items: center; gap: 12px; padding: 12px 0; border-bottom: 1px solid var(--rule-inner); }
.never .icon { color: var(--text-2); }
.events { display: grid; grid-template-columns: 140px minmax(0, 1fr); margin: 0 0 12px; }
.events dt, .events dd { margin: 0; padding: 12px 0; border-bottom: 1px solid var(--rule-inner); }
.events dt { color: var(--text-3); }
.limits-form { max-width: none; margin-bottom: 8px; }
/* ---- Service pages ---- */
.service { min-height: 100vh; display: flex; justify-content: center; padding: 48px 16px; }
.service-box { width: 100%; max-width: 720px; display: flex; flex-direction: column; gap: 16px; }
@@ -438,6 +570,25 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we
.panel-tools { width: 100%; justify-content: space-between; }
.facts { grid-template-columns: 1fr; gap: 2px; }
.facts dd { margin-bottom: 8px; }
.panel > h2 { flex-direction: column; align-items: flex-start; gap: 4px; }
.trades-head .cells { grid-template-columns: 1fr 1fr; }
.trades { margin: 0 -18px; }
.trade-row { grid-template-columns: minmax(0, 1fr) auto 16px; gap: 4px 12px; padding: 12px 18px; }
.trade-row > span:first-child { grid-column: 1 / -1; color: var(--text-3); font-size: 13px; }
.trade-row .wide, .trade-header, .limits .wide, .filters .btn:last-child { display: none; }
.why { grid-template-columns: 1fr; padding: 4px 18px 18px; }
.filters > label:not(.search) { flex: 1 1 140px; }
.filters select { width: 100%; }
.stages { grid-template-columns: 1fr 1fr; gap: 10px; }
.strategy { grid-template-columns: 1fr; }
.strategy > div { padding: 18px; }
.strategy > div + div { border-left: 0; border-top: 1px solid var(--rule); }
.risk-top { grid-template-columns: 1fr; gap: 14px; }
.observing { grid-template-columns: 1fr; }
.observing dt { border-bottom: 0; padding-bottom: 0; }
.observing dd { flex-direction: column; align-items: flex-start; }
.events { grid-template-columns: 1fr; }
.events dt { border-bottom: 0; padding-bottom: 0; }
.bottombar {
display: grid; grid-template-columns: repeat(5, 1fr); gap: 4px; position: fixed; left: 0; right: 0; bottom: 0;
padding: 6px 6px calc(6px + env(safe-area-inset-bottom)); background: var(--surface); border-top: 1px solid var(--rule); z-index: 10;
+9
View File
@@ -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) : "—";
}
+287 -19
View File
@@ -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>&nbsp;</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);
}
+39 -1
View File
@@ -156,6 +156,17 @@ internal static partial class Endpoints
"text/csv; charset=utf-8", $"anubis-posizioni-{day}.csv");
});
// The closed trades of the Operazioni screen as CSV (SPEC 13.6), with the same filters as the page.
api.MapGet("/operazioni.csv", async (AnubisHost host, ShellData shell, IClock clock, string? cerca, string? conto, string? strategia, string? esito, string? periodo,
CancellationToken ct) =>
{
var filter = TradeFilter.Parse(cerca, conto, strategia, esito, periodo, null);
var view = await TradesView.LoadAsync(host.Services!, clock, filter, int.MaxValue, ct).ConfigureAwait(false);
var day = TimeZoneInfo.ConvertTime(clock.UtcNow, shell.Zone).ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
return Results.File(System.Text.Encoding.UTF8.GetPreamble().Concat(System.Text.Encoding.UTF8.GetBytes(view.Csv())).ToArray(),
"text/csv; charset=utf-8", $"anubis-operazioni-{day}.csv");
});
// The external sources and the live feed: what is on, what is off and why (SPEC 4.4).
api.MapGet("/data/sources", async (AnubisHost host, IClock clock, CancellationToken ct) =>
{
@@ -246,6 +257,7 @@ internal static partial class Endpoints
"pause" or "pausa" when current == "active" => "paused",
"resume" or "riprendi" when current == "paused" => "active",
"stop" or "ferma" => "stopped",
"close" or "chiudi" => "stopped",
"restart" or "riattiva" when current == "stopped" => "active",
_ => null,
};
@@ -256,7 +268,33 @@ internal static partial class Endpoints
: "Comando non ammesso nello stato attuale del bot.");
}
await settings.SetAsync(SettingsStore.BotState.Key, target, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
var by = context.User.Identity?.Name ?? "utente";
if (host.Services.Trading is { Risk: { } risk } trading)
{
// The switch of SPEC 9.3 goes through the risk engine: it cancels the orders under way and keeps the stops.
switch (command)
{
case "stop" or "ferma":
await risk.StopAllAsync(trading.Managers, by, "manual_stop", "Ferma tutto dall'interfaccia: annullo gli ordini in attesa e non apro posizioni. Gli stop restano.", ct)
.ConfigureAwait(false);
return (true, target);
case "close" or "chiudi":
await risk.CloseAllAsync(trading.Managers, by, ct).ConfigureAwait(false);
return (true, target);
case "restart" or "riattiva":
try
{
await risk.RestartAsync(by, ct).ConfigureAwait(false);
return (true, target);
}
catch (InvalidOperationException ex)
{
return (false, ex.Message);
}
}
}
await settings.SetAsync(SettingsStore.BotState.Key, target, by, ct).ConfigureAwait(false);
return (true, target);
}
+161 -2
View File
@@ -35,6 +35,9 @@ internal static partial class Forms
signed.MapPost("/chiavi/{broker}/togli", RemoveKeysAsync);
signed.MapPost("/capitale/{broker}", SetCapitalAsync);
signed.MapPost("/laboratorio", PlanTrialAsync);
signed.MapPost("/strategie/{strategy}/{choice}", StrategyStageAsync);
signed.MapPost("/rischio/limiti", SetLimitsAsync);
signed.MapPost("/rischio/{key}", SetRiskSettingAsync);
}
private static string Back(IFormCollection form, string fallback)
@@ -173,8 +176,8 @@ internal static partial class Forms
private static async Task<IResult> BotAsync(string command, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
var back = Back(form, "/");
var (ok, _) = await Endpoints.BotCommandAsync(host, command, context, ct).ConfigureAwait(false);
return Results.Redirect(ok ? back : With(back, "errore", "bot"));
var (ok, message) = await Endpoints.BotCommandAsync(host, command, context, ct).ConfigureAwait(false);
return Results.Redirect(ok ? back : With(back, "errore", message.Contains("STOP", StringComparison.Ordinal) ? "file-stop" : "bot"));
}
/// <summary>The user's choice for an account in prudent mode after the 15 minutes (SPEC 7.4): align or leave out.</summary>
@@ -309,6 +312,13 @@ internal static partial class Forms
return Results.Redirect(back + "?errore=importo#conti");
}
// 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)
{
return Results.Redirect(back + "?errore=" + refusal + "#conti");
}
try
{
await trading.SetCapitalAsync(broker, amount, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
@@ -325,6 +335,155 @@ internal static partial class Forms
return Results.Redirect(back + "?ok=capitale#conti");
}
/// <summary>
/// The user's choices on the Strategie screen (SPEC 12.3, 12.4): observation and simulation from a button, real
/// money only through the procedure, with the phrase, the password and the second factor checked by the stage book.
/// </summary>
private static async Task<IResult> StrategyStageAsync(string strategy, string choice, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
if (host.IsDemo || host.Services is not { } services || !Anubis.Trading.StrategyNames.Base.Any(b => b.Name == strategy))
{
return Results.Redirect("/strategie?errore=scelta");
}
if (services.Trading?.Stages is not { } stages)
{
return Results.Redirect("/strategie?errore=motore");
}
var by = context.User.Identity?.Name ?? "utente";
try
{
switch (choice)
{
case "simulazione":
var stage = await stages.GetAsync(strategy, ct).ConfigureAwait(false);
if (stage?.Qualification is not { Passed: true })
{
// A strategy that did not pass its backtest stays in observation (SPEC 12.3).
return Results.Redirect("/strategie?errore=backtest");
}
await stages.MoveAsync(strategy, Anubis.Trading.StrategyStages.Simulation, "user", by, ct).ConfigureAwait(false);
return Results.Redirect("/strategie?ok=simulazione");
case "osservazione":
var current = await stages.GetAsync(strategy, ct).ConfigureAwait(false);
if (current is not null && Anubis.Trading.StrategyStages.IsLive(current.Stage))
{
await stages.RevokeAsync(strategy, by, "user", ct).ConfigureAwait(false);
return Results.Redirect("/strategie?ok=simulazione");
}
await stages.MoveAsync(strategy, Anubis.Trading.StrategyStages.Observation, "user", by, ct).ConfigureAwait(false);
return Results.Redirect("/strategie?ok=osservazione");
case "reale" when Guid.TryParse(form["conto"].ToString(), out var account):
var code = form["codice"].ToString();
await stages.ConfirmLiveAsync(new Anubis.Trading.LiveConfirmation(strategy, account, form["frase"].ToString(), form["password"].ToString(),
string.IsNullOrWhiteSpace(code) ? null : code.Trim(), by), ct).ConfigureAwait(false);
return Results.Redirect("/strategie?ok=reale");
default:
return Results.Redirect("/strategie?errore=scelta");
}
}
catch (Anubis.Trading.LiveConfirmationException ex)
{
var error = ex.Code switch
{
"phrase" => "frase",
"password" => "password",
"requirements" => "requisiti",
"account" => "conto",
Anubis.Risk.RiskReasons.NoConsent => "consenso",
_ => "scelta",
};
return Results.Redirect("/strategie?errore=" + error);
}
}
/// <summary>
/// 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)
{
const string back = "/impostazioni";
if (host.IsDemo || host.Services is not { } services)
{
return Results.Redirect(back + "?errore=motore#rischio");
}
var current = new Dictionary<string, string>(StringComparer.Ordinal);
var next = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var definition in Anubis.Risk.RiskSettings.Limits)
{
current[definition.Key] = (await services.Settings.GetAsync(definition.Key, ct).ConfigureAwait(false)).Value;
var typed = form[definition.Key].ToString().Trim().Replace(',', '.');
if (typed.Length == 0)
{
next[definition.Key] = current[definition.Key];
continue;
}
if (definition.Check?.Invoke(typed) is not null)
{
return Results.Redirect(back + "?errore=limite#rischio");
}
next[definition.Key] = typed;
}
var limits = Anubis.Risk.RiskSettings.From(k => next[k]);
if (limits.DrawdownHalf >= limits.DrawdownStop || limits.DailyLoss > limits.WeeklyLoss)
{
return Results.Redirect(back + "?errore=ordine-limiti#rischio");
}
if (Anubis.Risk.RiskSettings.From(k => current[k]).RaisedBy(limits))
{
if (await RaiseRefusalAsync(services, null, form, ct).ConfigureAwait(false) is { } refusal)
{
return Results.Redirect(back + "?errore=" + refusal + "#rischio");
}
}
var by = context.User.Identity?.Name ?? "utente";
foreach (var (key, value) in next.Where(n => n.Value != current[n.Key]))
{
await services.Settings.SetAsync(key, value, by, ct).ConfigureAwait(false);
}
return Results.Redirect(back + "?ok=limiti#rischio");
}
/// <summary>The day-trade guard and the scenarios of the Rischio screen: they change no limit, so no procedure.</summary>
private static async Task<IResult> SetRiskSettingAsync(string key, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
{
const string back = "/impostazioni";
if (key != Anubis.Risk.RiskSettings.PdtGuard.Key && key != Anubis.Risk.Scenarios.Setting.Key)
{
return Results.Redirect(back + "?errore=impostazione#rischio");
}
var result = await Endpoints.SetSettingAsync(host, key, form["valore"].ToString(), context, ct).ConfigureAwait(false);
return Results.Redirect(result is IStatusCodeHttpResult { StatusCode: StatusCodes.Status204NoContent } ? back + "?ok=rischio#rischio" : back + "?errore=scenari#rischio");
}
/// <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)
{
var stages = services.Trading?.Stages ?? new Anubis.Trading.StageBook(services.Db, new SystemClock(), Anubis.Trading.TradingConsent.None, (_, _, _) => Task.FromResult(false));
try
{
var code = form["codice"].ToString();
await stages.ConfirmRaiseAsync(broker, form["frase"].ToString(), form["password"].ToString(), string.IsNullOrWhiteSpace(code) ? null : code.Trim(), ct).ConfigureAwait(false);
return null;
}
catch (Anubis.Trading.LiveConfirmationException ex)
{
return ex.Code == "phrase" ? "frase-rischio" : "password-rischio";
}
}
/// <summary>
/// A new backtest trial (SPEC 12.2): the plan is written and queued at once, then the page of the trial follows it.
/// A field that cannot be read goes back as a code; the chosen strategy is kept, nothing typed travels in the address.
+124
View File
@@ -0,0 +1,124 @@
using System.Globalization;
using System.Text.Json;
using Anubis.Core;
using Anubis.Trading;
namespace Anubis.Server;
/// <summary>
/// The fixed templates that turn the reason codes of the decisions table into plain Italian (SPEC 5.2): the "why"
/// card of a trade and the diary use these, never free text written at decision time. An unknown code is shown as
/// it is, so nothing is ever hidden.
/// </summary>
internal static class ReasonTexts
{
private static readonly Dictionary<string, string> Texts = new(StringComparer.Ordinal)
{
// Strategies.
["trend_entry"] = "La chiusura ha superato i massimi recenti su almeno un orizzonte: è iniziata una tendenza al rialzo.",
["trend_increase"] = "Più orizzonti erano d'accordo sulla tendenza: il peso è salito.",
["trend_reduce"] = "La tendenza si è indebolita, o la moneta è diventata più agitata: il peso è sceso.",
["trend_exit"] = "La tendenza si è interrotta: il prezzo è finito sotto lo stop mobile.",
["trend_stop"] = "Lo stop mobile è salito con il prezzo.",
["momentum_entry"] = "Era tra i titoli più forti degli ultimi mesi, con il mercato in salita.",
["momentum_increase"] = "Il peso obiettivo è salito alla revisione settimanale.",
["momentum_reduce"] = "Il peso obiettivo è sceso alla revisione settimanale.",
["momentum_exit_rank"] = "Non era più tra i 30 titoli più forti.",
["momentum_exit_trend"] = "Il mercato nel suo insieme è girato al ribasso: niente più azioni.",
["momentum_stop"] = "Lo stop di protezione è stato aggiornato.",
["meanrev_entry"] = "Era sceso per qualche seduta di fila ma restava sopra la sua media a 200 giorni: un ribasso breve di un titolo che nel lungo periodo sale.",
["meanrev_exit_average"] = "Il prezzo è tornato sopra la media a 5 giorni: il rimbalzo cercato è arrivato.",
["meanrev_exit_rsi"] = "L'indicatore di forza è tornato alto: il rimbalzo è avvenuto.",
["meanrev_exit_earnings"] = "Uscita prima della trimestrale.",
["meanrev_exit_time"] = "Tempo scaduto: nessun rimbalzo in 5 sedute.",
// Exits recorded on the trade.
["stop"] = "Stop di protezione raggiunto.",
["exit"] = "Uscita decisa dalla strategia.",
["signal"] = "Uscita sul segnale della strategia.",
["residue"] = "Resto troppo piccolo per essere venduto, tolto dal registro.",
["adjustment"] = "Rettifica dopo l'allineamento con il conto.",
// Correctives.
["crypto_regime_below_average"] = "Il mercato crypto era sotto la sua media: acquisti ridotti.",
["crypto_regime_high_volatility"] = "Il mercato crypto era molto agitato: acquisti ridotti.",
["calendar_event"] = "Un dato economico importante era vicino: niente nuove posizioni in quell'ora.",
// Risk.
["risk_reduction"] = "Ordine rimpicciolito dai limiti di rischio.",
["daily_loss_block"] = "Perdita del giorno oltre il limite: niente nuovi ingressi per 24 ore.",
["switch_tripped"] = "Interruttore scattato: il bot aspetta la tua conferma.",
["bot_paused"] = "Bot in pausa: niente nuovi ingressi.",
["bot_stopped"] = "Bot fermato con \"Ferma tutto\".",
["invested_limit"] = "Capitale investito al limite: niente soldi presi in prestito.",
["position_limit"] = "Ridotto al peso massimo di una posizione.",
["crypto_limit"] = "Quota delle crypto sul totale al limite.",
["trade_risk_limit"] = "Ridotto perché il rischio dell'operazione restasse entro il limite.",
["stop_above_price"] = "Stop sopra il prezzo: ordine rifiutato.",
["stale_price"] = "Prezzo troppo vecchio: niente acquisti finché i dati non tornano freschi.",
["price_gap"] = "Prezzo dell'ordine troppo lontano dall'ultimo prezzo.",
["clock_skew"] = "Orologio non allineato con quello del broker.",
["owned_by_other_strategy"] = "La posizione appartiene a un'altra strategia.",
["no_short_selling"] = "Niente vendite allo scoperto: venduto solo quanto posseduto.",
["no_leverage"] = "Niente leva: l'ordine sta nella liquidità disponibile.",
["not_owned_by_bot"] = "La posizione non è del bot: non la tocca.",
["live_not_confirmed"] = "Soldi veri non confermati per questa strategia.",
["exit_only"] = "Strategia in sola uscita: niente nuovi acquisti.",
["live_not_allowed"] = "Soldi veri non permessi dalla configurazione d'avvio.",
["observation"] = "Strategia in osservazione: produce segnali, nessun ordine.",
["orders_per_minute"] = "Troppi ordini in un minuto: il bot si è fermato.",
["pdt_guard"] = "Guardia sulle operazioni in giornata: niente posizioni in più oggi.",
["no_fx_rate"] = "Manca il cambio euro-dollaro: niente acquisti in dollari.",
["unknown_instrument"] = "Strumento sconosciuto.",
};
// The exits in the few words of a table column; the full sentence stays for the "why" card.
private static readonly Dictionary<string, string> ShortExits = new(StringComparer.Ordinal)
{
["trend_exit"] = "La tendenza si è interrotta: prezzo sotto lo stop mobile",
["momentum_exit_rank"] = "Non era più tra i 30 titoli più forti",
["momentum_exit_trend"] = "Il mercato è girato al ribasso",
["meanrev_exit_average"] = "Tornata sopra la media a 5 giorni",
["meanrev_exit_rsi"] = "Rimbalzo arrivato: forza tornata alta",
["meanrev_exit_earnings"] = "Uscita prima della trimestrale",
["meanrev_exit_time"] = "Tempo scaduto: nessun rimbalzo in 5 sedute",
["stop"] = "Stop di protezione raggiunto",
};
/// <summary>Why a trade was closed, in a short sentence.</summary>
public static string Exit(string? code) => code is null ? "Chiusa" : ShortExits.TryGetValue(code, out var text) ? text : Text(code).TrimEnd('.');
public static string Text(string code) => Texts.TryGetValue(code, out var text) ? text : code;
/// <summary>The lines of one stage of a decision. <paramref name="data"/> is the JSON of the numbers the stage used.</summary>
public static IEnumerable<WhyLine> Stage(string stage, string outcome, IReadOnlyList<string> reasons, string? data)
{
ArgumentNullException.ThrowIfNull(reasons);
var good = outcome is DecisionOutcomes.Passed or DecisionOutcomes.Proposed or DecisionOutcomes.Same;
if (stage == DecisionStages.Risk && outcome == DecisionOutcomes.Passed && reasons.Count == 0)
{
yield return new WhyLine("Tutti i limiti di rischio rispettati" + Asked(data), true);
yield break;
}
foreach (var reason in reasons)
{
yield return new WhyLine(Text(reason).TrimEnd('.') + (stage == DecisionStages.Risk ? Asked(data) : ""), good || stage == DecisionStages.Strategy);
}
}
// "(chiesti 0,05, passati 0,03)" when the stage shrank the order.
private static string Asked(string? data)
{
if (data is null)
{
return "";
}
using var json = JsonDocument.Parse(data);
if (json.RootElement.TryGetProperty("asked", out var asked) && json.RootElement.TryGetProperty("allowed", out var allowed) &&
asked.TryGetDecimal(out var a) && allowed.TryGetDecimal(out var b) && b < a)
{
return $" (chiesti {Format.Quantity(a)}, passati {Format.Quantity(b)})";
}
return "";
}
}
+134
View File
@@ -0,0 +1,134 @@
using Anubis.Core;
using Anubis.Data;
using Anubis.Risk;
using Anubis.Strategies;
using Anubis.Trading;
namespace Anubis.Server;
/// <summary>A row of the limits table: what is used now against the threshold, and what happens beyond it.</summary>
internal sealed record LimitRow(string Label, string Now, string? Detail, decimal? Usage, string Threshold, string Beyond, string Key);
/// <summary>A point of the fall from the high, as a fraction: 0 at the high, −0,03 three percent below.</summary>
internal sealed record DrawdownPoint(DateTimeOffset At, decimal Drawdown);
/// <summary>
/// The Rischio screen (SPEC 9, 13.6, mockup 07): the emergency switch, the automatic blocks, the limits with what
/// they use now, the fall from the high, the scenarios and the risk events. One world, as on Conti.
/// </summary>
internal sealed record RiskView(
string BotState,
bool StopFile,
bool CloseAllPending,
string World,
WorldRisk Risk,
RiskLimits Limits,
IReadOnlyList<LimitRow> Rows,
IReadOnlyList<DrawdownPoint> Drawdown,
IReadOnlyList<ScenarioResult> Scenarios,
IReadOnlyList<(DateTimeOffset At, string Kind, string Severity, string Message, string? World)> Events,
(DateTimeOffset From, DateTimeOffset To, string Title)? NextCalendarBlock,
(DateTimeOffset From, DateTimeOffset To, string Title)? LastCalendarBlock,
bool PdtGuard,
bool HasPositions)
{
public bool AnyBlock => Risk.State.Tripped || Risk.EntriesBlocked || Risk.Multiplier < 1m || BotState != "active";
public static async Task<RiskView> LoadAsync(AppServices services, IClock clock, TimeZoneInfo zone, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(services);
var engine = services.Trading?.Risk ?? new RiskEngine(services.Db, clock, new Ledger(services.Db, clock),
new StageBook(services.Db, clock, TradingConsent.None, (_, _, _) => Task.FromResult(false)), services.Settings, new FxStore(services.Db, clock),
(_, _) => Task.FromResult<Instrument?>(null), (_, _) => Task.FromResult<Quote?>(null));
var limits = await RiskSettings.LoadAsync(services.Settings, cancellationToken).ConfigureAwait(false);
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);
var bot = (await services.Settings.GetAsync(SettingsStore.BotState.Key, cancellationToken).ConfigureAwait(false)).Value;
var now = clock.UtcNow;
var (index, sent) = await services.Db.ReadAsync(async s =>
{
var i = await s.QueryAsync("SELECT taken_at, twr_index FROM equity_snapshots WHERE scope = 'total' AND world = @w AND twr_index IS NOT NULL ORDER BY taken_at, id",
r => new IndexPoint(r.Moment("taken_at"), r.Money("twr_index")), ("w", world)).ConfigureAwait(false);
var o = await s.QueryAsync(
"SELECT o.account_id, COUNT(*) AS n FROM orders o WHERE o.submitted_at >= @f AND o.purpose IN ('entry', 'exit') GROUP BY o.account_id",
r => (Account: r.Id("account_id"), Count: r.Number("n")), ("f", now - TimeSpan.FromMinutes(1))).ConfigureAwait(false);
return (i, o);
}, cancellationToken).ConfigureAwait(false);
var shown = accounts.Accounts.Select(a => a.Id).ToHashSet();
var equity = accounts.TotalEur;
var positions = accounts.Positions;
var biggest = positions.MaxBy(p => p.ValueEur);
var crypto = positions.Where(p => p.Broker == Venues.Okx).Sum(p => p.ValueEur);
decimal Rate(PositionRow p) => p.Last == 0m ? 0m : p.ValueEur / (p.Quantity * p.Last);
var atRisk = positions.Select(p => p.Stop is { } stop ? Math.Max(0m, p.ValueEur - (p.Quantity * stop * Rate(p))) : p.ValueEur).ToList();
var perMinute = sent.Where(x => shown.Contains(x.Account)).Select(x => x.Count).DefaultIfEmpty(0).Max();
string Pct(decimal fraction, int decimals = 2, bool sign = false) => Format.Percent(fraction * 100m, decimals, sign);
decimal? Use(decimal value, decimal limit) => limit <= 0m ? null : Math.Clamp(value / limit, 0m, 1m);
var m = risk.Measures;
var rows = new List<LimitRow>
{
new("Perdita in un giorno", m.DayChange >= 0m ? "nessuna" : Pct(m.DayChange), m.DayChange >= 0m ? $"oggi {Pct(m.DayChange, 2, true)}" : null,
Use(-m.DayChange, limits.DailyLoss), Pct(-limits.DailyLoss), "Niente nuovi ingressi per 24 ore", RiskSettings.DailyLoss.Key),
new("Perdita in una settimana", m.WeekChange >= 0m ? "nessuna" : Pct(m.WeekChange), m.WeekChange >= 0m ? $"{Pct(m.WeekChange, 2, true)}" : null,
Use(-m.WeekChange, limits.WeeklyLoss), Pct(-limits.WeeklyLoss), "Rischio dimezzato per sette giorni", RiskSettings.WeeklyLoss.Key),
new("Calo dal massimo", Pct(m.Drawdown), Worst(index, risk.State.PeakFrom) is { } worst && worst < m.Drawdown ? $"peggiore {Pct(worst)}" : null,
Use(-m.Drawdown, limits.DrawdownStop), $"{Pct(-limits.DrawdownHalf, 0)} e {Pct(-limits.DrawdownStop, 0)}",
$"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",
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),
"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",
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),
new("Età dei prezzi", "controllata a ogni ordine", null, null, $"{(int)limits.MaxPriceAge.TotalSeconds} secondi", "Non apro posizioni finché i dati non tornano freschi",
RiskSettings.MaxPriceAge.Key),
};
var drawdown = new List<DrawdownPoint>();
var peak = 0m;
foreach (var p in index.Where(p => risk.State.PeakFrom is null || p.At >= risk.State.PeakFrom))
{
peak = Math.Max(peak, p.Index);
drawdown.Add(new DrawdownPoint(p.At, peak > 0m ? (p.Index / peak) - 1m : 0m));
}
var scenarioText = (await services.Settings.GetAsync(Anubis.Risk.Scenarios.Setting.Key, cancellationToken).ConfigureAwait(false)).Value;
var dollars = accounts.Accounts.Where(a => a.Currency == "USD").Sum(a => a.Eur(a.Equity));
var scenarios = Anubis.Risk.Scenarios.Compute(Anubis.Risk.Scenarios.Parse(scenarioText),
[.. positions.Select(p => new ScenarioPosition(p.Broker == Venues.Okx, p.ValueEur, p.Stop is { } stop ? p.Quantity * stop * Rate(p) : null))], dollars, equity);
var calendar = await new CalendarEventStore(services.Db, clock).BetweenAsync(now.AddDays(-14), now.AddDays(14), cancellationToken).ConfigureAwait(false);
var windows = calendar.Select(e => (Event: e, Window: CalendarBlocks.Window(e))).Where(x => x.Window is not null)
.Select(x => (x.Window!.Value.From, x.Window.Value.To, x.Event.Title)).OrderBy(x => x.From).ToList();
(DateTimeOffset, DateTimeOffset, string)? next = windows.FirstOrDefault(w => w.To > now) is { Title: not null } n ? n : null;
(DateTimeOffset, DateTimeOffset, string)? last = windows.LastOrDefault(w => w.To <= now) is { Title: not null } l ? l : null;
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);
}
private static decimal? Worst(IReadOnlyList<IndexPoint> index, DateTimeOffset? from)
{
decimal? worst = null;
var peak = 0m;
foreach (var p in index.Where(p => from is null || p.At >= from))
{
peak = Math.Max(peak, p.Index);
var d = peak > 0m ? (p.Index / peak) - 1m : 0m;
worst = worst is null ? d : Math.Min(worst.Value, d);
}
return worst;
}
}
+166
View File
@@ -0,0 +1,166 @@
using Anubis.Backtest;
using Anubis.Core;
using Anubis.Data;
using Anubis.Strategies;
using Anubis.Trading;
namespace Anubis.Server;
/// <summary>A strategy of the Strategie screen: its stage, results, requirements and what the user can do next.</summary>
internal sealed record StrategyCard(
StrategyStage Stage,
string Name,
string Description,
IReadOnlyList<string> Rules,
string Account,
string Currency,
decimal CapitalEur,
decimal ResultEur,
decimal ResultPercent,
decimal WorstFall,
int Closed,
int Winners,
IReadOnlyList<string> Open,
IReadOnlyList<(DateTimeOffset At, decimal Index)> Curve,
IReadOnlyList<Requirement> Requirements,
string Phrase,
int? DaysToGo)
{
public string Color => "var(--s-" + Stage.Strategy.Replace('_', '-') + ")";
public bool AllMet => Requirements.All(r => r.Met);
}
/// <summary>
/// The Strategie screen (SPEC 12.3, 13.6, mockup 04): the path to real money in four stages, a card for each base
/// strategy with its requirements, and the ones in observation with the reason.
/// </summary>
internal sealed record StrategiesView(IReadOnlyList<StrategyCard> Cards, bool LiveAllowed, IReadOnlyList<(Guid Id, string Name, string Broker)> LiveAccounts)
{
/// <summary>What each base strategy does, in four lines (SPEC 8).</summary>
public static readonly IReadOnlyDictionary<string, IReadOnlyList<string>> Rules = new Dictionary<string, IReadOnlyList<string>>(StringComparer.Ordinal)
{
[StrategyNames.CryptoTrend] =
[
"Guarda le 10 monete in euro più scambiate una volta al giorno, dopo la chiusura delle 00:00 UTC",
"Entra quando il prezzo segna nuovi massimi su più periodi, da 5 a 360 giorni",
"Più una moneta è agitata, meno ne compra",
"Mai a leva, mai al ribasso",
],
[StrategyNames.EquityMomentum] =
[
"Rifà la classifica ogni lunedì e tiene fino a 12 titoli",
"Vende chi esce dai primi 30 o tocca lo stop",
"Compra solo quando il mercato nel suo insieme sale",
"Solo azioni singole, nessun ETF americano",
],
[StrategyNames.EquityMeanrev] =
[
"Solo titoli sopra la loro media a 200 giorni",
"Esce al rimbalzo, oppure dopo 5 sedute",
"Salta i giorni prima delle trimestrali",
"Mai uscita nello stesso giorno dell'acquisto",
],
};
public static async Task<StrategiesView> LoadAsync(AppServices services, IClock clock, bool liveAllowed, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(services);
var stages = services.Trading?.Stages ?? new StageBook(services.Db, clock, TradingConsent.None, (_, _, _) => Task.FromResult(false));
var ledger = services.Trading?.Ledger ?? new Ledger(services.Db, clock);
var rate = (await new FxStore(services.Db, clock).LatestAsync("EUR", "USD", cancellationToken).ConfigureAwait(false))?.Rate ?? 0m;
var accounts = await services.Db.ReadAsync(s => s.QueryAsync("SELECT id, name, broker, environment, base_currency FROM accounts",
r => (Id: r.Id("id"), Name: r.Text("name"), Broker: r.Text("broker"), Environment: r.Text("environment"), Currency: r.Text("base_currency"))), cancellationToken)
.ConfigureAwait(false);
var equities = await ledger.EquitiesAsync(cancellationToken).ConfigureAwait(false);
var positions = await ledger.PositionsAsync(null, cancellationToken).ConfigureAwait(false);
var cards = new List<StrategyCard>();
foreach (var stage in await stages.AllAsync(cancellationToken).ConfigureAwait(false))
{
if (!StrategyNames.Base.Any(b => b.Name == stage.Strategy))
{
continue;
}
var family = StrategyCatalog.Find(stage.Strategy);
var ledgerAccount = stage.OrdersAccount ?? stage.AccountId;
var account = accounts.FirstOrDefault(a => a.Id == ledgerAccount);
var usd = account.Currency == "USD";
decimal Eur(decimal amount) => usd ? (rate > 0m ? amount / rate : 0m) : amount;
var equity = equities.FirstOrDefault(e => e.AccountId == ledgerAccount && e.Strategy == stage.Strategy);
// As on Conti: each position is valued to the cent before the sum, so both pages show the same figure.
var held = positions.Where(p => p.AccountId == ledgerAccount && p.Strategy == stage.Strategy).Sum(p => Math.Round(p.Value, 2, MidpointRounding.AwayFromZero));
var result = equity is null ? 0m : equity.Cash + held - equity.Flows;
var since = stage.StageSince ?? DateTimeOffset.MinValue;
var (curve, trades) = await services.Db.ReadAsync(async s =>
{
var c = await s.QueryAsync(
"SELECT taken_at, twr_index FROM equity_snapshots WHERE scope = 'strategy' AND account_id = @a AND strategy = @s AND twr_index IS NOT NULL ORDER BY taken_at, id",
r => (At: r.Moment("taken_at"), Index: r.Money("twr_index")), ("a", ledgerAccount), ("s", stage.Strategy)).ConfigureAwait(false);
var t = await s.QueryAsync("SELECT realized FROM trades WHERE account_id = @a AND strategy = @s AND status = 'closed'", r => r.Money("realized"),
("a", ledgerAccount), ("s", stage.Strategy)).ConfigureAwait(false);
return (c, t);
}, cancellationToken).ConfigureAwait(false);
var peak = 0m;
var worst = 0m;
foreach (var p in curve)
{
peak = Math.Max(peak, p.Index);
worst = Math.Min(worst, peak > 0m ? (p.Index / peak) - 1m : 0m);
}
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) ?? "?");
}
var requirements = await stages.RequirementsAsync(stage.Strategy, cancellationToken).ConfigureAwait(false);
var next = stage.Stage == StrategyStages.Reduced ? StrategyStages.Real : StrategyStages.Reduced;
var days = requirements.FirstOrDefault(r => r.Key == "days");
int? toGo = days is { Met: false } && stage.StageSince is { } from
? Math.Max(1, (int)Math.Ceiling(((stage.Stage == StrategyStages.Reduced ? StageBook.ReducedDays : StageBook.SimulationDays) - (clock.UtcNow - from).TotalDays)))
: null;
var flows = equity?.Flows ?? 0m;
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));
}
var live = accounts.Where(a => a.Environment == TradingEnvironments.Live).Select(a => (a.Id, a.Name, a.Broker)).ToList();
return new StrategiesView([.. cards.OrderBy(c => StrategyNames.Base.ToList().FindIndex(b => b.Name == c.Stage.Strategy))], liveAllowed, live);
}
/// <summary>A requirement not met yet only because time has to pass or nothing could be measured so far.</summary>
public static bool IsPending(Requirement requirement)
{
ArgumentNullException.ThrowIfNull(requirement);
return !requirement.Met && (requirement.Key is "days" or "trades" || requirement.Value is "da misurare" or "nessuna esecuzione");
}
/// <summary>Why a strategy is in observation, in words: the outcome of its backtest, or the user's choice.</summary>
public static string ObservationReason(StrategyStage stage)
{
ArgumentNullException.ThrowIfNull(stage);
if (stage.Qualification is { Passed: false } q)
{
return q.Verdict;
}
if (stage.Qualification is null)
{
return "Il backtest non è ancora stato fatto: finché manca resta in osservazione.";
}
return stage.StageReason switch
{
"user" or null => "Superato il backtest: puoi portarla in simulazione quando vuoi.",
var r => "Tornata in osservazione: " + ReasonTexts.Text(r) + ".",
};
}
/// <summary>The report of a strategy's backtest in the repository, for the link.</summary>
public static string? ReportOf(StrategyStage stage) => stage.Qualification?.Report ?? BacktestOutcomes.Find(stage.Strategy)?.Report;
}
+198
View File
@@ -0,0 +1,198 @@
using System.Globalization;
using System.Text;
using Anubis.Core;
using Anubis.Data;
using Anubis.Trading;
namespace Anubis.Server;
/// <summary>The filters of the Operazioni screen, read from the address so a filtered page can be bookmarked.</summary>
internal sealed record TradeFilter(string? Search, Guid? Account, string? Strategy, string? Result, string Period, int Page)
{
public const int PageSize = 20;
public static readonly IReadOnlyList<(string Key, string Label)> Periods = [("avvio", "Dall'avvio"), ("7", "Ultimi 7 giorni"), ("30", "Ultimi 30 giorni"), ("90", "Ultimi 90 giorni")];
public static readonly IReadOnlyList<(string Key, string Label)> Results = [("", "Guadagni e perdite"), ("guadagni", "Solo guadagni"), ("perdite", "Solo perdite")];
public static TradeFilter Parse(string? search, string? account, string? strategy, string? result, string? period, string? page) => new(
string.IsNullOrWhiteSpace(search) ? null : search.Trim(),
Guid.TryParse(account, out var a) ? a : null,
string.IsNullOrWhiteSpace(strategy) ? null : strategy,
result is "guadagni" or "perdite" ? result : null,
Periods.Any(p => p.Key == period) ? period! : "avvio",
int.TryParse(page, NumberStyles.None, CultureInfo.InvariantCulture, out var p) && p > 0 ? p : 1);
/// <summary>The query string of this filter with one value changed.</summary>
public string Query(int? page = null)
{
var parts = new List<string>();
void Add(string key, string? value)
{
if (!string.IsNullOrEmpty(value))
{
parts.Add(key + "=" + Uri.EscapeDataString(value));
}
}
Add("cerca", Search);
Add("conto", Account?.ToString());
Add("strategia", Strategy);
Add("esito", Result);
Add("periodo", Period == "avvio" ? null : Period);
var p = page ?? Page;
Add("pagina", p > 1 ? p.ToString(CultureInfo.InvariantCulture) : null);
return parts.Count == 0 ? "" : "?" + string.Join('&', parts);
}
}
/// <summary>A step of the "why" card: a stage of a decision in plain Italian.</summary>
internal sealed record WhyLine(string Text, bool Good);
/// <summary>A closed trade of the Operazioni screen, in its own currency and in euro.</summary>
internal sealed record TradeRow(Guid Id, string Symbol, string Name, string Strategy, string Account, string Currency, DateTimeOffset OpenedAt, DateTimeOffset ClosedAt,
decimal Quantity, decimal EntryPrice, decimal ExitPrice, decimal Realized, decimal RealizedEur, decimal Fees, string ExitReason, string? ExitCode,
IReadOnlyList<WhyLine> Bought, IReadOnlyList<WhyLine> Sold, decimal? EntrySlipBp, decimal? ExitSlipBp)
{
public decimal Percent => EntryPrice * Quantity == 0m ? 0m : Realized / (EntryPrice * Quantity) * 100m;
}
/// <summary>
/// The Operazioni screen (SPEC 13.6, mockup 03): closed trades with their figures, filters, the result of each
/// trade as bars, and for each one the "why" card built from the rows of the decisions table (SPEC 5.2).
/// </summary>
internal sealed record TradesView(
IReadOnlyList<TradeRow> Rows,
int Matching,
int Total,
DateTimeOffset? Since,
decimal Gains,
decimal Losses,
int Winners,
decimal Fees,
IReadOnlyList<(DateTimeOffset At, decimal Eur, string Symbol)> Bars,
IReadOnlyList<(Guid Id, string Name)> Accounts,
IReadOnlyList<string> Strategies)
{
public int Losers => Matching - Winners;
/// <summary>Euro gained for each euro lost: null while nothing was lost.</summary>
public decimal? PerEuroLost => Losses < 0m ? Gains / -Losses : null;
public decimal Net => Gains + Losses;
public static async Task<TradesView> LoadAsync(AppServices services, IClock clock, TradeFilter filter, int? limit, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(filter);
var rate = (await new FxStore(services.Db, clock).LatestAsync("EUR", "USD", cancellationToken).ConfigureAwait(false))?.Rate ?? 0m;
var (accounts, trades) = await services.Db.ReadAsync(async s =>
{
var a = await s.QueryAsync("SELECT id, name, environment, base_currency FROM accounts ORDER BY broker DESC, created_at",
r => (Id: r.Id("id"), Name: r.Text("name"), Environment: r.Text("environment"), Currency: r.Text("base_currency"))).ConfigureAwait(false);
var t = await s.QueryAsync(
"SELECT t.id, t.account_id, t.instrument_id, t.strategy, t.opened_at, t.closed_at, t.bought_quantity, t.bought_value, t.sold_quantity, t.sold_value, t.fees, t.realized, " +
"t.exit_reason, i.symbol, i.name FROM trades t JOIN instruments i ON i.id = t.instrument_id WHERE t.status = 'closed' ORDER BY t.closed_at DESC, t.id",
r => new Closed(r.Id("id"), r.Id("account_id"), r.Id("instrument_id"), r.Text("strategy"), r.Moment("opened_at"), r.Moment("closed_at"), r.Money("bought_quantity"),
r.Money("bought_value"), r.Money("sold_quantity"), r.Money("sold_value"), r.Money("fees"), r.Money("realized"), r.TextOrNull("exit_reason"), r.Text("symbol"),
r.TextOrNull("name") ?? "")).ConfigureAwait(false);
return (a, t);
}, cancellationToken).ConfigureAwait(false);
// One world only, as on the Conti screen: real accounts when there are any, so finto and vero never add up.
var world = accounts.Any(a => TradingEnvironments.World(a.Environment) == Worlds.Real) ? Worlds.Real : Worlds.Simulated;
var shown = accounts.Where(a => TradingEnvironments.World(a.Environment) == world).ToDictionary(a => a.Id);
decimal Eur(Guid account, decimal amount) => shown[account].Currency == "USD" ? (rate > 0m ? amount / rate : 0m) : amount;
var all = trades.Where(t => shown.ContainsKey(t.Account)).ToList();
var from = filter.Period switch
{
"7" => clock.UtcNow.AddDays(-7),
"30" => clock.UtcNow.AddDays(-30),
"90" => clock.UtcNow.AddDays(-90),
_ => (DateTimeOffset?)null,
};
var matching = all.Where(t =>
(filter.Account is null || t.Account == filter.Account) &&
(filter.Strategy is null || t.Strategy == filter.Strategy) &&
(from is null || t.ClosedAt >= from) &&
(filter.Result is null || (filter.Result == "guadagni" ? t.Realized >= 0m : t.Realized < 0m)) &&
(filter.Search is null || t.Symbol.Contains(filter.Search, StringComparison.OrdinalIgnoreCase) || t.Name.Contains(filter.Search, StringComparison.OrdinalIgnoreCase)))
.ToList();
var page = limit is { } n ? matching.Take(n).ToList() : matching.Skip((filter.Page - 1) * TradeFilter.PageSize).Take(TradeFilter.PageSize).ToList();
var rows = new List<TradeRow>();
foreach (var t in page)
{
var (bought, sold, entrySlip, exitSlip, code) = await WhyAsync(services, t, cancellationToken).ConfigureAwait(false);
var quantity = t.BoughtQuantity;
rows.Add(new TradeRow(t.Id, t.Symbol, t.Name, t.Strategy, shown[t.Account].Name, shown[t.Account].Currency, t.OpenedAt, t.ClosedAt, quantity,
quantity == 0m ? 0m : t.BoughtValue / quantity, t.SoldQuantity == 0m ? 0m : t.SoldValue / t.SoldQuantity, t.Realized,
Math.Round(Eur(t.Account, t.Realized), 2, MidpointRounding.AwayFromZero), t.Fees, ReasonTexts.Exit(code ?? t.ExitReason), code ?? t.ExitReason, bought, sold, entrySlip,
exitSlip));
}
var bars = matching.OrderBy(t => t.ClosedAt).Select(t => (t.ClosedAt, Math.Round(Eur(t.Account, t.Realized), 2, MidpointRounding.AwayFromZero), t.Symbol)).ToList();
return new TradesView(rows, matching.Count, all.Count, all.Count > 0 ? all.Min(t => t.ClosedAt) : null,
bars.Where(b => b.Item2 >= 0m).Sum(b => b.Item2), bars.Where(b => b.Item2 < 0m).Sum(b => b.Item2), bars.Count(b => b.Item2 >= 0m),
matching.Sum(t => Math.Round(Eur(t.Account, t.Fees), 2, MidpointRounding.AwayFromZero)), bars,
[.. shown.Values.Select(a => (a.Id, a.Name))], [.. all.Select(t => t.Strategy).Distinct().Order(StringComparer.Ordinal)]);
}
/// <summary>The trades as CSV for an Italian spreadsheet: semicolons, decimal commas, one row per closed trade.</summary>
public string Csv()
{
var text = new StringBuilder("chiusa_il;aperta_il;strumento;nome;strategia;conto;quantita;prezzo_entrata;prezzo_uscita;valuta;risultato;risultato_eur;commissioni;motivo\n");
foreach (var r in Rows)
{
text.Append(string.Join(';', Moment(r.ClosedAt), Moment(r.OpenedAt), Clean(r.Symbol), Clean(r.Name), r.Strategy, Clean(r.Account), Number(r.Quantity), Number(r.EntryPrice),
Number(r.ExitPrice), r.Currency, Number(r.Realized), Number(r.RealizedEur), Number(r.Fees), Clean(r.ExitReason))).Append('\n');
}
return text.ToString();
static string Moment(DateTimeOffset at) => at.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture);
static string Number(decimal value) => (Math.Round(value, 8) / 1.000000000000000000000000000000000m).ToString(CultureInfo.InvariantCulture).Replace('.', ',');
static string Clean(string value) => value.Replace(';', ',').Replace('\n', ' ');
}
private sealed record Closed(Guid Id, Guid Account, Guid Instrument, string Strategy, DateTimeOffset OpenedAt, DateTimeOffset ClosedAt, decimal BoughtQuantity, decimal BoughtValue,
decimal SoldQuantity, decimal SoldValue, decimal Fees, decimal Realized, string? ExitReason, string Symbol, string Name);
/// <summary>
/// The decisions behind a trade: the first purchase and the last sale of its executions, matched to their decision
/// through the order key (the hash of the decision id), and every stage of those decisions in words.
/// </summary>
private static async Task<(List<WhyLine> Bought, List<WhyLine> Sold, decimal? EntrySlip, decimal? ExitSlip, string? ExitCode)> WhyAsync(AppServices services, Closed t,
CancellationToken cancellationToken)
{
var (executions, decisions) = await services.Db.ReadAsync(async s =>
{
var e = await s.QueryAsync(
"SELECT side, order_key, reference_price, purpose, started_at FROM executions WHERE account_id = @a AND instrument_id = @i AND strategy = @s AND started_at >= @f AND started_at <= @t " +
"ORDER BY started_at, id",
r => (Side: r.Text("side"), Key: r.Text("order_key"), Reference: r.MoneyOrNull("reference_price"), Purpose: r.Text("purpose")),
("a", t.Account), ("i", t.Instrument), ("s", t.Strategy), ("f", t.OpenedAt.AddMinutes(-5)), ("t", t.ClosedAt)).ConfigureAwait(false);
var d = await s.QueryAsync(
"SELECT decision_id, stage, outcome, reasons, data FROM decisions WHERE strategy = @s AND symbol = @sym AND created_at >= @f AND created_at <= @t ORDER BY created_at, id",
r => (Id: r.Id("decision_id"), Stage: r.Text("stage"), Outcome: r.Text("outcome"), Reasons: r.Text("reasons"), Data: r.TextOrNull("data")),
("s", t.Strategy), ("sym", t.Symbol), ("f", t.OpenedAt.AddDays(-1)), ("t", t.ClosedAt.AddMinutes(5))).ConfigureAwait(false);
return (e, d);
}, cancellationToken).ConfigureAwait(false);
var byKey = decisions.GroupBy(d => d.Id).ToDictionary(g => ClientOrderIds.Key(g.Key), g => g.ToList(), StringComparer.Ordinal);
List<WhyLine> Lines(string? key) => key is not null && byKey.TryGetValue(key, out var rows)
? [.. rows.SelectMany(r => ReasonTexts.Stage(r.Stage, r.Outcome, System.Text.Json.JsonSerializer.Deserialize<List<string>>(r.Reasons) ?? [], r.Data))]
: [];
var buy = executions.FirstOrDefault(e => e.Side == "buy");
var sell = executions.LastOrDefault(e => e.Side == "sell");
var sold = Lines(sell.Key);
var code = sell.Key is not null && byKey.TryGetValue(sell.Key, out var exitRows)
? exitRows.Where(r => r.Stage == DecisionStages.Strategy).SelectMany(r => System.Text.Json.JsonSerializer.Deserialize<List<string>>(r.Reasons) ?? []).FirstOrDefault()
: sell.Purpose is "stop" or "protective" ? "stop" : null;
decimal? entrySlip = buy.Reference is > 0m && t.BoughtQuantity > 0m ? Math.Round(((t.BoughtValue / t.BoughtQuantity) / buy.Reference.Value - 1m) * 10_000m, 1) : null;
decimal? exitSlip = sell.Reference is > 0m && t.SoldQuantity > 0m ? Math.Round((1m - (t.SoldValue / t.SoldQuantity) / sell.Reference.Value) * 10_000m, 1) : null;
return (Lines(buy.Key), sold, entrySlip, exitSlip, code);
}
}
+70 -9
View File
@@ -120,10 +120,25 @@ public static class DemoMode
["Mean reversion"] = ("equity_meanrev", alpaca, 1740.15m, 1236.71m, 0.25m),
};
var currencyOf = new Dictionary<Guid, string> { [okx] = "EUR", [alpaca] = "USD" };
// F.4: 58 days of 60 in simulation, after a passed backtest (an example: the real outcomes are in docs/backtests).
foreach (var (name, account, capital, _, share) in strategies.Values)
{
await s.ExecuteAsync("INSERT INTO strategy_state (id, strategy, account_id, stage, capital, share, state, created_at, updated_at) VALUES (@id, @n, @a, 'simulation', @c, @sh, @st, @t, @t)",
cancellationToken, ("id", ids.Next()), ("n", name), ("a", account), ("c", capital), ("sh", share), ("st", new DbJson("{\"day\":58,\"of\":60}")), ("t", now))
var example = new Trading.Qualification
{
Passed = true,
Verdict = "Superato (dato di esempio).",
Report = "docs/backtests/" + name + ".md",
MaxDrawdown = 0.18m,
ExpectedSlippageBp = 8m,
RoundTripCost = 0.0056m,
ExpectedPathP5 = [.. Enumerable.Range(1, 365).Select(d => Math.Round(-0.012 * Math.Sqrt(d), 4))],
};
await s.ExecuteAsync(
"INSERT INTO strategy_state (id, strategy, account_id, stage, stage_since, stage_reason, qualification, capital, share, state, created_at, updated_at) " +
"VALUES (@id, @n, @a, 'simulation', @since, 'user', @q, @c, @sh, @st, @t, @t)",
cancellationToken, ("id", ids.Next()), ("n", name), ("a", account), ("since", now.AddDays(-58)),
("q", new DbJson(JsonSerializer.Serialize(example, Trading.Qualification.Json))), ("c", capital), ("sh", share),
("st", new DbJson("{\"day\":58,\"of\":60}")), ("t", now))
.ConfigureAwait(false);
}
@@ -177,20 +192,22 @@ public static class DemoMode
[
("account", okx, null, 4000m, 231.60m),
("account", alpaca, null, 6000m, 180.86m),
("strategy", null, "crypto_trend", 4000m, 231.60m),
("strategy", null, "equity_momentum", 4500m, 169.50m),
("strategy", null, "equity_meanrev", 1500m, 11.36m),
("strategy", okx, "crypto_trend", 4000m, 231.60m),
("strategy", alpaca, "equity_momentum", 4500m, 169.50m),
("strategy", alpaca, "equity_meanrev", 1500m, 11.36m),
];
foreach (var (day, equity, benchmark, drawdown) in daily)
{
var at = day == DateOnly.FromDateTime(Now.DateTime) ? now : new DateTimeOffset(day.ToDateTime(new TimeOnly(22, 0)), rome.GetUtcOffset(day.ToDateTime(new TimeOnly(22, 0))));
await s.ExecuteAsync("INSERT INTO equity_snapshots (id, taken_at, scope, world, currency, equity, benchmark, drawdown_pct, created_at) VALUES (@id, @at, 'total', 'simulated', 'EUR', @e, @b, @d, @t)",
cancellationToken, ("id", ids.Next()), ("at", at), ("e", equity), ("b", benchmark), ("d", drawdown), ("t", now)).ConfigureAwait(false);
await s.ExecuteAsync("INSERT INTO equity_snapshots (id, taken_at, scope, world, currency, equity, benchmark, drawdown_pct, twr_index, created_at) VALUES (@id, @at, 'total', 'simulated', 'EUR', @e, @b, @d, @x, @t)",
cancellationToken, ("id", ids.Next()), ("at", at), ("e", equity), ("b", benchmark), ("d", drawdown), ("x", Math.Round(equity / 10000m, 6)), ("t", now)).ConfigureAwait(false);
foreach (var (scope, account, strategy, start, result) in series)
{
var value = Math.Round(start + (equity - 10000m) * result / total, 2, MidpointRounding.AwayFromZero);
await s.ExecuteAsync("INSERT INTO equity_snapshots (id, taken_at, scope, world, currency, account_id, strategy, equity, created_at) VALUES (@id, @at, @sc, 'simulated', 'EUR', @a, @st, @e, @t)",
cancellationToken, ("id", ids.Next()), ("at", at), ("sc", scope), ("a", account), ("st", strategy), ("e", value), ("t", now)).ConfigureAwait(false);
// Without deposits along the way the index is the value over the start.
await s.ExecuteAsync("INSERT INTO equity_snapshots (id, taken_at, scope, world, currency, account_id, strategy, equity, twr_index, created_at) VALUES (@id, @at, @sc, 'simulated', 'EUR', @a, @st, @e, @x, @t)",
cancellationToken, ("id", ids.Next()), ("at", at), ("sc", scope), ("a", account), ("st", strategy), ("e", value), ("x", Math.Round(value / start, 6)), ("t", now))
.ConfigureAwait(false);
}
}
@@ -269,6 +286,50 @@ public static class DemoMode
"VALUES (@id, @a, @i, @s, 'closed', @o, @c, @q, @b, @q, @sv, @f, @r, @e, @t, @t)",
cancellationToken, ("id", ids.Next()), ("a", account), ("i", instrument), ("s", strategy), ("o", closed.AddDays(-5)), ("c", closed), ("q", quantity), ("b", bought),
("sv", bought + realized + fee), ("f", fee), ("r", realized), ("e", realized >= 0m ? "signal" : "stop"), ("t", now)).ConfigureAwait(false);
await SeedWhyAsync(s, ids, account, instrument, strategy, symbol, quantity, bought, bought + realized + fee, closed.AddDays(-5), closed, realized < 0m, now, cancellationToken)
.ConfigureAwait(false);
}
}
// F.6: the decisions behind each trade, so its "why" card has lines: the strategy's reason, correctives and risk on
// the purchase; the strategy's exit on a sale it decided, or the protective stop that sold at a loss.
private static async Task SeedWhyAsync(DbSession s, IdSource ids, Guid account, Guid instrument, string strategy, string symbol, decimal quantity, decimal bought,
decimal sold, DateTimeOffset opened, DateTimeOffset closed, bool stopped, DateTimeOffset now, CancellationToken cancellationToken)
{
var (entry, exit) = strategy switch
{
"crypto_trend" => ("trend_entry", "trend_exit"),
"equity_momentum" => ("momentum_entry", "momentum_exit_rank"),
_ => ("meanrev_entry", "meanrev_exit_average"),
};
async Task DecideAsync(Guid decision, string stage, string outcome, string[] reasons, DateTimeOffset at) =>
await s.ExecuteAsync(
"INSERT INTO decisions (id, decision_id, strategy, account_id, symbol, stage, outcome, reasons, data, created_at) VALUES (@id, @d, @s, @a, @sym, @st, @o, @r, NULL, @t)",
cancellationToken, ("id", ids.Next()), ("d", decision), ("s", strategy), ("a", account), ("sym", symbol), ("st", stage), ("o", outcome),
("r", new DbJson(JsonSerializer.Serialize(reasons))), ("t", at)).ConfigureAwait(false);
async Task ExecuteAsync(string side, string purpose, Guid decision, decimal reference, DateTimeOffset at) =>
await s.ExecuteAsync(
"INSERT INTO executions (id, account_id, instrument_id, strategy, side, purpose, quantity, filled, order_key, sequence, step, reference_price, status, started_at, created_at, updated_at) " +
"VALUES (@id, @a, @i, @s, @side, @p, @q, @q, @k, 1, 0, @r, @st, @at, @t, @t)",
cancellationToken, ("id", ids.Next()), ("a", account), ("i", instrument), ("s", strategy), ("side", side), ("p", purpose), ("q", quantity),
("k", Trading.ClientOrderIds.Key(decision)), ("r", Math.Round(reference, 6)), ("st", Trading.ExecutionStates.Done), ("at", at), ("t", now)).ConfigureAwait(false);
var buy = ids.Next();
await DecideAsync(buy, Trading.DecisionStages.Strategy, Trading.DecisionOutcomes.Proposed, [entry], opened.AddMinutes(-1)).ConfigureAwait(false);
await DecideAsync(buy, Trading.DecisionStages.Correctives, Trading.DecisionOutcomes.Passed, [], opened.AddMinutes(-1)).ConfigureAwait(false);
await DecideAsync(buy, Trading.DecisionStages.Risk, Trading.DecisionOutcomes.Passed, [], opened.AddMinutes(-1)).ConfigureAwait(false);
await ExecuteAsync("buy", "entry", buy, bought / quantity / 1.0002m, opened).ConfigureAwait(false);
if (stopped)
{
await ExecuteAsync("sell", "protective", ids.Next(), sold / quantity * 1.0003m, closed).ConfigureAwait(false);
}
else
{
var sale = ids.Next();
await DecideAsync(sale, Trading.DecisionStages.Strategy, Trading.DecisionOutcomes.Proposed, [exit], closed.AddMinutes(-1)).ConfigureAwait(false);
await ExecuteAsync("sell", "exit", sale, sold / quantity * 1.0001m, closed).ConfigureAwait(false);
}
}
+4
View File
@@ -467,6 +467,10 @@ public sealed class RiskEngine(Database db, IClock clock, Ledger ledger, StageBo
return total;
}
/// <summary>What the bot as a whole remembers: a "stop and close all" still waiting for the open.</summary>
public async Task<BotRiskState> BotAsync(CancellationToken cancellationToken) =>
await LoadAsync<BotRiskState>(BotRow, cancellationToken).ConfigureAwait(false) ?? new BotRiskState();
/// <summary>The risk events, newest first, for the Rischio screen.</summary>
public Task<List<(DateTimeOffset At, string Kind, string Severity, string Message, string? World)>> EventsAsync(int limit, CancellationToken cancellationToken) =>
db.ReadAsync(s => s.QueryAsync("SELECT occurred_at, kind, severity, message, world FROM risk_events ORDER BY occurred_at DESC, id DESC LIMIT @n",
+29
View File
@@ -348,6 +348,35 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent,
}, cancellationToken).ConfigureAwait(false);
}
/// <summary>The phrase that confirms more risk while real money is in play.</summary>
public const string RaisePhrase = "confermo più rischio con soldi veri";
/// <summary>True when a strategy, of <paramref name="broker"/> or of any broker when null, is in reduced or real.</summary>
public async Task<bool> AnyLiveAsync(string? broker, CancellationToken cancellationToken) =>
(await AllAsync(cancellationToken).ConfigureAwait(false)).Any(s => StrategyStages.IsLive(s.Stage) && (broker is null || StrategyNames.BrokerOf(s.Strategy) == broker));
/// <summary>
/// Raising a risk limit or the capital while a strategy has real money needs the confirmation of SPEC 12.4: the
/// typed phrase and a fresh password and second factor. Without real money in play it passes as it is.
/// </summary>
public async Task ConfirmRaiseAsync(string? broker, string? phrase, string? password, string? code, CancellationToken cancellationToken)
{
if (!await AnyLiveAsync(broker, cancellationToken).ConfigureAwait(false))
{
return;
}
if (!string.Equals(phrase?.Trim(), RaisePhrase, StringComparison.Ordinal))
{
throw new LiveConfirmationException("phrase", $"Con soldi veri in gioco, per alzare un limite scrivi \"{RaisePhrase}\".");
}
if (password is null || !await reauthenticate(password, code, cancellationToken).ConfigureAwait(false))
{
throw new LiveConfirmationException("password", "Password o codice non corretti.");
}
}
/// <summary>
/// The user takes real money away from a strategy (SPEC 12.3, 12.4): back to simulation, and the real positions,
/// if any, stay in exit only until they are at zero.
+179
View File
@@ -0,0 +1,179 @@
using System.Net;
using Anubis.Core;
using Anubis.Db;
using Anubis.Risk;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>
/// The Operazioni, Strategie and Rischio screens and the risk part of Impostazioni (issue #45; mockups 03, 04, 07).
/// </summary>
[TestClass]
public sealed class StrategyScreensTests
{
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheDemoShowsTradesStrategiesAndRiskAsInTheMockups()
{
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]);
var demoRoot = server.Host.Config.Data.Root;
try
{
// Mockup 03: the balance of the 41 trades of appendix F, and the "why" of each from the decisions.
var trades = await server.TextAsync("/operazioni");
foreach (var text in new[]
{
"1,62", "+239,27", "22 su 41", "53,7%", "+28,42", "20,31", "14,82", "Mostrate 20 di 41", "Tornata sopra la media a 5 giorni",
"Perché l'ho comprata", "Tutti i limiti di rischio rispettati", "Stop di protezione raggiunto",
})
{
StringAssert.Contains(trades, text, $"Missing {text} on Operazioni.");
}
StringAssert.Contains(await server.TextAsync("/operazioni?esito=perdite"), "Mostrate 19 di 19");
using (var csv = await server.GetAsync("/api/operazioni.csv"))
{
Assert.AreEqual(HttpStatusCode.OK, csv.StatusCode);
Assert.AreEqual("text/csv", csv.Content.Headers.ContentType?.MediaType);
var lines = System.Text.Encoding.UTF8.GetString((await csv.Content.ReadAsByteArrayAsync())[3..]).Split('\n', StringSplitOptions.RemoveEmptyEntries);
Assert.HasCount(42, lines, "a header and the 41 trades");
}
// Mockup 04: the four stages, 58 days of 60, the same result as on Conti.
var strategies = await server.TextAsync("/strategie");
foreach (var text in new[] { "Il percorso verso i soldi veri", "Reale ridotto", "3 strategie", "+231,60", "Giorni in simulazione", "58", "Disponibile tra 2 giorni" })
{
StringAssert.Contains(strategies, text, $"Missing {text} on Strategie.");
}
Assert.IsFalse(strategies.Contains("/azioni/strategie/", StringComparison.Ordinal), "The demo changes no stage.");
// Mockup 07: no block, the limits with their use, the worst fall of the demo, the scenarios.
var risk = await server.TextAsync("/rischio");
foreach (var text in new[] { "Nessun blocco attivo", "64,1%", "2,82% il 5 set", "Se succedesse domani", "465", "Cosa il bot non può fare, mai" })
{
StringAssert.Contains(risk, text, $"Missing {text} on Rischio.");
}
var settings = await server.TextAsync("/impostazioni");
StringAssert.Contains(settings, "Perdita in un giorno (%)");
Assert.IsFalse(settings.Contains("/azioni/rischio/limiti", StringComparison.Ordinal), "No risk form in the demo.");
}
finally
{
TempFolder.Delete(demoRoot);
}
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AStrategyThatFailedItsBacktestCannotEnterTheSimulation()
{
var network = new FakeHttp().On(_ => true, _ => FakeHttp.Respond("not here", HttpStatusCode.NotFound));
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), marketHttp: network, trading: true);
await server.SignInFirstTimeAsync();
// The outcome file of crypto_trend says "not passed"; the stock ones wait for the Alpaca keys.
var page = await server.TextAsync("/strategie");
StringAssert.Contains(page, "Non supera i test");
StringAssert.Contains(page, "In attesa dei dati");
Assert.IsFalse(page.Contains("/azioni/strategie/crypto_trend/simulazione", StringComparison.Ordinal), "No button for a strategy that did not pass.");
using var refused = await server.PostFormAsync("/strategie", "/azioni/strategie/crypto_trend/simulazione");
Assert.AreEqual("/strategie?errore=backtest", ServerHarness.Location(refused));
Assert.AreEqual(StrategyStages.Observation, (await server.Host.Services!.Trading!.Stages.GetAsync(StrategyNames.CryptoTrend, CancellationToken.None))!.Stage);
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task LimitsGoDownFreelyAndUpOnlyWithThePhraseWhileAStrategyUsesRealMoney()
{
var network = new FakeHttp().On(_ => true, _ => FakeHttp.Respond("not here", HttpStatusCode.NotFound));
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), marketHttp: network, trading: true);
var password = await server.SignInFirstTimeAsync();
var services = server.Host.Services!;
var daily = RiskSettings.DailyLoss.Key;
// Out of range, or the halving after the switch: nothing changes.
using (var wrong = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (daily, "50")))
{
Assert.AreEqual("/impostazioni?errore=limite#rischio", ServerHarness.Location(wrong));
}
using (var order = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (RiskSettings.DrawdownHalf.Key, "20")))
{
Assert.AreEqual("/impostazioni?errore=ordine-limiti#rischio", ServerHarness.Location(order));
}
// Lower is always allowed.
using (var lower = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (daily, "1,5")))
{
Assert.AreEqual("/impostazioni?ok=limiti#rischio", ServerHarness.Location(lower));
}
Assert.AreEqual("1.5", (await services.Settings.GetAsync(daily, CancellationToken.None)).Value);
// A strategy with real money: raising needs the phrase and the password, and the form asks for them.
await services.Db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET stage = 'reduced' WHERE strategy = @s", CancellationToken.None,
("s", StrategyNames.CryptoTrend)), CancellationToken.None);
StringAssert.Contains(await server.TextAsync("/impostazioni"), StageBook.RaisePhrase);
using (var bare = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (daily, "2")))
{
Assert.AreEqual("/impostazioni?errore=frase-rischio#rischio", ServerHarness.Location(bare));
}
using (var badPassword = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (daily, "2"), ("frase", StageBook.RaisePhrase), ("password", "not-it")))
{
Assert.AreEqual("/impostazioni?errore=password-rischio#rischio", ServerHarness.Location(badPassword));
}
Assert.AreEqual("1.5", (await services.Settings.GetAsync(daily, CancellationToken.None)).Value, "Refused raises change nothing.");
using (var confirmed = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (daily, "2"), ("frase", StageBook.RaisePhrase), ("password", password)))
{
Assert.AreEqual("/impostazioni?ok=limiti#rischio", ServerHarness.Location(confirmed));
}
Assert.AreEqual("2", (await services.Settings.GetAsync(daily, CancellationToken.None)).Value);
// Lowering again needs nothing, even now.
using var lowerAgain = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (daily, "1"));
Assert.AreEqual("/impostazioni?ok=limiti#rischio", ServerHarness.Location(lowerAgain));
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task StopCloseAndRestartGoThroughTheRiskEngine()
{
var network = new FakeHttp().On(_ => true, _ => FakeHttp.Respond("not here", HttpStatusCode.NotFound));
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), marketHttp: network, trading: true);
await server.SignInFirstTimeAsync();
var services = server.Host.Services!;
async Task<string> StateAsync() => (await services.Settings.GetAsync(SettingsStore.BotState.Key, CancellationToken.None)).Value;
using (var stop = await server.PostFormAsync("/rischio", "/azioni/bot/ferma", ("ritorno", "/rischio")))
{
StringAssert.StartsWith(ServerHarness.Location(stop), "/rischio");
}
Assert.AreEqual("stopped", await StateAsync());
StringAssert.Contains(await server.TextAsync("/rischio"), "Riparti");
// With the STOP file in the data folder the restart is refused.
var stopFile = services.Trading!.Risk!.StopFile!;
await File.WriteAllTextAsync(stopFile, "");
using (var refused = await server.PostFormAsync("/rischio", "/azioni/bot/riattiva", ("ritorno", "/rischio")))
{
StringAssert.Contains(ServerHarness.Location(refused), "errore=file-stop");
}
Assert.AreEqual("stopped", await StateAsync());
File.Delete(stopFile);
using (var restart = await server.PostFormAsync("/rischio", "/azioni/bot/riattiva", ("ritorno", "/rischio")))
{
Assert.IsFalse(ServerHarness.Location(restart).Contains("errore", StringComparison.Ordinal), ServerHarness.Location(restart));
}
Assert.AreEqual("active", await StateAsync());
}
}