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": break; + case "search": + + break; + case "ban": + + break; + case "tick": + + break; case "logout": break; diff --git a/src/Anubis.Server/Components/Pages/Impostazioni.razor b/src/Anubis.Server/Components/Pages/Impostazioni.razor index 52a35e8..cf5d79b 100644 --- a/src/Anubis.Server/Components/Pages/Impostazioni.razor +++ b/src/Anubis.Server/Components/Pages/Impostazioni.razor @@ -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.", })

} @@ -30,7 +33,7 @@ }
@@ -135,7 +138,56 @@ }
+
+

Rischio

+

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) + { +
+ + @foreach (var l in _limits) + { + + } + @if (_anyLive) + { + + + + } + + +

Protezione day trade

+
+ + + + + +

Scenari «Se succedesse domani»

+
+ + + + + + } + else + { +
+ @foreach (var l in _limits) + { +
@l.Label
@l.Value
+ } +
+ } +
+
+

Dati

@if (Host.Services!.MarketData is not { } market) { @@ -302,7 +354,13 @@ private sealed record BrokerSetup(string Broker, string Title, string Short, IReadOnlyList Keys, AccountState? State, EntrustedCapital? Entrusted, IReadOnlyList Strategies); + private sealed record LimitField(string Key, string Label, string Value, bool ReadOnly); + private readonly List _limits = []; + private bool _anyLive; + private string _pdt = "off"; + private string _scenarios = ""; private IReadOnlyList _sources = []; + private SettingValue _meetings = new(SettingsStore.CentralBankMeetings.Key, "", false, null); private List _history = []; private IReadOnlyList _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), }; diff --git a/src/Anubis.Server/Components/Pages/Operazioni.razor b/src/Anubis.Server/Components/Pages/Operazioni.razor index 12359a1..080259c 100644 --- a/src/Anubis.Server/Components/Pages/Operazioni.razor +++ b/src/Anubis.Server/Components/Pages/Operazioni.razor @@ -1,5 +1,233 @@ +@inherits LoadedComponent @page "/operazioni" +@inject AnubisHost Host +@inject ShellData Shell +@inject IClock Clock +@using Anubis.Trading Operazioni · Anubis -Quando il bot comincerà a lavorare, qui troverai ogni operazione con il suo risultato e il perché di ogni ingresso e uscita. +@{ + var v = _view; + var c = _currency; + var f = _filter; +} +@if (v.Total == 0) +{ + 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 Strategie. +} +else +{ +
+
+

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")

+
+
In guadagno
@v.Winners su @v.Matching@Format.Percent(v.Matching == 0 ? 0 : (decimal)v.Winners / v.Matching * 100m)
+
Guadagno medio
@(v.Winners == 0 ? "—" : Shell.Money(v.Gains / v.Winners, c, withSign: true))su @v.Winners @(v.Winners == 1 ? "operazione" : "operazioni")
+
Perdita media
@(v.Losers == 0 ? "—" : Shell.Money(v.Losses / v.Losers, c, withSign: true))su @v.Losers @(v.Losers == 1 ? "operazione" : "operazioni")
+
Commissioni
@Shell.Money(v.Fees, c)già tolte
+
+
+
+

Risultato di ogni operazione dalla prima all'ultima; in alto i guadagni, in basso le perdite

+ @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); + + + @for (var i = 0; i < v.Bars.Count; i++) + { + var b = v.Bars[i]; + var h = Math.Abs(b.Eur) / max * 70m; + + } + +

@Day(v.Bars[0].At)@Day(v.Bars[^1].At)

+

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.

+ } +
+
+ +
+

Operazioni chiuse

