diff --git a/src/Anubis.Server/Assets/app.css b/src/Anubis.Server/Assets/app.css
index 2e81dd9..c445c49 100644
--- a/src/Anubis.Server/Assets/app.css
+++ b/src/Anubis.Server/Assets/app.css
@@ -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;
diff --git a/src/Anubis.Server/Components/Icon.razor b/src/Anubis.Server/Components/Icon.razor
index 1de3da8..5267197 100644
--- a/src/Anubis.Server/Components/Icon.razor
+++ b/src/Anubis.Server/Components/Icon.razor
@@ -80,6 +80,15 @@
case "lock":
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.")
+ @if (!Shell.IsDemo) + { + +Per ogni euro perso ne ha guadagnati
+@(v.PerEuroLost is { } per ? Shell.Money(per, c) : "—")
+Guadagni incassati finora: @Shell.Money(v.Net, c, withSign: true)@(f.Period == "avvio" && f.Strategy is null && f.Account is null ? "" : " con i filtri scelti")
+La migliore @Shell.Money(best.Eur, c, withSign: true) su @best.Symbol, la peggiore @Shell.Money(worst.Eur, c, withSign: true) su @worst.Symbol.
+ } + else + { +Nessuna operazione con questi filtri.
+ } +Nessuna operazione con questi filtri.
+ } + else + { +Per questa operazione non c'è la traccia della decisione d'acquisto: è precedente al registro delle decisioni o è stata aperta senza strategia.
+ } + else + { +@t.ExitReason.
+ } + else + { +"Ferma tutto", in alto, blocca il bot. Dopo averlo usato il bot si riattiva solo da qui, mai da solo e mai da Telegram.
- } +@{ + var v = _view; + var c = _currency; +} +@if (_message is { } message) +{ +C'è il file STOP nella cartella dei dati: toglilo, poi conferma qui la ripartenza.
Con Ferma tutto 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.
+ @if (!Shell.IsDemo) + { +Anche un file chiamato STOP nella cartella dei dati ferma tutto entro un minuto.
| Limite | Adesso | Quanto ne sto usando | Soglia | Se lo supero |
|---|---|---|---|---|
| @row.Label | +@row.Now@if (row.Detail is { } d) { |
+ + @if (row.Usage is { } u) + { + + } + | +@row.Threshold | +@row.Beyond | +
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.
+ @if (v.Drawdown.Count < 2) + { +Ancora troppo poche fotografie per disegnare la curva.
+ } + 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))); + +
+ @if (-worst.Drawdown < v.Limits.DrawdownHalf / 5m)
+ {
+
Quanto perderei con le posizioni di adesso. Gli scenari si cambiano in Impostazioni.
+ @if (!v.HasPositions) + { +Nessuna posizione aperta: oggi nessuno scenario costerebbe nulla.
+ } + else + { +| Scenario | Senza stop | Con gli stop |
|---|---|---|
| @s.Scenario.Label | +@Shell.Money(s.WithoutStops, c, decimals: 0) (@Format.Percent(s.WithoutStopsShare * 100m, 1, withSign: true)) | +@(s.SameWithStops ? "uguale" : "circa " + Shell.Money(s.WithStops ?? 0m, c, decimals: 0)) | +
@StageText(stage)
++ @if (here.Count == 0) + { + Nessuna strategia + } + else + { + @foreach (var x in here) + { + + } + @(here.Count == 1 ? "1 strategia" : $"{here.Count} strategie") + } +
+@s.Description
+Conto @s.Account. Capitale assegnato: @Shell.Money(s.CapitalEur, c, decimals: 0).
+@Shell.Money(s.ResultEur, c, withSign: true)
@(s.DaysToGo is { } d ? $"Disponibile tra {d} {(d == 1 ? "giorno" : "giorni")}, se gli altri requisiti reggono" : "Non ancora: mancano dei requisiti")
+ @if (s.Requirements.Any(r => !r.Met && !StrategiesView.IsPending(r))) + { +@(v.LiveAllowed ? "Serve un conto reale di " + (broker == "okx" ? "OKX" : "Alpaca") + " nelle Impostazioni." : "La configurazione d'avvio non consente i soldi veri.")
+ } + else + { +Nessuna strategia di base in osservazione.
+ } + else + { +@report}
+ @if (passed && !Shell.IsDemo)
+ {
+
+ }
+ else if (!passed)
+ {
+ (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+ { + 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 (); + 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 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; + } +} diff --git a/src/Anubis.Server/StrategiesView.cs b/src/Anubis.Server/StrategiesView.cs new file mode 100644 index 0000000..8e831e6 --- /dev/null +++ b/src/Anubis.Server/StrategiesView.cs @@ -0,0 +1,166 @@ +using Anubis.Backtest; +using Anubis.Core; +using Anubis.Data; +using Anubis.Strategies; +using Anubis.Trading; + +namespace Anubis.Server; + +/// A strategy of the Strategie screen: its stage, results, requirements and what the user can do next. +internal sealed record StrategyCard( + StrategyStage Stage, + string Name, + string Description, + IReadOnlyListRules, + string Account, + string Currency, + decimal CapitalEur, + decimal ResultEur, + decimal ResultPercent, + decimal WorstFall, + int Closed, + int Winners, + IReadOnlyList Open, + IReadOnlyList<(DateTimeOffset At, decimal Index)> Curve, + IReadOnlyList Requirements, + string Phrase, + int? DaysToGo) +{ + public string Color => "var(--s-" + Stage.Strategy.Replace('_', '-') + ")"; + + public bool AllMet => Requirements.All(r => r.Met); +} + +/// +/// 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. +/// +internal sealed record StrategiesView(IReadOnlyListCards, bool LiveAllowed, IReadOnlyList<(Guid Id, string Name, string Broker)> LiveAccounts) +{ + /// What each base strategy does, in four lines (SPEC 8). + public static readonly IReadOnlyDictionary> Rules = new Dictionary >(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 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 (); + 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 (); + 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); + } + + /// A requirement not met yet only because time has to pass or nothing could be measured so far. + 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"); + } + + ///Why a strategy is in observation, in words: the outcome of its backtest, or the user's choice. + 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) + ".", + }; + } + + ///The report of a strategy's backtest in the repository, for the link. + public static string? ReportOf(StrategyStage stage) => stage.Qualification?.Report ?? BacktestOutcomes.Find(stage.Strategy)?.Report; +} diff --git a/src/Anubis.Server/TradesView.cs b/src/Anubis.Server/TradesView.cs new file mode 100644 index 0000000..2909280 --- /dev/null +++ b/src/Anubis.Server/TradesView.cs @@ -0,0 +1,198 @@ +using System.Globalization; +using System.Text; +using Anubis.Core; +using Anubis.Data; +using Anubis.Trading; + +namespace Anubis.Server; + +///The filters of the Operazioni screen, read from the address so a filtered page can be bookmarked. +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); + + ///The query string of this filter with one value changed. + public string Query(int? page = null) + { + var parts = new List(); + 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); + } +} + +/// A step of the "why" card: a stage of a decision in plain Italian. +internal sealed record WhyLine(string Text, bool Good); + +///A closed trade of the Operazioni screen, in its own currency and in euro. +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, + IReadOnlyListBought, IReadOnlyList Sold, decimal? EntrySlipBp, decimal? ExitSlipBp) +{ + public decimal Percent => EntryPrice * Quantity == 0m ? 0m : Realized / (EntryPrice * Quantity) * 100m; +} + +/// +/// 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). +/// +internal sealed record TradesView( + IReadOnlyListRows, + 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 Strategies) +{ + public int Losers => Matching - Winners; + + /// Euro gained for each euro lost: null while nothing was lost. + public decimal? PerEuroLost => Losses < 0m ? Gains / -Losses : null; + + public decimal Net => Gains + Losses; + + public static async TaskLoadAsync(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 (); + 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)]); + } + + /// The trades as CSV for an Italian spreadsheet: semicolons, decimal commas, one row per closed trade. + 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); + + ///+ /// 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. + /// + private static async Task<(ListBought, List 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 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 >(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
>(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); + } +} diff --git a/src/Anubis/Demo/DemoMode.cs b/src/Anubis/Demo/DemoMode.cs index 8f8494d..ae142fb 100644 --- a/src/Anubis/Demo/DemoMode.cs +++ b/src/Anubis/Demo/DemoMode.cs @@ -120,10 +120,25 @@ public static class DemoMode ["Mean reversion"] = ("equity_meanrev", alpaca, 1740.15m, 1236.71m, 0.25m), }; var currencyOf = new Dictionary
{ [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); } } diff --git a/src/Anubis/Trading/RiskEngine.cs b/src/Anubis/Trading/RiskEngine.cs index bb68abf..b0aeed2 100644 --- a/src/Anubis/Trading/RiskEngine.cs +++ b/src/Anubis/Trading/RiskEngine.cs @@ -467,6 +467,10 @@ public sealed class RiskEngine(Database db, IClock clock, Ledger ledger, StageBo return total; } + /// What the bot as a whole remembers: a "stop and close all" still waiting for the open. + public async TaskBotAsync(CancellationToken cancellationToken) => + await LoadAsync (BotRow, cancellationToken).ConfigureAwait(false) ?? new BotRiskState(); + /// The risk events, newest first, for the Rischio screen. public Task> 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", diff --git a/src/Anubis/Trading/Stages.cs b/src/Anubis/Trading/Stages.cs index 668265b..17b27ca 100644 --- a/src/Anubis/Trading/Stages.cs +++ b/src/Anubis/Trading/Stages.cs @@ -348,6 +348,35 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent, }, cancellationToken).ConfigureAwait(false); } + ///
The phrase that confirms more risk while real money is in play. + public const string RaisePhrase = "confermo più rischio con soldi veri"; + + ///True when a strategy, of + public async Taskor of any broker when null, is in reduced or real. AnyLiveAsync(string? broker, CancellationToken cancellationToken) => + (await AllAsync(cancellationToken).ConfigureAwait(false)).Any(s => StrategyStages.IsLive(s.Stage) && (broker is null || StrategyNames.BrokerOf(s.Strategy) == broker)); + + /// + /// 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. + /// + 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."); + } + } + ////// 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. diff --git a/tests/Anubis.Tests/StrategyScreensTests.cs b/tests/Anubis.Tests/StrategyScreensTests.cs new file mode 100644 index 0000000..e5f6a40 --- /dev/null +++ b/tests/Anubis.Tests/StrategyScreensTests.cs @@ -0,0 +1,179 @@ +using System.Net; +using Anubis.Core; +using Anubis.Db; +using Anubis.Risk; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// +/// The Operazioni, Strategie and Rischio screens and the risk part of Impostazioni (issue #45; mockups 03, 04, 07). +/// +[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 TaskStateAsync() => (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()); + } +}