diff --git a/src/Anubis.Server/Assets/app.css b/src/Anubis.Server/Assets/app.css
index d9ca913..08d3c9f 100644
--- a/src/Anubis.Server/Assets/app.css
+++ b/src/Anubis.Server/Assets/app.css
@@ -522,6 +522,123 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we
.events dt { color: var(--text-3); }
.limits-form { max-width: none; margin-bottom: 8px; }
+/* ---- Panoramica, under the top block (mockup 01) ---- */
+.phone-only { display: none !important; }
+.next-decision { display: flex; align-items: flex-start; gap: 10px; color: var(--text-2); font-size: 14px; }
+.next-decision .icon { margin-top: 2px; color: var(--text-3); }
+.overview-row { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 20px; align-items: stretch; }
+.overview-row-wide { grid-template-columns: minmax(0, 1.85fr) minmax(0, 1fr); align-items: start; }
+.overview-empty { grid-column: span 2; display: flex; flex-direction: column; gap: 8px; color: var(--text-2); }
+.overview-account { display: flex; flex-direction: column; }
+.overview-account h2 { font-size: 15px; line-height: 22px; }
+.overview-account .account-value { margin: 12px 0 0; gap: 12px; }
+.overview-account .account-equity { font-size: 28px; line-height: 34px; }
+.split-bar.thin { height: 8px; margin-top: 16px; }
+.split-key { display: flex; justify-content: space-between; gap: 12px; flex-wrap: wrap; margin-top: 10px; color: var(--text-2); font-size: 13px; }
+.split-key > span { display: inline-flex; align-items: center; }
+.split-key .swatch { width: 9px; height: 9px; margin-right: 4px; }
+.split-key .swatch:last-of-type { margin-right: 8px; }
+.split-key strong { color: var(--text); font-weight: 600; margin-left: 6px; font-variant-numeric: tabular-nums; }
+.month { display: flex; align-items: flex-end; justify-content: space-between; gap: 12px; margin-top: 16px; padding-top: 14px; border-top: 1px solid var(--rule-inner); }
+.month > div { display: flex; flex-direction: column; }
+.month strong { font-weight: 650; font-variant-numeric: tabular-nums; }
+.spark-mini { width: 120px; height: 36px; flex: none; overflow: visible; }
+.spark-mini polyline { fill: none; stroke: var(--text-2); stroke-width: 1.5; stroke-linejoin: round; }
+.spark-mini circle { fill: var(--text); }
+.overview-account > .note { margin-top: 14px; }
+.status-pill { display: inline-flex; align-items: center; gap: 6px; font-size: 13.5px; font-weight: 600; }
+.status-pill.attention { color: var(--attention); }
+.overview-risk { display: flex; flex-direction: column; }
+.overview-risk .panel-head { margin-bottom: 10px; }
+.overview-risk > .note { margin-top: 14px; }
+.overview-risk .more { margin-top: 10px; align-self: flex-start; }
+.limit-list { display: flex; flex-direction: column; gap: 12px; }
+.limit { display: flex; flex-direction: column; gap: 6px; }
+.limit-line { display: flex; justify-content: space-between; gap: 12px; color: var(--text-2); font-size: 13.5px; font-variant-numeric: tabular-nums; }
+.limit-line strong { color: var(--text); font-weight: 650; }
+.usage.notched { overflow: visible; }
+.notch { position: absolute; top: -4px; width: 2px; height: 14px; margin-left: -1px; background: var(--text); border-radius: 1px; }
+.panel-head h2 .note { margin-left: 8px; }
+.overview-positions { padding-bottom: 6px; }
+.strategy-list { list-style: none; margin: 0; padding: 0; }
+.strategy-list li { display: flex; flex-direction: column; gap: 4px; padding: 14px 0; border-bottom: 1px solid var(--rule-inner); }
+.strategy-list li:first-child { padding-top: 4px; }
+.strategy-line { display: flex; justify-content: space-between; gap: 12px; font-variant-numeric: tabular-nums; }
+.strategy-line strong { display: inline-flex; align-items: center; font-weight: 650; }
+.strategy-bar { display: block; height: 8px; margin: 4px 0 6px; }
+.strategy-bar span { display: block; height: 100%; border-radius: 4px; }
+.info-note { margin-top: 18px; padding: 12px 16px; border-radius: 10px; background: var(--info-bg); color: var(--link); font-size: 13.5px; }
+.overview-tiles { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 28px; align-items: start; }
+.tile .panel-head { margin-bottom: 8px; }
+.tile h2 { font-size: 15px; }
+.news-list { list-style: none; margin: 0; padding: 0; }
+.news-list li { display: flex; flex-direction: column; gap: 4px; padding: 12px 0; border-bottom: 1px solid var(--rule-inner); }
+.news-list li:first-child { padding-top: 4px; }
+.news-list li:last-child { border-bottom: 0; }
+.news-list strong { font-weight: 600; }
+.news-list .attention { align-items: flex-start; font-size: 13.5px; }
+.news-list .attention .icon { margin-top: 2px; }
+.news-list .muted { font-size: 13.5px; }
+.tile > p + .limit { margin-top: 14px; }
+.tile-facts { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 8px 12px; margin: 16px 0 0; padding-top: 12px; border-top: 1px solid var(--rule-inner); font-size: 13.5px; }
+.tile-facts dt { color: var(--text-2); }
+.tile-facts dd { margin: 0; text-align: right; font-weight: 600; }
+.system-tiles { list-style: none; margin: 0; padding: 0; }
+.system-tiles li { display: grid; grid-template-columns: 16px auto minmax(0, 1fr); gap: 10px; align-items: center; padding: 8px 0; border-bottom: 1px solid var(--rule-inner); font-size: 13.5px; }
+.system-tiles li:last-child { border-bottom: 0; }
+.system-tiles .muted { text-align: right; }
+.ok > .icon { color: var(--gain); }
+.warn > .icon { color: var(--attention); }
+.off > .icon { color: var(--text-3); }
+.phone-list { list-style: none; margin: 0; padding: 0; }
+.phone-list li { display: flex; justify-content: space-between; gap: 12px; padding: 14px 0; border-top: 1px solid var(--rule-inner); }
+.phone-list li > span { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
+.phone-list .num { align-items: flex-end; text-align: right; font-variant-numeric: tabular-nums; }
+.phone-list .sub { display: inline-flex; align-items: center; gap: 6px; color: var(--text-2); font-size: 14px; }
+.phone-list .sub.gain, .phone-list strong.gain { color: var(--gain); }
+.phone-list .sub.loss, .phone-list strong.loss { color: var(--loss); }
+.phone-list .swatch { margin-right: 0; }
+.phone-list .dot.down { background: var(--loss); }
+
+/* ---- Diario e sistema (mockup 08) ---- */
+.journal-columns { display: grid; grid-template-columns: minmax(0, 1.75fr) minmax(0, 1fr); gap: 24px; align-items: start; }
+.journal { padding: 24px 26px; }
+.journal-head { display: flex; align-items: center; justify-content: space-between; gap: 12px 16px; flex-wrap: wrap; }
+.journal-search { flex: 0 1 330px; }
+.chips { display: flex; flex-wrap: wrap; gap: 8px; margin: 16px 0 8px; }
+.chip { display: inline-flex; align-items: center; min-height: 32px; padding: 0 14px; border: 1px solid var(--control); border-radius: 999px; color: var(--text); text-decoration: none; font-size: 14px; }
+.chip:hover { background: var(--surface-2); }
+.chip.on { background: var(--text); border-color: var(--text); color: var(--surface); font-weight: 550; }
+.journal-found { margin-top: 12px; }
+.panel h3.journal-day { margin: 28px 0 0; padding-bottom: 10px; border-bottom: 2px solid var(--text); font-size: 14.5px; }
+.journal-list { list-style: none; margin: 0; padding: 0; }
+.journal-list li { display: grid; grid-template-columns: 44px 22px minmax(0, 1fr) auto; gap: 12px; align-items: start; padding: 12px 0; border-bottom: 1px solid var(--rule-inner); }
+.journal-list time { color: var(--text-3); font-variant-numeric: tabular-nums; }
+.journal-icon { color: var(--text-2); margin-top: 1px; }
+.attention-entry .journal-icon { color: var(--attention); }
+.journal-text { min-width: 0; display: flex; flex-direction: column; gap: 4px; overflow-wrap: anywhere; }
+.journal-text strong { font-weight: 650; }
+.journal-rest { color: var(--text-2); }
+.journal-kind { color: var(--text-3); font-size: 13.5px; text-align: right; }
+.journal-more { display: flex; justify-content: center; margin-top: 18px; }
+.journal-side { display: flex; flex-direction: column; gap: 24px; min-width: 0; }
+.journal-side .panel-head { margin-bottom: 4px; }
+.system-parts { list-style: none; margin: 0; padding: 0; }
+.system-parts li { display: flex; align-items: flex-start; gap: 12px; padding: 12px 0; border-top: 1px solid var(--rule-inner); }
+.system-parts li > .icon { margin-top: 2px; }
+.system-parts li > span { display: flex; flex-direction: column; min-width: 0; }
+.system-parts strong { font-weight: 600; }
+.system-parts li > span > span { color: var(--text-2); }
+.job-list li { grid-template-columns: 96px minmax(0, 1fr); }
+.job-list li:last-child { border-bottom: 0; }
+.host { display: flex; flex-direction: column; gap: 12px; }
+.host > h2 { margin-bottom: 0; }
+.host .btn { align-self: flex-start; }
+@media (max-width: 1180px) {
+ .overview-row { grid-template-columns: repeat(2, minmax(0, 1fr)); }
+ .overview-row-wide, .journal-columns { grid-template-columns: minmax(0, 1fr); }
+}
+
/* ---- 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; }
@@ -601,3 +718,22 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we
.bottom-item.active { background: var(--surface-2); color: var(--text); font-weight: 650; }
.nav-item, .btn, .more-list a { min-height: 44px; }
}
+
+/* Panoramica and Diario on the phone: mockup 09, and mockup 08 stacked in one column */
+@media (max-width: 760px) {
+ .desk-only { display: none !important; }
+ .cells > .cell-extra { display: none; }
+ section.phone-only, div.phone-only, ul.phone-only { display: block !important; }
+ a.phone-only { display: inline-block !important; }
+ span.phone-only { display: inline !important; }
+ .overview-row, .overview-row-wide, .overview-tiles { grid-template-columns: minmax(0, 1fr); gap: 14px; }
+ .half-next .moves { margin-top: 4px; border-top: 1px solid var(--rule); }
+ .phone-list li:last-child { padding-bottom: 4px; }
+ .journal { padding: 18px; }
+ .journal-search { flex: 1 1 100%; }
+ .journal-list li { grid-template-columns: 40px 18px minmax(0, 1fr); gap: 4px 10px; }
+ .journal-kind { grid-column: 3; text-align: left; font-size: 12.5px; line-height: 16px; }
+ .chip { min-height: 40px; }
+ .journal-side { gap: 14px; }
+ .job-list li { grid-template-columns: 84px minmax(0, 1fr); }
+}
diff --git a/src/Anubis.Server/Components/Pages/Diario.razor b/src/Anubis.Server/Components/Pages/Diario.razor
index 280efa1..c03aaa0 100644
--- a/src/Anubis.Server/Components/Pages/Diario.razor
+++ b/src/Anubis.Server/Components/Pages/Diario.razor
@@ -5,86 +5,157 @@
Diario e sistema · Anubis
-
-
- Diario
- @if (_entries.Count == 0)
+@{
+ var d = _diary;
+ var s = _system;
+}
+
+
+
+
Diario
+
+
+
+ @foreach (var (key, label, _) in DiaryView.Filters)
+ {
+ @label
+ }
+
+ @if (d.Search is { } search)
{
- Ancora nessuna voce.
+
+ @(d.Days.Sum(x => x.Entries.Count) switch { 0 => "Nessuna voce", 1 => "Una voce", var n => $"{n} voci" }) con «@search»@(d.Truncated ? $", le {DiaryView.MaxSearchResults} più recenti" : "").
+ Togli la ricerca
+
}
- else
+ @if (d.IsEmpty && d.Search is null)
{
-
-
- Quando Tipo Voce
-
- @foreach (var e in _entries)
- {
- @Format.ShortDate(e.At, Shell.Now, Shell.Zone) @e.Kind @e.Text
- }
-
-
-
+ @(d.Filter == "tutto" ? "Ancora nessuna voce. Qui il bot scrive ogni decisione, ordine e controllo, in parole semplici, appena succede." : "Nessuna voce di questo tipo finora.")
+ }
+ @foreach (var day in d.Days)
+ {
+ @day.Heading
+
+ @foreach (var e in day.Entries)
+ {
+
+ @TimeZoneInfo.ConvertTime(e.At, Shell.Zone).ToString("HH:mm", CultureInfo.InvariantCulture)
+
+
+
@if (e.Lead is { } lead) {@lead }@foreach (var piece in e.Main) {if (piece.Class is { } css) {@piece.Text } else {@piece.Text}}
+ @if (e.Rest is { } rest)
+ {
+
@rest
+ }
+ @if (e.Trade is { } trade)
+ {
+
Perché l'ho comprata e venduta
+ }
+
+ @e.Kind
+
+ }
+
+ }
+ @if (d.HasOlder)
+ {
+
}
-
- Sistema
-
- Versione @AnubisInfo.Version
- Piattaforma @(Host.Config.Platform == PlatformKind.Docker ? "Docker" : "Desktop")
- Database @(Host.Config.Db?.Engine == DbEngine.Postgres ? "PostgreSQL" : "SQLite") · risponde
- In funzione da @Format.Ago(Shell.Now - _since).Replace(" fa", "", StringComparison.Ordinal)
-
- Lavori in programma
-
- @foreach (var job in _upcoming)
- {
- @Format.ShortDate(job.DueUtc, Shell.Now, Shell.Zone) @job.Description
- }
-
- @if (_jobs.Count > 0)
- {
- Ultimi lavori
-
- @foreach (var job in _jobs)
+
+
+
+
+
Come sta il sistema
+ @(s.AllWell ? "Tutto regolare" : "Qualcosa da controllare")
+
+
+ @foreach (var part in s.Parts)
{
- @(job.Finished is { } f ? Format.ShortDate(f, Shell.Now, Shell.Zone) : "—") @job.Description: @Outcome(job.Outcome)
+
+
+ @part.Name @part.Detail
+
}
- }
-
+
+
+
+ Lavori in programma
+ @if (s.Jobs.Count == 0)
+ {
+ Nessun lavoro in programma: il pianificatore parte con il motore.
+ }
+ else
+ {
+
+ @foreach (var job in s.Jobs)
+ {
+ @job.Time @job.Text
+ }
+
+ }
+
+
+
+ Il computer che lo ospita
+ @foreach (var r in s.Resources)
+ {
+
+
@r.Label @r.Value @if (r.Of is { } of) { su @of }
+
+
+ }
+ @s.Running
+ Scarica i registri tecnici
+
+
@code {
- private List<(DateTimeOffset At, string Kind, string Text)> _entries = [];
- private List<(string Description, DateTimeOffset? Finished, string? Outcome)> _jobs = [];
- private IReadOnlyList _upcoming = [];
- private DateTimeOffset _since;
+ private DiaryView _diary = null!;
+ private SystemView _system = null!;
[CascadingParameter]
public HttpContext? HttpContext { get; set; }
+ [SupplyParameterFromQuery(Name = "tipo")]
+ public string? Tipo { get; set; }
+
+ [SupplyParameterFromQuery(Name = "cerca")]
+ public string? Cerca { get; set; }
+
+ [SupplyParameterFromQuery(Name = "giorni")]
+ public string? Giorni { get; set; }
+
protected override async Task LoadAsync()
{
var ct = HttpContext?.RequestAborted ?? CancellationToken.None;
- var services = Host.Services!;
- (_entries, _jobs) = await services.Db.ReadAsync(async s =>
- {
- var entries = await s.QueryAsync("SELECT occurred_at, kind, message FROM journal ORDER BY occurred_at DESC LIMIT 200",
- r => (r.Moment("occurred_at"), r.Text("kind"), r.Text("message")));
- var jobs = await s.QueryAsync("SELECT description, last_finished_at, last_outcome FROM jobs ORDER BY last_finished_at DESC",
- r => (r.Text("description"), r.MomentOrNull("last_finished_at"), r.TextOrNull("last_outcome")));
- return (entries, jobs);
- }, ct);
- _upcoming = services.Scheduler.Upcoming(10);
- _since = Host.Status.Since;
+ _diary = await DiaryView.LoadAsync(Host.Services!.Db, Tipo, Cerca, Giorni, Shell.Now, Shell.Zone, ct);
+ _system = await SystemView.LoadAsync(Host, Shell, ct);
}
- private static string Outcome(string? outcome) => outcome switch
+ private static string PartClass(PartState state) => state switch
{
- "succeeded" => "fatto",
- "failed" => "non riuscito",
- "skipped" => "saltato, orario superato",
- _ => "in attesa",
+ PartState.Ok => "ok",
+ PartState.Warn => "warn",
+ _ => "off",
};
+
+ private static string PartIcon(PartState state) => state switch
+ {
+ PartState.Ok => "tick",
+ PartState.Warn => "alert",
+ _ => "clock",
+ };
+
+ private static string Css(decimal value) => Math.Round(value, 3).ToString("0.###", CultureInfo.InvariantCulture);
}
diff --git a/src/Anubis.Server/Components/Pages/Panoramica.razor b/src/Anubis.Server/Components/Pages/Panoramica.razor
index 65f86ae..643c148 100644
--- a/src/Anubis.Server/Components/Pages/Panoramica.razor
+++ b/src/Anubis.Server/Components/Pages/Panoramica.razor
@@ -2,12 +2,20 @@
@page "/"
@inject AnubisHost Host
@inject ShellData Shell
+@using Anubis.Trading
+@using Anubis.Data
Panoramica · Anubis
@{
var o = _overview;
+ var p = _panorama;
var c = _currency;
+ var moves = p.DemoMoves ?? o.Next;
+ var last = p.DemoLast ?? o.Last;
+ // On the phone only the first two moves of the bot, without the calendar's events (SPEC 13.4).
+ var phoneMoves = moves.Select((m, i) => (m, i)).Where(x => !x.m.Calendar).Take(2).Select(x => x.i).ToHashSet();
+ var v = p.Accounts;
}
@if (!o.CapitalSet && !Shell.IsDemo)
{
@@ -42,7 +50,9 @@
@Shell.Money(o.Result.Amount, c, withSign: true)
@Format.Percent(o.Result.Percent, 2, withSign: true)
- Dal @Format.LongDate(o.From), partendo da @Shell.Money(o.FromEquity, c). Commissioni già tolte.
+ var from = Format.LongDate(o.From);
+ var year = from.LastIndexOf(' ');
+ Dal @from[..year]@from[year..] , partendo da @Shell.Money(o.FromEquity, c). Commissioni già tolte.
@foreach (var (cell, i) in o.Cells.Select((x, i) => (x, i)))
{
@@ -63,47 +73,321 @@
Adesso e dopo
@if (_runningDays is { } days)
{
- Attivo da @days giorni senza interruzioni
+ Attivo da @days giorni senza interruzioni
}
@Statement(o)
- Prossime mosse
- @if (o.Next.Count == 0)
+ @if (p.NextDecision is { } decision)
{
- Niente in programma.
+ @decision
+ }
+ Prossime mosse
+ @if (moves.Count == 0)
+ {
+ Niente in programma: le mosse compaiono quando il motore di trading lavora con almeno una strategia.
}
else
{
- @foreach (var move in o.Next)
+ @for (var i = 0; i < moves.Count; i++)
{
- @move.Time @move.Text
+ var move = moves[i];
+ @move.Time @move.Text@if (move.Where is { } where) { (@where) }
}
}
- Ultime azioni
- @if (o.Last.Count == 0)
+
+
Ultime azioni
+ @if (last.Count == 0)
+ {
+
Ancora nessuna voce nel diario.
+ }
+ else
+ {
+
+ @foreach (var action in last)
+ {
+ @action.When @action.Text
+ }
+
+ }
+
Apri il diario completo
+
+ Tutte le mosse e il diario
+
+
+
+@* Accounts and the four limits (mockup 01); on the phone a compact list of the accounts (mockup 09). *@
+
+ @if (!v.HasAccounts)
+ {
+
+ Nessun conto ancora.
+ Il bot crea da solo i due simulatori interni, OKX e Alpaca, al primo avvio del motore di trading. I conti di prova compaiono quando ne aggiungi le chiavi in Impostazioni .
+
+ }
+ @foreach (var a in v.Accounts)
+ {
+ var up = a.Result >= 0;
+ var held = v.Positions.Where(x => x.AccountId == a.Id).ToList();
+ var slices = held.GroupBy(x => x.Strategy).OrderBy(g => StrategyNames.Base.ToList().FindIndex(b => b.Name == g.Key))
+ .Select(g => (Strategy: g.Key, Eur: g.Sum(x => x.ValueEur))).ToList();
+ var shares = Format.Shares([.. slices.Select(s => s.Eur), a.Eur(a.Cash)]);
+ var trend = p.Trends.GetValueOrDefault(a.Id);
+
+
+
@a.Name @a.Kind
+ @(Down(a) ? "Non risponde" : "Connesso")
+
+
+
@Shell.Money(a.Eur(a.Equity), c)
+
@Shell.Money(a.Eur(a.Result), c, withSign: true) (@Format.Percent(a.Percent, 2, withSign: true))
+
+
+ @for (var i = 0; i < slices.Count; i++)
+ {
+ if (shares[i] > 0)
+ {
+
+ }
+ }
+ @if (shares[^1] > 0)
+ {
+
+ }
+
+
+ @foreach (var s in slices) { }Investito @Shell.Money(a.InvestedEur, c)
+ Liquidità @Shell.Money(a.Eur(a.Cash), c)
+
+
+
+ Ultimi 30 giorni
+ @(trend is null ? "—" : Shell.Money(trend.Month, c, withSign: true))
+
+ @if (trend is { Points.Count: > 1 } t)
+ {
+
+
+
+
+ }
+
+ @AccountNote(a, held)
+
+ }
+
+
+
Rischio
+ @(p.LimitsKept ? "Tutti i limiti rispettati" : "Un limite chiede attenzione")
+
+
+ @foreach (var l in p.Limits)
+ {
+
+
@l.Label @l.Value su @l.Threshold
+
= 0.8m ? "high" : null)">
+
+ @if (l.Worst is { } w)
+ {
+
+ }
+
+
+ }
+
+ @if (p.Limits[1].Worst is not null && _worst is { } worst)
{
- Ancora nessuna voce nel diario.
+ La tacca segna il calo peggiore finora: @Format.Percent(worst * 100m, 2).
+ }
+ Vedi tutti i limiti
+
+
+
+@if (v.HasAccounts)
+{
+
+ Conti
+
+ @foreach (var a in v.Accounts)
+ {
+ var up = a.Result >= 0;
+
+ @a.Name @a.Kind, @(Down(a) ? "non risponde" : "connesso")
+ @Shell.Money(a.Eur(a.Equity), c) @Shell.Money(a.Eur(a.Result), c, withSign: true)
+
+ }
+
+
+}
+
+@* Positions by value and the strategies (mockup 01); on the phone the first four positions (mockup 09). *@
+
+
+
+
Posizioni aperte
+ @if (v.Positions.Count > 0)
+ {
+ @v.Positions.Count, per @Shell.Money(v.InvestedEur, c). Risultato aperto @Shell.Money(v.OpenResultEur, c, withSign: true)
+ }
+
+ @if (v.Positions.Count > 0)
+ {
+
@v.Positions.Count, risultato @Shell.Money(v.OpenResultEur, c, withSign: true)
+ }
+
Dettaglio
+
+ @if (v.Positions.Count == 0)
+ {
+ Nessuna posizione aperta. Quando una strategia compra, qui vedi ogni posizione con il suo valore, il risultato e lo stop che la protegge.
}
else
{
-
- @foreach (var action in o.Last)
+
+
+
+ Strumento Strategia Valore Risultato Stop
+
+
+ @foreach (var x in v.Positions)
+ {
+ var gain = x.ResultEur >= 0;
+
+ @x.Symbol @x.Name
+ @StrategyNames.Label(x.Strategy)
+ @Shell.Money(x.ValueEur, c)
+ @Shell.Money(x.ResultEur, c, withSign: true) (@Format.Percent(x.Percent, 2, withSign: true))
+ @if (x.Stop is { } stop) {@Format.Money(stop, x.Currency, decimals: AccountsView.StopDecimals(stop)) (@Format.Percent(x.Last == 0 ? 0 : (stop / x.Last - 1m) * 100m, 1)) } else {nessuno }
+
+ }
+
+
+
+
+ @foreach (var x in v.Positions.Take(4))
{
- @action.When @action.Text
+ var gain = x.ResultEur >= 0;
+
+ @x.Symbol @StrategyNames.Label(x.Strategy)
+ @Shell.Money(x.ValueEur, c)@Shell.Money(x.ResultEur, c, withSign: true)
+
}
- Tutto il diario
+ @(v.Positions.Count > 4 ? $"Vedi le altre {v.Positions.Count - 4}" : "Vedi i conti")
+ }
+
+
+
+ @if (p.Strategies.Count == 0)
+ {
+ Le strategie compaiono quando parte il motore di trading.
+ }
+ else
+ {
+
+ }
+ @if (!p.AnyLive)
+ {
+ Nessuna strategia usa soldi veri. Passano al conto reale solo dopo aver superato tutti i requisiti, e solo se lo confermi tu.
+ }
+
+
+
+
+
+
Rischio
+ @(p.LimitsKept ? "Limiti rispettati" : "Da controllare")
+
+
+ @foreach (var l in new[] { p.Limits[2], p.Limits[1] })
+ {
+
+
@l.Label @l.Value su @l.Threshold.Replace(",00%", "%", StringComparison.Ordinal)
+
+
+ @if (l.Worst is { } w)
+ {
+
+ }
+
+
}
+@* News, model and system (mockup 01): sections without a frame, under a dark rule (SPEC 13.2). *@
+
+
+
+ @if (p.News is null)
+ {
+ La lettura delle notizie non è ancora attiva. Quando lo sarà, qui vedrai le tre che contano di più per le tue posizioni e cosa ne ho fatto.
+ }
+ else
+ {
+
+ @foreach (var n in p.News)
+ {
+
+ @n.When, @n.About
+ @n.Title
+ @if (n.Active) { }@n.Effect
+
+ }
+
+ }
+
+
+
+ @if (p.Learning is not { } m)
+ {
+ L'apprendimento non è ancora attivo. Quando lo sarà, il modello osserverà i segnali delle strategie e qui vedrai quanto ci azzecca, prima che possa decidere qualcosa.
+ }
+ else
+ {
+ Il modello osserva e impara, ma non decide ancora.
+
+
Segnali già valutati @m.Signals su @m.Needed necessari
+
+
+
+ Previsioni azzeccate @m.Precision% su dati mai visti
+ Ultimo addestramento @m.Trained
+ Prossima verifica @m.NextCheck
+
+ }
+
+
+
+
+ @foreach (var part in p.System.Tiles)
+ {
+ @part.Name @part.Detail
+ }
+
+
+
+
@code {
private Overview _overview = null!;
+ private PanoramaView _panorama = null!;
private string _currency = "EUR";
private string _period = "avvio";
private int? _runningDays;
+ private decimal? _worst;
[CascadingParameter]
public HttpContext? HttpContext { get; set; }
@@ -118,6 +402,8 @@
var services = Host.Services!;
_currency = Shell.Effective((await services.Settings.GetAsync(SettingsStore.Currency.Key, ct)).Value);
_overview = await Overview.LoadAsync(services, _period, Shell.Now, Shell.Zone, ct);
+ _panorama = await PanoramaView.LoadAsync(Host, Shell, _overview, ct);
+ _worst = _panorama.Limits[1].Worst is { } share ? -share * (await Anubis.Risk.RiskSettings.LoadAsync(services.Settings, ct)).DrawdownStop : null;
using var aggregates = Shell.Aggregates();
_runningDays = aggregates?.RootElement.GetProperty("giorno").GetInt32();
}
@@ -135,4 +421,60 @@
: $"{o.PositionsWithoutStop} senza stop";
return o.Positions == 1 ? $"Sorveglio una posizione, {stops}. {orders}" : $"Sorveglio {o.Positions} posizioni, {stops}. {orders}";
}
+
+ private static bool Down(AccountCard a) => a.State.LastOutcome == ReconcileOutcomes.Unreachable;
+
+ private string AccountNote(AccountCard a, IReadOnlyList held)
+ {
+ var count = held.Count == 1 ? "1 posizione" : $"{held.Count} posizioni";
+ if (held.Count == 0)
+ {
+ count = "Nessuna posizione aperta";
+ }
+
+ if (a.Broker != Venues.Alpaca)
+ {
+ var stops = held.Count(x => x.Stop is not null);
+ var stopText = held.Count == 0 ? "" : stops == 1 ? ", 1 stop attivo" : $", {stops} stop attivi";
+ return $"{count}{stopText}. Commissioni pagate finora: {Shell.Money(a.Eur(a.Fees), _currency)}.";
+ }
+
+ var fractions = held.Any(x => x.Quantity != decimal.Truncate(x.Quantity));
+ var stopsText = held.Count == 0 ? ""
+ : " Stop permanenti sulle azioni intere" + (!fractions ? "." : _panorama.FractionStops is { } back
+ ? $"; sulle frazioni tornano alle {TimeZoneInfo.ConvertTime(back, Shell.Zone).ToString("HH:mm", CultureInfo.InvariantCulture)}."
+ : "; sulle frazioni valgono fino alla chiusura.");
+ var dollars = a.Currency == "USD" && a.Rate > 0m ? $" Conto in dollari: {Format.Money(a.Equity, "USD")} al cambio {Format.Quantity(a.Rate)}." : "";
+ return count + "." + stopsText + dollars;
+ }
+
+ private static string PartClass(PartState state) => state switch
+ {
+ PartState.Ok => "ok",
+ PartState.Warn => "warn",
+ _ => "off",
+ };
+
+ private static string PartIcon(PartState state) => state switch
+ {
+ PartState.Ok => "tick",
+ PartState.Warn => "alert",
+ _ => "clock",
+ };
+
+ private static string Css(decimal value) => Math.Round(value, 3).ToString("0.###", CultureInfo.InvariantCulture);
+
+ private static string Spark(IReadOnlyList points)
+ {
+ var (min, max) = (points.Min(), points.Max());
+ var range = Math.Max(0.01m, max - min);
+ return string.Join(' ', points.Select((x, i) => Css(i * 116m / (points.Count - 1) + 2m) + "," + Css(32m - (x - min) / range * 28m)));
+ }
+
+ private static (string X, string Y) SparkEnd(IReadOnlyList points)
+ {
+ var (min, max) = (points.Min(), points.Max());
+ var range = Math.Max(0.01m, max - min);
+ return ("118", Css(32m - (points[^1] - min) / range * 28m));
+ }
}
diff --git a/src/Anubis.Server/DiaryView.cs b/src/Anubis.Server/DiaryView.cs
new file mode 100644
index 0000000..5e622cb
--- /dev/null
+++ b/src/Anubis.Server/DiaryView.cs
@@ -0,0 +1,243 @@
+using System.Globalization;
+using System.Text.RegularExpressions;
+using Anubis.Core;
+using Anubis.Db;
+using Anubis.Trading;
+
+namespace Anubis.Server;
+
+/// A piece of a diary line: plain text, or an amount coloured as a gain or a loss (always with its sign).
+internal sealed record DiaryPiece(string Text, string? Class = null);
+
+///
+/// A diary entry as the page draws it (mockup 08): the first sentence as the main line, the rest underneath; a rule
+/// the bot changed shows its lead in bold; a sale that closed a trade links to its "why".
+///
+internal sealed record DiaryEntry(DateTimeOffset At, string Kind, string Icon, string? Lead, IReadOnlyList Main, string? Rest, bool Attention, string? Trade);
+
+internal sealed record DiaryDay(DateOnly Day, string Heading, IReadOnlyList Entries);
+
+///
+/// The diary of "Diario e sistema" (SPEC 13.6): in order of time, grouped by local day, with filters by kind and a
+/// search. Static pages: the filters and "Mostra i giorni precedenti" are links with query values.
+///
+internal sealed partial record DiaryView(IReadOnlyList Days, string Filter, string? Search, int Range, bool HasOlder, bool Truncated)
+{
+ /// The risk kind of the filters: not a kind of its own in the journal, but the codes of the risk engine and its relatives.
+ public const string RiskKind = "Rischio";
+
+ public const int DefaultRange = 2;
+ public const int MaxSearchResults = 200;
+
+ /// The filter chips, in the order of the mockup: query value, label, kind.
+ public static readonly IReadOnlyList<(string Key, string Label, string? Kind)> Filters =
+ [
+ ("tutto", "Tutto", null),
+ ("decisioni", "Decisioni", DiaryKinds.Decisions),
+ ("ordini", "Ordini", DiaryKinds.Orders),
+ ("notizie", "Notizie", DiaryKinds.News),
+ ("rischio", "Rischio", RiskKind),
+ ("apprendimento", "Apprendimento", DiaryKinds.Learning),
+ ("sistema", "Sistema", DiaryKinds.System),
+ ];
+
+ /// Journal codes that speak of risk without passing through risk_events: refused orders, keys, prudent accounts, the guard.
+ private static readonly string[] _riskCodes = ["order_rejected", "stop_rejected", "key_can_withdraw", "account_prudent", "guard_intervention", "clock_gap", "sell_not_filled"];
+
+ private const string RiskCondition = "(code IN (SELECT kind FROM risk_events) OR code IN ('order_rejected', 'stop_rejected', 'key_can_withdraw', 'account_prudent', 'guard_intervention', 'clock_gap', 'sell_not_filled'))";
+
+ private static readonly string[] _daysLong = ["domenica", "lunedì", "martedì", "mercoledì", "giovedì", "venerdì", "sabato"];
+ private static readonly string[] _monthsLong = ["gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre"];
+ private static readonly CompareInfo _compare = CultureInfo.GetCultureInfo("it-IT").CompareInfo;
+
+ public bool IsEmpty => Days.Count == 0;
+
+ /// The query string of this view with one value changed, for the links of the page.
+ public string Link(string? filter = null, int? range = null)
+ {
+ var parts = new List();
+ var f = filter ?? Filter;
+ if (f != "tutto")
+ {
+ parts.Add("tipo=" + Uri.EscapeDataString(f));
+ }
+
+ if (!string.IsNullOrEmpty(Search))
+ {
+ parts.Add("cerca=" + Uri.EscapeDataString(Search));
+ }
+
+ var r = range ?? Range;
+ if (r != DefaultRange)
+ {
+ parts.Add("giorni=" + r.ToString(CultureInfo.InvariantCulture));
+ }
+
+ return "/diario" + (parts.Count == 0 ? "" : "?" + string.Join('&', parts));
+ }
+
+ public static async Task LoadAsync(Database db, string? filter, string? search, string? days, DateTimeOffset now, TimeZoneInfo zone, CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(db);
+ var key = Filters.Any(f => f.Key == filter) ? filter! : "tutto";
+ var kind = Filters.First(f => f.Key == key).Kind;
+ var text = string.IsNullOrWhiteSpace(search) ? null : search.Trim();
+ if (text is { Length: > 100 })
+ {
+ text = text[..100];
+ }
+
+ var range = int.TryParse(days, NumberStyles.None, CultureInfo.InvariantCulture, out var n) ? Math.Clamp(n, 1, 3650) : DefaultRange;
+ var (where, parameters) = kind switch
+ {
+ null => ("1 = 1", Array.Empty<(string, object?)>()),
+ RiskKind => (RiskCondition, []),
+ _ => ("kind = @k AND NOT " + RiskCondition, new (string, object?)[] { ("k", kind) }),
+ };
+
+ var (rows, older, truncated) = await db.ReadAsync(async s =>
+ {
+ const string columns = "SELECT occurred_at, kind, code, message FROM journal WHERE ";
+ if (text is not null)
+ {
+ // The search reads the whole diary, newest first; the comparison is done here, the same on both engines,
+ // ignoring case and accents.
+ var all = await s.QueryAsync(columns + where + " ORDER BY occurred_at DESC LIMIT 5000", Row, parameters).ConfigureAwait(false);
+ var found = all.Where(r => _compare.IndexOf(r.Message, text, CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace) >= 0).ToList();
+ return (found.Take(MaxSearchResults).ToList(), false, found.Count > MaxSearchResults);
+ }
+
+ // The range ends on the newest day that has an entry, so a quiet bot never shows an empty page.
+ var latest = await s.FirstOrDefaultAsync("SELECT MAX(occurred_at) AS at FROM journal WHERE " + where, r => r.MomentOrNull("at"), parameters).ConfigureAwait(false);
+ if (latest is null)
+ {
+ return ([], false, false);
+ }
+
+ var today = LocalDay(now, zone);
+ var anchor = LocalDay(latest.Value, zone) is var last && last < today ? last : today;
+ var from = Start(anchor.AddDays(1 - range), zone);
+ var withFrom = parameters.Append(("from", from)).ToArray();
+ var list = await s.QueryAsync(columns + where + " AND occurred_at >= @from ORDER BY occurred_at DESC LIMIT 2000", Row, withFrom).ConfigureAwait(false);
+ var before = await s.CountAsync("SELECT COUNT(*) FROM journal WHERE " + where + " AND occurred_at < @from", withFrom).ConfigureAwait(false);
+ return (list.ToList(), before > 0, list.Count >= 2000);
+ }, cancellationToken).ConfigureAwait(false);
+
+ var risky = rows.Count == 0 ? new HashSet(StringComparer.Ordinal)
+ : (await db.ReadAsync(s => s.QueryAsync("SELECT DISTINCT kind FROM risk_events", r => r.Text("kind")), cancellationToken).ConfigureAwait(false))
+ .Concat(_riskCodes).ToHashSet(StringComparer.Ordinal);
+ var day0 = LocalDay(now, zone);
+ var grouped = rows
+ .GroupBy(r => LocalDay(r.At, zone))
+ .Select(g => new DiaryDay(g.Key, Heading(g.Key, day0), [.. g.Select(r => Entry(r.At, risky.Contains(r.Code) ? RiskKind : r.Kind, r.Code, r.Message))]))
+ .ToList();
+ return new DiaryView(grouped, key, text, range, older, truncated);
+
+ static (DateTimeOffset At, string Kind, string Code, string Message) Row(DbRow r) => (r.Moment("occurred_at"), r.Text("kind"), r.Text("code"), r.Text("message"));
+ }
+
+ /// "Oggi, venerdì 9 ottobre", "Ieri, giovedì 8 ottobre", "Mercoledì 7 ottobre"; the year when it is not this one.
+ public static string Heading(DateOnly day, DateOnly today)
+ {
+ var name = $"{_daysLong[(int)day.DayOfWeek]} {day.Day.ToString(CultureInfo.InvariantCulture)} {_monthsLong[day.Month - 1]}" +
+ (day.Year == today.Year ? "" : " " + day.Year.ToString(CultureInfo.InvariantCulture));
+ return day == today ? "Oggi, " + name : day == today.AddDays(-1) ? "Ieri, " + name : char.ToUpperInvariant(name[0]) + name[1..];
+ }
+
+ /// Splits a diary sentence the way the mockup draws it.
+ public static DiaryEntry Entry(DateTimeOffset at, string kind, string code, string message)
+ {
+ ArgumentNullException.ThrowIfNull(message);
+ // The demo's row of appendix F says in words where the link goes; the link is drawn, the words are not.
+ var text = DemoLink().Replace(message, "").Trim();
+ string main;
+ string? rest = null;
+ string? lead = null;
+ var reason = text.IndexOf(" Motivo: ", StringComparison.Ordinal);
+ var attention = reason > 0;
+ if (attention)
+ {
+ // A rule changed by the bot: what it decided, in bold up to the colon, then why.
+ main = text[..reason];
+ rest = text[(reason + 1)..];
+ var colon = main.IndexOf(':', StringComparison.Ordinal);
+ if (colon > 0)
+ {
+ lead = main[..(colon + 1)];
+ main = main[(colon + 1)..];
+ }
+ }
+ else if (text.Length > 80 && SentenceEnd().Match(text) is { Success: true } end)
+ {
+ // Long entries: the first sentence on the main line, the explanation underneath. Short ones stay on one line.
+ main = text[..end.Index];
+ rest = text[(end.Index + end.Length)..];
+ }
+ else
+ {
+ main = text;
+ }
+
+ string? trade = null;
+ if (kind == DiaryKinds.Orders && Sale().Match(text) is { Success: true } sale)
+ {
+ // A sale that closed a trade: its "why" is on the Operazioni page, found by the instrument.
+ trade = sale.Groups["symbol"].Value.Split('/')[0];
+ }
+
+ return new DiaryEntry(at, kind, IconOf(kind), lead, Pieces(main), rest, attention, trade);
+ }
+
+ private static List Pieces(string text)
+ {
+ var pieces = new List();
+ var position = 0;
+ foreach (Match m in SignedAmount().Matches(text))
+ {
+ if (m.Index > position)
+ {
+ pieces.Add(new DiaryPiece(text[position..m.Index]));
+ }
+
+ pieces.Add(new DiaryPiece(m.Value, m.Value[0] == '+' ? "gain" : "loss"));
+ position = m.Index + m.Length;
+ }
+
+ if (position < text.Length)
+ {
+ pieces.Add(new DiaryPiece(text[position..]));
+ }
+
+ return pieces;
+ }
+
+ private static string IconOf(string kind) => kind switch
+ {
+ DiaryKinds.Orders => "arrows",
+ DiaryKinds.Decisions => "layers",
+ DiaryKinds.News => "news",
+ DiaryKinds.Learning => "network",
+ RiskKind => "shield",
+ _ => "sliders",
+ };
+
+ private static DateOnly LocalDay(DateTimeOffset moment, TimeZoneInfo zone) => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(moment, zone).DateTime);
+
+ private static DateTimeOffset Start(DateOnly day, TimeZoneInfo zone)
+ {
+ var local = day.ToDateTime(TimeOnly.MinValue);
+ return new DateTimeOffset(local, zone.GetUtcOffset(local)).ToUniversalTime();
+ }
+
+ [GeneratedRegex(@"\s*\(con il collegamento ""[^""]*""\)")]
+ private static partial Regex DemoLink();
+
+ [GeneratedRegex(@"(?<=[.!?])\s+(?=[A-ZÀ-Ý0-9])")]
+ private static partial Regex SentenceEnd();
+
+ [GeneratedRegex(@"^Vendut[oaie] \S+ (?\S+) a [^:]+: [+−]")]
+ private static partial Regex Sale();
+
+ [GeneratedRegex(@"(?
+ {
+ var folder = host.Config.Data.Logs;
+ var day = TimeZoneInfo.ConvertTime(clock.UtcNow, shell.Zone).ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
+ return Results.File(LogArchive(folder), "application/zip", $"anubis-registri-{day}.zip");
+ });
+
// 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) =>
{
@@ -219,6 +228,32 @@ internal static partial class Endpoints
internal static IResult Error(int status, string code, string message) => Results.Json(new ApiError(code, message), _json, statusCode: status);
+ /// The daily log files (anubis-*.log) of a folder in a zip, newest first; an empty zip when there are none yet.
+ internal static byte[] LogArchive(string folder)
+ {
+ using var buffer = new MemoryStream();
+ using (var zip = new System.IO.Compression.ZipArchive(buffer, System.IO.Compression.ZipArchiveMode.Create, leaveOpen: true))
+ {
+ var files = Directory.Exists(folder) ? Directory.EnumerateFiles(folder, "anubis-*.log").OrderDescending(StringComparer.Ordinal).ToList() : [];
+ foreach (var file in files)
+ {
+ try
+ {
+ using var source = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
+ var entry = zip.CreateEntry(Path.GetFileName(file), System.IO.Compression.CompressionLevel.Optimal);
+ using var target = entry.Open();
+ source.CopyTo(target);
+ }
+ catch (IOException)
+ {
+ // A file removed by the rotation in the meantime: the others still go.
+ }
+ }
+ }
+
+ return buffer.ToArray();
+ }
+
private static async ValueTask CsrfFilterAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
{
var http = context.HttpContext;
diff --git a/src/Anubis.Server/Overview.cs b/src/Anubis.Server/Overview.cs
index d0943f3..dbb18fc 100644
--- a/src/Anubis.Server/Overview.cs
+++ b/src/Anubis.Server/Overview.cs
@@ -9,7 +9,8 @@ public sealed record EquityPoint(DateTimeOffset At, DateOnly Day, decimal Equity
internal sealed record PeriodResult(string Label, decimal Amount, decimal Percent);
-internal sealed record NextMove(string Time, string Text);
+/// A move of the bot with its time; is the account, marks an economic event.
+internal sealed record NextMove(string Time, string Text, string? Where = null, bool Calendar = false);
internal sealed record LastAction(string When, string Text);
@@ -30,7 +31,8 @@ internal sealed record Overview(
int OpenOrders,
IReadOnlyList Next,
IReadOnlyList Last,
- bool CapitalSet = true)
+ bool CapitalSet = true,
+ DateTimeOffset? NextDecision = null)
{
public static readonly IReadOnlyList<(string Key, string Label)> Periods = [("avvio", "Dall'avvio"), ("30", "30 giorni"), ("7", "7 giorni"), ("oggi", "Oggi")];
@@ -52,7 +54,7 @@ internal sealed record Overview(
var open = await s.CountAsync(
$"SELECT COUNT(*) FROM orders o JOIN accounts a ON a.id = o.account_id WHERE a.environment IN ({mine}) " +
"AND o.status IN ('created', 'submitted', 'partially_filled') AND (o.purpose IS NULL OR o.purpose <> 'stop')").ConfigureAwait(false);
- var j = await s.QueryAsync("SELECT occurred_at, message FROM journal ORDER BY occurred_at DESC LIMIT 4",
+ var j = await s.QueryAsync("SELECT occurred_at, message FROM journal ORDER BY occurred_at DESC LIMIT 3",
r => (At: r.Moment("occurred_at"), Text: r.Text("message"))).ConfigureAwait(false);
var capital = await s.CountAsync("SELECT COUNT(*) FROM capital_changes").ConfigureAwait(false);
return (p, held.Count, held.Count(x => x.Stop is null), open, j, capital > 0);
@@ -65,14 +67,18 @@ internal sealed record Overview(
.Select(g => g.Last())
.ToList();
- var next = services.Scheduler.Upcoming(5)
+ // The moves are the jobs that decide or send orders (SPEC 13.2), not the background work that runs every minute.
+ var moves = services.Scheduler.Upcoming(200).Where(u => u.IsMove).Take(5).ToList();
+ var next = moves
.Select(u => new NextMove(TimeZoneInfo.ConvertTime(u.DueUtc, zone).ToString("HH:mm", System.Globalization.CultureInfo.InvariantCulture), u.Description))
.ToList();
- var last = journal.Select(j => new LastAction(Format.ShortDate(j.At, now, zone), j.Text)).ToList();
+ DateTimeOffset? decision = moves.Count > 0 ? moves[0].DueUtc : null;
+ // Today's actions show the time alone, as in the mockup: "02:06", "Ieri 21:58".
+ var last = journal.Select(j => new LastAction(Today(Format.ShortDate(j.At, now, zone)), j.Text)).ToList();
if (daily.Count == 0)
{
- return new Overview([], [], new PeriodResult("", 0, 0), default, 0, [], (int)positions, (int)withoutStop, (int)orders, next, last, capitalSet);
+ return new Overview([], [], new PeriodResult("", 0, 0), default, 0, [], (int)positions, (int)withoutStop, (int)orders, next, last, capitalSet, decision);
}
var latest = daily[^1];
@@ -104,6 +110,8 @@ internal sealed record Overview(
cells.Add(new PeriodResult("Senza bot", amount, basis == 0m ? 0m : amount / basis * 100m));
}
- return new Overview(daily, series, Between("", start), start.Day, start.Equity, cells, (int)positions, (int)withoutStop, (int)orders, next, last, capitalSet);
+ return new Overview(daily, series, Between("", start), start.Day, start.Equity, cells, (int)positions, (int)withoutStop, (int)orders, next, last, capitalSet, decision);
}
+
+ private static string Today(string shortDate) => shortDate.StartsWith("Oggi ", StringComparison.Ordinal) ? shortDate["Oggi ".Length..] : shortDate;
}
diff --git a/src/Anubis.Server/PanoramaView.cs b/src/Anubis.Server/PanoramaView.cs
new file mode 100644
index 0000000..61b4b93
--- /dev/null
+++ b/src/Anubis.Server/PanoramaView.cs
@@ -0,0 +1,214 @@
+using System.Globalization;
+using System.Text.Json;
+using Anubis.Core;
+using Anubis.Data;
+using Anubis.Risk;
+using Anubis.Trading;
+
+namespace Anubis.Server;
+
+/// The last 30 days of an account: the result net of flows and the daily values in euro for the small line.
+internal sealed record AccountTrend(decimal Month, IReadOnlyList Points);
+
+/// A news item of the "Notizie che contano" tile; when its effect is still on.
+internal sealed record PanoramaNews(string When, string About, string Title, string Effect, bool Active);
+
+/// The model at a glance: signals counted toward the 300, precision on unseen cases, training and next check.
+internal sealed record PanoramaLearning(int Signals, int Needed, int Precision, string Trained, string NextCheck);
+
+/// One of the four limits of the Panoramica (SPEC 13.6): value, threshold, share used and, for the fall, the worst so far.
+internal sealed record PanoramaLimit(string Label, string Value, string Threshold, decimal Share, decimal? Worst = null);
+
+/// A strategy at a glance: result, the bar against the best one, its stage in words and its trades.
+internal sealed record PanoramaStrategy(string Name, string Color, decimal Result, decimal Bar, string Stage, string Trades);
+
+///
+/// Everything under the top block of the Panoramica (SPEC 13.6, mockup 01): accounts with their last 30 days, the
+/// four main limits, positions, strategies, news, model and system. In demo mode the values of appendix F that
+/// exist only as totals come from the aggregates (SPEC 13.1); outside it news and the model are not active yet.
+///
+internal sealed record PanoramaView(
+ AccountsView Accounts,
+ IReadOnlyDictionary Trends,
+ IReadOnlyList Limits,
+ bool LimitsKept,
+ IReadOnlyList Strategies,
+ bool AnyLive,
+ SystemView System,
+ IReadOnlyList? DemoMoves,
+ IReadOnlyList? DemoLast,
+ string? NextDecision,
+ IReadOnlyList? News,
+ PanoramaLearning? Learning,
+ DateTimeOffset? FractionStops)
+{
+ private static readonly CultureInfo _it = CultureInfo.InvariantCulture;
+
+ public static async Task LoadAsync(AnubisHost host, ShellData shell, Overview overview, CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(host);
+ ArgumentNullException.ThrowIfNull(shell);
+ ArgumentNullException.ThrowIfNull(overview);
+ var services = host.Services!;
+ var clock = host.Clock;
+ var risk = await RiskView.LoadAsync(services, clock, shell.Zone, cancellationToken).ConfigureAwait(false);
+ var accounts = await AccountsView.LoadAsync(services, clock, shell.Zone, cancellationToken).ConfigureAwait(false);
+ var strategies = await StrategiesView.LoadAsync(services, clock, false, cancellationToken).ConfigureAwait(false);
+ var system = await SystemView.LoadAsync(host, shell, cancellationToken).ConfigureAwait(false);
+ var trends = await TrendsAsync(services, accounts, shell.Now, shell.Zone, cancellationToken).ConfigureAwait(false);
+
+ // The four limits of the Panoramica, read from the same rows as the Rischio page.
+ var rows = risk.Rows.ToDictionary(r => r.Key);
+ var day = rows[RiskSettings.DailyLoss.Key];
+ var invested = rows[RiskSettings.MaxInvested.Key];
+ var biggest = rows[RiskSettings.MaxPosition.Key];
+ var fall = risk.Risk.Measures.Drawdown;
+ decimal? worst = risk.Drawdown.Count > 0 ? risk.Drawdown.Min(d => d.Drawdown) : null;
+ var stop = risk.Limits.DrawdownStop;
+ var limits = new List
+ {
+ new("Perdita di oggi", day.Now, day.Threshold, day.Usage ?? 0m),
+ new("Calo dal massimo", Format.Percent(fall * 100m, 2), Format.Percent(-stop * 100m, 2), stop <= 0m ? 0m : Math.Clamp(-fall / stop, 0m, 1m),
+ worst is { } w && stop > 0m ? Math.Clamp(-w / stop, 0m, 1m) : null),
+ new("Capitale investito", invested.Now, invested.Threshold, invested.Usage ?? 0m),
+ new("Posizione più grande" + (biggest.Detail is { } symbol ? $" ({symbol.Split('/')[0]})" : ""), biggest.Now, biggest.Threshold, biggest.Usage ?? 0m),
+ };
+ var kept = !risk.AnyBlock && risk.Rows.All(r => r.Usage is null or < 1m);
+
+ // Strategies: the bar compares each result with the best one; the stage says what is still missing.
+ var best = strategies.Cards.Select(c => Math.Abs(c.ResultEur)).DefaultIfEmpty(0m).Max();
+ var cards = strategies.Cards.Select(c => new PanoramaStrategy(c.Name, c.Color, c.ResultEur, best == 0m ? 0m : Math.Abs(c.ResultEur) / best, Stage(c), Trades(c))).ToList();
+ var anyLive = strategies.Cards.Any(c => StrategyStages.IsLive(c.Stage.Stage));
+
+ // The daily stops of the fractions come back with the orders after the open (SPEC 7.2).
+ DateTimeOffset? fractions = accounts.MarketOpen ? null : accounts.MarketNext + (services.Trading?.Engine.Options.OrdersAfterOpen ?? new LiveEngineOptions().OrdersAfterOpen);
+
+ using var aggregates = shell.Aggregates();
+ if (aggregates is null)
+ {
+ return new PanoramaView(accounts, trends, limits, kept, cards, anyLive, system, null, null, Decision(overview.NextDecision, shell.Now, shell.Zone), null, null, fractions);
+ }
+
+ var root = aggregates.RootElement;
+ var demo = root.GetProperty("panoramica");
+ var moves = demo.GetProperty("mosse").EnumerateArray().Select(m => new NextMove(m.GetProperty("ora").GetString()!, m.GetProperty("testo").GetString()!,
+ m.TryGetProperty("dove", out var where) ? where.GetString() : null, m.GetProperty("calendario").GetBoolean())).ToList();
+ var last = demo.GetProperty("ultime_azioni").EnumerateArray().Select(a => new LastAction(a.GetProperty("quando").GetString()!, a.GetProperty("testo").GetString()!)).ToList();
+ var news = root.GetProperty("notizie").GetProperty("panoramica").EnumerateArray().Select(n => new PanoramaNews(n.GetProperty("quando").GetString()!,
+ n.GetProperty("riguarda").GetString()!, n.GetProperty("titolo").GetString()!, n.GetProperty("effetto").GetString()!, n.GetProperty("in_corso").GetBoolean())).ToList();
+ var model = root.GetProperty("apprendimento");
+ var learning = new PanoramaLearning(model.GetProperty("segnali").GetInt32(), model.GetProperty("necessari").GetInt32(), model.GetProperty("precisione_pct").GetInt32(),
+ model.GetProperty("ultimo_addestramento").GetString()!, model.GetProperty("prossima_verifica").GetString()!);
+
+ // The 30-day results of appendix F.2: the generated daily series of each account only ends on its total.
+ var month = root.GetProperty("conti").EnumerateArray().ToDictionary(c => c.GetProperty("nome").GetString()!,
+ c => decimal.Parse(c.GetProperty("trenta_giorni").GetString()!, _it), StringComparer.Ordinal);
+ var demoTrends = accounts.Accounts.ToDictionary(a => a.Id,
+ a => new AccountTrend(month.GetValueOrDefault(a.Name, trends.GetValueOrDefault(a.Id)?.Month ?? 0m), trends.GetValueOrDefault(a.Id)?.Points ?? []));
+ return new PanoramaView(accounts, demoTrends, limits, kept, cards, anyLive, system, moves, last, demo.GetProperty("prossima_decisione").GetString(), news, learning, fractions);
+ }
+
+ private static async Task> TrendsAsync(AppServices services, AccountsView accounts, DateTimeOffset now, TimeZoneInfo zone,
+ CancellationToken cancellationToken)
+ {
+ var shown = accounts.Accounts.ToDictionary(a => a.Id);
+ var world = accounts.Accounts.Any(a => TradingEnvironments.World(a.Environment) == Worlds.Real) ? Worlds.Real : Worlds.Simulated;
+ var rows = await services.Db.ReadAsync(s => s.QueryAsync(
+ "SELECT taken_at, account_id, currency, equity, flows FROM equity_snapshots WHERE scope = 'account' AND world = @w AND taken_at >= @f ORDER BY taken_at, id",
+ r => (At: r.Moment("taken_at"), Account: r.IdOrNull("account_id"), Currency: r.TextOrNull("currency"), Equity: r.Money("equity"), Flows: r.MoneyOrNull("flows") ?? 0m),
+ ("w", world), ("f", now.AddDays(-32))), cancellationToken).ConfigureAwait(false);
+ var result = new Dictionary();
+ foreach (var group in rows.Where(r => r.Account is { } id && shown.ContainsKey(id)).GroupBy(r => r.Account!.Value))
+ {
+ var account = shown[group.Key];
+ decimal Eur(decimal amount, string? currency) => currency == "USD" ? account.Eur(amount) : amount;
+ var daily = group.GroupBy(r => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(r.At, zone).DateTime)).Select(g => g.Last()).ToList();
+ var latest = daily[^1];
+ var latestDay = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(latest.At, zone).DateTime);
+ var start = daily.LastOrDefault(p => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(p.At, zone).DateTime) <= latestDay.AddDays(-30));
+ start = start == default ? daily[0] : start;
+ var month = Eur(latest.Equity, latest.Currency) - Eur(start.Equity, start.Currency) - (Eur(latest.Flows, latest.Currency) - Eur(start.Flows, start.Currency));
+ var points = daily.Where(p => p.At >= start.At).Select(p => Eur(p.Equity - p.Flows, p.Currency)).ToList();
+ result[group.Key] = new AccountTrend(month, points);
+ }
+
+ return result;
+ }
+
+ /// Where a strategy is on its path, with the requirement that is furthest away: "In simulazione, giorno 58 di 60".
+ private static string Stage(StrategyCard card)
+ {
+ var stage = card.Stage.Stage;
+ if (stage == StrategyStages.Observation)
+ {
+ return "In osservazione";
+ }
+
+ if (stage == StrategyStages.Real)
+ {
+ return "Con soldi veri";
+ }
+
+ var where = stage == StrategyStages.Reduced ? "In reale ridotto" : "In simulazione";
+ var missing = card.Requirements
+ .Where(r => !r.Met && r.Key is "days" or "trades")
+ .Select(r => (r.Key, Value: Whole(r.Value), Target: Whole(r.Target)))
+ .Where(r => r.Value is not null && r.Target is > 0)
+ .OrderBy(r => (decimal)r.Value!.Value / r.Target!.Value)
+ .FirstOrDefault();
+ return missing.Key switch
+ {
+ "days" => $"{where}, giorno {missing.Value} di {missing.Target}",
+ "trades" => $"{where}, {missing.Value} operazioni su {missing.Target}",
+ _ => where,
+ };
+
+ static int? Whole(string text)
+ {
+ var digits = new string(text.Where(char.IsAsciiDigit).ToArray());
+ return int.TryParse(digits, NumberStyles.None, _it, out var n) ? n : null;
+ }
+ }
+
+ private static string Trades(StrategyCard card)
+ {
+ var open = card.Open.Distinct().Count();
+ var positions = open switch
+ {
+ 0 => "Nessuna posizione aperta",
+ 1 => "1 posizione aperta",
+ _ => $"{open} posizioni aperte",
+ };
+ var closed = card.Closed switch
+ {
+ 0 => "nessuna operazione chiusa",
+ 1 => $"1 operazione chiusa ({(card.Winners == 1 ? "in guadagno" : "in perdita")})",
+ _ => $"{card.Closed} operazioni chiuse ({card.Winners} in guadagno)",
+ };
+ return positions + ", " + closed;
+ }
+
+ /// "Prossima decisione tra 7 ore e 14 minuti, alle 15:35."
+ private static string? Decision(DateTimeOffset? due, DateTimeOffset now, TimeZoneInfo zone)
+ {
+ if (due is not { } at || at <= now)
+ {
+ return null;
+ }
+
+ var wait = at - now;
+ var hours = (int)wait.TotalHours;
+ var minutes = wait.Minutes;
+ var span = (hours, minutes) switch
+ {
+ (0, <= 1) => "un minuto",
+ (0, _) => $"{minutes} minuti",
+ (1, 0) => "un'ora",
+ (_, 0) => $"{hours} ore",
+ (1, _) => $"un'ora e {minutes} minuti",
+ _ => $"{hours} ore e {minutes} minuti",
+ };
+ var time = TimeZoneInfo.ConvertTime(at, zone).ToString("HH:mm", _it);
+ return wait < TimeSpan.FromHours(24) ? $"Prossima decisione tra {span}, alle {time}." : $"Prossima decisione {Format.ShortDate(at, now, zone).ToLowerInvariant()}.";
+ }
+}
diff --git a/src/Anubis.Server/SystemView.cs b/src/Anubis.Server/SystemView.cs
new file mode 100644
index 0000000..01f4e81
--- /dev/null
+++ b/src/Anubis.Server/SystemView.cs
@@ -0,0 +1,332 @@
+using System.Diagnostics;
+using System.Globalization;
+using System.Text.Json;
+using Anubis.Core;
+using Anubis.Data;
+using Anubis.Db;
+using Anubis.Platform;
+
+namespace Anubis.Server;
+
+/// How a component is doing: working, off by choice or not there yet, or in need of a look.
+internal enum PartState
+{
+ Ok,
+ Off,
+ Warn,
+}
+
+/// A component of the system with a line on how it is doing.
+internal sealed record SystemPart(string Name, string Detail, PartState State);
+
+/// A resource of the computer: what is used, out of how much, as a share for the bar.
+internal sealed record HostResource(string Label, string Value, string? Of, decimal Share);
+
+/// A job in the scheduler, with its time as people say it ("15:35", "Dom 03:00").
+internal sealed record PlannedJob(string Time, string Text);
+
+///
+/// The "Diario e sistema" right column and the Sistema tile of the Panoramica (SPEC 13.6, mockups 01 and 08): the
+/// components with their state, the jobs in the scheduler, the resources of the computer, version and platform.
+/// In demo mode the values of appendix F.10 (SPEC 13.1); otherwise the real services, process and disk.
+///
+internal sealed record SystemView(
+ IReadOnlyList Parts,
+ IReadOnlyList Tiles,
+ IReadOnlyList Jobs,
+ IReadOnlyList Resources,
+ string Running)
+{
+ private static readonly CultureInfo _it = CultureInfo.InvariantCulture;
+ private static readonly string[] _days = ["Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab"];
+ private static readonly string[] _months = ["gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre"];
+
+ /// Nothing needs a look; components that are off by choice or not active yet do not count.
+ public bool AllWell => Parts.All(p => p.State != PartState.Warn);
+
+ public static async Task LoadAsync(AnubisHost host, ShellData shell, CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(host);
+ ArgumentNullException.ThrowIfNull(shell);
+ using var aggregates = shell.Aggregates();
+ return aggregates is not null ? Demo(aggregates.RootElement, shell) : await RealAsync(host, shell, cancellationToken).ConfigureAwait(false);
+ }
+
+ private static SystemView Demo(JsonElement root, ShellData shell)
+ {
+ var system = root.GetProperty("sistema");
+ var accounts = root.GetProperty("conti").EnumerateArray().ToList();
+ var okxMs = accounts[0].GetProperty("risposta_ms").GetInt32();
+ var alpacaMs = accounts[1].GetProperty("risposta_ms").GetInt32();
+ var database = root.GetProperty("database").GetString()!;
+ var size = Format.Number(Dec(system, "database_gb"), 1) + " GB";
+ var telegram = system.GetProperty("telegram_ultimo").GetString();
+ var parts = new List
+ {
+ new("Motore di trading", $"attivo, un controllo ogni {system.GetProperty("controllo_secondi").GetInt32()} secondi", PartState.Ok),
+ new("Prezzi da OKX Europe", $"in diretta, risposta in {okxMs} ms", PartState.Ok),
+ new("Prezzi da Alpaca", "collegato, " + Market(shell), PartState.Ok),
+ new("Lettura delle notizie", $"{system.GetProperty("notizie_fonti").GetInt32()} fonti, ultima lettura alle {system.GetProperty("notizie_ultima").GetString()}", PartState.Ok),
+ new("Database " + database, $"{size}, ultimo salvataggio alle {system.GetProperty("ultimo_salvataggio").GetString()}", PartState.Ok),
+ new("Telegram", $"collegato, ultimo messaggio alle {telegram}", PartState.Ok),
+ };
+ var tiles = new List
+ {
+ new("OKX Europe", $"connesso, {okxMs} ms", PartState.Ok),
+ new("Alpaca", $"connesso, {alpacaMs} ms", PartState.Ok),
+ new("Prezzi di mercato", $"aggiornati {root.GetProperty("dati_aggiornati_secondi").GetInt32()} s fa", PartState.Ok),
+ new("Notizie", $"{root.GetProperty("notizie").GetProperty("lette_24h").GetInt32()} lette in 24 ore", PartState.Ok),
+ new("Database", $"{database}, {size}", PartState.Ok),
+ new("Telegram", $"ultimo messaggio alle {telegram}", PartState.Ok),
+ };
+ var jobs = system.GetProperty("lavori").EnumerateArray()
+ .Select(j => new PlannedJob(j.GetProperty("ora").GetString()!, j.GetProperty("testo").GetString()!)).ToList();
+ var memory = Dec(system, "memoria_gb");
+ var memoryTotal = system.GetProperty("memoria_totale_gb").GetDecimal();
+ var disk = Dec(system, "disco_gb");
+ var diskTotal = system.GetProperty("disco_totale_gb").GetDecimal();
+ var resources = new List
+ {
+ new("Processore", system.GetProperty("cpu_pct").GetInt32().ToString(_it) + "%", null, system.GetProperty("cpu_pct").GetDecimal() / 100m),
+ new("Memoria", Format.Number(memory, 1) + " GB", Format.Number(memoryTotal), memory / memoryTotal),
+ new("Spazio per i dati", Format.Number(disk, 1) + " GB", Format.Number(diskTotal), disk / diskTotal),
+ };
+ var started = DateOnly.ParseExact(root.GetProperty("avvio").GetString()!, "yyyy-MM-dd", _it);
+ var running = $"Anubis {root.GetProperty("versione").GetString()} in {root.GetProperty("piattaforma").GetString()}, acceso dal {started.Day} {_months[started.Month - 1]}: " +
+ $"{root.GetProperty("giorno").GetInt32()} giorni senza interruzioni.";
+ return new SystemView(parts, tiles, jobs, resources, running);
+ }
+
+ private static async Task RealAsync(AnubisHost host, ShellData shell, CancellationToken cancellationToken)
+ {
+ var services = host.Services!;
+ var now = shell.Now;
+ var zone = shell.Zone;
+ var parts = new List();
+ var tiles = new List();
+
+ // The trading engine, and the state the user chose for the bot.
+ var bot = (await services.Settings.GetAsync(SettingsStore.BotState.Key, cancellationToken).ConfigureAwait(false)).Value;
+ var trading = services.Trading;
+ parts.Add(trading switch
+ {
+ null => new SystemPart("Motore di trading", "spento: le strategie non lavorano", PartState.Off),
+ { IsStarted: false } => new SystemPart("Motore di trading", "non è ancora partito: se non parte entro qualche minuto, guarda i registri tecnici", PartState.Warn),
+ _ when bot == "stopped" => new SystemPart("Motore di trading", "fermo con Ferma tutto: riparte solo con la tua conferma, dalla pagina Rischio", PartState.Warn),
+ _ => new SystemPart("Motore di trading",
+ $"{(bot == "paused" ? "in pausa" : "attivo")}, un controllo ogni {(int)trading.TickInterval.TotalSeconds} secondi", PartState.Ok),
+ });
+
+ // The two price feeds: the live OKX connection, the state of the Alpaca source.
+ var market = services.MarketData;
+ var sources = market is null ? [] : await new SourceStateStore(services.Db, host.Clock).ListAsync(cancellationToken).ConfigureAwait(false);
+ var okx = sources.FirstOrDefault(s => s.Source == MarketDataService.OkxSource);
+ var (okxPart, okxTile) = market switch
+ {
+ null => (new SystemPart("Prezzi da OKX Europe", "spenti", PartState.Off), new SystemPart("OKX Europe", "spento", PartState.Off)),
+ { LiveConnected: true } => (new SystemPart("Prezzi da OKX Europe", "in diretta", PartState.Ok), new SystemPart("OKX Europe", "connesso", PartState.Ok)),
+ _ when Failing(okx) => (new SystemPart("Prezzi da OKX Europe", "non rispondono: riprovo da solo", PartState.Warn), new SystemPart("OKX Europe", "non risponde", PartState.Warn)),
+ _ => (new SystemPart("Prezzi da OKX Europe", "in collegamento", PartState.Off), new SystemPart("OKX Europe", "in collegamento", PartState.Off)),
+ };
+ parts.Add(okxPart);
+ var alpaca = sources.FirstOrDefault(s => s.Source == MarketDataService.AlpacaSource);
+ var (alpacaPart, alpacaTile) = (market, alpaca) switch
+ {
+ (null, _) => (new SystemPart("Prezzi da Alpaca", "spenti", PartState.Off), new SystemPart("Alpaca", "spento", PartState.Off)),
+ (_, null) => (new SystemPart("Prezzi da Alpaca", "in attesa del primo collegamento", PartState.Off), new SystemPart("Alpaca", "in attesa", PartState.Off)),
+ (_, { Enabled: false }) => (new SystemPart("Prezzi da Alpaca", "spenti: mancano le chiavi del conto di prova, in Impostazioni", PartState.Off),
+ new SystemPart("Alpaca", "senza chiavi", PartState.Off)),
+ _ when Failing(alpaca) => (new SystemPart("Prezzi da Alpaca", "non rispondono: riprovo da solo", PartState.Warn), new SystemPart("Alpaca", "non risponde", PartState.Warn)),
+ _ => (new SystemPart("Prezzi da Alpaca", "collegato, " + Market(shell, market.UsCalendar), PartState.Ok), new SystemPart("Alpaca", "connesso", PartState.Ok)),
+ };
+ parts.Add(alpacaPart);
+ tiles.Add(okxTile);
+ tiles.Add(alpacaTile);
+ var newest = market?.Freshness.Snapshot().Select(s => s.LastDataAt).Max();
+ tiles.Add(newest is { } at
+ ? new SystemPart("Prezzi di mercato", "aggiornati " + Ago(now - at), now - at > TimeSpan.FromMinutes(5) ? PartState.Warn : PartState.Ok)
+ : new SystemPart("Prezzi di mercato", "in attesa dei primi prezzi", PartState.Off));
+
+ // News arrive with phase 7 (SPEC 10).
+ parts.Add(new SystemPart("Lettura delle notizie", "non ancora attiva", PartState.Off));
+ tiles.Add(new SystemPart("Notizie", "non ancora attive", PartState.Off));
+
+ // The database: engine, size, last backup.
+ var engine = services.Db.Engine == DbEngine.Postgres ? "PostgreSQL" : "SQLite";
+ var bytes = await SizeAsync(services.Db, host.Config.Db, cancellationToken).ConfigureAwait(false);
+ var backups = services.Backups.List();
+ var lastBackup = backups.Count == 0 ? null : (DateTimeOffset?)backups.Max(b => b.TakenAt);
+ var size = bytes is { } b ? Bytes(b) : null;
+ var saved = lastBackup is { } l ? "ultimo salvataggio " + When(l, now, zone) : "nessun salvataggio ancora";
+ parts.Add(new SystemPart("Database " + engine, (size is null ? "" : size + ", ") + saved, PartState.Ok));
+ tiles.Add(new SystemPart("Database", engine + (size is null ? "" : ", " + size), PartState.Ok));
+
+ // Telegram: the last message that really left (SPEC 14), never one only queued.
+ var telegram = services.Telegram;
+ var settings = telegram is null ? null : await telegram.ReadAsync(cancellationToken).ConfigureAwait(false);
+ if (telegram is null || settings is null)
+ {
+ parts.Add(new SystemPart("Telegram", "non configurato: si imposta in Impostazioni", PartState.Off));
+ tiles.Add(new SystemPart("Telegram", "non configurato", PartState.Off));
+ }
+ else
+ {
+ var summary = await telegram.Sender.SummaryAsync(cancellationToken).ConfigureAwait(false);
+ var last = summary.LastSentAt is { } sent ? "ultimo messaggio " + When(sent, now, zone) : "nessun messaggio inviato ancora";
+ var stuck = summary.Retrying + summary.GaveUp > 0;
+ parts.Add(new SystemPart("Telegram", stuck ? "alcuni messaggi non sono partiti: riprovo da solo; " + last : "collegato, " + last, stuck ? PartState.Warn : PartState.Ok));
+ tiles.Add(new SystemPart("Telegram", last, stuck ? PartState.Warn : PartState.Ok));
+ }
+
+ // Appointments only: the jobs that run every minute or every hour are background work.
+ var jobs = services.Scheduler.Upcoming(200).Where(u => !u.Periodic).Take(7)
+ .Select(u => new PlannedJob(JobTime(u.DueUtc, now, zone), u.Description)).ToList();
+
+ var since = host.Status.Since;
+ var platform = host.Config.Platform == PlatformKind.Docker ? "in Docker" : "come applicazione desktop";
+ var localSince = TimeZoneInfo.ConvertTime(since, zone);
+ var days = (int)Math.Floor((now - since).TotalDays);
+ var running = days >= 1
+ ? $"Anubis {AnubisInfo.Version} {platform}, acceso dal {localSince.Day} {_months[localSince.Month - 1]}: {days} {(days == 1 ? "giorno" : "giorni")} senza interruzioni."
+ : $"Anubis {AnubisInfo.Version} {platform}, acceso oggi alle {localSince.ToString("HH:mm", _it)}.";
+ return new SystemView(parts, tiles, jobs, MeasureHost(host.Config.Data), running);
+ }
+
+ private static bool Failing(SourceState? state) =>
+ state is { LastError: not null } && (state.LastSuccessAt is null || state.LastRequestAt > state.LastSuccessAt);
+
+ private static string Market(ShellData shell, IMarketCalendar? calendar = null)
+ {
+ var (open, next) = AccountsView.MarketState(calendar, shell.Now);
+ var time = TimeZoneInfo.ConvertTime(next, shell.Zone).ToString("HH:mm", _it);
+ return open ? "mercato aperto fino alle " + time : "mercato chiuso fino alle " + time;
+ }
+
+ private static async Task SizeAsync(Database db, DbSettings? settings, CancellationToken cancellationToken)
+ {
+ try
+ {
+ if (db.Engine == DbEngine.Postgres)
+ {
+ return await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT pg_database_size(current_database()) AS n", r => (long?)r.Number("n")), cancellationToken)
+ .ConfigureAwait(false);
+ }
+
+ if (settings?.SqlitePath is { } path && File.Exists(path))
+ {
+ var wal = path + "-wal";
+ return new FileInfo(path).Length + (File.Exists(wal) ? new FileInfo(wal).Length : 0);
+ }
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.Data.Common.DbException)
+ {
+ // The size is a detail: without it the line still says engine and backups.
+ }
+
+ return null;
+ }
+
+ ///
+ /// Processor of this process (share of all cores since the last look, or since it started), its memory against
+ /// what the container or computer gives it, and the disk that holds the data folder.
+ ///
+ private static List MeasureHost(DataDirectory data)
+ {
+ var list = new List();
+ var cpu = CpuSampler.Share();
+ list.Add(new HostResource("Processore", Format.Number(cpu * 100m) + "%", null, cpu));
+
+ using var process = Process.GetCurrentProcess();
+ var used = process.WorkingSet64;
+ var total = GC.GetGCMemoryInfo().TotalAvailableMemoryBytes;
+ if (total > 0)
+ {
+ list.Add(new HostResource("Memoria", Bytes(used), Bytes(total, unit: false), Math.Clamp((decimal)used / total, 0m, 1m)));
+ }
+
+ try
+ {
+ var drive = new DriveInfo(Path.GetPathRoot(Path.GetFullPath(data.Root))!);
+ if (drive.IsReady && drive.TotalSize > 0)
+ {
+ var taken = drive.TotalSize - drive.AvailableFreeSpace;
+ list.Add(new HostResource("Spazio per i dati", Bytes(taken), Bytes(drive.TotalSize, unit: false), Math.Clamp((decimal)taken / drive.TotalSize, 0m, 1m)));
+ }
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException)
+ {
+ // A disk that cannot be measured is left out rather than shown wrong.
+ }
+
+ return list;
+ }
+
+ /// A size as people read it: "780 MB", "1,8 GB"; without the unit for the "su 50" after the value.
+ public static string Bytes(long bytes, bool unit = true)
+ {
+ const decimal giga = 1024m * 1024m * 1024m;
+ var gb = bytes / giga;
+ if (!unit)
+ {
+ return Format.Number(gb, gb >= 10m ? 0 : 1);
+ }
+
+ return gb >= 1m ? Format.Number(gb, 1) + " GB" : Format.Number(Math.Max(1m, bytes / (1024m * 1024m))) + " MB";
+ }
+
+ private static string When(DateTimeOffset moment, DateTimeOffset now, TimeZoneInfo zone)
+ {
+ var text = Format.ShortDate(moment, now, zone);
+ return text.StartsWith("Oggi ", StringComparison.Ordinal) ? "alle " + text["Oggi ".Length..] : text.StartsWith("Ieri ", StringComparison.Ordinal) ? "ieri alle " + text["Ieri ".Length..] : "del " + text;
+ }
+
+ private static string Ago(TimeSpan elapsed) => elapsed.TotalSeconds < 60 ? $"{Math.Max(0, (int)elapsed.TotalSeconds)} s fa" : Format.Ago(elapsed);
+
+ /// The time alone within a day, otherwise the day too: "15:35", "Dom 03:00".
+ public static string JobTime(DateTimeOffset due, DateTimeOffset now, TimeZoneInfo zone)
+ {
+ var local = TimeZoneInfo.ConvertTime(due, zone);
+ var time = local.ToString("HH:mm", _it);
+ return due - now < TimeSpan.FromHours(24) ? time : _days[(int)local.DayOfWeek] + " " + time;
+ }
+
+ private static decimal Dec(JsonElement element, string name) => decimal.Parse(element.GetProperty(name).GetString()!, _it);
+
+ /// The processor used by this process between two looks, as a share of all cores.
+ private static class CpuSampler
+ {
+ private static readonly Lock _gate = new();
+ private static (long Ticks, TimeSpan Cpu)? _last;
+
+ public static decimal Share()
+ {
+ using var process = Process.GetCurrentProcess();
+ var cpu = process.TotalProcessorTime;
+ var ticks = Stopwatch.GetTimestamp();
+ lock (_gate)
+ {
+ TimeSpan wall;
+ TimeSpan used;
+ if (_last is { } last && Stopwatch.GetElapsedTime(last.Ticks, ticks) >= TimeSpan.FromSeconds(1))
+ {
+ wall = Stopwatch.GetElapsedTime(last.Ticks, ticks);
+ used = cpu - last.Cpu;
+ }
+ else
+ {
+ // First look, or two looks too close together: the average since the process started.
+ wall = Uptime(process);
+ used = cpu;
+ }
+
+ _last = (ticks, cpu);
+ var share = wall <= TimeSpan.Zero ? 0d : used.TotalMilliseconds / (wall.TotalMilliseconds * Environment.ProcessorCount);
+ return Math.Clamp((decimal)share, 0m, 1m);
+ }
+ }
+
+ // A measure of the process, not a business time: the system clock against the process's own start, since the
+ // injected clock may stand still (demo) or run in another world (tests).
+ private static TimeSpan Uptime(Process process) => DateTime.UtcNow - process.StartTime.ToUniversalTime();
+ }
+}
diff --git a/src/Anubis/Core/Scheduling.cs b/src/Anubis/Core/Scheduling.cs
index c927fb9..1c8bdcb 100644
--- a/src/Anubis/Core/Scheduling.cs
+++ b/src/Anubis/Core/Scheduling.cs
@@ -149,6 +149,9 @@ public sealed record JobRun(string Name, DateTimeOffset DueUtc, DateTimeOffset S
public sealed record UpcomingRun(string Name, string Description, DateTimeOffset DueUtc)
{
public bool IsMove { get; init; }
+
+ /// A job that comes back at a fixed interval (every minute, every hour): background work, not an appointment.
+ public bool Periodic { get; init; }
}
///
@@ -221,7 +224,7 @@ public sealed partial class Scheduler(IClock clock, EventBus bus, ILogger j.Due is not null)
.OrderBy(j => j.Due)
.Take(count)
- .Select(j => new UpcomingRun(j.Job.Name, j.Job.Description, j.Due!.Value) { IsMove = j.Job.IsMove })
+ .Select(j => new UpcomingRun(j.Job.Name, j.Job.Description, j.Due!.Value) { IsMove = j.Job.IsMove, Periodic = j.Job.Schedule is IntervalSchedule })
.ToList();
}
}
diff --git a/src/Anubis/Demo/Data/aggregates.json b/src/Anubis/Demo/Data/aggregates.json
index 9e0650b..e7b2527 100644
--- a/src/Anubis/Demo/Data/aggregates.json
+++ b/src/Anubis/Demo/Data/aggregates.json
@@ -50,10 +50,45 @@
{ "nome": "equity_meanrev", "etichetta": "Mean reversion azioni USA", "conto": "Alpaca", "giorno": 58, "di": 60, "quota_pct": 15, "capitale": "1500", "risultato": "11.36", "risultato_pct": "0.76", "calo_peggiore_pct": "-1.1", "chiuse": 21, "in_guadagno": 10 }
],
"operazioni": { "chiuse": 41, "in_guadagno": 22, "guadagno_medio": "28.42", "perdita_media": "-20.31", "rapporto": "1.62", "incassati": "239.28", "commissioni": "14.82" },
- "notizie": { "lette_24h": 312, "sulle_posizioni": 9, "con_effetto": 2, "spesa_oggi": "0.04", "tetto": "0.50" },
- "apprendimento": { "stato": "observation", "segnali": 212, "necessari": 300, "precisione_pct": 56 },
+ "notizie": {
+ "lette_24h": 312, "sulle_posizioni": 9, "con_effetto": 2, "spesa_oggi": "0.04", "tetto": "0.50",
+ "panoramica": [
+ { "quando": "06:10", "riguarda": "su SOL", "titolo": "Rinviato di una settimana l'aggiornamento della rete Solana", "effetto": "Negativa: per 24 ore non aumento SOL", "in_corso": true },
+ { "quando": "Ieri 22:41", "riguarda": "su JPM", "titolo": "JPMorgan pubblica i conti martedì prima dell'apertura", "effetto": "Evento in arrivo: niente mean reversion su JPM fino a martedì", "in_corso": true },
+ { "quando": "07:52", "riguarda": "sul mercato in generale", "titolo": "I verbali della banca centrale USA non cambiano le attese sui tassi", "effetto": "Nessun effetto: non cambio nulla", "in_corso": false }
+ ]
+ },
+ "panoramica": {
+ "prossima_decisione": "Prossima decisione tra 7 ore e 14 minuti, all'apertura di Wall Street.",
+ "mosse": [
+ { "ora": "15:35", "testo": "Rimetto gli stop del giorno sulle frazioni di 6 azioni", "dove": "Alpaca", "calendario": false },
+ { "ora": "16:00", "testo": "Esce la fiducia dei consumatori USA: impatto medio, non blocco gli ingressi", "calendario": true },
+ { "ora": "21:55", "testo": "Controllo AAPL: vendo se è sopra la media a 5 giorni", "calendario": false },
+ { "ora": "22:20", "testo": "Wall Street ha chiuso: calcolo i segnali sulle azioni", "calendario": false },
+ { "ora": "02:05", "testo": "Chiusura giornaliera crypto: ricalcolo i trend di 10 monete", "calendario": false }
+ ],
+ "ultime_azioni": [
+ { "quando": "02:06", "testo": "Alzato lo stop di BTC a 66.180 € (era 65.400 €)" },
+ { "quando": "Ieri 21:58", "testo": "Venduto MSFT: +9,84 $ in 3 giorni" },
+ { "quando": "Ieri 15:36", "testo": "Comprate 2 AAPL a 259,80 $" }
+ ]
+ },
+ "apprendimento": {
+ "stato": "observation", "segnali": 212, "necessari": 300, "precisione_pct": 56,
+ "ultimo_addestramento": "domenica 4 ottobre", "prossima_verifica": "domenica 11 ottobre, 03:00"
+ },
"sistema": {
"controllo_secondi": 5, "notizie_fonti": 16, "database_gb": "1.8", "ultimo_salvataggio": "03:30", "telegram_ultimo": "08:00",
- "cpu_pct": 6, "memoria_gb": "1.1", "memoria_totale_gb": 4, "disco_gb": "2.3", "disco_totale_gb": 50
+ "cpu_pct": 6, "memoria_gb": "1.1", "memoria_totale_gb": 4, "disco_gb": "2.3", "disco_totale_gb": 50,
+ "notizie_ultima": "08:20",
+ "lavori": [
+ { "ora": "15:35", "testo": "Stop del giorno sulle azioni" },
+ { "ora": "21:55", "testo": "Uscite della mean reversion" },
+ { "ora": "22:20", "testo": "Segnali sulle azioni" },
+ { "ora": "02:05", "testo": "Segnali sulle crypto" },
+ { "ora": "03:00", "testo": "Controllo del modello" },
+ { "ora": "03:30", "testo": "Salvataggio del database" },
+ { "ora": "Dom 03:00", "testo": "Verifica settimanale del modello" }
+ ]
}
}
diff --git a/tests/Anubis.Tests/OverviewScreenTests.cs b/tests/Anubis.Tests/OverviewScreenTests.cs
new file mode 100644
index 0000000..035fb36
--- /dev/null
+++ b/tests/Anubis.Tests/OverviewScreenTests.cs
@@ -0,0 +1,162 @@
+using System.IO.Compression;
+using System.Net;
+using Anubis.Server;
+using Anubis.Trading;
+
+namespace Anubis.Tests;
+
+/// The Panoramica and "Diario e sistema" screens (issue #51, mockups 01, 08 and 09).
+[TestClass]
+public sealed class OverviewScreenTests
+{
+ [TestMethod]
+ [TestCategory(Category.Integration)]
+ public async Task TheDemoPanoramicaShowsAccountsPositionsAndLimits()
+ {
+ var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]);
+ var demoRoot = server.Host.Config.Data.Root;
+ try
+ {
+ var page = await server.TextAsync("/");
+ foreach (var text in new[]
+ {
+ // Adesso e dopo (F.10).
+ "Prossima decisione tra 7 ore e 14 minuti, all'apertura di Wall Street.", "Rimetto gli stop del giorno sulle frazioni di 6 azioni",
+ "Alzato lo stop di BTC a 66.180", "Apri il diario completo", "Tutte le mosse e il diario",
+ // The two accounts with their last 30 days (F.2).
+ "4.231,60", "+231,60", "2.326,50", "1.905,10", "+158,20", "3 posizioni, 3 stop attivi.",
+ "6.180,86", "4.344,63", "1.836,23", "+93,50", "sulle frazioni tornano alle 15:35",
+ // The four limits (F.10).
+ "Tutti i limiti rispettati", "Perdita di oggi", "nessuna", "−2,00%", "Calo dal massimo", "−15,00%", "Capitale investito", "64,1%",
+ "Posizione più grande (BTC)", "12,5%", "La tacca segna il calo peggiore finora: −2,82%.", "Vedi tutti i limiti",
+ // Positions by value, strategies, news, model, system.
+ "BTC/EUR", "1.299,84", "66.180", "(−7,3%)", "Vedi le altre 6",
+ "In simulazione, giorno 58 di 60", "In simulazione, 21 operazioni su 30", "1 posizione aperta, 21 operazioni chiuse (10 in guadagno)",
+ "Nessuna strategia usa soldi veri.",
+ "Rinviato di una settimana l'aggiornamento della rete Solana", "Negativa: per 24 ore non aumento SOL",
+ "Il modello osserva e impara, ma non decide ancora.", "domenica 11 ottobre, 03:00",
+ "connesso, 84 ms", "PostgreSQL, 1,8 GB", "ultimo messaggio alle 08:00",
+ })
+ {
+ StringAssert.Contains(page, text, $"Missing «{text}» on the Panoramica.");
+ }
+
+ Assert.IsLessThan(page.IndexOf("ETH/EUR", StringComparison.Ordinal), page.IndexOf("BTC/EUR", StringComparison.Ordinal), "Positions in order of value.");
+ }
+ finally
+ {
+ await server.DisposeAsync();
+ TempFolder.Delete(demoRoot);
+ }
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Integration)]
+ public async Task TheDiaryFiltersAndSearches()
+ {
+ var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]);
+ var demoRoot = server.Host.Config.Data.Root;
+ try
+ {
+ var all = await server.TextAsync("/diario");
+ StringAssert.Contains(all, "Oggi, venerdì 9 ottobre");
+ StringAssert.Contains(all, "Ieri, giovedì 8 ottobre");
+ StringAssert.Contains(all, "Ho cambiato una regola per 24 ore:");
+ StringAssert.Contains(all, "Motivo: l'aggiornamento della rete Solana è stato rinviato di una settimana.");
+ StringAssert.Contains(all, "href=\"/operazioni?cerca=MSFT\"");
+ StringAssert.Contains(all, "Perché l'ho comprata e venduta");
+ Assert.IsFalse(all.Contains("(con il collegamento", StringComparison.Ordinal), "The demo's note on the link is not shown.");
+ StringAssert.Contains(all, "Tutto regolare");
+ StringAssert.Contains(all, "collegato, mercato chiuso fino alle 15:30");
+ StringAssert.Contains(all, "Dom 03:00");
+ StringAssert.Contains(all, "Anubis 0.9.2 in Docker, acceso dal 12 agosto: 58 giorni senza interruzioni.");
+
+ // A kind at a time.
+ var orders = await server.TextAsync("/diario?tipo=ordini");
+ StringAssert.Contains(orders, "Alzato lo stop di BTC/EUR");
+ Assert.IsFalse(orders.Contains("Inviato il riepilogo del mattino", StringComparison.Ordinal));
+ Assert.IsFalse(orders.Contains("Controllo del modello: nessuna anomalia.", StringComparison.Ordinal));
+ StringAssert.Contains(await server.TextAsync("/diario?tipo=rischio"), "Nessuna voce di questo tipo finora.");
+
+ // The search ignores case and accents, and keeps the kind chosen.
+ var search = await server.TextAsync("/diario?cerca=MARTEDI");
+ StringAssert.Contains(search, "Ho messo una restrizione fino a martedì:");
+ Assert.IsFalse(search.Contains("Alzato lo stop", StringComparison.Ordinal));
+ StringAssert.Contains(search, "Una voce con «MARTEDI»");
+ var none = await server.TextAsync("/diario?tipo=ordini&cerca=solana");
+ StringAssert.Contains(none, "Nessuna voce con «solana»");
+ }
+ finally
+ {
+ await server.DisposeAsync();
+ TempFolder.Delete(demoRoot);
+ }
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Integration)]
+ public async Task TheLogsDownloadNeedsASessionAndIsAZip()
+ {
+ await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite());
+ var logs = server.Host.Config.Data.Logs;
+ Directory.CreateDirectory(logs);
+ await File.WriteAllTextAsync(Path.Combine(logs, "anubis-2099-01-01.log"), "{\"message\":\"una riga\"}\n");
+ await File.WriteAllTextAsync(Path.Combine(logs, "altro.txt"), "non è un registro");
+
+ using (var anonymous = await server.GetAsync("/api/registri.zip"))
+ {
+ Assert.AreEqual(HttpStatusCode.Unauthorized, anonymous.StatusCode);
+ }
+
+ await server.SignInFirstTimeAsync();
+ using (var zip = await server.GetAsync("/api/registri.zip"))
+ {
+ Assert.AreEqual(HttpStatusCode.OK, zip.StatusCode);
+ Assert.AreEqual("application/zip", zip.Content.Headers.ContentType?.MediaType);
+ await using var stream = await zip.Content.ReadAsStreamAsync();
+ using var archive = new ZipArchive(stream, ZipArchiveMode.Read);
+ var names = archive.Entries.Select(e => e.Name).ToList();
+ Assert.Contains("anubis-2099-01-01.log", names);
+ Assert.DoesNotContain("altro.txt", names);
+ using var reader = new StreamReader(archive.GetEntry("anubis-2099-01-01.log")!.Open());
+ StringAssert.Contains(await reader.ReadToEndAsync(), "una riga");
+ }
+
+ // A new installation: the screens say what is missing instead of showing numbers.
+ var home = await server.TextAsync("/");
+ StringAssert.Contains(home, "La lettura delle notizie non è ancora attiva.");
+ StringAssert.Contains(home, "L'apprendimento non è ancora attivo.");
+ var diary = await server.TextAsync("/diario");
+ StringAssert.Contains(diary, "Come sta il sistema");
+ StringAssert.Contains(diary, "non configurato");
+ StringAssert.Contains(diary, "Il computer che lo ospita");
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Unit)]
+ public void DiaryEntriesAreSplitAsTheMockupDraws()
+ {
+ var at = DateTimeOffset.UnixEpoch;
+ var rule = DiaryView.Entry(at, DiaryKinds.News, "demo", "Ho cambiato una regola per 24 ore: non aumento la posizione su SOL. Motivo: la rete è ferma.");
+ Assert.AreEqual("Ho cambiato una regola per 24 ore:", rule.Lead);
+ Assert.AreEqual("Motivo: la rete è ferma.", rule.Rest);
+ Assert.IsTrue(rule.Attention);
+
+ var long1 = DiaryView.Entry(at, DiaryKinds.Orders, "stop_moved", "Alzato lo stop di BTC/EUR da 65.400 € a 66.180 €. Lo stop segue il prezzo quando sale.");
+ Assert.AreEqual("Alzato lo stop di BTC/EUR da 65.400 € a 66.180 €.", string.Concat(long1.Main.Select(p => p.Text)));
+ Assert.AreEqual("Lo stop segue il prezzo quando sale.", long1.Rest);
+ Assert.IsNull(long1.Trade);
+
+ var shortOne = DiaryView.Entry(at, DiaryKinds.News, "demo", "Voce non confermata su un exchange. Nessuna azione: ricontrollo tra 2 ore.");
+ Assert.IsNull(shortOne.Rest, "A short entry stays on one line.");
+
+ var sale = DiaryView.Entry(at, DiaryKinds.Orders, "fill", "Venduta 1 MSFT a 522,14 $: +9,84 $ in 3 giorni.");
+ Assert.AreEqual("MSFT", sale.Trade);
+ Assert.AreEqual("gain", sale.Main.Single(p => p.Class is not null).Class);
+ Assert.AreEqual("ETH", DiaryView.Entry(at, DiaryKinds.Orders, "fill", "Venduto 0,1 ETH/EUR a 2.500 €: −12,00 € in 4 giorni.").Trade);
+ Assert.IsNull(DiaryView.Entry(at, DiaryKinds.Orders, "fill", "Comprate 2 AAPL a 259,80 $.").Trade, "A purchase has no closed trade to explain.");
+
+ Assert.AreEqual("Oggi, venerdì 9 ottobre", DiaryView.Heading(new DateOnly(2026, 10, 9), new DateOnly(2026, 10, 9)));
+ Assert.AreEqual("Mercoledì 7 ottobre", DiaryView.Heading(new DateOnly(2026, 10, 7), new DateOnly(2026, 10, 9)));
+ }
+}