+
+ + + + + + + Esporta CSV +
+ + @if (v.Rows.Count == 0) + { +

Nessuna operazione con questi filtri.

+ } + else + { +
+ + @foreach (var t in v.Rows) + { + var gain = t.RealizedEur >= 0; +
+ + @When(t.ClosedAt) + @t.Symbol @t.Name + @StrategyNames.Label(t.Strategy) + @Duration(t) + @Format.Money(t.EntryPrice, t.Currency, decimals: t.EntryPrice >= 1m ? 2 : 4) → @Format.Money(t.ExitPrice, t.Currency, decimals: t.ExitPrice >= 1m ? 2 : 4) + @Shell.Money(t.RealizedEur, c, withSign: true) (@Format.Percent(t.Percent, 2, withSign: true)) + @t.ExitReason + +
+
+

Perché l'ho comprata

+ @if (t.Bought.Count == 0) + { +

Per questa operazione non c'è la traccia della decisione d'acquisto: è precedente al registro delle decisioni o è stata aperta senza strategia.

+ } + else + { +
    + @foreach (var line in t.Bought) + { +
  • @line.Text
  • + } +
+ } +
+
+

Perché l'ho venduta

+ @if (t.Sold.Count == 0) + { +

@t.ExitReason.

+ } + else + { +
    + @foreach (var line in t.Sold) + { +
  • @line.Text
  • + } +
+ } + +
+
+
+ } +
+ var pages = (v.Matching + TradeFilter.PageSize - 1) / TradeFilter.PageSize; +
+ Mostrate @v.Rows.Count di @v.Matching + @if (f.Page > 1) + { + Più recenti + } + @if (f.Page < pages) + { + Più vecchie + } +
+ } +
+} + +@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) : "—"; +} diff --git a/src/Anubis.Server/Components/Pages/Rischio.razor b/src/Anubis.Server/Components/Pages/Rischio.razor index 26eefce..07cb977 100644 --- a/src/Anubis.Server/Components/Pages/Rischio.razor +++ b/src/Anubis.Server/Components/Pages/Rischio.razor @@ -1,30 +1,298 @@ @inherits LoadedComponent @page "/rischio" @inject AnubisHost Host +@inject ShellData Shell +@inject IClock Clock +@using Anubis.Trading +@using Anubis.Risk Rischio · Anubis -
-

Interruttore

- @if (_bot == "stopped") - { -

"Ferma tutto" è acceso: il bot non apre e non gestisce operazioni finché non lo riattivi.

-
- - - - - } - 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) +{ +

@message

+} +
+
+
+

Interruttore d'emergenza

+ @BotText(v.BotState) +
+ @if (v.BotState == "stopped") + { +

+ @if (v.Risk.State.Tripped) + { + L'interruttore è scattato: il calo dal massimo ha superato il @Format.Percent(v.Limits.DrawdownStop * 100m, 0). + } + Il bot non apre posizioni e non vende per le strategie; gli stop di protezione restano attivi. + @if (v.CloseAllPending) + { + Sta vendendo tutte le posizioni: ciò che è su un mercato chiuso parte all'apertura. + } +

+ @if (v.StopFile) + { +

C'è il file STOP nella cartella dei dati: toglilo, poi conferma qui la ripartenza.

+ } + @if (!Shell.IsDemo) + { +
+ + + + + } + } + else + { +

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.

+ } +
+
+

Blocchi automatici

+ @if (!v.AnyBlock) + { +

Nessun blocco attivo

+ } + else + { +
    + @if (v.Risk.State.Tripped) + { +
  • Interruttore scattato @(v.Risk.State.TrippedAt is { } at ? "il " + Moment(at) : ""): aspetta la tua conferma.
  • + } + @if (v.Risk.State.DailyBlockUntil is { } until && until > Clock.UtcNow) + { +
  • Perdita del giorno oltre il limite: niente nuovi ingressi fino a @Moment(until).
  • + } + @if (v.Risk.State.WeeklyHalvingUntil is { } half && half > Clock.UtcNow) + { +
  • Perdita della settimana oltre il limite: rischio dimezzato fino a @Moment(half).
  • + } + @if (v.Risk.Measures.Drawdown <= -v.Limits.DrawdownHalf && !v.Risk.State.Tripped) + { +
  • Calo dal massimo oltre il @Format.Percent(v.Limits.DrawdownHalf * 100m, 0): rischio dimezzato.
  • + } + @if (v.BotState == "paused") + { +
  • Bot in pausa: niente nuovi ingressi, stop e uscite proseguono.
  • + } + @if (v.BotState == "stopped" && !v.Risk.State.Tripped) + { +
  • Ferma tutto acceso.
  • + } +
+ } +
+
Prossimo blocco in programma
+ @if (v.NextCalendarBlock is { } next) + { +
@Capital(Local(next.From, "dddd d MMMM")), dalle @Local(next.From, "HH:mm") alle @Local(next.To, "HH:mm")@next.Title: in quell'ora non apro posizioni.
+ } + else + { +
Nessun dato economico importante nei prossimi 14 giorni.
+ } +
Ultimo blocco scattato
+ @if (v.LastCalendarBlock is { } last) + { +
@Capital(Local(last.From, "dddd d MMMM")), dalle @Local(last.From, "HH:mm") alle @Local(last.To, "HH:mm")@last.Title.
+ } + else + { +
Nessuno negli ultimi 14 giorni.
+ } +
Protezione day trade (azioni)
+
@(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 $.")
+
+
+
+ +
+
+

I limiti Valgono per tutte le strategie insieme@(v.World == Worlds.Real ? ", sui conti veri" : ", nel mondo simulato"). Si cambiano dalle impostazioni, mai da soli.

+
+
+ + + + + + @foreach (var row in v.Rows) + { + + + + + + + + } + +
LimiteAdessoQuanto ne sto usandoSogliaSe lo supero
@row.Label@row.Now@if (row.Detail is { } d) { (@d)} + @if (row.Usage is { } u) + { + + } + @row.Threshold@row.Beyond
+
-Limiti di perdita, calo dal massimo, esposizione e scenari arrivano con le strategie e il controllo del rischio. + +
+
+

Quanto è sceso dal massimo

+

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))); + + + 0% + @Format.Percent(floor * 100m, 1) + + + + @Format.Percent(worst.Drawdown * 100m, 2) il @Local(worst.At, "d MMM") + +

