Build the Panoramica and Diario e sistema screens as in the mockups (refs #51)

Panoramica now follows mockup 01. Below "Finora" and "Adesso e dopo" it
shows:
- the two account cards with the invested/cash bar and a 30-day trend;
- the four risk limits;
- the open positions by value;
- the strategies;
- the news, learning and system tiles.

On the phone it follows mockup 09: Conti as a list, four positions with
"Vedi le altre", and two limits. Outside the demo, news and learning say
they are not active yet (Phases 7 and 8). The next moves are the scheduler's
moves only, no longer every interval job.

Diario e sistema follows mockup 08:
- the diary grouped by day, with search and filter chips (plain links, no
  JavaScript) and older days on request;
- how each component is doing;
- the scheduled jobs;
- the host's processor, memory and disk;
- the technical logs as a zip, for signed-in users only.

In demo mode the screens show the values of appendix F.10. Tests cover the
demo figures, the filters and search, and the logs download.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-11 20:32:19 +01:00
1 parent 84c540786c
commit e96ca70a1a
11 files changed
+1666 -85

No files matched your search

+136
View File
@@ -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); }
}
+131 -60
View File
@@ -5,86 +5,157 @@
<PageTitle>Diario e sistema · Anubis</PageTitle>
<div class="columns">
<section class="panel">
<h2>Diario</h2>
@if (_entries.Count == 0)
@{
var d = _diary;
var s = _system;
}
<div class="journal-columns">
<section class="panel journal" aria-labelledby="diario">
<div class="journal-head">
<h2 id="diario">Diario</h2>
<form class="search journal-search" method="get" action="/diario" role="search">
@if (d.Filter != "tutto")
{
<input type="hidden" name="tipo" value="@d.Filter" />
}
<Icon Name="search" Size="16" />
<label class="visually-hidden" for="cerca-diario">Cerca nel diario</label>
<input id="cerca-diario" type="search" name="cerca" value="@d.Search" placeholder="Cerca nel diario" maxlength="100" />
</form>
</div>
<nav class="chips" aria-label="Tipo di voce">
@foreach (var (key, label, _) in DiaryView.Filters)
{
<a href="@d.Link(filter: key, range: DiaryView.DefaultRange)" class="chip @(key == d.Filter ? "on" : null)" aria-current="@(key == d.Filter ? "true" : null)">@label</a>
}
</nav>
@if (d.Search is { } search)
{
<p class="note">Ancora nessuna voce.</p>
<p class="note journal-found">
@(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" : "").
<a href="@(new DiaryView([], d.Filter, null, DiaryView.DefaultRange, false, false).Link())">Togli la ricerca</a>
</p>
}
else
@if (d.IsEmpty && d.Search is null)
{
<div class="table-wrap">
<table class="table">
<thead><tr><th scope="col">Quando</th><th scope="col">Tipo</th><th scope="col">Voce</th></tr></thead>
<tbody>
@foreach (var e in _entries)
{
<tr><td class="nowrap">@Format.ShortDate(e.At, Shell.Now, Shell.Zone)</td><td>@e.Kind</td><td>@e.Text</td></tr>
}
</tbody>
</table>
</div>
<p class="note">@(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.")</p>
}
@foreach (var day in d.Days)
{
<h3 class="journal-day">@day.Heading</h3>
<ol class="journal-list">
@foreach (var e in day.Entries)
{
<li class="@(e.Attention ? "attention-entry" : null)">
<time datetime="@e.At.ToString("o", CultureInfo.InvariantCulture)">@TimeZoneInfo.ConvertTime(e.At, Shell.Zone).ToString("HH:mm", CultureInfo.InvariantCulture)</time>
<Icon Name="@e.Icon" Size="18" Class="journal-icon" />
<div class="journal-text">
<p>@if (e.Lead is { } lead) {<strong>@lead</strong>}@foreach (var piece in e.Main) {if (piece.Class is { } css) {<strong class="@css">@piece.Text</strong>} else {@piece.Text}}</p>
@if (e.Rest is { } rest)
{
<p class="journal-rest">@rest</p>
}
@if (e.Trade is { } trade)
{
<a href="/operazioni?cerca=@Uri.EscapeDataString(trade)">Perché l'ho comprata e venduta</a>
}
</div>
<span class="journal-kind">@e.Kind</span>
</li>
}
</ol>
}
@if (d.HasOlder)
{
<div class="journal-more"><a class="btn" href="@d.Link(range: d.Range + 7)">Mostra i giorni precedenti</a></div>
}
</section>
<section class="panel">
<h2>Sistema</h2>
<dl class="facts">
<dt>Versione</dt><dd>@AnubisInfo.Version</dd>
<dt>Piattaforma</dt><dd>@(Host.Config.Platform == PlatformKind.Docker ? "Docker" : "Desktop")</dd>
<dt>Database</dt><dd>@(Host.Config.Db?.Engine == DbEngine.Postgres ? "PostgreSQL" : "SQLite") · risponde</dd>
<dt>In funzione da</dt><dd>@Format.Ago(Shell.Now - _since).Replace(" fa", "", StringComparison.Ordinal)</dd>
</dl>
<h3 class="list-title">Lavori in programma</h3>
<ul class="moves">
@foreach (var job in _upcoming)
{
<li><span class="move-time">@Format.ShortDate(job.DueUtc, Shell.Now, Shell.Zone)</span><span>@job.Description</span></li>
}
</ul>
@if (_jobs.Count > 0)
{
<h3 class="list-title">Ultimi lavori</h3>
<ul class="moves moves-past">
@foreach (var job in _jobs)
<div class="journal-side">
<section class="panel" aria-labelledby="sistema">
<div class="panel-head">
<h2 id="sistema">Come sta il sistema</h2>
<span class="status-pill @(s.AllWell ? "gain" : "attention")"><Icon Name="@(s.AllWell ? "check" : "alert")" Size="16" />@(s.AllWell ? "Tutto regolare" : "Qualcosa da controllare")</span>
</div>
<ul class="system-parts">
@foreach (var part in s.Parts)
{
<li><span class="move-time">@(job.Finished is { } f ? Format.ShortDate(f, Shell.Now, Shell.Zone) : "—")</span><span>@job.Description: @Outcome(job.Outcome)</span></li>
<li class="@PartClass(part.State)">
<Icon Name="@PartIcon(part.State)" Size="16" />
<span><strong>@part.Name</strong><span>@part.Detail</span></span>
</li>
}
</ul>
}
</section>
</section>
<section class="panel" aria-labelledby="lavori">
<h2 id="lavori">Lavori in programma</h2>
@if (s.Jobs.Count == 0)
{
<p class="note">Nessun lavoro in programma: il pianificatore parte con il motore.</p>
}
else
{
<ul class="moves job-list">
@foreach (var job in s.Jobs)
{
<li><span class="move-time">@job.Time</span><span>@job.Text</span></li>
}
</ul>
}
</section>
<section class="plain host" aria-labelledby="computer">
<h2 id="computer">Il computer che lo ospita</h2>
@foreach (var r in s.Resources)
{
<div class="limit">
<div class="limit-line"><span>@r.Label</span><span><strong>@r.Value</strong>@if (r.Of is { } of) {<span class="muted"> su @of</span>}</span></div>
<span class="usage @(r.Share >= 0.85m ? "high" : null)"><span style="width: @Css(r.Share * 100m)%"></span></span>
</div>
}
<p class="note">@s.Running</p>
<a class="btn" href="/api/registri.zip" download><Icon Name="download" Size="18" />Scarica i registri tecnici</a>
</section>
</div>
</div>
@code {
private List<(DateTimeOffset At, string Kind, string Text)> _entries = [];
private List<(string Description, DateTimeOffset? Finished, string? Outcome)> _jobs = [];
private IReadOnlyList<UpcomingRun> _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);
}
@@ -2,12 +2,20 @@
@page "/"
@inject AnubisHost Host
@inject ShellData Shell
@using Anubis.Trading
@using Anubis.Data
<PageTitle>Panoramica · Anubis</PageTitle>
@{
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 @@
<span class="big-number">@Shell.Money(o.Result.Amount, c, withSign: true)</span>
<span class="badge @(gain ? "badge-gain" : "badge-loss")"><Arrow Up="gain" />@Format.Percent(o.Result.Percent, 2, withSign: true)</span>
</div>
<p class="note">Dal @Format.LongDate(o.From), partendo da @Shell.Money(o.FromEquity, c). Commissioni già tolte.</p>
var from = Format.LongDate(o.From);
var year = from.LastIndexOf(' ');
<p class="note">Dal @from[..year]<span class="desk-only">@from[year..]</span>, partendo da @Shell.Money(o.FromEquity, c).<span class="desk-only"> Commissioni già tolte.</span></p>
<div class="cells">
@foreach (var (cell, i) in o.Cells.Select((x, i) => (x, i)))
{
@@ -63,47 +73,321 @@
<h2><Icon Name="next" Size="18" />Adesso e dopo</h2>
@if (_runningDays is { } days)
{
<span class="note">Attivo da @days giorni senza interruzioni</span>
<span class="note desk-only">Attivo da @days giorni senza interruzioni</span>
}
</div>
<p class="statement">@Statement(o)</p>
<h3 class="list-title">Prossime mosse</h3>
@if (o.Next.Count == 0)
@if (p.NextDecision is { } decision)
{
<p class="note">Niente in programma.</p>
<p class="next-decision desk-only"><Icon Name="clock" Size="16" />@decision</p>
}
<h3 class="list-title desk-only">Prossime mosse</h3>
@if (moves.Count == 0)
{
<p class="note">Niente in programma: le mosse compaiono quando il motore di trading lavora con almeno una strategia.</p>
}
else
{
<ul class="moves">
@foreach (var move in o.Next)
@for (var i = 0; i < moves.Count; i++)
{
<li><span class="move-time">@move.Time</span><span>@move.Text</span></li>
var move = moves[i];
<li class="@(phoneMoves.Contains(i) ? null : "desk-only")"><span class="move-time">@move.Time</span><span>@move.Text@if (move.Where is { } where) {<span class="muted desk-only"> (@where)</span>}</span></li>
}
</ul>
}
<h3 class="list-title">Ultime azioni</h3>
@if (o.Last.Count == 0)
<div class="desk-only">
<h3 class="list-title">Ultime azioni</h3>
@if (last.Count == 0)
{
<p class="note">Ancora nessuna voce nel diario.</p>
}
else
{
<ul class="moves moves-past">
@foreach (var action in last)
{
<li><span class="move-time">@action.When</span><span>@action.Text</span></li>
}
</ul>
}
<a class="more" href="/diario">Apri il diario completo</a>
</div>
<a class="more phone-only" href="/diario">Tutte le mosse e il diario</a>
</div>
</section>
@* Accounts and the four limits (mockup 01); on the phone a compact list of the accounts (mockup 09). *@
<div class="overview-row">
@if (!v.HasAccounts)
{
<section class="panel overview-empty desk-only">
<p class="empty-title">Nessun conto ancora.</p>
<p>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 <a href="/impostazioni#conti">Impostazioni</a>.</p>
</section>
}
@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);
<section class="panel overview-account desk-only" aria-label="@a.Name">
<div class="account-head">
<h2>@a.Name <span class="tag">@a.Kind</span></h2>
<span class="link-state @(Down(a) ? "down" : null)"><span class="dot"></span>@(Down(a) ? "Non risponde" : "Connesso")</span>
</div>
<div class="account-value">
<span class="account-equity">@Shell.Money(a.Eur(a.Equity), c)</span>
<span class="cell-change @(up ? "gain" : "loss")"><Arrow Up="up" />@Shell.Money(a.Eur(a.Result), c, withSign: true) (@Format.Percent(a.Percent, 2, withSign: true))</span>
</div>
<div class="split-bar thin" role="img" aria-label="Investito @Shell.Money(a.InvestedEur, c), liquidità @Shell.Money(a.Eur(a.Cash), c)">
@for (var i = 0; i < slices.Count; i++)
{
if (shares[i] > 0)
{
<span style="width: @Css(shares[i])%; background: var(--s-@slices[i].Strategy.Replace('_', '-'))"></span>
}
}
@if (shares[^1] > 0)
{
<span style="width: @Css(shares[^1])%; background: var(--cash)"></span>
}
</div>
<div class="split-key">
<span>@foreach (var s in slices) {<span class="swatch" style="background: var(--s-@s.Strategy.Replace('_', '-'))"></span>}Investito <strong>@Shell.Money(a.InvestedEur, c)</strong></span>
<span><span class="swatch" style="background: var(--cash)"></span>Liquidità <strong>@Shell.Money(a.Eur(a.Cash), c)</strong></span>
</div>
<div class="month">
<div>
<span class="cell-label">Ultimi 30 giorni</span>
<strong>@(trend is null ? "—" : Shell.Money(trend.Month, c, withSign: true))</strong>
</div>
@if (trend is { Points.Count: > 1 } t)
{
<svg class="spark-mini" viewBox="0 0 120 36" role="img" aria-label="Andamento degli ultimi 30 giorni">
<polyline points="@Spark(t.Points)" />
<circle cx="@SparkEnd(t.Points).X" cy="@SparkEnd(t.Points).Y" r="2.5" />
</svg>
}
</div>
<p class="note">@AccountNote(a, held)</p>
</section>
}
<section class="panel overview-risk desk-only" aria-labelledby="rischio-sintesi">
<div class="panel-head">
<h2 id="rischio-sintesi">Rischio</h2>
<span class="status-pill @(p.LimitsKept ? "gain" : "attention")"><Icon Name="@(p.LimitsKept ? "check" : "alert")" Size="16" />@(p.LimitsKept ? "Tutti i limiti rispettati" : "Un limite chiede attenzione")</span>
</div>
<div class="limit-list">
@foreach (var l in p.Limits)
{
<div class="limit">
<div class="limit-line"><span>@l.Label</span><span><strong>@l.Value</strong> <span class="muted">su @l.Threshold</span></span></div>
<span class="usage @(l.Worst is null ? null : "notched") @(l.Share >= 0.8m ? "high" : null)">
<span style="width: @Css(l.Share * 100m)%"></span>
@if (l.Worst is { } w)
{
<i class="notch" style="left: @Css(w * 100m)%"></i>
}
</span>
</div>
}
</div>
@if (p.Limits[1].Worst is not null && _worst is { } worst)
{
<p class="note">Ancora nessuna voce nel diario.</p>
<p class="note">La tacca segna il calo peggiore finora: @Format.Percent(worst * 100m, 2).</p>
}
<a class="more" href="/rischio">Vedi tutti i limiti</a>
</section>
</div>
@if (v.HasAccounts)
{
<section class="panel phone-only" aria-labelledby="conti-telefono">
<h2 id="conti-telefono">Conti</h2>
<ul class="phone-list">
@foreach (var a in v.Accounts)
{
var up = a.Result >= 0;
<li>
<span><strong>@a.Name</strong><span class="sub"><span class="dot @(Down(a) ? "down" : null)"></span>@a.Kind, @(Down(a) ? "non risponde" : "connesso")</span></span>
<span class="num"><strong>@Shell.Money(a.Eur(a.Equity), c)</strong><span class="sub @(up ? "gain" : "loss")"><Arrow Up="up" /><strong>@Shell.Money(a.Eur(a.Result), c, withSign: true)</strong></span></span>
</li>
}
</ul>
</section>
}
@* Positions by value and the strategies (mockup 01); on the phone the first four positions (mockup 09). *@
<div class="overview-row overview-row-wide">
<section class="panel overview-positions" aria-labelledby="posizioni-sintesi">
<div class="panel-head">
<h2 id="posizioni-sintesi">Posizioni aperte
@if (v.Positions.Count > 0)
{
<span class="note desk-only">@v.Positions.Count, per @Shell.Money(v.InvestedEur, c). Risultato aperto @Shell.Money(v.OpenResultEur, c, withSign: true)</span>
}
</h2>
@if (v.Positions.Count > 0)
{
<span class="note phone-only">@v.Positions.Count, risultato @Shell.Money(v.OpenResultEur, c, withSign: true)</span>
}
<a class="desk-only" href="/conti">Dettaglio</a>
</div>
@if (v.Positions.Count == 0)
{
<p class="note">Nessuna posizione aperta. Quando una strategia compra, qui vedi ogni posizione con il suo valore, il risultato e lo stop che la protegge.</p>
}
else
{
<ul class="moves moves-past">
@foreach (var action in o.Last)
<div class="table-wrap desk-only">
<table class="table positions">
<thead>
<tr><th scope="col">Strumento</th><th scope="col">Strategia</th><th scope="col" class="num">Valore</th><th scope="col" class="num">Risultato</th><th scope="col" class="num">Stop</th></tr>
</thead>
<tbody>
@foreach (var x in v.Positions)
{
var gain = x.ResultEur >= 0;
<tr>
<th scope="row"><strong>@x.Symbol</strong> <span class="muted">@x.Name</span></th>
<td class="nowrap"><span class="swatch round" style="background: var(--s-@x.Strategy.Replace('_', '-'))"></span>@StrategyNames.Label(x.Strategy)</td>
<td class="num">@Shell.Money(x.ValueEur, c)</td>
<td class="num nowrap @(gain ? "gain" : "loss")"><strong>@Shell.Money(x.ResultEur, c, withSign: true) (@Format.Percent(x.Percent, 2, withSign: true))</strong></td>
<td class="num nowrap">@if (x.Stop is { } stop) {@Format.Money(stop, x.Currency, decimals: AccountsView.StopDecimals(stop))<span class="muted"> (@Format.Percent(x.Last == 0 ? 0 : (stop / x.Last - 1m) * 100m, 1))</span>} else {<span class="muted">nessuno</span>}</td>
</tr>
}
</tbody>
</table>
</div>
<ul class="phone-list phone-only">
@foreach (var x in v.Positions.Take(4))
{
<li><span class="move-time">@action.When</span><span>@action.Text</span></li>
var gain = x.ResultEur >= 0;
<li>
<span><strong>@x.Symbol</strong><span class="sub"><span class="swatch round" style="background: var(--s-@x.Strategy.Replace('_', '-'))"></span>@StrategyNames.Label(x.Strategy)</span></span>
<span class="num">@Shell.Money(x.ValueEur, c)<strong class="sub @(gain ? "gain" : "loss")">@Shell.Money(x.ResultEur, c, withSign: true)</strong></span>
</li>
}
</ul>
<a class="more" href="/diario">Tutto il diario</a>
<a class="more phone-only" href="/conti">@(v.Positions.Count > 4 ? $"Vedi le altre {v.Positions.Count - 4}" : "Vedi i conti")</a>
}
</section>
<section class="panel overview-strategies desk-only" aria-labelledby="strategie-sintesi">
<div class="panel-head">
<h2 id="strategie-sintesi">Strategie</h2>
<a href="/strategie">Dettaglio</a>
</div>
@if (p.Strategies.Count == 0)
{
<p class="note">Le strategie compaiono quando parte il motore di trading.</p>
}
else
{
<ul class="strategy-list">
@foreach (var s in p.Strategies)
{
<li>
<div class="strategy-line"><strong><span class="swatch round" style="background: @s.Color"></span>@s.Name</strong><strong>@Shell.Money(s.Result, c, withSign: true)</strong></div>
<span class="strategy-bar"><span style="width: @Css(Math.Max(s.Bar * 100m, 2m))%; background: @s.Color"></span></span>
<span class="note">@s.Stage</span>
<span class="note">@s.Trades</span>
</li>
}
</ul>
}
@if (!p.AnyLive)
{
<p class="info-note">Nessuna strategia usa soldi veri. Passano al conto reale solo dopo aver superato tutti i requisiti, e solo se lo confermi tu.</p>
}
</section>
</div>
<section class="panel phone-only" aria-labelledby="rischio-telefono">
<div class="panel-head">
<h2 id="rischio-telefono">Rischio</h2>
<span class="status-pill @(p.LimitsKept ? "gain" : "attention")"><Icon Name="@(p.LimitsKept ? "check" : "alert")" Size="16" />@(p.LimitsKept ? "Limiti rispettati" : "Da controllare")</span>
</div>
<div class="limit-list">
@foreach (var l in new[] { p.Limits[2], p.Limits[1] })
{
<div class="limit">
<div class="limit-line"><span>@l.Label</span><span><strong>@l.Value</strong> <span class="muted">su @l.Threshold.Replace(",00%", "%", StringComparison.Ordinal)</span></span></div>
<span class="usage @(l.Worst is null ? null : "notched")">
<span style="width: @Css(l.Share * 100m)%"></span>
@if (l.Worst is { } w)
{
<i class="notch" style="left: @Css(w * 100m)%"></i>
}
</span>
</div>
}
</div>
</section>
@* News, model and system (mockup 01): sections without a frame, under a dark rule (SPEC 13.2). *@
<div class="overview-tiles desk-only">
<section class="plain tile" aria-labelledby="notizie-sintesi">
<div class="panel-head"><h2 id="notizie-sintesi">Notizie che contano</h2><a href="/notizie">Tutte</a></div>
@if (p.News is null)
{
<p class="note">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.</p>
}
else
{
<ul class="news-list">
@foreach (var n in p.News)
{
<li>
<span class="note">@n.When, @n.About</span>
<strong>@n.Title</strong>
<span class="@(n.Active ? "attention" : "muted")">@if (n.Active) {<Icon Name="alert" Size="16" />}@n.Effect</span>
</li>
}
</ul>
}
</section>
<section class="plain tile" aria-labelledby="apprendimento-sintesi">
<div class="panel-head"><h2 id="apprendimento-sintesi">Apprendimento</h2><a href="/apprendimento">Dettaglio</a></div>
@if (p.Learning is not { } m)
{
<p class="note">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.</p>
}
else
{
<p><strong>Il modello osserva e impara, ma non decide ancora.</strong></p>
<div class="limit">
<div class="limit-line"><span>Segnali già valutati</span><span><strong>@m.Signals</strong> <span class="muted">su @m.Needed necessari</span></span></div>
<span class="usage"><span style="width: @Css(Math.Min(100m, m.Signals * 100m / Math.Max(1, m.Needed)))%"></span></span>
</div>
<dl class="tile-facts">
<dt>Previsioni azzeccate</dt><dd>@m.Precision% su dati mai visti</dd>
<dt>Ultimo addestramento</dt><dd>@m.Trained</dd>
<dt>Prossima verifica</dt><dd>@m.NextCheck</dd>
</dl>
}
</section>
<section class="plain tile" aria-labelledby="sistema-sintesi">
<div class="panel-head"><h2 id="sistema-sintesi">Sistema</h2><a href="/diario">Dettaglio</a></div>
<ul class="system-tiles">
@foreach (var part in p.System.Tiles)
{
<li class="@PartClass(part.State)"><Icon Name="@PartIcon(part.State)" Size="16" /><span>@part.Name</span><span class="muted">@part.Detail</span></li>
}
</ul>
</section>
</div>
@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<PositionRow> 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<decimal> 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<decimal> 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));
}
}
+243
View File
@@ -0,0 +1,243 @@
using System.Globalization;
using System.Text.RegularExpressions;
using Anubis.Core;
using Anubis.Db;
using Anubis.Trading;
namespace Anubis.Server;
/// <summary>A piece of a diary line: plain text, or an amount coloured as a gain or a loss (always with its sign).</summary>
internal sealed record DiaryPiece(string Text, string? Class = null);
/// <summary>
/// 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".
/// </summary>
internal sealed record DiaryEntry(DateTimeOffset At, string Kind, string Icon, string? Lead, IReadOnlyList<DiaryPiece> Main, string? Rest, bool Attention, string? Trade);
internal sealed record DiaryDay(DateOnly Day, string Heading, IReadOnlyList<DiaryEntry> Entries);
/// <summary>
/// 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.
/// </summary>
internal sealed partial record DiaryView(IReadOnlyList<DiaryDay> Days, string Filter, string? Search, int Range, bool HasOlder, bool Truncated)
{
/// <summary>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.</summary>
public const string RiskKind = "Rischio";
public const int DefaultRange = 2;
public const int MaxSearchResults = 200;
/// <summary>The filter chips, in the order of the mockup: query value, label, kind.</summary>
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),
];
/// <summary>Journal codes that speak of risk without passing through risk_events: refused orders, keys, prudent accounts, the guard.</summary>
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;
/// <summary>The query string of this view with one value changed, for the links of the page.</summary>
public string Link(string? filter = null, int? range = null)
{
var parts = new List<string>();
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<DiaryView> 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<string>(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"));
}
/// <summary>"Oggi, venerdì 9 ottobre", "Ieri, giovedì 8 ottobre", "Mercoledì 7 ottobre"; the year when it is not this one.</summary>
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..];
}
/// <summary>Splits a diary sentence the way the mockup draws it.</summary>
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<DiaryPiece> Pieces(string text)
{
var pieces = new List<DiaryPiece>();
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+ (?<symbol>\S+) a [^:]+: [+−]")]
private static partial Regex Sale();
[GeneratedRegex(@"(?<![\w])[+−]\d[\d.,]*\s?[€$]")]
private static partial Regex SignedAmount();
}
+35
View File
@@ -174,6 +174,15 @@ internal static partial class Endpoints
"text/csv; charset=utf-8", $"anubis-operazioni-{day}.csv");
});
// The technical logs of the data folder as one zip (SPEC 13.6, "Diario e sistema"). They are redacted when
// written (JsonLog); only the files the log writer names, read while it keeps writing the newest one.
api.MapGet("/registri.zip", (AnubisHost host, ShellData shell, IClock clock) =>
{
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);
/// <summary>The daily log files (anubis-*.log) of a folder in a zip, newest first; an empty zip when there are none yet.</summary>
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<object?> CsrfFilterAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
{
var http = context.HttpContext;
+15 -7
View File
@@ -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);
/// <summary>A move of the bot with its time; <paramref name="Where"/> is the account, <paramref name="Calendar"/> marks an economic event.</summary>
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<NextMove> Next,
IReadOnlyList<LastAction> 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;
}
+214
View File
@@ -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;
/// <summary>The last 30 days of an account: the result net of flows and the daily values in euro for the small line.</summary>
internal sealed record AccountTrend(decimal Month, IReadOnlyList<decimal> Points);
/// <summary>A news item of the "Notizie che contano" tile; <paramref name="Active"/> when its effect is still on.</summary>
internal sealed record PanoramaNews(string When, string About, string Title, string Effect, bool Active);
/// <summary>The model at a glance: signals counted toward the 300, precision on unseen cases, training and next check.</summary>
internal sealed record PanoramaLearning(int Signals, int Needed, int Precision, string Trained, string NextCheck);
/// <summary>One of the four limits of the Panoramica (SPEC 13.6): value, threshold, share used and, for the fall, the worst so far.</summary>
internal sealed record PanoramaLimit(string Label, string Value, string Threshold, decimal Share, decimal? Worst = null);
/// <summary>A strategy at a glance: result, the bar against the best one, its stage in words and its trades.</summary>
internal sealed record PanoramaStrategy(string Name, string Color, decimal Result, decimal Bar, string Stage, string Trades);
/// <summary>
/// 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.
/// </summary>
internal sealed record PanoramaView(
AccountsView Accounts,
IReadOnlyDictionary<Guid, AccountTrend> Trends,
IReadOnlyList<PanoramaLimit> Limits,
bool LimitsKept,
IReadOnlyList<PanoramaStrategy> Strategies,
bool AnyLive,
SystemView System,
IReadOnlyList<NextMove>? DemoMoves,
IReadOnlyList<LastAction>? DemoLast,
string? NextDecision,
IReadOnlyList<PanoramaNews>? News,
PanoramaLearning? Learning,
DateTimeOffset? FractionStops)
{
private static readonly CultureInfo _it = CultureInfo.InvariantCulture;
public static async Task<PanoramaView> 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<PanoramaLimit>
{
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<Dictionary<Guid, AccountTrend>> 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<Guid, AccountTrend>();
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;
}
/// <summary>Where a strategy is on its path, with the requirement that is furthest away: "In simulazione, giorno 58 di 60".</summary>
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;
}
/// <summary>"Prossima decisione tra 7 ore e 14 minuti, alle 15:35."</summary>
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()}.";
}
}
+332
View File
@@ -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;
/// <summary>How a component is doing: working, off by choice or not there yet, or in need of a look.</summary>
internal enum PartState
{
Ok,
Off,
Warn,
}
/// <summary>A component of the system with a line on how it is doing.</summary>
internal sealed record SystemPart(string Name, string Detail, PartState State);
/// <summary>A resource of the computer: what is used, out of how much, as a share for the bar.</summary>
internal sealed record HostResource(string Label, string Value, string? Of, decimal Share);
/// <summary>A job in the scheduler, with its time as people say it ("15:35", "Dom 03:00").</summary>
internal sealed record PlannedJob(string Time, string Text);
/// <summary>
/// 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.
/// </summary>
internal sealed record SystemView(
IReadOnlyList<SystemPart> Parts,
IReadOnlyList<SystemPart> Tiles,
IReadOnlyList<PlannedJob> Jobs,
IReadOnlyList<HostResource> 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"];
/// <summary>Nothing needs a look; components that are off by choice or not active yet do not count.</summary>
public bool AllWell => Parts.All(p => p.State != PartState.Warn);
public static async Task<SystemView> 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<SystemPart>
{
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<SystemPart>
{
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<HostResource>
{
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<SystemView> RealAsync(AnubisHost host, ShellData shell, CancellationToken cancellationToken)
{
var services = host.Services!;
var now = shell.Now;
var zone = shell.Zone;
var parts = new List<SystemPart>();
var tiles = new List<SystemPart>();
// 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<long?> 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;
}
/// <summary>
/// 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.
/// </summary>
private static List<HostResource> MeasureHost(DataDirectory data)
{
var list = new List<HostResource>();
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;
}
/// <summary>A size as people read it: "780 MB", "1,8 GB"; without the unit for the "su 50" after the value.</summary>
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);
/// <summary>The time alone within a day, otherwise the day too: "15:35", "Dom 03:00".</summary>
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);
/// <summary>The processor used by this process between two looks, as a share of all cores.</summary>
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();
}
}
+4 -1
View File
@@ -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; }
/// <summary>A job that comes back at a fixed interval (every minute, every hour): background work, not an appointment.</summary>
public bool Periodic { get; init; }
}
/// <summary>
@@ -221,7 +224,7 @@ public sealed partial class Scheduler(IClock clock, EventBus bus, ILogger<Schedu
return _jobs.Values.Where(j => 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();
}
}
+38 -3
View File
@@ -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" }
]
}
}
+162
View File
@@ -0,0 +1,162 @@
using System.IO.Compression;
using System.Net;
using Anubis.Server;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>The Panoramica and "Diario e sistema" screens (issue #51, mockups 01, 08 and 09).</summary>
[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)));
}
}