Merge remote-tracking branch 'origin/main' into drill-offline
ci / test (postgres) (push) Successful in 4m15s
ci / test (sqlite) (push) Successful in 4m20s
ci / test (postgres) (pull_request) Successful in 4m1s
ci / test (sqlite) (pull_request) Successful in 4m28s
ci / image (push) Successful in 1m52s
ci / image (pull_request) Successful in 1m6s
ci / test (postgres) (push) Successful in 4m15s
ci / test (sqlite) (push) Successful in 4m20s
ci / test (postgres) (pull_request) Successful in 4m1s
ci / test (sqlite) (pull_request) Successful in 4m28s
ci / image (push) Successful in 1m52s
ci / image (pull_request) Successful in 1m6s
# Conflicts: # src/Anubis/Data/MarketDataService.cs
This commit is contained in:
commit
974ebd863f
43 files changed
+4229
-41
No files matched your search
@@ -634,9 +634,56 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we
|
||||
.host { display: flex; flex-direction: column; gap: 12px; }
|
||||
.host > h2 { margin-bottom: 0; }
|
||||
.host .btn { align-self: flex-start; }
|
||||
|
||||
/* ---- Notizie e mercato (mockup 05) ---- */
|
||||
.page-lead { margin: 0 0 20px; font-size: 15px; line-height: 22px; }
|
||||
.news-columns { display: grid; grid-template-columns: minmax(0, 1.75fr) minmax(0, 1fr); gap: 24px; align-items: start; }
|
||||
.news-panel { padding: 24px 26px; }
|
||||
.news-panel > .panel-head { padding-bottom: 16px; margin-bottom: 0; border-bottom: 1px solid var(--rule); }
|
||||
.news-rows { list-style: none; margin: 0; padding: 0; }
|
||||
.news-rows li { display: flex; flex-direction: column; gap: 8px; padding: 18px 0; border-bottom: 1px solid var(--rule); }
|
||||
.news-meta { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 10px; margin: 0; color: var(--text-3); font-size: 13.5px; }
|
||||
.tag-strong { color: var(--text); font-weight: 600; }
|
||||
.tag-outline { background: none; border: 1px solid var(--control); color: var(--text); font-weight: 400; }
|
||||
.panel h3.news-title { margin: 0; font-size: 16px; line-height: 22px; font-weight: 600; }
|
||||
.news-summary { margin: 0; color: var(--text-2); font-size: 14px; line-height: 20px; }
|
||||
.news-facts { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 24px; margin: 0; color: var(--text-2); font-size: 13.5px; }
|
||||
.tone { display: inline-flex; align-items: center; gap: 8px; }
|
||||
.tone .tone-text { color: var(--text-2); }
|
||||
.tone-flat { display: inline-block; width: 10px; height: 2px; background: currentColor; }
|
||||
.importance { display: inline-flex; align-items: center; gap: 8px; }
|
||||
.importance-bars { display: inline-flex; gap: 2px; }
|
||||
.importance-bars span { width: 5px; height: 12px; border-radius: 1.5px; background: var(--track); }
|
||||
.importance-bars span.on { background: var(--text); }
|
||||
.news-rows .notice { margin: 4px 0 0; }
|
||||
.news-action { margin: 0; font-size: 13.5px; color: var(--text-2); }
|
||||
.news-action strong, .news-rows .notice strong { font-weight: 650; color: inherit; }
|
||||
.news-action strong { color: var(--text); }
|
||||
.news-more { display: flex; justify-content: center; padding-top: 16px; }
|
||||
.news-empty { padding: 16px 0 4px; }
|
||||
.news-side .panel { padding: 22px 26px; }
|
||||
.gauges { list-style: none; margin: 14px 0 0; padding: 0; display: flex; flex-direction: column; gap: 18px; }
|
||||
.gauge-head { display: flex; justify-content: space-between; align-items: baseline; gap: 12px; font-size: 13.5px; color: var(--text-2); }
|
||||
.gauge-head strong { color: var(--text); font-size: 15px; font-weight: 650; }
|
||||
.gauge-track { position: relative; height: 4px; margin: 10px 6px 6px; border-radius: 2px; background: var(--track); }
|
||||
.gauge-track.centered::before { content: ""; position: absolute; left: 50%; top: -5px; width: 1px; height: 14px; background: var(--control); }
|
||||
.gauge-dot { position: absolute; top: 50%; width: 12px; height: 12px; margin: -6px 0 0 -6px; border-radius: 50%; background: var(--text); }
|
||||
.gauge-ends { display: flex; justify-content: space-between; gap: 12px; color: var(--text-3); font-size: 12.5px; }
|
||||
.gauges li .hint { margin: 4px 0 0; }
|
||||
.gauges-note { margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--rule); }
|
||||
.calendar-list { list-style: none; margin: 12px 0 0; padding: 0; }
|
||||
.calendar-list li { display: flex; flex-direction: column; gap: 2px; padding: 14px 0; border-top: 1px solid var(--rule); font-size: 13.5px; }
|
||||
.calendar-list li:last-child { padding-bottom: 2px; }
|
||||
.calendar-list strong { font-size: 14.5px; font-weight: 600; }
|
||||
.attention-text { color: var(--attention); }
|
||||
.source-list { list-style: none; margin: 8px 0 12px; padding: 0; }
|
||||
.source-list li { display: grid; grid-template-columns: 16px minmax(0, 1fr) auto; gap: 12px; align-items: center; padding: 9px 0; border-bottom: 1px solid var(--rule-inner); font-size: 14px; }
|
||||
.source-list li > span:first-child { display: inline-flex; }
|
||||
.source-list .muted { text-align: right; }
|
||||
|
||||
@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); }
|
||||
.overview-row-wide, .journal-columns, .news-columns { grid-template-columns: minmax(0, 1fr); }
|
||||
}
|
||||
|
||||
/* ---- Service pages ---- */
|
||||
@@ -736,4 +783,8 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we
|
||||
.chip { min-height: 40px; }
|
||||
.journal-side { gap: 14px; }
|
||||
.job-list li { grid-template-columns: 84px minmax(0, 1fr); }
|
||||
.news-panel, .news-side .panel { padding: 18px; }
|
||||
.news-panel > .panel-head .segmented { display: flex; width: 100%; }
|
||||
.news-panel > .panel-head .segmented a { flex: 1 1 0; text-align: center; padding: 8px 6px; min-height: 44px; display: flex; align-items: center; justify-content: center; }
|
||||
.news-columns, .news-side { gap: 14px; }
|
||||
}
|
||||
@@ -28,6 +28,9 @@
|
||||
"telegram-tolto" => "Telegram tolto: non ti scrivo più finché non lo rimetti.",
|
||||
"segnale" => "Segnale di vita salvato: la prima chiamata è andata bene, da adesso lo chiamo ogni minuto.",
|
||||
"segnale-tolto" => "Segnale di vita tolto.",
|
||||
"fonte" => "Fonte aggiornata: vale dal prossimo giro delle notizie, tra al massimo 2 minuti.",
|
||||
"chiave" => "Chiave salvata. Non la mostro più: se serve cambiarla, scrivine una nuova.",
|
||||
"chiave-tolta" => "Chiave tolta.",
|
||||
|
||||
_ => "Fatto.",
|
||||
})</p>
|
||||
@@ -38,7 +41,7 @@
|
||||
}
|
||||
|
||||
<nav class="tabs" aria-label="Sezioni delle impostazioni">
|
||||
<a href="#aspetto">Aspetto</a><a href="#conti">Conti</a><a href="#rischio">Rischio</a><a href="#telegram">Telegram</a><a href="#dati">Dati</a><a href="#sicurezza">Sicurezza</a><a href="#sistema">Sistema</a><a href="#modifiche">Modifiche</a>
|
||||
<a href="#aspetto">Aspetto</a><a href="#conti">Conti</a><a href="#rischio">Rischio</a><a href="#telegram">Telegram</a><a href="#dati">Dati</a><a href="#notizie">Notizie</a><a href="#sicurezza">Sicurezza</a><a href="#sistema">Sistema</a><a href="#modifiche">Modifiche</a>
|
||||
</nav>
|
||||
|
||||
<section class="panel" id="aspetto">
|
||||
@@ -314,10 +317,88 @@
|
||||
}
|
||||
<p class="hint"><a href="/api/data/quality?format=md&days=30">Rapporto sulla qualità dei dati degli ultimi 30 giorni</a></p>
|
||||
|
||||
</section>
|
||||
|
||||
<section class="panel" id="notizie">
|
||||
<h2>Notizie e calendario</h2>
|
||||
<p class="hint">Le notizie e gli eventi in calendario non fanno mai comprare: possono solo fermare o rimandare un acquisto, e ogni volta il diario dice perché.</p>
|
||||
|
||||
<h3>Regole</h3>
|
||||
@foreach (var rule in _newsRules)
|
||||
{
|
||||
var definition = SettingsStore.Definition(rule.Key);
|
||||
<form method="post" action="/azioni/impostazioni/@rule.Key" class="form-inline">
|
||||
<AntiforgeryToken />
|
||||
<input type="hidden" name="ritorno" value="/impostazioni#notizie" />
|
||||
<label for="@rule.Key">@definition.Label</label>
|
||||
<select id="@rule.Key" name="valore" disabled="@(rule.ReadOnly || Shell.IsDemo)" data-autosubmit>
|
||||
<option value="on" selected="@(rule.Value != "off")">Accesa</option>
|
||||
<option value="off" selected="@(rule.Value == "off")">Spenta</option>
|
||||
</select>
|
||||
@if (rule.ReadOnly)
|
||||
{
|
||||
<span class="hint">Fissato da @rule.Source: si cambia lì.</span>
|
||||
}
|
||||
else if (!Shell.IsDemo)
|
||||
{
|
||||
<noscript><button class="btn btn-small" type="submit">Salva</button></noscript>
|
||||
}
|
||||
</form>
|
||||
}
|
||||
|
||||
<h3>Fonti delle notizie</h3>
|
||||
@if (_newsSources.Count == 0)
|
||||
{
|
||||
<p class="note">Le fonti compaiono qui dopo il primo giro delle notizie, che parte con i dati di mercato.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p class="hint">Una notizia da una sola fonte non affidabile non cambia nulla finché un'altra fonte non la conferma.</p>
|
||||
<div class="table-wrap">
|
||||
<table class="table">
|
||||
<thead><tr><th scope="col">Fonte</th><th scope="col">Leggo</th><th scope="col">Affidabile</th><th scope="col">Ultima lettura</th><th scope="col">Stato</th><th scope="col"><span class="sr-only">Salva</span></th></tr></thead>
|
||||
<tbody>
|
||||
@foreach (var f in _newsSources)
|
||||
{
|
||||
var form = "fonte-" + f.Id.ToString("N");
|
||||
<tr>
|
||||
<td>@f.Name</td>
|
||||
<td><input type="checkbox" name="attiva" form="@form" checked="@f.Enabled" disabled="@Shell.IsDemo" aria-label="Leggo @f.Name" /></td>
|
||||
<td><input type="checkbox" name="affidabile" form="@form" checked="@f.Trusted" disabled="@Shell.IsDemo" aria-label="@f.Name è affidabile" /></td>
|
||||
<td class="nowrap">@(f.LastOkAt is { } at ? Format.ShortDate(at, Shell.Now, Shell.Zone) : "—")</td>
|
||||
<td>@(!f.Enabled ? "spenta" : f.LastError is { } problem ? "non risponde: " + problem : "risponde")</td>
|
||||
<td>
|
||||
@if (!Shell.IsDemo)
|
||||
{
|
||||
<form id="@form" method="post" action="/azioni/notizie/fonti/@f.Id"><AntiforgeryToken /><button class="btn btn-small" type="submit">Salva</button></form>
|
||||
}
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
|
||||
<h3>Modello linguistico</h3>
|
||||
<p class="hint">Facoltativo. Rilegge le notizie delle ultime 24 ore sulle tue posizioni e sugli strumenti candidati, otto per richiesta: può aggiungere una restrizione, mai toglierla, e non vede né chiavi né conti. Senza chiave tutto funziona lo stesso con il classificatore locale. Con Ollama, sul tuo computer o nella tua rete, la chiave non serve.</p>
|
||||
@DataKey(Anubis.News.NewsModelSettings.KeySecret, "Chiave del modello linguistico")
|
||||
@ModelSetting(Anubis.News.NewsModelSettings.Provider.Key, "servizio", "Servizio", null)
|
||||
@ModelSetting(Anubis.News.NewsModelSettings.Model.Key, "modello", "Modello", null)
|
||||
@ModelSetting(Anubis.News.NewsModelSettings.Address.Key, "indirizzo", "Indirizzo (vuoto per quello solito del servizio)", null)
|
||||
@ModelSetting(Anubis.News.NewsModelSettings.PriceIn.Key, "prezzo-letti", "Dollari per milione di token letti", 4)
|
||||
@ModelSetting(Anubis.News.NewsModelSettings.PriceOut.Key, "prezzo-scritti", "Dollari per milione di token scritti", 4)
|
||||
@ModelSetting(Anubis.News.NewsModelSettings.DailyCap.Key, "tetto", "Tetto di spesa al giorno (€)", 2)
|
||||
<p class="note">I prezzi in dollari li conto come euro: la spesa calcolata è un po' più alta di quella vera, mai più bassa. Il tetto vale da mezzanotte a mezzanotte; prima di ogni richiesta controllo che anche il caso peggiore ci stia dentro.</p>
|
||||
|
||||
<h3>Calendario</h3>
|
||||
<p class="hint">Senza chiave di Finnhub non conosco le date delle trimestrali e la mean reversion non usa il suo filtro; senza chiave di FRED il calendario usa solo Forex Factory. Le chiavi sono gratuite.</p>
|
||||
@DataKey("FINNHUB_API_KEY", "Chiave di Finnhub")
|
||||
@DataKey("FRED_API_KEY", "Chiave di FRED")
|
||||
<h3>Riunioni di Fed e BCE</h3>
|
||||
<form method="post" action="/azioni/impostazioni/@SettingsStore.CentralBankMeetings.Key" class="form">
|
||||
<AntiforgeryToken />
|
||||
<input type="hidden" name="ritorno" value="/impostazioni#dati" />
|
||||
<input type="hidden" name="ritorno" value="/impostazioni#notizie" />
|
||||
<label for="riunioni">Un giorno di decisione per riga, per esempio «FED 2027-01-27» o «BCE 2027-02-04». Aggiungi le date del nuovo anno quando le banche le pubblicano.</label>
|
||||
<textarea id="riunioni" name="valore" rows="8" spellcheck="false" readonly="@_meetings.ReadOnly">@_meetings.Value</textarea>
|
||||
<button class="btn" type="submit">Salva l'elenco</button>
|
||||
@@ -454,6 +535,10 @@
|
||||
private IReadOnlyList<Anubis.Data.SourceState> _sources = [];
|
||||
|
||||
private SettingValue _meetings = new(SettingsStore.CentralBankMeetings.Key, "", false, null);
|
||||
private readonly List<SettingValue> _newsRules = [];
|
||||
private readonly Dictionary<string, SettingValue> _llm = [];
|
||||
private IReadOnlyList<Anubis.News.NewsSource> _newsSources = [];
|
||||
private readonly Dictionary<string, SecretStatus> _dataKeys = [];
|
||||
private List<SettingChange> _history = [];
|
||||
private IReadOnlyList<BackupInfo> _backups = [];
|
||||
private bool _hasSecondFactor;
|
||||
@@ -483,6 +568,20 @@
|
||||
_history = await services.Settings.HistoryAsync(null, 50, ct);
|
||||
_meetings = await services.Settings.GetAsync(SettingsStore.CentralBankMeetings.Key, ct);
|
||||
_sources = await new Anubis.Data.SourceStateStore(services.Db, Clock).ListAsync(ct);
|
||||
foreach (var rule in Anubis.News.NewsRuleSettings.All)
|
||||
{
|
||||
_newsRules.Add(await services.Settings.GetAsync(rule.Key, ct));
|
||||
}
|
||||
|
||||
foreach (var setting in Anubis.News.NewsModelSettings.All)
|
||||
{
|
||||
_llm[setting.Key] = await services.Settings.GetAsync(setting.Key, ct);
|
||||
}
|
||||
_newsSources = await new Anubis.News.NewsStore(services.Db, Clock).ListSourcesAsync(ct);
|
||||
foreach (var name in Forms.DataKeys)
|
||||
{
|
||||
_dataKeys[name] = await services.Secrets.StatusAsync(name, ct);
|
||||
}
|
||||
foreach (var definition in Anubis.Risk.RiskSettings.Limits)
|
||||
{
|
||||
var value = await services.Settings.GetAsync(definition.Key, ct);
|
||||
@@ -554,10 +653,95 @@
|
||||
"segnale" => "L'indirizzo non va bene: serve https:// (http solo nella rete di casa).",
|
||||
"segnale-fallito" => "Il servizio di controllo non ha risposto bene alla prova: non ho salvato l'indirizzo.",
|
||||
"scenari" => "Gli scenari non sono validi: una riga ciascuno, con descrizione e tre percentuali separate da punto e virgola.",
|
||||
"fonte" => "Fonte sconosciuta: ricarica la pagina e riprova.",
|
||||
"chiave" => "La chiave è vuota o contiene spazi: copiala di nuovo così come la dà il servizio.",
|
||||
"chiave-ambiente" => "Questa chiave arriva dalle variabili d'ambiente: si cambia nella configurazione del container.",
|
||||
"tetto" => $"Il tetto di spesa va scritto in euro, da 0 a {Anubis.News.NewsModelSettings.MaxCap:0}, per esempio 0,50.",
|
||||
"modello" => "Valore non valido per il modello linguistico: il nome come lo dà il servizio, un indirizzo https:// (http:// solo nella tua rete), prezzi da 0 a 200.",
|
||||
|
||||
_ => PasswordMessages.For(Errore),
|
||||
};
|
||||
|
||||
// A key of SPEC 13.5 that is not a broker's: its state, a field to replace it, a button to take it away. Never the value.
|
||||
// One setting of the language model: a choice for the service, a field for the others; amounts shown in Italian.
|
||||
private RenderFragment ModelSetting(string key, string id, string label, int? decimals)
|
||||
{
|
||||
var definition = SettingsStore.Definition(key);
|
||||
var value = _llm.GetValueOrDefault(key) ?? new SettingValue(key, definition.Default, false, null);
|
||||
var locked = value.ReadOnly || Shell.IsDemo;
|
||||
var shown = decimals is { } d ? Format.Number(decimal.Parse(value.Value, CultureInfo.InvariantCulture), d) : value.Value;
|
||||
var provider = _llm.GetValueOrDefault(Anubis.News.NewsModelSettings.Provider.Key)?.Value ?? Anubis.News.NewsModelProviders.Anthropic;
|
||||
return @<form method="post" action="/azioni/impostazioni/@key" class="form-inline">
|
||||
<AntiforgeryToken />
|
||||
<input type="hidden" name="ritorno" value="/impostazioni#notizie" />
|
||||
<label for="@id">@label</label>
|
||||
@if (definition.Allowed is { } choices)
|
||||
{
|
||||
<select id="@id" name="valore" disabled="@locked" data-autosubmit>
|
||||
@foreach (var choice in choices)
|
||||
{
|
||||
<option value="@choice" selected="@(choice == value.Value)">@ProviderName(choice)</option>
|
||||
}
|
||||
</select>
|
||||
@if (!locked)
|
||||
{
|
||||
<noscript><button class="btn btn-small" type="submit">Salva</button></noscript>
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
<input id="@id" name="valore" inputmode="@(decimals is null ? "text" : "decimal")" autocomplete="off" spellcheck="false" value="@shown"
|
||||
placeholder="@(key == Anubis.News.NewsModelSettings.Address.Key ? Anubis.News.NewsModelProviders.DefaultAddress(provider).ToString() : null)"
|
||||
readonly="@locked" required="@(key != Anubis.News.NewsModelSettings.Address.Key)" />
|
||||
@if (!locked)
|
||||
{
|
||||
<button class="btn btn-small" type="submit">Salva</button>
|
||||
}
|
||||
}
|
||||
@if (value.ReadOnly)
|
||||
{
|
||||
<span class="hint">Fissato da @value.Source: si cambia lì.</span>
|
||||
}
|
||||
</form>;
|
||||
}
|
||||
|
||||
private static string ProviderName(string provider) => provider switch
|
||||
{
|
||||
Anubis.News.NewsModelProviders.Anthropic => "Anthropic (Claude)",
|
||||
Anubis.News.NewsModelProviders.OpenAi => "Compatibile con OpenAI",
|
||||
Anubis.News.NewsModelProviders.Ollama => "Ollama, sul tuo computer o in rete",
|
||||
_ => provider,
|
||||
};
|
||||
|
||||
private RenderFragment DataKey(string name, string label)
|
||||
{
|
||||
var status = _dataKeys.GetValueOrDefault(name) ?? new SecretStatus(name, false, false, null);
|
||||
var id = "k-" + name.ToLowerInvariant();
|
||||
return @<div class="data-key">
|
||||
<p><strong>@label</strong>: @KeyState(status).</p>
|
||||
@if (status.FromEnvironment)
|
||||
{
|
||||
<p class="hint">Si cambia nella configurazione del container (@name).</p>
|
||||
}
|
||||
else if (!Shell.IsDemo)
|
||||
{
|
||||
<form method="post" action="/azioni/chiavi-dati/@name" class="form-inline">
|
||||
<AntiforgeryToken />
|
||||
<label for="@id">@(status.IsSet ? "Nuova chiave" : "Chiave")</label>
|
||||
<input id="@id" name="chiave" type="password" autocomplete="off" spellcheck="false" maxlength="512" required />
|
||||
<button class="btn btn-small" type="submit">Salva</button>
|
||||
</form>
|
||||
@if (status.IsSet)
|
||||
{
|
||||
<form method="post" action="/azioni/chiavi-dati/@name/togli" class="form-inline">
|
||||
<AntiforgeryToken />
|
||||
<button class="btn btn-small btn-danger" type="submit" data-confirm="Tolgo la chiave: quello che la usa smette di funzionare finché non ne metti un'altra. Confermi?">Togli la chiave</button>
|
||||
</form>
|
||||
}
|
||||
}
|
||||
</div>;
|
||||
}
|
||||
|
||||
private string KeyState(SecretStatus status) => status switch
|
||||
{
|
||||
{ FromEnvironment: true } => "Dalle variabili d'ambiente",
|
||||
|
||||
@@ -1,5 +1,235 @@
|
||||
@inherits LoadedComponent
|
||||
@page "/notizie"
|
||||
@inject AnubisHost Host
|
||||
@inject ShellData Shell
|
||||
@using Anubis.News
|
||||
|
||||
<PageTitle>Notizie e mercato · Anubis</PageTitle>
|
||||
|
||||
<Pending Title="Nessuna notizia letta finora.">La lettura delle notizie, l'umore del mercato e il calendario degli eventi arrivano in una fase successiva.</Pending>
|
||||
@{
|
||||
var v = _view;
|
||||
var rows = Filtered(v.Board.Rows).ToList();
|
||||
var count = _filter switch
|
||||
{
|
||||
"effetto" => v.Board.Active,
|
||||
"posizioni" => v.Board.OnPositions,
|
||||
_ => v.Board.Read,
|
||||
};
|
||||
var shown = _all ? rows : rows.Take(Shown).ToList();
|
||||
}
|
||||
<p class="lead page-lead">@Lead(v)</p>
|
||||
|
||||
<div class="news-columns">
|
||||
<section class="panel news-panel" aria-labelledby="letto">
|
||||
<div class="panel-head">
|
||||
<h2 id="letto">Cosa ho letto e cosa ne ho fatto</h2>
|
||||
<nav class="segmented" aria-label="Filtro delle notizie">
|
||||
<a class="@(_filter == "effetto" ? "on" : null)" href="/notizie?filtro=effetto" aria-current="@(_filter == "effetto" ? "page" : null)">Con effetto, @v.Board.Active</a>
|
||||
<a class="@(_filter == "posizioni" ? "on" : null)" href="/notizie?filtro=posizioni" aria-current="@(_filter == "posizioni" ? "page" : null)">Sulle tue posizioni, @v.Board.OnPositions</a>
|
||||
<a class="@(_filter == "tutte" ? "on" : null)" href="/notizie?filtro=tutte" aria-current="@(_filter == "tutte" ? "page" : null)">Tutte, @v.Board.Read</a>
|
||||
</nav>
|
||||
</div>
|
||||
@if (rows.Count == 0)
|
||||
{
|
||||
<p class="note news-empty">@Empty(v)</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<ul class="news-rows">
|
||||
@foreach (var n in shown)
|
||||
{
|
||||
<li>
|
||||
<p class="news-meta">
|
||||
<span>@Format.ShortDate(n.At, Shell.Now, Shell.Zone)@(n.Publisher.Length > 0 ? ", da " + n.Publisher : "")</span>
|
||||
<span class="tag tag-strong">@n.About</span>
|
||||
@if (n.SingleSource)
|
||||
{
|
||||
<span class="tag tag-outline">Una sola fonte</span>
|
||||
}
|
||||
</p>
|
||||
<h3 class="news-title">@n.Title</h3>
|
||||
@if (n.Summary is { } summary)
|
||||
{
|
||||
<p class="news-summary"><span class="sr-only">Riassunto del modello linguistico: </span>@summary</p>
|
||||
}
|
||||
<p class="news-facts">
|
||||
<span class="tone @(n.Direction < 0 ? "loss" : n.Direction > 0 ? "gain" : null)">
|
||||
@if (n.Direction == 0)
|
||||
{
|
||||
<span class="tone-flat" aria-hidden="true"></span>
|
||||
}
|
||||
else
|
||||
{
|
||||
<Arrow Up="@(n.Direction > 0)" />
|
||||
}
|
||||
<span class="tone-text">@n.Tone</span>
|
||||
</span>
|
||||
<span class="importance">
|
||||
<span class="importance-bars" aria-hidden="true">
|
||||
@for (var i = 1; i <= 5; i++)
|
||||
{
|
||||
<span class="@(i <= n.Importance ? "on" : null)"></span>
|
||||
}
|
||||
</span>
|
||||
Importanza @n.Importance su 5
|
||||
</span>
|
||||
</p>
|
||||
@if (n.Active)
|
||||
{
|
||||
<p class="notice notice-attention"><Icon Name="alert" Size="16" /><span><strong>Cosa ho fatto:</strong> @Inline(n.Action)</span></p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p class="news-action"><strong>Cosa ho fatto:</strong> @Inline(n.Action)</p>
|
||||
}
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
@if (!_all && count > shown.Count)
|
||||
{
|
||||
<div class="news-more"><a class="btn" href="/notizie?filtro=@_filter&tutte=1">Mostra le altre @(count - shown.Count)</a></div>
|
||||
}
|
||||
}
|
||||
</section>
|
||||
|
||||
<div class="journal-side news-side">
|
||||
<section class="panel" aria-labelledby="umore">
|
||||
<h2 id="umore">Umore del mercato</h2>
|
||||
<ul class="gauges">
|
||||
@foreach (var g in v.Mood)
|
||||
{
|
||||
<li>
|
||||
<div class="gauge-head">
|
||||
<span>@g.Label</span>
|
||||
@if (g.Value is { } value)
|
||||
{
|
||||
<span><strong>@value</strong> @g.Words</span>
|
||||
}
|
||||
else
|
||||
{
|
||||
<span class="muted">non ancora letto</span>
|
||||
}
|
||||
</div>
|
||||
<div class="gauge-track @(g.Centered ? "centered" : null)" aria-hidden="true">
|
||||
@if (g.Position is { } position)
|
||||
{
|
||||
<span class="gauge-dot" style="left: @Css(position * 100)%"></span>
|
||||
}
|
||||
</div>
|
||||
<div class="gauge-ends"><span>@g.Left</span><span>@g.Right</span></div>
|
||||
@if (g.Stale is { } stale)
|
||||
{
|
||||
<p class="hint">Ultimo valore @stale.</p>
|
||||
}
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
<p class="note gauges-note">Sono indizi che il modello tiene in conto. Da soli non fanno comprare né vendere.</p>
|
||||
<p class="hint">@Anubis.Data.FearGreed.Attribution.</p>
|
||||
</section>
|
||||
|
||||
<section class="panel" aria-labelledby="calendario">
|
||||
<h2 id="calendario">In calendario</h2>
|
||||
@if (v.Calendar.Count == 0)
|
||||
{
|
||||
<p class="note">Nessun evento importante nei prossimi giorni.@(Shell.IsDemo || v.Collecting ? "" : " Il calendario si scarica con i dati di mercato.")</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<ul class="calendar-list">
|
||||
@foreach (var e in v.Calendar)
|
||||
{
|
||||
<li>
|
||||
<span class="muted">@e.When</span>
|
||||
<strong>@e.Title</strong>
|
||||
<span class="@(e.Matters ? "attention-text" : "muted")">@e.Effect</span>
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
</section>
|
||||
|
||||
<section class="plain" aria-labelledby="fonti">
|
||||
<h2 id="fonti">Da dove leggo</h2>
|
||||
@if (v.Sources.Count == 0)
|
||||
{
|
||||
<p class="note">Non leggo ancora nessuna fonte. Le notizie si scaricano con i dati di mercato.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<ul class="source-list">
|
||||
@foreach (var s in v.Sources)
|
||||
{
|
||||
<li>
|
||||
<span class="@(s.Ok ? "gain" : "loss")"><Icon Name="@(s.Ok ? "check" : "alert")" Size="16" /></span>
|
||||
<span>@s.Name</span>
|
||||
<span class="muted">@s.Frequency</span>
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
<p class="note">@v.Spending</p>
|
||||
<p class="hint"><a href="/impostazioni#notizie">Fonti e regole nelle impostazioni</a></p>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
/// <summary>The rows shown before "Mostra le altre", as in the mockup.</summary>
|
||||
private const int Shown = 6;
|
||||
|
||||
private NewsView _view = null!;
|
||||
private string _filter = "posizioni";
|
||||
private bool _all;
|
||||
|
||||
[CascadingParameter]
|
||||
public HttpContext? HttpContext { get; set; }
|
||||
|
||||
[SupplyParameterFromQuery(Name = "filtro")]
|
||||
public string? Filtro { get; set; }
|
||||
|
||||
[SupplyParameterFromQuery(Name = "tutte")]
|
||||
public string? Tutte { get; set; }
|
||||
|
||||
protected override async Task LoadAsync()
|
||||
{
|
||||
var ct = HttpContext?.RequestAborted ?? CancellationToken.None;
|
||||
_view = await NewsView.LoadAsync(Host, Shell, ct);
|
||||
|
||||
// Without positions the default filter would be empty: then all the news.
|
||||
_filter = Filtro is "effetto" or "posizioni" or "tutte" ? Filtro : _view.Board.OnPositions > 0 ? "posizioni" : "tutte";
|
||||
_all = Tutte == "1";
|
||||
}
|
||||
|
||||
private IEnumerable<NewsBoardRow> Filtered(IEnumerable<NewsBoardRow> rows) => _filter switch
|
||||
{
|
||||
"effetto" => rows.Where(r => r.Active),
|
||||
"posizioni" => rows.Where(r => r.OnPositions),
|
||||
_ => rows,
|
||||
};
|
||||
|
||||
private static string Lead(NewsView v)
|
||||
{
|
||||
var read = v.Board.Read == 1 ? "1 notizia letta" : $"{v.Board.Read} notizie lette";
|
||||
var active = v.Board.Active switch
|
||||
{
|
||||
0 => "nessuna con un effetto in corso",
|
||||
1 => "1 con un effetto in corso",
|
||||
var n => $"{n} con un effetto in corso",
|
||||
};
|
||||
return $"{read} nelle ultime 24 ore, {active}.";
|
||||
}
|
||||
|
||||
private string Empty(NewsView v) => _filter switch
|
||||
{
|
||||
"effetto" => "Nessuna notizia ha un effetto in corso: compro e vendo come dicono le strategie.",
|
||||
"posizioni" => "Nessuna notizia sulle tue posizioni nelle ultime 24 ore.",
|
||||
_ when !v.Collecting && !Shell.IsDemo => "Non leggo ancora notizie: la raccolta parte con i dati di mercato. Le fonti si scelgono nelle impostazioni.",
|
||||
_ => "Nessuna notizia nelle ultime 24 ore.",
|
||||
};
|
||||
|
||||
// "Niente. Confermano…" reads "niente. Confermano…" after "Cosa ho fatto:".
|
||||
private static string Inline(string text) => text.Length == 0 ? text : char.ToLowerInvariant(text[0]) + text[1..];
|
||||
|
||||
private static string Css(double value) => value.ToString("0.##", CultureInfo.InvariantCulture);
|
||||
}
|
||||
@@ -342,7 +342,11 @@
|
||||
<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>
|
||||
<p class="note">La lettura delle notizie è spenta insieme ai dati di mercato. Quando la accendi, qui vedrai le tre che contano di più per le tue posizioni e cosa ne ho fatto.</p>
|
||||
}
|
||||
else if (p.News.Count == 0)
|
||||
{
|
||||
<p class="note">Nessuna notizia sulle tue posizioni nelle ultime 24 ore, e nessuna restrizione in corso.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
@@ -44,6 +44,67 @@ internal static partial class Forms
|
||||
signed.MapPost("/strategie/{strategy}/{choice}", StrategyStageAsync);
|
||||
signed.MapPost("/rischio/limiti", SetLimitsAsync);
|
||||
signed.MapPost("/rischio/{key}", SetRiskSettingAsync);
|
||||
signed.MapPost("/notizie/fonti/{id:guid}", SetNewsSourceAsync);
|
||||
signed.MapPost("/chiavi-dati/{name}", SaveDataKeyAsync);
|
||||
signed.MapPost("/chiavi-dati/{name}/togli", RemoveDataKeyAsync);
|
||||
}
|
||||
|
||||
/// <summary>The optional keys of SPEC 13.5 that are not a broker's: the language model, Finnhub, FRED.</summary>
|
||||
internal static readonly IReadOnlyList<string> DataKeys = [Anubis.News.NewsModelSettings.KeySecret, "FINNHUB_API_KEY", "FRED_API_KEY"];
|
||||
|
||||
private static async Task<IResult> SetNewsSourceAsync(Guid id, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
||||
{
|
||||
const string back = "/impostazioni";
|
||||
if (host.IsDemo || host.Services is not { } services)
|
||||
{
|
||||
return Results.Redirect(back + "?errore=motore#notizie");
|
||||
}
|
||||
|
||||
var enabled = form["attiva"].ToString() == "on";
|
||||
var trusted = form["affidabile"].ToString() == "on";
|
||||
var found = await new Anubis.News.NewsStore(services.Db, host.Clock).SetSourceAsync(id, enabled, trusted, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
|
||||
return Results.Redirect(back + (found ? "?ok=fonte#notizie" : "?errore=fonte#notizie"));
|
||||
}
|
||||
|
||||
// A key is saved as it is: FRED and Finnhub say whether it works at the next round, in the state of the sources.
|
||||
private static async Task<IResult> SaveDataKeyAsync(string name, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
||||
{
|
||||
const string back = "/impostazioni";
|
||||
if (!DataKeys.Contains(name))
|
||||
{
|
||||
return Results.Redirect(back + "?errore=impostazione#notizie");
|
||||
}
|
||||
|
||||
if (host.IsDemo || host.Services is not { } services)
|
||||
{
|
||||
return Results.Redirect(back + "?errore=motore#notizie");
|
||||
}
|
||||
|
||||
if ((await services.Secrets.StatusAsync(name, ct).ConfigureAwait(false)).FromEnvironment)
|
||||
{
|
||||
return Results.Redirect(back + "?errore=chiave-ambiente#notizie");
|
||||
}
|
||||
|
||||
var value = form["chiave"].ToString().Trim();
|
||||
if (value.Length is 0 or > 512 || value.Any(c => char.IsWhiteSpace(c) || char.IsControl(c)))
|
||||
{
|
||||
return Results.Redirect(back + "?errore=chiave#notizie");
|
||||
}
|
||||
|
||||
await services.Secrets.SetAsync(name, value, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
|
||||
return Results.Redirect(back + "?ok=chiave#notizie");
|
||||
}
|
||||
|
||||
private static async Task<IResult> RemoveDataKeyAsync(string name, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
||||
{
|
||||
const string back = "/impostazioni";
|
||||
if (!DataKeys.Contains(name) || host.IsDemo || host.Services is not { } services)
|
||||
{
|
||||
return Results.Redirect(back + "?errore=motore#notizie");
|
||||
}
|
||||
|
||||
await services.Secrets.RemoveAsync(name, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
|
||||
return Results.Redirect(back + "?ok=chiave-tolta#notizie");
|
||||
}
|
||||
|
||||
/// <summary>The notice of a long absence (SPEC 5.6) goes away once the user has seen it.</summary>
|
||||
@@ -176,11 +237,38 @@ internal static partial class Forms
|
||||
private static async Task<IResult> SetSettingAsync(string key, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
||||
{
|
||||
var back = Back(form, "/impostazioni");
|
||||
if (key != SettingsStore.Theme.Key && key != SettingsStore.Currency.Key && key != SettingsStore.CentralBankMeetings.Key && key != SettingsStore.TelegramStatus.Key)
|
||||
var news = Anubis.News.NewsRuleSettings.All.Any(d => d.Key == key);
|
||||
var model = Anubis.News.NewsModelSettings.All.Any(d => d.Key == key);
|
||||
if (key != SettingsStore.Theme.Key && key != SettingsStore.Currency.Key && key != SettingsStore.CentralBankMeetings.Key && key != SettingsStore.TelegramStatus.Key &&
|
||||
!news && !model)
|
||||
{
|
||||
return Results.Redirect(With(back, "errore", "impostazione"));
|
||||
}
|
||||
|
||||
if ((news || model) && host.IsDemo)
|
||||
{
|
||||
return Results.Redirect(With(back, "errore", "motore"));
|
||||
}
|
||||
|
||||
if (model)
|
||||
{
|
||||
// Amounts as the user writes them, "0,50" or "0,50 €", stored as "0.50"; the other values trimmed.
|
||||
var value = form["valore"].ToString().Trim();
|
||||
if (Anubis.News.NewsModelSettings.IsAmount(key))
|
||||
{
|
||||
value = Anubis.News.NewsModelSettings.Amount(value)?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? value;
|
||||
}
|
||||
|
||||
var definition = SettingsStore.Definition(key);
|
||||
if ((definition.Check?.Invoke(value) is not null) || (definition.Allowed is { } allowed && !allowed.Contains(value, StringComparer.Ordinal)))
|
||||
{
|
||||
return Results.Redirect(With(back, "errore", key == Anubis.News.NewsModelSettings.DailyCap.Key ? "tetto" : "modello"));
|
||||
}
|
||||
|
||||
var saved = await Endpoints.SetSettingAsync(host, key, value, context, ct).ConfigureAwait(false);
|
||||
return Results.Redirect(saved is IStatusCodeHttpResult { StatusCode: StatusCodes.Status204NoContent } ? back : With(back, "errore", "impostazione"));
|
||||
}
|
||||
|
||||
if (key == SettingsStore.CentralBankMeetings.Key && Anubis.Data.CentralBanks.Check(form["valore"].ToString()) is not null)
|
||||
{
|
||||
return Results.Redirect(With(back, "errore", "riunioni"));
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
using System.Globalization;
|
||||
using Anubis.Core;
|
||||
using Anubis.Data;
|
||||
using Anubis.News;
|
||||
using Anubis.Strategies;
|
||||
|
||||
namespace Anubis.Server;
|
||||
|
||||
/// <summary>
|
||||
/// A gauge of "Umore del mercato" (SPEC 10.4): the value with its label, the dot on a track from <paramref name="Left"/> to
|
||||
/// <paramref name="Right"/>. <paramref name="Position"/> is from 0 to 1, null while the indicator has not been read.
|
||||
/// </summary>
|
||||
internal sealed record MoodGauge(string Label, string? Value, string? Words, double? Position, string Left, string Right, bool Centered, string? Stale);
|
||||
|
||||
/// <summary>An event of "In calendario" with the effect it will have; <paramref name="Matters"/> when it holds entries.</summary>
|
||||
internal sealed record CalendarRow(string When, string Title, string Effect, bool Matters);
|
||||
|
||||
/// <summary>A line of "Da dove leggo": the source, how often, and whether it answers.</summary>
|
||||
internal sealed record SourceRow(string Name, string Frequency, bool Ok);
|
||||
|
||||
/// <summary>
|
||||
/// The Notizie e mercato screen (SPEC 13.6, mockup 05): what the bot read and did, the mood of the market, the calendar
|
||||
/// with the effect of each event, the sources and the spending on the language model. In demo mode the counts, the
|
||||
/// sources and the spending of appendix F.9 come from the aggregates; the rows come from the database.
|
||||
/// </summary>
|
||||
internal sealed record NewsView(
|
||||
NewsBoardResult Board,
|
||||
IReadOnlyList<MoodGauge> Mood,
|
||||
IReadOnlyList<CalendarRow> Calendar,
|
||||
IReadOnlyList<SourceRow> Sources,
|
||||
string Spending,
|
||||
bool Collecting)
|
||||
{
|
||||
/// <summary>How far ahead the calendar looks: a week of economic data, a month of central banks, two weeks of earnings.</summary>
|
||||
public static readonly TimeSpan EconomicAhead = TimeSpan.FromDays(7);
|
||||
|
||||
public static readonly TimeSpan CentralBanksAhead = TimeSpan.FromDays(31);
|
||||
|
||||
public static readonly TimeSpan EarningsAhead = TimeSpan.FromDays(14);
|
||||
|
||||
public const int CalendarRows = 6;
|
||||
|
||||
private static readonly CultureInfo _it = CultureInfo.InvariantCulture;
|
||||
|
||||
public static async Task<NewsView> LoadAsync(AnubisHost host, ShellData shell, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(host);
|
||||
ArgumentNullException.ThrowIfNull(shell);
|
||||
var services = host.Services!;
|
||||
var clock = host.Clock;
|
||||
var now = clock.UtcNow;
|
||||
var board = await new NewsBoard(services.Db, clock, services.Settings).LoadAsync(cancellationToken).ConfigureAwait(false);
|
||||
var switches = await NewsRuleSettings.LoadAsync(services.Settings, cancellationToken).ConfigureAwait(false);
|
||||
var mood = await MoodAsync(new MoodStore(services.Db, clock), now, cancellationToken).ConfigureAwait(false);
|
||||
var calendar = await CalendarAsync(services, clock, shell.Zone, switches, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
using var aggregates = shell.Aggregates();
|
||||
if (aggregates?.RootElement.GetProperty("notizie") is { } demo)
|
||||
{
|
||||
var counted = board with
|
||||
{
|
||||
Read = demo.GetProperty("lette_24h").GetInt32(),
|
||||
OnPositions = demo.GetProperty("sulle_posizioni").GetInt32(),
|
||||
Active = demo.GetProperty("con_effetto").GetInt32(),
|
||||
};
|
||||
var sources = demo.GetProperty("fonti").EnumerateArray()
|
||||
.Select(f => new SourceRow(f.GetProperty("nome").GetString()!, f.GetProperty("frequenza").GetString()!, true)).ToList();
|
||||
var spending = $"Tutte le notizie passano da un modello locale, gratuito. Solo le {demo.GetProperty("sulle_posizioni").GetInt32()} rilevanti sono state rilette " +
|
||||
$"da un modello linguistico: oggi è costato {Format.Money(decimal.Parse(demo.GetProperty("spesa_oggi").GetString()!, _it))} " +
|
||||
$"su un tetto di {Format.Money(decimal.Parse(demo.GetProperty("tetto").GetString()!, _it))}.";
|
||||
return new NewsView(counted, mood, calendar, sources, spending, true);
|
||||
}
|
||||
|
||||
var (rows, collecting) = await SourcesAsync(services, shell, clock, cancellationToken).ConfigureAwait(false);
|
||||
// Only reads what was spent: the screen never asks the model anything.
|
||||
var model = await new NewsAnalyst(services.Db, clock, services.Settings, services.Secrets.RevealAsync,
|
||||
(_, _) => throw new InvalidOperationException("La schermata non interroga il modello.")).SpendingAsync(cancellationToken).ConfigureAwait(false);
|
||||
return new NewsView(board, mood, calendar, rows, SpendingText(model), collecting);
|
||||
}
|
||||
|
||||
/// <summary>The spending of the day in words (SPEC 13.6): what the language model read and what it cost, against the cap.</summary>
|
||||
public static string SpendingText(ModelSpending model)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(model);
|
||||
const string Local = "Tutte le notizie passano da un modello locale, gratuito, sul tuo computer.";
|
||||
if (!model.Configured)
|
||||
{
|
||||
return Local + " Il modello linguistico non è configurato: oggi non è costato nulla.";
|
||||
}
|
||||
|
||||
var read = model.Judged switch
|
||||
{
|
||||
0 => "Oggi il modello linguistico non ha ancora riletto nessuna notizia",
|
||||
1 => "Oggi il modello linguistico ha riletto 1 notizia sulle tue posizioni e sugli strumenti candidati",
|
||||
var n => $"Oggi il modello linguistico ha riletto {n} notizie sulle tue posizioni e sugli strumenti candidati",
|
||||
};
|
||||
var full = model.Spent >= model.Cap ? " Il tetto è raggiunto: fino a mezzanotte giudica solo il modello locale." : "";
|
||||
return $"{Local} {read}: è costato {Format.Money(model.Spent)} su un tetto di {Format.Money(model.Cap)}.{full}";
|
||||
}
|
||||
|
||||
private static async Task<IReadOnlyList<MoodGauge>> MoodAsync(MoodStore store, DateTimeOffset now, CancellationToken cancellationToken)
|
||||
{
|
||||
var fear = await store.LatestAsync(MoodIndicators.FearGreed, cancellationToken).ConfigureAwait(false);
|
||||
var vix = await store.LatestAsync(MoodIndicators.Vix, cancellationToken).ConfigureAwait(false);
|
||||
var funding = await store.LatestAsync(MoodIndicators.BtcFunding, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// A reading older than three days is shown with its date: the mood of last week is not today's.
|
||||
string? Stale(MoodReading? r) => r is { } x && now - x.AsOf > TimeSpan.FromDays(3) ? "letto " + Format.ShortDate(x.AsOf, now, Zones.Rome, false) : null;
|
||||
return
|
||||
[
|
||||
new("Crypto: paura o avidità", fear is { } f ? Format.Number((decimal)f.Value) : null, fear is { } f2 ? "su 100, " + MoodLabels.FearGreed(f2.Value) : null,
|
||||
fear is { } f3 ? Math.Clamp(f3.Value / 100, 0, 1) : null, "Paura estrema", "Avidità estrema", false, Stale(fear)),
|
||||
new("Azioni USA: nervosismo atteso", vix is { } v ? Format.Number((decimal)v.Value, 1) : null, vix is { } v2 ? MoodLabels.Vix(v2.Value) : null,
|
||||
vix is { } v3 ? Math.Clamp((v3.Value - 10) / 30, 0, 1) : null, "Calmo (10)", "Panico (40)", false, Stale(vix)),
|
||||
new("Bitcoin: scommesse a leva", funding is { } b ? Format.Percent((decimal)b.Value * 100m, 3, withSign: true) : null,
|
||||
funding is { } b2 ? MoodLabels.Funding(b2.Value, TimeSpan.FromHours(8)) : null,
|
||||
funding is { } b3 ? Math.Clamp(0.5 + (b3.Value / 0.0008), 0, 1) : null, "Troppi al ribasso", "Troppi al rialzo", true, Stale(funding)),
|
||||
];
|
||||
}
|
||||
|
||||
// The events that change something or that the user expects to see: this week's US and euro data of medium or high
|
||||
// impact, the central banks of the next month, the earnings of the stocks held or watched.
|
||||
private static async Task<IReadOnlyList<CalendarRow>> CalendarAsync(AppServices services, IClock clock, TimeZoneInfo zone, NewsRuleSwitches switches,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var now = clock.UtcNow;
|
||||
var events = await new CalendarEventStore(services.Db, clock).BetweenAsync(now, now + CentralBanksAhead, cancellationToken).ConfigureAwait(false);
|
||||
var (held, noted) = await services.Db.ReadAsync(async s =>
|
||||
{
|
||||
var h = await s.QueryAsync("SELECT i.symbol FROM positions p JOIN instruments i ON i.id = p.instrument_id WHERE i.venue = @v AND p.quantity > 0",
|
||||
r => r.Text("symbol"), ("v", Venues.Alpaca)).ConfigureAwait(false);
|
||||
var n = await s.QueryAsync("SELECT subject FROM news_notes WHERE kind = @k", r => r.Text("subject"), ("k", NewsReasons.Earnings)).ConfigureAwait(false);
|
||||
return (h, n);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
var stocks = held.ToHashSet(StringComparer.Ordinal);
|
||||
var withNote = noted.ToHashSet(StringComparer.Ordinal);
|
||||
|
||||
var shown = events.Where(e => e.Kind switch
|
||||
{
|
||||
CalendarEventKinds.Economic => e.OccursAt - now <= EconomicAhead && e.Currency is "USD" or "EUR" && e.Impact is "High" or "Medium",
|
||||
CalendarEventKinds.CentralBank => true,
|
||||
CalendarEventKinds.Earnings => e.OccursAt - now <= EarningsAhead && e.Symbol is { } s && (stocks.Contains(s) || withNote.Contains("event:" + e.SourceKey)),
|
||||
_ => false,
|
||||
}).OrderBy(e => e.OccursAt).Take(CalendarRows);
|
||||
|
||||
return [.. shown.Select(e => Row(e, now, zone, switches))];
|
||||
}
|
||||
|
||||
private static CalendarRow Row(CalendarEvent e, DateTimeOffset now, TimeZoneInfo zone, NewsRuleSwitches switches)
|
||||
{
|
||||
var local = TimeZoneInfo.ConvertTime(e.OccursAt, zone);
|
||||
var day = DateOnly.FromDateTime(local.DateTime);
|
||||
var today = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(now, zone).DateTime);
|
||||
var dayText = day == today ? "Oggi" : day == today.AddDays(1) ? "Domani" : Capital(Format.Day(day));
|
||||
if (e.Kind == CalendarEventKinds.Earnings)
|
||||
{
|
||||
var session = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(e.OccursAt, Zones.NewYork).DateTime);
|
||||
var sessionText = session.DayNumber - today.DayNumber is > 0 and < 7 ? Format.Day(session).Split(' ')[0] : Format.Day(session);
|
||||
var (when, until) = e.TimeHint switch
|
||||
{
|
||||
"bmo" => (", prima dell'apertura", $"fino a {sessionText}"),
|
||||
"dmh" => (", durante la seduta", $"fino a {sessionText}"),
|
||||
"amc" => (", dopo la chiusura", "fino alla seduta dopo i conti"),
|
||||
_ => ("", "fino alla seduta dopo i conti"),
|
||||
};
|
||||
return switches.Earnings
|
||||
? new CalendarRow(dayText + when, e.Title, $"Riguarda {e.Symbol}: niente mean reversion {until}", true)
|
||||
: new CalendarRow(dayText + when, e.Title, $"Riguarda {e.Symbol}: la regola è spenta, nessun effetto", false);
|
||||
}
|
||||
|
||||
var whenText = e.TimeKnown ? $"{dayText}, {local:HH:mm}" : dayText;
|
||||
var impact = e.Impact switch
|
||||
{
|
||||
"High" => "Impatto alto",
|
||||
"Medium" => "Impatto medio",
|
||||
_ => "Impatto basso",
|
||||
};
|
||||
if (CalendarBlocks.Window(e) is { } window)
|
||||
{
|
||||
if (!switches.Macro)
|
||||
{
|
||||
return new CalendarRow(whenText, e.Title, impact + ": la regola è spenta, nessun blocco", false);
|
||||
}
|
||||
|
||||
var from = TimeZoneInfo.ConvertTime(window.From, zone);
|
||||
var to = TimeZoneInfo.ConvertTime(window.To, zone);
|
||||
return new CalendarRow(whenText, e.Title, string.Create(_it, $"{impact}: nessun nuovo ingresso dalle {from:HH:mm} alle {to:HH:mm}"), true);
|
||||
}
|
||||
|
||||
return new CalendarRow(whenText, e.Title, impact + ": nessun blocco", false);
|
||||
}
|
||||
|
||||
private static async Task<(IReadOnlyList<SourceRow> Rows, bool Collecting)> SourcesAsync(AppServices services, ShellData shell, IClock clock, CancellationToken cancellationToken)
|
||||
{
|
||||
var feeds = await new NewsStore(services.Db, clock).ListSourcesAsync(cancellationToken).ConfigureAwait(false);
|
||||
var on = feeds.Where(f => f.Enabled).ToList();
|
||||
var rows = new List<SourceRow>();
|
||||
var press = on.Where(f => f.Name != "SEC").ToList();
|
||||
if (press.Count > 0)
|
||||
{
|
||||
var failing = press.Count(f => f.LastError is not null);
|
||||
rows.Add(new SourceRow($"{press.Count} testate e banche centrali", failing == 0 ? "ogni 2 minuti" : $"{failing} non rispondono", failing == 0));
|
||||
}
|
||||
|
||||
if (on.FirstOrDefault(f => f.Name == "SEC") is { } sec)
|
||||
{
|
||||
rows.Add(new SourceRow("Comunicati alla SEC", sec.LastError is null ? "ogni 2 minuti" : "non risponde", sec.LastError is null));
|
||||
}
|
||||
|
||||
var states = await new SourceStateStore(services.Db, clock).ListAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (states.FirstOrDefault(s => s.Source == ForexFactory.Source) is { } calendar)
|
||||
{
|
||||
var ok = calendar.LastError is null && calendar.LastSuccessAt is not null;
|
||||
rows.Add(new SourceRow("Calendario economico",
|
||||
calendar.LastSuccessAt is { } at ? "aggiornato " + Inline(Format.ShortDate(at, shell.Now, shell.Zone)) : "non ancora letto", ok));
|
||||
}
|
||||
|
||||
return (rows, services.MarketData is not null && on.Count > 0);
|
||||
}
|
||||
|
||||
private static string Capital(string text) => text.Length == 0 ? text : char.ToUpperInvariant(text[0]) + text[1..];
|
||||
|
||||
private static string Inline(string text) => text.Length == 0 ? text : char.ToLowerInvariant(text[0]) + text[1..];
|
||||
}
|
||||
@@ -44,6 +44,16 @@ internal sealed record PanoramaView(
|
||||
{
|
||||
private static readonly CultureInfo _it = CultureInfo.InvariantCulture;
|
||||
|
||||
/// <summary>"Notizie che contano" (SPEC 13.6): first those with an effect in force, then the latest on the positions or their markets.</summary>
|
||||
internal static IReadOnlyList<PanoramaNews> Matters(Anubis.News.NewsBoardResult board, ShellData shell)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(board);
|
||||
ArgumentNullException.ThrowIfNull(shell);
|
||||
return [.. board.Rows.Where(r => r.Active || r.OnPositions).Take(3).Select(r => new PanoramaNews(
|
||||
Format.ShortDate(r.At, shell.Now, shell.Zone), "su " + r.About, r.Title,
|
||||
r.Active ? $"{r.Tone.Split(',')[0]}: {char.ToLowerInvariant(r.Action[0])}{r.Action[1..].TrimEnd('.')}" : "Nessun effetto: non cambio nulla", r.Active))];
|
||||
}
|
||||
|
||||
public static async Task<PanoramaView> LoadAsync(AnubisHost host, ShellData shell, Overview overview, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(host);
|
||||
@@ -86,7 +96,9 @@ internal sealed record PanoramaView(
|
||||
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 board = await new Anubis.News.NewsBoard(services.Db, clock, services.Settings).LoadAsync(cancellationToken).ConfigureAwait(false);
|
||||
return new PanoramaView(accounts, trends, limits, kept, cards, anyLive, system, null, null, Decision(overview.NextDecision, shell.Now, shell.Zone),
|
||||
services.MarketData is null && board.Rows.Count == 0 ? null : Matters(board, shell), null, fractions);
|
||||
}
|
||||
|
||||
var root = aggregates.RootElement;
|
||||
|
||||
Reference in new issue
Block a user