+ @if (-worst.Drawdown < v.Limits.DrawdownHalf / 5m) + { + 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. + } + else + { + 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. + } +

+ } +
+
+

Se succedesse domani

+

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 + { +
+ + + + @foreach (var s in v.Scenarios) + { + + + + + + } + +
ScenarioSenza stopCon 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))
+
+

Gli stop non sono una garanzia: in un crollo improvviso il prezzo può saltarli. E nessuno stop protegge dal cambio.

+ } +
+
+ +
+
+

Cosa il bot non può fare, mai

+
    +
  • Usare soldi presi in prestito o vendere allo scoperto
  • +
  • Prelevare o spostare denaro: le chiavi dei conti non lo permettono
  • +
  • Toccare posizioni che non ha aperto lui
  • +
  • Passare ai soldi veri senza la tua conferma
  • +
  • Rischiare di più per recuperare una perdita
  • +
  • Comprare di più perché lo suggerisce una notizia o il modello
  • +
+
+
+
+

Eventi di rischio

+ @if (v.Events.Count == 0) + { + Nessun limite superato dall'avvio + } +
+ @if (v.Events.Count > 0) + { +
+ @foreach (var e in v.Events) + { +
@Local(e.At, "d MMMM")
+
@e.Message
+ } +
+ Vedi tutto nel diario + } +
+
@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..]; } diff --git a/src/Anubis.Server/Components/Pages/Strategie.razor b/src/Anubis.Server/Components/Pages/Strategie.razor index 08c50f0..9b81385 100644 --- a/src/Anubis.Server/Components/Pages/Strategie.razor +++ b/src/Anubis.Server/Components/Pages/Strategie.razor @@ -1,5 +1,234 @@ +@inherits LoadedComponent @page "/strategie" +@inject AnubisHost Host +@inject ShellData Shell +@inject IClock Clock +@using Anubis.Trading Strategie · Anubis -Arrivano dopo il laboratorio: ognuna con la sua descrizione, i requisiti per passare allo stadio successivo e i risultati. +@{ + 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) +{ +

@message

+} +
+

Il percorso verso i soldi veri Una strategia avanza solo se supera tutti i requisiti e se lo confermi tu. Se peggiora, torna indietro da sola.

+
    + @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(); +
  1. + @(i + 1) + @Capital(StrategyStages.Label(stage)) +

    @StageText(stage)

    +

    + @if (here.Count == 0) + { + Nessuna strategia + } + else + { + @foreach (var x in here) + { + + } + @(here.Count == 1 ? "1 strategia" : $"{here.Count} strategie") + } +

    +
  2. + } +
+
+ +@foreach (var s in working) +{ + var up = s.ResultEur >= 0; +
+
+

@s.Name @(s.Stage.ExitOnly ? "Sola uscita" : "In " + StrategyStages.Label(s.Stage.Stage).ToLower(CultureInfo.GetCultureInfo("it-IT")))

+

@s.Description

+
    + @foreach (var rule in s.Rules) + { +
  • @rule
  • + } +
+

Conto @s.Account. Capitale assegnato: @Shell.Money(s.CapitalEur, c, decimals: 0).

+
+
+

@Shell.Money(s.ResultEur, c, withSign: true) @Format.Percent(s.ResultPercent, 2, withSign: true)

+ @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))); + + } + +
+
+

Requisiti per @(s.Stage.Stage == StrategyStages.Reduced ? "il reale pieno" : StrategyStages.IsLive(s.Stage.Stage) ? "restare con soldi veri" : "usare soldi veri")

+
    + @foreach (var r in s.Requirements) + { +
  • + + @r.Label: @r.Value (@r.Target) +
  • + } +
+ @if (s.Stage.ExitOnly) + { +

Tornata indietro con posizioni vere ancora aperte: le gestisce fino a zero, con i loro stop, senza nuovi acquisti.

+ } + @if (StrategyStages.IsLive(s.Stage.Stage) && !Shell.IsDemo) + { +
+ + + + } + @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) + { +

@(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))) + { +

Per ora non merita soldi veri. Resta in simulazione finché non migliora.

+ } + } + else if (!v.LiveAllowed || accounts.Count == 0 || Shell.IsDemo) + { +

@(v.LiveAllowed ? "Serve un conto reale di " + (broker == "okx" ? "OKX" : "Alpaca") + " nelle Impostazioni." : "La configurazione d'avvio non consente i soldi veri.")

+ } + else + { +
+ @target +
+ +

Stai per affidare soldi veri a @s.Name@(s.Stage.Stage == StrategyStages.Simulation ? ", con un quarto del capitale" : ""). Per confermare scrivi la frase qui sotto e la tua password.

+ + + + + + +
+ } + } + @if (s.Stage.Stage == StrategyStages.Simulation && !Shell.IsDemo) + { +
+ + + + } +
+
+} + +
+ + @if (watching.Count == 0) + { +

Nessuna strategia di base in osservazione.

+ } + else + { +
+ @foreach (var s in watching) + { + var report = StrategiesView.ReportOf(s.Stage); + var passed = s.Stage.Qualification?.Passed == true; +
@s.Name
+
+ @StrategiesView.ObservationReason(s.Stage)@if (report is not null) { Rapporto: @report} + @if (passed && !Shell.IsDemo) + { +
+ } + else if (!passed) + { + @(s.Stage.Qualification?.Verdict.Contains("Alpaca", StringComparison.Ordinal) == true ? "In attesa dei dati" : "Non supera i test") + } +
+ } +
+ } +
+ +@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); +} diff --git a/src/Anubis.Server/Endpoints.cs b/src/Anubis.Server/Endpoints.cs index 7ac0522..406bd08 100644 --- a/src/Anubis.Server/Endpoints.cs +++ b/src/Anubis.Server/Endpoints.cs @@ -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); } diff --git a/src/Anubis.Server/Forms.cs b/src/Anubis.Server/Forms.cs index e13a5ed..92f8e34 100644 --- a/src/Anubis.Server/Forms.cs +++ b/src/Anubis.Server/Forms.cs @@ -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 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")); } /// The user's choice for an account in prudent mode after the 15 minutes (SPEC 7.4): align or leave out. @@ -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"); } + /// + /// 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. + /// + private static async Task 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); + } + } + + /// + /// 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). + /// + private static async Task 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(StringComparer.Ordinal); + var next = new Dictionary(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"); + } + + /// The day-trade guard and the scenarios of the Rischio screen: they change no limit, so no procedure. + private static async Task 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"); + } + + /// Null when more risk may go ahead; otherwise the error code for the page. + private static async Task 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"; + } + } + /// /// 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. diff --git a/src/Anubis.Server/ReasonTexts.cs b/src/Anubis.Server/ReasonTexts.cs new file mode 100644 index 0000000..8f4fbd5 --- /dev/null +++ b/src/Anubis.Server/ReasonTexts.cs @@ -0,0 +1,124 @@ +using System.Globalization; +using System.Text.Json; +using Anubis.Core; +using Anubis.Trading; + +namespace Anubis.Server; + +/// +/// 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. +/// +internal static class ReasonTexts +{ + private static readonly Dictionary 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 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", + }; + + /// Why a trade was closed, in a short sentence. + 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; + + /// The lines of one stage of a decision. is the JSON of the numbers the stage used. + public static IEnumerable Stage(string stage, string outcome, IReadOnlyList 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 ""; + } +} diff --git a/src/Anubis.Server/RiskView.cs b/src/Anubis.Server/RiskView.cs new file mode 100644 index 0000000..7101cda --- /dev/null +++ b/src/Anubis.Server/RiskView.cs @@ -0,0 +1,134 @@ +using Anubis.Core; +using Anubis.Data; +using Anubis.Risk; +using Anubis.Strategies; +using Anubis.Trading; + +namespace Anubis.Server; + +/// A row of the limits table: what is used now against the threshold, and what happens beyond it. +internal sealed record LimitRow(string Label, string Now, string? Detail, decimal? Usage, string Threshold, string Beyond, string Key); + +/// A point of the fall from the high, as a fraction: 0 at the high, −0,03 three percent below. +internal sealed record DrawdownPoint(DateTimeOffset At, decimal Drawdown); + +/// +/// 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. +/// +internal sealed record RiskView( + string BotState, + bool StopFile, + bool CloseAllPending, + string World, + WorldRisk Risk, + RiskLimits Limits, + IReadOnlyList Rows, + IReadOnlyList Drawdown, + IReadOnlyList 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 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(null), (_, _) => Task.FromResult(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, + IReadOnlyList Rules, + 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(IReadOnlyList Cards, 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, + IReadOnlyList Bought, 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( + IReadOnlyList 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 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 Task 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(); + 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<(List Bought, 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 Task BotAsync(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 or of any broker when null, is in reduced or real. + public async Task 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 Task 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()); + } +}