diff --git a/CLAUDE.md b/CLAUDE.md index 0af2bc2..4e5be10 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -19,7 +19,7 @@ Dalla radice del repository: `./tasks.ps1 ` (Windows) o `sh ./tasks.sh - `ci`: come la CI. Esegue `check`, poi i test su PostgreSQL (avvia `docker compose up -d --wait postgres`, porta 55432) e infine l'immagine. Richiede Docker. - `hooks`: attiva `.githooks/pre-commit`, che esegue `check` prima di ogni commit. Si fa una volta per copia del repository. - `seed-demo`: la modalità dimostrativa con i dati dell'appendice F, in una cartella e un database a parte, solo dal computer stesso. -- `screenshots`: fotografa Panoramica, Conti, Diario e Impostazioni a 1440 px (chiaro e scuro) e a 390 px in `artifacts/screenshots/`. Usa Edge o Chrome già installati. +- `screenshots`: fotografa Panoramica, Conti, Diario, Notizie e Impostazioni a 1440 px (chiaro e scuro) e a 390 px in `artifacts/screenshots/`. Usa Edge o Chrome già installati. - `release-win`: lo zip di prova per Windows in `artifacts/release/` (ADR 0013), da allegare alla release `v0.N.0` su Gitea. - `desktop-win` (Fase 10): non ancora disponibile. - `docker compose up --build`: l'applicazione su http://localhost:8787 con PostgreSQL, `/health` risponde `ok`. Primo accesso con `ANUBIS_ADMIN_PASSWORD` del compose. diff --git a/docs/STATE.md b/docs/STATE.md index e3d0997..f9a2111 100644 --- a/docs/STATE.md +++ b/docs/STATE.md @@ -101,6 +101,11 @@ Aggiornato: 2026-11-16 - ogni restrizione compare nel diario con il suo motivo, e ogni riga si spegne in Impostazioni; - dopo un'assenza valgono solo le restrizioni ancora in corso; - lo stato di ogni strumento tiene il tono a 1 e 3 giorni, il numero di storie rispetto alla norma e la restrizione in corso. + - Schermata Notizie e mercato (#60, ADR 0014 punti 13–14): + - l'elenco "cosa ho letto e cosa ne ho fatto" con tre filtri, e per ogni notizia la frase di cosa ha fatto il bot e perché; + - l'umore del mercato, il calendario con l'effetto di ogni evento, le fonti e la spesa del giorno; + - in Impostazioni → Notizie: le righe di 10.5, le fonti, la chiave e il tetto del modello linguistico, le chiavi di Finnhub e FRED, le riunioni di Fed e BCE; + - nella demo la schermata corrisponde al mockup (fotografie con `tasks screenshots /notizie`). ## In corso @@ -109,16 +114,14 @@ Nulla. ## Prossimo passo 1. L'utente scarica lo zip della release `v0.7.0` da Gitea (Release), lo fa girare e poi incolla il rapporto: doppio clic su `Prepara i dati da incollare.cmd`, oppure il pulsante in Diario e sistema. Il rapporto si analizza e si salva in `docs/diagnostica/`; da lì si chiude #55. -2. Intanto la Fase 7 va avanti sul branch `fase-7`. Raccolta (#56), primo giudizio con il classificatore (#57) e regole di 10.5 (#59) sono fatti. Restano: - - la schermata Notizie con gli interruttori delle regole (#60); - - l'analista facoltativo (#58). +2. Intanto la Fase 7 va avanti sul branch `fase-7`. Raccolta (#56), primo giudizio con il classificatore (#57), regole di 10.5 (#59) e schermata Notizie (#60) sono fatti. Resta l'analista facoltativo (#58), poi la chiusura della fase (#61). 3. Con le chiavi del conto paper di Alpaca si possono anche fare i backtest azionari (`anubis backtest base`) e chiudere i criteri delle Fasi 2 e 3 in attesa. ## Da sapere - Le immagini .NET 10 sono su Ubuntu 24.04, non Debian (ADR 0006). - La prova nel container `anubis-prova` è chiusa (ADR 0013). I compiti programmati che la sorvegliavano sono spenti; il container si può fermare con `docker stop anubis-prova`. -- La modalità dimostrativa mostra le schermate costruite fin qui. Notizie e apprendimento appaiono solo con i dati dell'appendice F: fuori dalla demo arrivano con le Fasi 7 e 8. Nella demo il motore di trading e Telegram sono spenti. +- La modalità dimostrativa mostra le schermate costruite fin qui. Le notizie fuori dalla demo si vedono dalla Fase 7; l'apprendimento appare solo con i dati dell'appendice F e arriva con la Fase 8. Nella demo il motore di trading e Telegram sono spenti. - In Docker il processo principale è la guardia; fuori da Docker (`tasks dev`, VS Code) il server gira da solo. - La guardia oggi apre solo i conti di prova: avrà i conti reali con la fase dei soldi veri (ADR 0012, punto 4). - Le chiavi dei conti di prova si inseriscono da Impostazioni → Conti e chiavi oppure nel file `.env`; quelle nelle variabili d'ambiente valgono di più. Una chiave OKX che permette i prelievi viene rifiutata. diff --git a/docs/adr/0014-scelte-fase-7.md b/docs/adr/0014-scelte-fase-7.md index 6b0c580..3364eee 100644 --- a/docs/adr/0014-scelte-fase-7.md +++ b/docs/adr/0014-scelte-fase-7.md @@ -107,9 +107,28 @@ Inoltre: **12. Le etichette d'umore (10.4)** sono quelle della Fase 2 (ADR 0008) e non cambiano. +**13. La schermata Notizie e mercato (13.1–13.6, F.9).** +- Ogni nota del bot su una storia conserva la frase "cosa ho fatto" e, se è una restrizione, la sua fine (`news_notes.action` e `news_notes.until`, migrazione 0010). La schermata legge la frase com'era al momento della decisione e non la ricalcola. +- Se una restrizione è ancora in corso ma la sua riga è stata spenta, la frase lo dice ("Ora la regola è spenta: la restrizione non vale più") e la notizia non conta più tra quelle con un effetto. +- Quando il bot non ha fatto nulla, il motivo viene dalle regole: la notizia riguarda il mercato e non un singolo strumento; non è confermata; la sua riga è spenta; è positiva (le notizie non fanno mai comprare); è solo leggermente negativa; il tono non è stato letto. +- L'elenco mostra le storie viste nelle ultime 24 ore e, in più, quelle più vecchie con una restrizione ancora in corso. Per prime vengono quelle con un effetto, poi le altre dalla più recente. +- I tre filtri: "con effetto" (una restrizione o un evento in corso); "sulle tue posizioni" (gli strumenti che il bot tiene, la loro classe e il mercato nel suo insieme); "tutte". Si apre su "sulle tue posizioni" quando c'è almeno una posizione. Sei righe, poi "Mostra le altre". +- Il calendario mostra al massimo sei eventi: i dati in dollari ed euro di impatto alto e medio dei prossimi 7 giorni, le banche centrali dei prossimi 31 e le trimestrali dei prossimi 14 per i titoli che il bot tiene. Accanto a ogni evento c'è l'effetto che avrà con le righe di oggi. +- Nella demo i conteggi (312, 9, 2), l'elenco delle fonti e la spesa del giorno vengono dagli aggregati dell'appendice F, come nelle altre schermate. +- Il numero delle notizie lette sta in una riga sotto il titolo e non nel sottotitolo della barra in alto, che in tutte le schermate dice data e aggiornamento. +- La Panoramica ora mostra le vere notizie che contano: quelle con un effetto o sulle posizioni, al massimo tre. + +**14. Le impostazioni di notizie e calendario (13.5).** +- Le righe di 10.5 si accendono e si spengono da una scelta Accesa/Spenta. Ogni cambio finisce nello storico della configurazione. +- Le fonti si possono spegnere e marcare come affidabili. Ogni cambio finisce nello storico con la chiave `news.source:`. Aggiungere fonti nuove non si può ancora: l'elenco è quello di SPEC 4.4. +- La chiave del modello linguistico (`LLM_API_KEY`) e quelle di Finnhub e FRED si salvano cifrate come le chiavi dei conti. Non si mostrano più e non si provano al momento: se una non funziona lo dice lo stato delle fonti al giro successivo. Una chiave che arriva dalle variabili d'ambiente non si cambia dalla pagina. +- Il tetto di spesa del modello linguistico è un'impostazione (`news.llm.daily_cap`, 0,50 € all'inizio, al massimo 10 €). Chiave e tetto restano pronti: la rilettura arriva con l'analista (#58). Finché non c'è, la schermata dice che oggi non è costato nulla. +- Le riunioni di Fed e BCE passano dalla sezione Dati a questa. +- Nella demo la sezione si vede ma non si cambia. + ## Conseguenze -- Le notizie si accumulano già nel database con il loro primo giudizio e, dal #59, fermano o spostano gli acquisti secondo 10.5. Analista e schermata arrivano con #58 e #60. +- Le notizie si accumulano già nel database con il loro primo giudizio e, dal #59, fermano o spostano gli acquisti secondo 10.5. Dal #60 si vedono nella schermata Notizie e mercato; l'analista arriva con #58. - Una parola chiave che sbaglia può fermare gli acquisti di uno strumento per 72 ore. È la direzione prudente: un acquisto in meno, mai uno in più. Se l'uso reale mostra troppe restrizioni inutili, la riga si spegne in Impostazioni e le parole si correggono con un test. - Le soglie di somiglianza e di età sono costanti nel codice. Se l'uso reale mostra storie unite o divise male, si cambiano con un nuovo ADR e un test che lo mostra. - I test leggono un archivio sintetico nel formato reale di ogni fonte (`tests/Anubis.Tests/Fixtures/news/`). Non chiamano mai internet. diff --git a/src/Anubis.Server/Assets/app.css b/src/Anubis.Server/Assets/app.css index 08d3c9f..2337e3e 100644 --- a/src/Anubis.Server/Assets/app.css +++ b/src/Anubis.Server/Assets/app.css @@ -634,9 +634,55 @@ 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-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 +782,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; } } diff --git a/src/Anubis.Server/Components/Pages/Impostazioni.razor b/src/Anubis.Server/Components/Pages/Impostazioni.razor index 1b7b094..a5803e4 100644 --- a/src/Anubis.Server/Components/Pages/Impostazioni.razor +++ b/src/Anubis.Server/Components/Pages/Impostazioni.razor @@ -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.", })

@@ -38,7 +41,7 @@ }
@@ -314,10 +317,91 @@ }

Rapporto sulla qualità dei dati degli ultimi 30 giorni

+
+ +
+

Notizie e calendario

+

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é.

+ +

Regole

+ @foreach (var rule in _newsRules) + { + var definition = SettingsStore.Definition(rule.Key); +
+ + + + + @if (rule.ReadOnly) + { + Fissato da @rule.Source: si cambia lì. + } + else if (!Shell.IsDemo) + { + + } + + } + +

Fonti delle notizie

+ @if (_newsSources.Count == 0) + { +

Le fonti compaiono qui dopo il primo giro delle notizie, che parte con i dati di mercato.

+ } + else + { +

Una notizia da una sola fonte non affidabile non cambia nulla finché un'altra fonte non la conferma.

+
+ + + + @foreach (var f in _newsSources) + { + var form = "fonte-" + f.Id.ToString("N"); + + + + + + + + + } + +
FonteLeggoAffidabileUltima letturaStatoSalva
@f.Name@(f.LastOkAt is { } at ? Format.ShortDate(at, Shell.Now, Shell.Zone) : "—")@(!f.Enabled ? "spenta" : f.LastError is { } problem ? "non risponde: " + problem : "risponde") + @if (!Shell.IsDemo) + { +
+ } +
+
+ } + +

Modello linguistico

+

Facoltativo. Rilegge solo le notizie sulle tue posizioni e sugli strumenti candidati: può aggiungere una restrizione, mai toglierla, e non vede né chiavi né conti. Senza modello tutto funziona lo stesso con il classificatore locale. La rilettura non è ancora attiva: chiave e tetto restano pronti per quando lo sarà.

+ @DataKey(Anubis.News.NewsModelSettings.KeySecret, "Chiave del modello linguistico") +
+ + + + + @if (!_llmCap.ReadOnly && !Shell.IsDemo) + { + + } + + +

Calendario

+

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.

+ @DataKey("FINNHUB_API_KEY", "Chiave di Finnhub") + @DataKey("FRED_API_KEY", "Chiave di FRED")

Riunioni di Fed e BCE

- + @@ -454,6 +538,10 @@ private IReadOnlyList _sources = []; private SettingValue _meetings = new(SettingsStore.CentralBankMeetings.Key, "", false, null); + private readonly List _newsRules = []; + private SettingValue _llmCap = new(Anubis.News.NewsModelSettings.DailyCap.Key, "0.50", false, null); + private IReadOnlyList _newsSources = []; + private readonly Dictionary _dataKeys = []; private List _history = []; private IReadOnlyList _backups = []; private bool _hasSecondFactor; @@ -483,6 +571,17 @@ _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)); + } + + _llmCap = await services.Settings.GetAsync(Anubis.News.NewsModelSettings.DailyCap.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,44 @@ "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.", _ => 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. + private RenderFragment DataKey(string name, string label) + { + var status = _dataKeys.GetValueOrDefault(name) ?? new SecretStatus(name, false, false, null); + var id = "k-" + name.ToLowerInvariant(); + return @
+

@label: @KeyState(status).

+ @if (status.FromEnvironment) + { +

Si cambia nella configurazione del container (@name).

+ } + else if (!Shell.IsDemo) + { + + + + + + + @if (status.IsSet) + { +
+ + + + } + } +
; + } + private string KeyState(SecretStatus status) => status switch { { FromEnvironment: true } => "Dalle variabili d'ambiente", diff --git a/src/Anubis.Server/Components/Pages/Notizie.razor b/src/Anubis.Server/Components/Pages/Notizie.razor index 30189c8..2e17798 100644 --- a/src/Anubis.Server/Components/Pages/Notizie.razor +++ b/src/Anubis.Server/Components/Pages/Notizie.razor @@ -1,5 +1,231 @@ +@inherits LoadedComponent @page "/notizie" +@inject AnubisHost Host +@inject ShellData Shell +@using Anubis.News Notizie e mercato · Anubis -La lettura delle notizie, l'umore del mercato e il calendario degli eventi arrivano in una fase successiva. +@{ + 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(); +} +

@Lead(v)

+ +
+
+ + @if (rows.Count == 0) + { +

@Empty(v)

+ } + else + { +
    + @foreach (var n in shown) + { +
  • +

    + @Format.ShortDate(n.At, Shell.Now, Shell.Zone)@(n.Publisher.Length > 0 ? ", da " + n.Publisher : "") + @n.About + @if (n.SingleSource) + { + Una sola fonte + } +

    +

    @n.Title

    +

    + 0 ? "gain" : null)"> + @if (n.Direction == 0) + { + + } + else + { + + } + @n.Tone + + + + Importanza @n.Importance su 5 + +

    + @if (n.Active) + { +

    Cosa ho fatto: @Inline(n.Action)

    + } + else + { +

    Cosa ho fatto: @Inline(n.Action)

    + } +
  • + } +
+ @if (!_all && count > shown.Count) + { + + } + } +
+ +
+
+

Umore del mercato

+
    + @foreach (var g in v.Mood) + { +
  • +
    + @g.Label + @if (g.Value is { } value) + { + @value @g.Words + } + else + { + non ancora letto + } +
    + +
    @g.Left@g.Right
    + @if (g.Stale is { } stale) + { +

    Ultimo valore @stale.

    + } +
  • + } +
+

Sono indizi che il modello tiene in conto. Da soli non fanno comprare né vendere.

+

@Anubis.Data.FearGreed.Attribution.

+
+ +
+

In calendario

+ @if (v.Calendar.Count == 0) + { +

Nessun evento importante nei prossimi giorni.@(Shell.IsDemo || v.Collecting ? "" : " Il calendario si scarica con i dati di mercato.")

+ } + else + { +
    + @foreach (var e in v.Calendar) + { +
  • + @e.When + @e.Title + @e.Effect +
  • + } +
+ } +
+ +
+

Da dove leggo

+ @if (v.Sources.Count == 0) + { +

Non leggo ancora nessuna fonte. Le notizie si scaricano con i dati di mercato.

+ } + else + { +
    + @foreach (var s in v.Sources) + { +
  • + + @s.Name + @s.Frequency +
  • + } +
+ } +

@v.Spending

+

Fonti e regole nelle impostazioni

+
+
+
+ +@code { + /// The rows shown before "Mostra le altre", as in the mockup. + 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 Filtered(IEnumerable 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); +} diff --git a/src/Anubis.Server/Components/Pages/Panoramica.razor b/src/Anubis.Server/Components/Pages/Panoramica.razor index 120500f..93cc807 100644 --- a/src/Anubis.Server/Components/Pages/Panoramica.razor +++ b/src/Anubis.Server/Components/Pages/Panoramica.razor @@ -342,7 +342,11 @@

Notizie che contano

Tutte
@if (p.News is null) { -

La lettura delle notizie non è ancora attiva. Quando lo sarà, qui vedrai le tre che contano di più per le tue posizioni e cosa ne ho fatto.

+

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.

+ } + else if (p.News.Count == 0) + { +

Nessuna notizia sulle tue posizioni nelle ultime 24 ore, e nessuna restrizione in corso.

} else { diff --git a/src/Anubis.Server/Forms.cs b/src/Anubis.Server/Forms.cs index 107a395..26ea047 100644 --- a/src/Anubis.Server/Forms.cs +++ b/src/Anubis.Server/Forms.cs @@ -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); + } + + /// The optional keys of SPEC 13.5 that are not a broker's: the language model, Finnhub, FRED. + internal static readonly IReadOnlyList DataKeys = [Anubis.News.NewsModelSettings.KeySecret, "FINNHUB_API_KEY", "FRED_API_KEY"]; + + private static async Task 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 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 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"); } /// The notice of a long absence (SPEC 5.6) goes away once the user has seen it. @@ -176,11 +237,32 @@ internal static partial class Forms private static async Task 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 cap = key == Anubis.News.NewsModelSettings.DailyCap.Key; + if (key != SettingsStore.Theme.Key && key != SettingsStore.Currency.Key && key != SettingsStore.CentralBankMeetings.Key && key != SettingsStore.TelegramStatus.Key && + !news && !cap) { return Results.Redirect(With(back, "errore", "impostazione")); } + if ((news || cap) && host.IsDemo) + { + return Results.Redirect(With(back, "errore", "motore")); + } + + if (cap) + { + // "0,50" as the user writes it; stored as "0.50". + var amount = form["valore"].ToString().Trim().Replace("€", "", StringComparison.Ordinal).Trim().Replace(',', '.'); + if (Anubis.News.NewsModelSettings.CheckCap(amount) is not null) + { + return Results.Redirect(With(back, "errore", "tetto")); + } + + var saved = await Endpoints.SetSettingAsync(host, key, amount, 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")); diff --git a/src/Anubis.Server/NewsView.cs b/src/Anubis.Server/NewsView.cs new file mode 100644 index 0000000..f7fad7e --- /dev/null +++ b/src/Anubis.Server/NewsView.cs @@ -0,0 +1,203 @@ +using System.Globalization; +using Anubis.Core; +using Anubis.Data; +using Anubis.News; +using Anubis.Strategies; + +namespace Anubis.Server; + +/// +/// A gauge of "Umore del mercato" (SPEC 10.4): the value with its label, the dot on a track from to +/// . is from 0 to 1, null while the indicator has not been read. +/// +internal sealed record MoodGauge(string Label, string? Value, string? Words, double? Position, string Left, string Right, bool Centered, string? Stale); + +/// An event of "In calendario" with the effect it will have; when it holds entries. +internal sealed record CalendarRow(string When, string Title, string Effect, bool Matters); + +/// A line of "Da dove leggo": the source, how often, and whether it answers. +internal sealed record SourceRow(string Name, string Frequency, bool Ok); + +/// +/// 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. +/// +internal sealed record NewsView( + NewsBoardResult Board, + IReadOnlyList Mood, + IReadOnlyList Calendar, + IReadOnlyList Sources, + string Spending, + bool Collecting) +{ + /// How far ahead the calendar looks: a week of economic data, a month of central banks, two weeks of earnings. + 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 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); + return new NewsView(board, mood, calendar, rows, + "Tutte le notizie passano da un modello locale, gratuito, sul tuo computer. La rilettura con un modello linguistico non è ancora attiva: oggi non è costato nulla.", + collecting); + } + + private static async Task> 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> 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 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(); + 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..]; +} diff --git a/src/Anubis.Server/PanoramaView.cs b/src/Anubis.Server/PanoramaView.cs index 61b4b93..8ef47e4 100644 --- a/src/Anubis.Server/PanoramaView.cs +++ b/src/Anubis.Server/PanoramaView.cs @@ -44,6 +44,16 @@ internal sealed record PanoramaView( { private static readonly CultureInfo _it = CultureInfo.InvariantCulture; + /// "Notizie che contano" (SPEC 13.6): first those with an effect in force, then the latest on the positions or their markets. + internal static IReadOnlyList 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 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; diff --git a/src/Anubis/Core/Settings.cs b/src/Anubis/Core/Settings.cs index 1c262f1..7feb1fa 100644 --- a/src/Anubis/Core/Settings.cs +++ b/src/Anubis/Core/Settings.cs @@ -45,7 +45,7 @@ public sealed class SettingsStore(Database db, IClock clock, EventBus bus, IRead public static readonly SettingDefinition TelegramStatus = new("telegram.status", "Stato periodico su Telegram", "never", ["never", "hourly", "daily"]); public static readonly IReadOnlyList All = - [Theme, Currency, BotState, CentralBankMeetings, TelegramStatus, .. Risk.RiskSettings.All, Risk.Scenarios.Setting, .. News.NewsRuleSettings.All]; + [Theme, Currency, BotState, CentralBankMeetings, TelegramStatus, .. Risk.RiskSettings.All, Risk.Scenarios.Setting, .. News.NewsRuleSettings.All, News.NewsModelSettings.DailyCap]; private readonly IReadOnlyDictionary _overrides = overrides ?? new Dictionary(); diff --git a/src/Anubis/Db/Migrations/0010_news_screen.sql b/src/Anubis/Db/Migrations/0010_news_screen.sql new file mode 100644 index 0000000..d5f7f63 --- /dev/null +++ b/src/Anubis/Db/Migrations/0010_news_screen.sql @@ -0,0 +1,6 @@ +-- The Notizie e mercato screen (issue #60, SPEC 13.6). + +-- What the bot did about a story, in the short words of the screen ("Per 24 ore non aumento la posizione su SOL."), +-- and until when it lasts: the filter "con effetto" shows the notes still in force. +ALTER TABLE news_notes ADD COLUMN action TEXT; +ALTER TABLE news_notes ADD COLUMN until {timestamp}; diff --git a/src/Anubis/Demo/Data/aggregates.json b/src/Anubis/Demo/Data/aggregates.json index e7b2527..c997edb 100644 --- a/src/Anubis/Demo/Data/aggregates.json +++ b/src/Anubis/Demo/Data/aggregates.json @@ -52,6 +52,7 @@ "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", + "fonti": [{ "nome": "Alpaca News", "frequenza": "in tempo reale" }, { "nome": "14 testate e banche centrali", "frequenza": "ogni 2 minuti" }, { "nome": "Comunicati alla SEC", "frequenza": "ogni 2 minuti" }, { "nome": "Calendario economico", "frequenza": "aggiornato alle 08:00" }], "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 }, diff --git a/src/Anubis/Demo/DemoMode.cs b/src/Anubis/Demo/DemoMode.cs index ae142fb..5df0a34 100644 --- a/src/Anubis/Demo/DemoMode.cs +++ b/src/Anubis/Demo/DemoMode.cs @@ -221,6 +221,7 @@ public static class DemoMode cancellationToken, ("id", ids.Next()), ("at", new DateTimeOffset(local, rome.GetUtcOffset(local))), ("k", row[3]), ("m", row[2]), ("t", now)).ConfigureAwait(false); } + await SeedNewsAsync(s, ids, rome, now, cancellationToken).ConfigureAwait(false); await s.ExecuteAsync("INSERT INTO config (id, key, value, created_at, updated_at) VALUES (@id, 'bot.state', @v, @t, @t)", cancellationToken, ("id", ids.Next()), ("v", new DbJson(JsonSerializer.Serialize("active"))), ("t", now)).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false); @@ -380,6 +381,97 @@ public static class DemoMode } } + // F.9: the six stories shown with the filter "sulle tue posizioni", what the bot did about each, the mood of the + // market and the four events of the calendar. The counts (312, 9, 2), the sources and the spending are aggregates. + private static async Task SeedNewsAsync(DbSession s, IdSource ids, TimeZoneInfo rome, DateTimeOffset now, CancellationToken cancellationToken) + { + var today = DateOnly.FromDateTime(Now.DateTime); + DateTimeOffset At(int daysAgo, int hour, int minute) + { + var local = today.AddDays(-daysAgo).ToDateTime(new TimeOnly(hour, minute)); + return new DateTimeOffset(local, rome.GetUtcOffset(local)).ToUniversalTime(); + } + + var sources = new Dictionary(StringComparer.Ordinal); + foreach (var (name, url, trusted) in new[] + { + ("Alpaca News", "https://data.alpaca.markets/v1beta1/news", true), + ("CoinDesk", "https://www.coindesk.com/arc/outboundfeeds/rss/", true), + ("MarketWatch", "https://feeds.content.dowjones.io/public/rss/mw_topstories", true), + ("The Block", "https://www.theblock.co/rss.xml", false), + }) + { + var id = ids.Next(); + sources[name] = (id, trusted); + await s.ExecuteAsync( + "INSERT INTO news_sources (id, url, name, kind, trusted, enabled, failures, last_checked_at, last_ok_at, created_at, updated_at) " + + "VALUES (@id, @u, @n, 'rss', @tr, @on, 0, @t, @t, @t, @t)", + cancellationToken, ("id", id), ("u", url), ("n", name), ("tr", trusted), ("on", true), ("t", now)).ConfigureAwait(false); + } + + var jpmUntil = new DateTimeOffset(2026, 10, 13, 20, 0, 0, TimeSpan.Zero); + var stories = new (DateTimeOffset At, string Source, string Scope, string Target, string Title, double Score, int Importance, string Kind, string Action, DateTimeOffset? Until)[] + { + (At(0, 6, 10), "CoinDesk", "instrument", "okx:SOL/EUR", "Rinviato di una settimana l'aggiornamento della rete Solana", -0.7, 3, + "news_negative", "Per 24 ore non aumento la posizione su SOL. Lo stop resta dov'è.", At(0, 6, 10).AddHours(24)), + (At(1, 22, 41), "Alpaca News", "instrument", "alpaca:JPM", "JPMorgan pubblica i conti martedì prima dell'apertura", 0.0, 3, + "calendar_earnings", "Niente nuovi acquisti di mean reversion su JPM fino a martedì. La posizione di momentum resta.", jpmUntil), + (At(0, 7, 52), "MarketWatch", "market", "us", "I verbali della banca centrale USA non cambiano le attese sui tassi", 0.05, 2, + "news_noted", "Niente. Confermano quello che il mercato sapeva già.", null), + (At(1, 19, 5), "Alpaca News", "instrument", "alpaca:NVDA", "Un analista alza il prezzo obiettivo di Nvidia", 0.4, 2, + "news_noted", "Niente. I giudizi degli analisti non entrano nelle decisioni.", null), + (At(1, 16, 20), "The Block", "class", "crypto", "Un exchange segnala prelievi rallentati per manutenzione", -0.7, 3, + "news_rechecked", "Niente, perché nessun'altra fonte la riportava. Ricontrollata alle 18:20: rientrata.", null), + (At(1, 14, 31), "Alpaca News", "market", "us", "Richieste di sussidi di disoccupazione USA sotto le attese", 0.35, 3, + "news_noted", "Niente. Dato di impatto medio: nessun blocco degli ingressi.", null), + }; + foreach (var n in stories) + { + var story = ids.Next(); + var (source, trusted) = sources[n.Source]; + await s.ExecuteAsync( + "INSERT INTO news_stories (id, title, title_key, published_at, first_seen_at, last_seen_at, sources, trusted, score, importance, created_at, updated_at) " + + "VALUES (@id, @ti, @k, @at, @at, @at, 1, @tr, @sc, @im, @t, @t)", + cancellationToken, ("id", story), ("ti", n.Title), ("k", n.Title.ToLowerInvariant()), ("at", n.At), ("tr", trusted), ("sc", n.Score), ("im", n.Importance), + ("t", now)).ConfigureAwait(false); + await s.ExecuteAsync( + "INSERT INTO news_items (id, story_id, source_id, url, url_key, publisher, title, language, published_at, score, importance, created_at) " + + "VALUES (@id, @st, @so, @u, @u, @p, @ti, 'it', @at, @sc, @im, @t)", + cancellationToken, ("id", ids.Next()), ("st", story), ("so", source), ("u", "https://esempio.invalid/notizie/" + story.ToString("N")), ("p", n.Source), + ("ti", n.Title), ("at", n.At), ("sc", n.Score), ("im", n.Importance), ("t", now)).ConfigureAwait(false); + await s.ExecuteAsync("INSERT INTO news_links (id, story_id, scope, target, via, created_at) VALUES (@id, @st, @sc, @tg, 'source', @t)", + cancellationToken, ("id", ids.Next()), ("st", story), ("sc", n.Scope), ("tg", n.Target), ("t", now)).ConfigureAwait(false); + await s.ExecuteAsync("INSERT INTO news_notes (id, subject, target, kind, action, until, created_at) VALUES (@id, @su, @tg, @k, @a, @u, @t)", + cancellationToken, ("id", ids.Next()), ("su", "story:" + story), ("tg", n.Target), ("k", n.Kind), ("a", n.Action), ("u", n.Until), ("t", n.At)).ConfigureAwait(false); + } + + foreach (var (indicator, asOf, value, label, source) in new[] + { + ("fear_greed", At(0, 2, 0), 41.0, "paura", "alternative.me"), + ("vix", At(1, 22, 15), 17.8, "calmo", "cboe"), + ("btc_funding", At(0, 8, 0), 0.00006, "nella norma", "okx_derivatives"), + }) + { + await s.ExecuteAsync("INSERT INTO market_mood (id, indicator, as_of, value, label, source, created_at) VALUES (@id, @i, @a, @v, @l, @s, @t)", + cancellationToken, ("id", ids.Next()), ("i", indicator), ("a", asOf), ("v", value), ("l", label), ("s", source), ("t", now)).ConfigureAwait(false); + } + + foreach (var (kind, title, at, known, symbol, hint, impact, key) in new (string, string, DateTimeOffset, bool, string?, string?, string?, string)[] + { + ("economic", "Fiducia dei consumatori USA", At(0, 16, 0), true, null, null, "Medium", "demo:confidence"), + ("earnings", "Conti trimestrali di JPMorgan", new DateTimeOffset(2026, 10, 13, 4, 0, 0, TimeSpan.Zero), false, "JPM", "bmo", null, "demo:jpm"), + ("economic", "Inflazione USA", At(-5, 14, 30), true, null, null, "High", "demo:cpi"), + ("central_bank", "Decisione sui tassi della banca centrale USA", At(-19, 19, 0), true, null, null, "High", "demo:fomc"), + }) + { + await s.ExecuteAsync( + "INSERT INTO calendar_events (id, kind, title, currency, symbol, occurs_at, time_known, time_hint, impact, source, source_key, created_at, updated_at) " + + "VALUES (@id, @k, @ti, 'USD', @sy, @at, @kn, @h, @im, 'demo', @key, @t, @t)", + cancellationToken, ("id", ids.Next()), ("k", kind), ("ti", title), ("sy", symbol), ("at", at), ("kn", known), ("h", hint), ("im", impact), + ("key", key), ("t", now)).ConfigureAwait(false); + } + } + /// Reads the aggregates file of a demo folder. public static JsonDocument? ReadAggregates(DataDirectory data) { diff --git a/src/Anubis/News/NewsBoard.cs b/src/Anubis/News/NewsBoard.cs new file mode 100644 index 0000000..3973a21 --- /dev/null +++ b/src/Anubis/News/NewsBoard.cs @@ -0,0 +1,210 @@ +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; + +namespace Anubis.News; + +/// A row of "Cosa ho letto e cosa ne ho fatto" (SPEC 13.6, mockup 05). +/// −1 negative, 0 neutral or unread, +1 positive: the arrow beside the tone. +/// An effect still in force: the row is shown first and its action in the colour of attention. +/// About a held instrument, the class of one, or the market. +public sealed record NewsBoardRow( + Guid Id, + DateTimeOffset At, + string Publisher, + string About, + bool SingleSource, + string Title, + string Tone, + int Direction, + int Importance, + string Action, + bool Active, + bool OnPositions); + +/// The stories of the last 24 hours with what the bot did, and the three counts of the filters. +public sealed record NewsBoardResult(IReadOnlyList Rows, int Read, int OnPositions, int Active); + +/// +/// What the Notizie e mercato screen lists (SPEC 13.6): every story read in the last 24 hours, plus older ones whose +/// effect is still in force, each with the action taken or the reason why the bot did nothing. The action comes from +/// the note the watcher wrote; for a story without one it follows the same rules of 10.5. +/// +public sealed class NewsBoard(Database db, IClock clock, SettingsStore? settings = null) +{ + public static readonly TimeSpan Window = TimeSpan.FromHours(24); + + public async Task LoadAsync(CancellationToken cancellationToken = default) + { + var now = clock.UtcNow; + var since = now - Window; + var switches = await NewsRuleSettings.LoadAsync(settings, cancellationToken).ConfigureAwait(false); + // A restriction lasts at most 72 hours: stories older than that and the window are never in force. + var oldest = since - NewsRules.Longest; + var (all, links, notes, held) = await db.ReadAsync(async s => + { + const string Recent = "st.first_seen_at >= @oldest"; + var st = await s.QueryAsync( + "SELECT st.id, st.title, st.published_at, st.first_seen_at, st.sources, st.trusted, st.score, st.severe, st.importance, " + + "(SELECT i.publisher FROM news_items i WHERE i.story_id = st.id ORDER BY i.created_at, i.id LIMIT 1) AS publisher " + + "FROM news_stories st WHERE " + Recent, + r => new StoryFact(r.Id("id"), r.Text("title"), r.TextOrNull("publisher") ?? "", r.Moment("published_at"), r.Moment("first_seen_at"), (int)r.Number("sources"), + r.Bool("trusted"), r.IsNull("score") ? null : r.Measure("score"), r.TextOrNull("severe"), (int)r.Number("importance")), + ("oldest", oldest)).ConfigureAwait(false); + var l = await s.QueryAsync( + "SELECT l.story_id, l.scope, l.target FROM news_links l JOIN news_stories st ON st.id = l.story_id WHERE " + Recent, + r => (Story: r.Id("story_id"), Scope: r.Text("scope"), Target: r.Text("target")), ("oldest", oldest)).ConfigureAwait(false); + var n = await s.QueryAsync( + "SELECT subject, target, kind, action, until, created_at FROM news_notes WHERE subject LIKE 'story:%' AND created_at >= @old", + r => (Subject: r.Text("subject"), Target: r.Text("target"), Kind: r.Text("kind"), Action: r.TextOrNull("action"), Until: r.MomentOrNull("until"), + At: r.Moment("created_at")), + ("old", oldest)).ConfigureAwait(false); + var h = await s.QueryAsync("SELECT i.venue, i.symbol, i.asset_class, p.quantity FROM positions p JOIN instruments i ON i.id = p.instrument_id", + r => (Target: r.Text("venue") + ":" + r.Text("symbol"), Class: r.Text("asset_class"), Quantity: r.Money("quantity"))).ConfigureAwait(false); + return (st, l, n, h); + }, cancellationToken).ConfigureAwait(false); + + var holding = held.Where(h => h.Quantity > 0m).ToList(); + var heldTargets = holding.Select(h => h.Target).ToHashSet(StringComparer.Ordinal); + var heldClasses = holding.Select(h => h.Class).ToHashSet(StringComparer.Ordinal); + var linksOf = links.ToLookup(l => l.Story); + var notesOf = notes.ToLookup(n => n.Subject); + // Older stories stay while their effect is in force: from a note, or from the rules for an instrument nobody watches. + var stories = all.Where(st => st.FirstSeenAt >= since || notesOf["story:" + st.Id].Any(n => n.Until > now) || + (linksOf[st.Id].Any(l => l.Scope == LinkScopes.Instrument) && NewsRules.Active([st], now, switches).Count > 0)).ToList(); + + var rows = new List(); + foreach (var story in stories) + { + var own = linksOf[story.Id].Select(l => (l.Scope, l.Target)).ToList(); + var instruments = own.Where(l => l.Scope == LinkScopes.Instrument).Select(l => l.Target).Distinct().Order(StringComparer.Ordinal).ToList(); + var storyNotes = notesOf["story:" + story.Id].OrderByDescending(n => n.At).ToList(); + var onPositions = own.Any(l => l.Scope switch + { + LinkScopes.Instrument => heldTargets.Contains(l.Target), + LinkScopes.Class => heldClasses.Contains(l.Target), + _ => holding.Count > 0, + }); + + var (action, active) = Act(story, instruments, storyNotes.Select(n => (n.Kind, n.Action, n.Until)).ToList(), heldTargets, switches, now); + var tone = ToneText(story.Score) + (NewsRules.Unconfirmed(story) ? ", non confermata" : "") + + (storyNotes.Any(n => n.Kind == NewsReasons.Earnings) ? ", evento in arrivo" : ""); + rows.Add(new NewsBoardRow(story.Id, story.Start, story.Publisher, About(own, instruments), story.Sources <= 1 && !story.Trusted, story.Title, tone, + Direction(story.Score), Math.Clamp(story.Importance, 1, 5), action, active, onPositions)); + } + + rows = [.. rows.OrderByDescending(r => r.Active).ThenByDescending(r => r.At).ThenBy(r => r.Id)]; + var read = stories.Count(st => st.FirstSeenAt >= since); + return new NewsBoardResult(rows, read, rows.Count(r => r.OnPositions), rows.Count(r => r.Active)); + } + + /// The five grades of SPEC 10.2 point 4 in words; an Italian title without the model has no tone. + public static string ToneText(double? score) => score is not { } s ? "Tono non letto" : NewsJudge.Grade(s) switch + { + Tone.Negative => "Negativa", + Tone.SlightlyNegative => "Leggermente negativa", + Tone.Neutral => "Neutra", + Tone.SlightlyPositive => "Leggermente positiva", + _ => "Positiva", + }; + + private static int Direction(double? score) => score switch + { + null => 0, + <= -0.2 => -1, + > 0.2 => 1, + _ => 0, + }; + + /// "SOL", "AAPL e MSFT", "Crypto", "Mercato": what a story is about, the strongest link first. + public static string About(IReadOnlyList<(string Scope, string Target)> links, IReadOnlyList instruments) + { + ArgumentNullException.ThrowIfNull(links); + ArgumentNullException.ThrowIfNull(instruments); + if (instruments.Count > 0) + { + var symbols = instruments.Select(t => t[(t.IndexOf(':', StringComparison.Ordinal) + 1)..].Split('-', '/')[0]).Distinct().ToList(); + return symbols.Count <= 3 ? Trading.DiaryText.List(symbols) : $"{Trading.DiaryText.List(symbols.Take(2))} e altri {symbols.Count - 2}"; + } + + var classes = links.Where(l => l.Scope == LinkScopes.Class).Select(l => l.Target).ToList(); + if (classes.Contains(AssetClasses.Crypto)) + { + return "Crypto"; + } + + if (classes.Contains(AssetClasses.Equity)) + { + return "Azioni"; + } + + return links.Any(l => l.Scope == LinkScopes.Market && l.Target == "us") ? "Mercato USA" : "Mercato"; + } + + // The note's words when the watcher wrote one; otherwise the rule of 10.5 the story meets, or why it meets none. + private static (string Action, bool Active) Act(StoryFact story, List instruments, IReadOnlyList<(string Kind, string? Action, DateTimeOffset? Until)> notes, + HashSet held, NewsRuleSwitches switches, DateTimeOffset now) + { + var restriction = notes.Where(n => n.Action is not null && n.Until is not null).OrderByDescending(n => n.Until).FirstOrDefault(); + if (restriction.Action is { } restricted) + { + var on = restriction.Kind switch + { + NewsReasons.Severe => switches.Severe, + NewsReasons.Negative => switches.Negative, + NewsReasons.Earnings => switches.Earnings, + _ => true, + }; + if (restriction.Until <= now) + { + return (restricted + " Restrizione finita.", false); + } + + return on ? (restricted, true) : (restricted + " Ora la regola è spenta: la restrizione non vale più.", false); + } + + if (notes.FirstOrDefault(n => n.Action is not null && n.Kind != NewsReasons.Unconfirmed).Action is { } other) + { + return (other, notes.Any(n => n.Kind == NewsReasons.Earnings)); + } + + if (notes.FirstOrDefault(n => n.Kind == NewsReasons.Unconfirmed).Action is { } unconfirmed) + { + return (unconfirmed, false); + } + + if (instruments.Count == 0) + { + return story.Score is <= -0.2 + ? ("Niente. Riguarda il mercato nel suo insieme: le restrizioni valgono per un singolo strumento.", false) + : ("Niente. Riguarda il mercato nel suo insieme e non cambia nessuna regola.", false); + } + + if (NewsRules.Unconfirmed(story)) + { + return ("Niente, perché nessun'altra fonte la riportava.", false); + } + + var matched = NewsRules.Active([story], story.Start, NewsRuleSwitches.AllOn) is { Count: > 0 } found ? found[0] : null; + if (matched is not null) + { + if (matched.Code == NewsReasons.Severe ? !switches.Severe : !switches.Negative) + { + return ("Niente: la regola per questo caso è spenta nelle impostazioni.", false); + } + + var target = instruments[0]; + var symbol = target[(target.IndexOf(':', StringComparison.Ordinal) + 1)..]; + var text = NewsActions.Restriction(matched, symbol, held.Contains(target)); + return matched.Until > now ? (text, true) : (text + " Restrizione finita.", false); + } + + return story.Score switch + { + > 0.2 => ("Niente. Le notizie positive non mi fanno comprare: servono solo a evitare guai.", false), + <= -0.2 => ("Niente. Le notizie solo leggermente negative non creano restrizioni.", false), + null => ("Niente. Nessuna parola di un caso grave e il tono non è stato letto.", false), + _ => ("Niente. Non cambia nessuna regola.", false), + }; + } +} diff --git a/src/Anubis/News/NewsDesk.cs b/src/Anubis/News/NewsDesk.cs index d492694..71610e2 100644 --- a/src/Anubis/News/NewsDesk.cs +++ b/src/Anubis/News/NewsDesk.cs @@ -155,8 +155,8 @@ public sealed class NewsWatcher(Database db, IClock clock, SettingsStore? settin foreach (var restriction in NewsRules.Active(stories, now, switches)) { var text = Restricted(restriction, symbol, held); - written += await NoteAsync("story:" + restriction.Story.Id, target, restriction.Code, text, restriction.Code == NewsReasons.Severe, cancellationToken) - .ConfigureAwait(false); + written += await NoteAsync("story:" + restriction.Story.Id, target, restriction.Code, text, NewsActions.Restriction(restriction, symbol, held), restriction.Until, + restriction.Code == NewsReasons.Severe, cancellationToken).ConfigureAwait(false); } if (!switches.Unconfirmed) @@ -170,13 +170,14 @@ public sealed class NewsWatcher(Database db, IClock clock, SettingsStore? settin if (now - story.FirstSeenAt < NewsRules.RecheckAfter) { written += await NoteAsync(subject, target, NewsReasons.Unconfirmed, - $"Voce non confermata su {Trading.DiaryText.Shown(symbol)}: {EntryGate.Motive(story)}. Nessuna azione: ricontrollo tra 2 ore.", false, cancellationToken) - .ConfigureAwait(false); + $"Voce non confermata su {Trading.DiaryText.Shown(symbol)}: {EntryGate.Motive(story)}. Nessuna azione: ricontrollo tra 2 ore.", + NewsActions.Unconfirmed(story.FirstSeenAt + NewsRules.RecheckAfter, Zone), null, false, cancellationToken).ConfigureAwait(false); } else if (now - story.FirstSeenAt < NewsRules.Longest) { written += await NoteAsync(subject, target, NewsReasons.Rechecked, - $"Ricontrollata la voce su {Trading.DiaryText.Shown(symbol)}: nessun'altra fonte la conferma, nessuna azione.", false, cancellationToken).ConfigureAwait(false); + $"Ricontrollata la voce su {Trading.DiaryText.Shown(symbol)}: nessun'altra fonte la conferma, nessuna azione.", + NewsActions.Rechecked(now, Zone), null, false, cancellationToken).ConfigureAwait(false); } } } @@ -224,13 +225,15 @@ public sealed class NewsWatcher(Database db, IClock clock, SettingsStore? settin _ => ("", "fino alla seduta dopo i conti"), }; var text = $"Ho messo una restrizione {until}: niente mean reversion su {e.Symbol}. Motivo: {e.Symbol} pubblica i conti {dayText}{when}."; - written += await NoteAsync("event:" + e.SourceKey, stocks[e.Symbol!], NewsReasons.Earnings, text, false, cancellationToken).ConfigureAwait(false); + written += await NoteAsync("event:" + e.SourceKey, stocks[e.Symbol!], NewsReasons.Earnings, text, $"Niente mean reversion su {e.Symbol} {until}.", null, false, + cancellationToken).ConfigureAwait(false); } return written; } - private Task NoteAsync(string subject, string target, string kind, string text, bool telegram, CancellationToken cancellationToken) => + private Task NoteAsync(string subject, string target, string kind, string text, string action, DateTimeOffset? until, bool telegram, + CancellationToken cancellationToken) => db.WriteAsync(async s => { var seen = await s.FirstOrDefaultAsync("SELECT id FROM news_notes WHERE subject = @s AND target = @t AND kind = @k", r => r.IdOrNull("id"), @@ -240,8 +243,8 @@ public sealed class NewsWatcher(Database db, IClock clock, SettingsStore? settin return 0; } - await s.ExecuteAsync("INSERT INTO news_notes (id, subject, target, kind, created_at) VALUES (@id, @s, @t, @k, @now)", cancellationToken, - ("id", Ids.NewId(clock)), ("s", subject), ("t", target), ("k", kind), ("now", clock.UtcNow)).ConfigureAwait(false); + await s.ExecuteAsync("INSERT INTO news_notes (id, subject, target, kind, action, until, created_at) VALUES (@id, @s, @t, @k, @a, @u, @now)", cancellationToken, + ("id", Ids.NewId(clock)), ("s", subject), ("t", target), ("k", kind), ("a", action), ("u", until), ("now", clock.UtcNow)).ConfigureAwait(false); await Trading.Diary.WriteAsync(s, clock, Trading.DiaryKinds.News, kind, text, new { subject, target }, cancellationToken).ConfigureAwait(false); if (telegram) { @@ -264,3 +267,27 @@ public sealed class NewsWatcher(Database db, IClock clock, SettingsStore? settin .Select(m => (m.Venue + ":" + m.Symbol, m.Symbol, holding.Contains(m.Venue + ":" + m.Symbol))).OrderBy(m => m.Item1, StringComparer.Ordinal)]; } } + +/// What the bot did about a story, in the short words of the Notizie e mercato screen (SPEC 13.6, F.9). +public static class NewsActions +{ + public static string Restriction(NewsRestriction r, string symbol, bool held) + { + ArgumentNullException.ThrowIfNull(r); + + // The screen names a coin without its quote: "SOL", as in the mockup; a stock by its ticker. + var shown = Trading.DiaryText.Coin(symbol); + if (r.Code == NewsReasons.Severe) + { + return held ? $"Per 72 ore niente nuovi acquisti di {shown}. Lo stop resta dov'è." : $"Per 72 ore niente nuovi acquisti di {shown}."; + } + + return held ? $"Per 24 ore non aumento la posizione su {shown}." : $"Per 24 ore non compro {shown}."; + } + + public static string Unconfirmed(DateTimeOffset recheck, TimeZoneInfo zone) => + $"Niente, perché nessun'altra fonte la riportava. La ricontrollo alle {TimeZoneInfo.ConvertTime(recheck, zone):HH:mm}."; + + public static string Rechecked(DateTimeOffset at, TimeZoneInfo zone) => + $"Niente, perché nessun'altra fonte la riportava. Ricontrollata alle {TimeZoneInfo.ConvertTime(at, zone):HH:mm}: nessuna conferma."; +} diff --git a/src/Anubis/News/NewsRules.cs b/src/Anubis/News/NewsRules.cs index 8b8d4c4..7085d7e 100644 --- a/src/Anubis/News/NewsRules.cs +++ b/src/Anubis/News/NewsRules.cs @@ -22,6 +22,9 @@ public static class NewsReasons /// Fourth row: earnings coming, no entries of equity_meanrev. public const string Earnings = "calendar_earnings"; + + /// A remark on a story that changes nothing, with the reason in its words (the demo; later the analyst of #58). + public const string Noted = "news_noted"; } /// What the rules know of a story linked to an instrument (the tables of 0008). @@ -209,3 +212,30 @@ public static class NewsRuleSettings private static SettingDefinition Switch(string key, string label) => new(key, label, On, [On, Off]); } + +/// +/// The optional language model of SPEC 10.2 point 5 and 10.3: its key is a secret (), its daily +/// spending cap a setting, 0,50 € unless changed. The reading itself arrives with the analyst (#58). +/// +public static class NewsModelSettings +{ + public const string KeySecret = "LLM_API_KEY"; + + /// The highest cap the form accepts: ten euro a day is already far more than reading a few dozen headlines costs. + public const decimal MaxCap = 10m; + + public static readonly SettingDefinition DailyCap = new("news.llm.daily_cap", "Tetto di spesa giornaliero del modello linguistico", "0.50", Check: CheckCap); + + public static string? CheckCap(string value) => + decimal.TryParse(value, System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.InvariantCulture, out var cap) && + cap >= 0m && cap <= MaxCap && decimal.Round(cap, 2) == cap + ? null + : $"Scrivi un importo in euro da 0 a {MaxCap:0}, con al massimo due decimali."; + + public static async Task CapAsync(SettingsStore settings, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(settings); + var value = (await settings.GetAsync(DailyCap.Key, cancellationToken).ConfigureAwait(false)).Value; + return decimal.Parse(value, System.Globalization.CultureInfo.InvariantCulture); + } +} diff --git a/src/Anubis/News/NewsStore.cs b/src/Anubis/News/NewsStore.cs index 1f9bcb3..a548556 100644 --- a/src/Anubis/News/NewsStore.cs +++ b/src/Anubis/News/NewsStore.cs @@ -86,6 +86,36 @@ public sealed class NewsStore(Database db, IClock clock) public async Task> ListSourcesAsync(CancellationToken cancellationToken) => await db.ReadAsync(s => s.QueryAsync($"SELECT {SourceColumns} FROM news_sources ORDER BY name", ReadSource), cancellationToken).ConfigureAwait(false); + /// + /// The user's choice for a source (SPEC 10.2 point 1, 13.5): read it or not, trust it or not. Each change goes to + /// the change log like any setting. False when there is no such source. + /// + public Task SetSourceAsync(Guid id, bool enabled, bool trusted, string changedBy, CancellationToken cancellationToken) + { + var now = clock.UtcNow; + return db.WriteAsync(async s => + { + var before = await s.FirstOrDefaultAsync("SELECT name, enabled, trusted FROM news_sources WHERE id = @id", + r => (Name: r.Text("name"), Enabled: r.Bool("enabled"), Trusted: r.Bool("trusted")), ("id", id)).ConfigureAwait(false); + if (before.Name is null) + { + return false; + } + + await s.ExecuteAsync("UPDATE news_sources SET enabled = @e, trusted = @t, updated_at = @now WHERE id = @id", cancellationToken, + ("e", enabled), ("t", trusted), ("now", now), ("id", id)).ConfigureAwait(false); + static string Words(bool on, bool sure) => (on ? "attiva" : "spenta") + (sure ? ", affidabile" : ", non affidabile"); + if (before.Enabled != enabled || before.Trusted != trusted) + { + await s.ExecuteAsync("INSERT INTO config_history (id, key, old_value, new_value, changed_by, created_at) VALUES (@id, @k, @o, @n, @by, @t)", cancellationToken, + ("id", Ids.NewId(clock)), ("k", "news.source:" + before.Name), ("o", new DbJson(System.Text.Json.JsonSerializer.Serialize(Words(before.Enabled, before.Trusted)))), + ("n", new DbJson(System.Text.Json.JsonSerializer.Serialize(Words(enabled, trusted)))), ("by", changedBy), ("t", now)).ConfigureAwait(false); + } + + return true; + }, cancellationToken); + } + /// How the last request to a source went: on success the validators for the next conditional request. public Task RecordCheckAsync(NewsSource source, bool ok, string? etag, string? lastModified, string? error, CancellationToken cancellationToken) { diff --git a/src/Anubis/Trading/ReasonCatalog.cs b/src/Anubis/Trading/ReasonCatalog.cs index cbb82de..18eb90f 100644 --- a/src/Anubis/Trading/ReasonCatalog.cs +++ b/src/Anubis/Trading/ReasonCatalog.cs @@ -41,6 +41,7 @@ public static class ReasonCatalog ["news_negative"] = "Una notizia negativa importante su questo strumento: niente acquisti né aumenti per 24 ore.", ["news_unconfirmed"] = "Una voce da una sola fonte non affidabile: nessuna azione, la ricontrollo dopo 2 ore.", ["news_rechecked"] = "La voce non è stata confermata da un'altra fonte: nessuna azione.", + ["news_noted"] = "Notizia letta: non cambia nessuna regola, nessuna azione.", ["news_keep_stop"] = "Con un evento grave in corso lo stop non si allarga.", ["calendar_earnings"] = "Trimestrale in arrivo: niente mean reversion su questo titolo fino alla pubblicazione.", // Risk. diff --git a/tests/Anubis.Tests/NewsScreenTests.cs b/tests/Anubis.Tests/NewsScreenTests.cs new file mode 100644 index 0000000..6f9f1f2 --- /dev/null +++ b/tests/Anubis.Tests/NewsScreenTests.cs @@ -0,0 +1,224 @@ +using System.Net; +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; +using Anubis.News; + +namespace Anubis.Tests; + +/// The Notizie e mercato screen and the news part of Impostazioni (issue #60; SPEC 13.5, 13.6, mockup 05). +[TestClass] +public sealed class NewsScreenTests +{ + private static readonly CancellationToken _none = CancellationToken.None; + private static readonly DateTimeOffset Now = new(2026, 11, 16, 10, 0, 0, TimeSpan.Zero); + + /// + /// Each story of the last 24 hours says what the bot did, or why it did nothing; the effects still in force come + /// first, and an older restriction still in force stays on the list. Switching a rule off ends its restriction. + /// + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheBoardSaysWhatTheBotDidAboutEachStoryAndWhy() + { + await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); + var clock = new ManualClock(Now); + var specs = new[] { "ETH-EUR", "SOL-EUR", "ADA-EUR", "BTC-EUR" }.ToDictionary(s => s[..3], s => MarketDataStoreTests.Okx(s)); + var catalog = new InstrumentCatalog(test.Db, clock); + await catalog.SyncAsync(Venues.Okx, [.. specs.Values], complete: false, _none).ConfigureAwait(false); + var sol = (await catalog.ListAsync(Venues.Okx, _none).ConfigureAwait(false)).Single(i => i.Symbol == "SOL-EUR").Id; + await test.Db.WriteAsync(async s => + { + var account = Ids.NewId(clock); + await s.ExecuteAsync("INSERT INTO accounts (id, name, broker, environment, base_currency, created_at) VALUES (@id, 'OKX Europe', 'okx', 'simulation', 'EUR', @t)", + _none, ("id", account), ("t", Now)).ConfigureAwait(false); + await s.ExecuteAsync( + "INSERT INTO positions (id, account_id, instrument_id, strategy, quantity, average_price, last_price, stop_price, opened_at, created_at, updated_at) " + + "VALUES (@id, @a, @i, 'crypto_trend', 2, 130, 128, 120, @t, @t, @t)", _none, ("id", Ids.NewId(clock)), ("a", account), ("i", sol), ("t", Now)).ConfigureAwait(false); + }, _none).ConfigureAwait(false); + + await NewsRulesTests.StoryAsync(test.Db, clock, specs["SOL"], "Solana upgrade delayed by a week", Now.AddHours(-2), 3, -0.7, "CoinDesk", trusted: true, + seen: Now.AddHours(-2)).ConfigureAwait(false); + await NewsRulesTests.StoryAsync(test.Db, clock, specs["ADA"], "Cardano exchange hacked", Now.AddHours(-1), 4, -0.9, "CoinDesk", trusted: true, seen: Now.AddHours(-1)) + .ConfigureAwait(false); + await NewsRulesTests.StoryAsync(test.Db, clock, specs["ETH"], "Ether rallies on ETF inflows", Now.AddHours(-3), 2, 0.5, "CoinDesk", trusted: true, seen: Now.AddHours(-3)) + .ConfigureAwait(false); + await NewsRulesTests.StoryAsync(test.Db, clock, specs["BTC"], "Bitcoin slips as traders take profit", Now.AddHours(-4), 2, -0.4, "CoinDesk", trusted: true, + seen: Now.AddHours(-4)).ConfigureAwait(false); + await NewsRulesTests.StoryAsync(test.Db, clock, specs["SOL"], "Solana validators report outage", Now.AddMinutes(-30), 3, -0.8, "The Block", trusted: false) + .ConfigureAwait(false); + var market = await NewsRulesTests.StoryAsync(test.Db, clock, specs["ETH"], "Fed minutes show caution on cuts", Now.AddHours(-5), 1, -0.5, "Federal Reserve", trusted: true, + seen: Now.AddHours(-5)).ConfigureAwait(false); + await test.Db.WriteAsync(s => s.ExecuteAsync("UPDATE news_links SET scope = 'market', target = 'market' WHERE story_id = @id", _none, ("id", (object?)market)), _none).ConfigureAwait(false); + await NewsRulesTests.StoryAsync(test.Db, clock, specs["ETH"], "Ether bridge exploited", Now.AddHours(-30), 3, -0.8, "CoinDesk", trusted: true, seen: Now.AddHours(-30)) + .ConfigureAwait(false); + await NewsRulesTests.StoryAsync(test.Db, clock, specs["BTC"], "Bitcoin exchange halts withdrawals after hack", Now.AddHours(-50), 4, -0.9, "CoinDesk", trusted: true, + seen: Now.AddHours(-50)).ConfigureAwait(false); + + // SOL is held: the watcher writes its notes. ADA and BTC are neither held nor candidates: the board says the rule all the same. + await new NewsWatcher(test.Db, clock).RunOnceAsync(_none).ConfigureAwait(false); + var settings = new SettingsStore(test.Db, clock, new EventBus()); + var board = await new NewsBoard(test.Db, clock, settings).LoadAsync(_none).ConfigureAwait(false); + + Assert.AreEqual(6, board.Read, "The six stories first seen in the last 24 hours."); + Assert.AreEqual(3, board.Active, "SOL for 24 hours, ADA and BTC for 72."); + Assert.AreEqual(3, board.OnPositions, "The two stories on SOL and the one on the market."); + CollectionAssert.AreEqual(new[] + { + "Cardano exchange hacked", "Solana upgrade delayed by a week", "Bitcoin exchange halts withdrawals after hack", + "Solana validators report outage", "Ether rallies on ETF inflows", "Bitcoin slips as traders take profit", "Fed minutes show caution on cuts", + }, board.Rows.Select(r => r.Title).ToList(), "Effects in force first, then the latest; the restriction that ended 6 hours ago is gone."); + + var rows = board.Rows.ToDictionary(r => r.Title); + Assert.AreEqual("Per 24 ore non aumento la posizione su SOL.", rows["Solana upgrade delayed by a week"].Action); + Assert.AreEqual("Per 72 ore niente nuovi acquisti di ADA.", rows["Cardano exchange hacked"].Action); + Assert.AreEqual("Niente, perché nessun'altra fonte la riportava. La ricontrollo alle 13:00.", rows["Solana validators report outage"].Action); + Assert.AreEqual("Negativa, non confermata", rows["Solana validators report outage"].Tone); + Assert.IsTrue(rows["Solana validators report outage"].SingleSource); + Assert.AreEqual("Niente. Le notizie positive non mi fanno comprare: servono solo a evitare guai.", rows["Ether rallies on ETF inflows"].Action); + Assert.AreEqual("Leggermente positiva", rows["Ether rallies on ETF inflows"].Tone); + Assert.AreEqual(1, rows["Ether rallies on ETF inflows"].Direction); + Assert.AreEqual("Niente. Le notizie solo leggermente negative non creano restrizioni.", rows["Bitcoin slips as traders take profit"].Action); + Assert.AreEqual("Niente. Riguarda il mercato nel suo insieme: le restrizioni valgono per un singolo strumento.", rows["Fed minutes show caution on cuts"].Action); + Assert.AreEqual("Mercato", rows["Fed minutes show caution on cuts"].About); + Assert.AreEqual("SOL", rows["Solana upgrade delayed by a week"].About); + Assert.AreEqual(-1, rows["Solana upgrade delayed by a week"].Direction); + + // The user switches the negative row off: SOL's restriction no longer holds, ADA's (a serious event) still does. + await settings.SetAsync(NewsRuleSettings.Negative.Key, NewsRuleSettings.Off, "test", _none).ConfigureAwait(false); + var off = (await new NewsBoard(test.Db, clock, settings).LoadAsync(_none).ConfigureAwait(false)).Rows.ToDictionary(r => r.Title); + Assert.IsFalse(off["Solana upgrade delayed by a week"].Active); + StringAssert.EndsWith(off["Solana upgrade delayed by a week"].Action, "Ora la regola è spenta: la restrizione non vale più."); + Assert.IsTrue(off["Cardano exchange hacked"].Active); + } + + /// The demo of appendix F.9 as in the mockup: rows, filters, mood, calendar, sources and spending. + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheDemoShowsTheNewsAndTheMarketAsInTheMockup() + { + var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]); + var demoRoot = server.Host.Config.Data.Root; + try + { + var page = await server.TextAsync("/notizie"); + foreach (var text in new[] + { + "312 notizie lette nelle ultime 24 ore, 2 con un effetto in corso.", "Con effetto, 2", "Sulle tue posizioni, 9", "Tutte, 312", + "Oggi 06:10, da CoinDesk", "Cosa ho fatto: per 24 ore non aumento la posizione su SOL. Lo stop resta dov'è.", + "Neutra, evento in arrivo", "niente nuovi acquisti di mean reversion su JPM fino a martedì. La posizione di momentum resta.", + "Mercato USA", "Una sola fonte", "Negativa, non confermata", "Leggermente positiva", "Importanza 3 su 5", "Importanza 2 su 5", + "niente, perché nessun'altra fonte la riportava. Ricontrollata alle 18:20: rientrata.", "Mostra le altre 3", + "Crypto: paura o avidità", "su 100, paura", "17,8", "calmo", "+0,006%", "nella norma", + "Oggi, 16:00", "Fiducia dei consumatori USA", "Impatto medio: nessun blocco", + "Martedì 13 ottobre, prima dell'apertura", "Riguarda JPM: niente mean reversion fino a martedì", + "Mercoledì 14 ottobre, 14:30", "Impatto alto: nessun nuovo ingresso dalle 14:00 alle 15:00", + "Mercoledì 28 ottobre, 19:00", "Impatto alto: nessun nuovo ingresso dalle 18:30 alle 20:00", + "Alpaca News", "in tempo reale", "14 testate e banche centrali", "Comunicati alla SEC", "aggiornato alle 08:00", + "oggi è costato 0,04 € su un tetto di 0,50 €", + }) + { + StringAssert.Contains(page, text, $"Missing {text} on Notizie e mercato."); + } + + // The order of the mockup: the two effects in force, then the latest. + var order = new[] { "Rinviato di una settimana", "JPMorgan pubblica i conti", "I verbali della banca centrale", "Un analista alza", "Un exchange segnala", "Richieste di sussidi" } + .Select(t => page.IndexOf(t, StringComparison.Ordinal)).ToList(); + CollectionAssert.AreEqual(order.Order().ToList(), order, "Rows in the order of the mockup."); + Assert.IsTrue(order.All(i => i >= 0)); + + var active = await server.TextAsync("/notizie?filtro=effetto"); + StringAssert.Contains(active, "Rinviato di una settimana"); + Assert.IsFalse(active.Contains("Un analista alza", StringComparison.Ordinal), "Only the effects in force."); + + var settings = await server.TextAsync("/impostazioni"); + StringAssert.Contains(settings, "Notizie e calendario"); + StringAssert.Contains(settings, NewsRuleSettings.Severe.Label); + Assert.IsFalse(settings.Contains("/azioni/notizie/fonti/", StringComparison.Ordinal), "The demo changes no source."); + Assert.IsFalse(settings.Contains("/azioni/chiavi-dati/", StringComparison.Ordinal), "The demo takes no key."); + } + finally + { + // The server first: on Windows a database still open cannot be deleted. + await server.DisposeAsync(); + TempFolder.Delete(demoRoot); + } + } + + /// The news part of Impostazioni: sources, rows of 10.5, cap and keys; every change in the change log, no key ever shown. + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheSettingsChangeSourcesRulesCapAndKeys() + { + await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite()); + await server.SignInFirstTimeAsync(); + var services = server.Host.Services!; + + // A new installation without market data: the screen says what is missing. + var empty = await server.TextAsync("/notizie"); + StringAssert.Contains(empty, "0 notizie lette nelle ultime 24 ore, nessuna con un effetto in corso."); + StringAssert.Contains(empty, "Non leggo ancora notizie"); + + var store = new NewsStore(services.Db, server.Host.Clock); + await store.EnsureDefaultsAsync(_none); + var coindesk = (await store.ListSourcesAsync(_none)).Single(s => s.Name == "CoinDesk"); + Assert.IsTrue(coindesk.Trusted); + using (var response = await server.PostFormAsync("/impostazioni", $"/azioni/notizie/fonti/{coindesk.Id}", ("attiva", "on"))) + { + Assert.AreEqual("/impostazioni?ok=fonte#notizie", ServerHarness.Location(response)); + } + + var after = (await store.ListSourcesAsync(_none)).Single(s => s.Name == "CoinDesk"); + Assert.IsTrue(after.Enabled); + Assert.IsFalse(after.Trusted, "The unchecked box takes the trust away."); + var history = await services.Settings.HistoryAsync(null, 10, _none); + Assert.IsTrue(history.Any(h => h.Key == "news.source:CoinDesk"), "The change is in the change log."); + + using (var response = await server.PostFormAsync("/impostazioni", $"/azioni/impostazioni/{NewsRuleSettings.Severe.Key}", ("valore", "off"), ("ritorno", "/impostazioni#notizie"))) + { + Assert.AreEqual("/impostazioni#notizie", ServerHarness.Location(response)); + } + + Assert.IsFalse((await NewsRuleSettings.LoadAsync(services.Settings, _none)).Severe); + + using (var response = await server.PostFormAsync("/impostazioni", $"/azioni/impostazioni/{NewsModelSettings.DailyCap.Key}", ("valore", "0,75"), ("ritorno", "/impostazioni#notizie"))) + { + Assert.AreEqual("/impostazioni#notizie", ServerHarness.Location(response)); + } + + Assert.AreEqual(0.75m, await NewsModelSettings.CapAsync(services.Settings, _none)); + using (var response = await server.PostFormAsync("/impostazioni", $"/azioni/impostazioni/{NewsModelSettings.DailyCap.Key}", ("valore", "tanto"), ("ritorno", "/impostazioni#notizie"))) + { + StringAssert.Contains(ServerHarness.Location(response), "errore=tetto"); + } + + const string typed = "chiave-di-prova-finnhub"; + using (var response = await server.PostFormAsync("/impostazioni", "/azioni/chiavi-dati/FINNHUB_API_KEY", ("chiave", typed))) + { + Assert.AreEqual("/impostazioni?ok=chiave#notizie", ServerHarness.Location(response)); + } + + Assert.AreEqual(typed, await services.Secrets.RevealAsync("FINNHUB_API_KEY", _none)); + var page = await server.TextAsync("/impostazioni"); + Assert.IsFalse(page.Contains(typed, StringComparison.Ordinal), "A saved key is never shown again."); + StringAssert.Contains(page, "Chiave di Finnhub: Impostata"); + + using (var response = await server.PostFormAsync("/impostazioni", "/azioni/chiavi-dati/FRED_API_KEY", ("chiave", "with space"))) + { + StringAssert.Contains(ServerHarness.Location(response), "errore=chiave"); + } + + using (var response = await server.PostFormAsync("/impostazioni", "/azioni/chiavi-dati/OKX_API_KEY", ("chiave", "abc"))) + { + StringAssert.Contains(ServerHarness.Location(response), "errore=impostazione", "Broker keys go through their own form, with the withdrawal check."); + } + + using (var response = await server.PostFormAsync("/impostazioni", "/azioni/chiavi-dati/FINNHUB_API_KEY/togli")) + { + Assert.AreEqual("/impostazioni?ok=chiave-tolta#notizie", ServerHarness.Location(response)); + } + + Assert.IsNull(await services.Secrets.RevealAsync("FINNHUB_API_KEY", _none)); + Assert.AreEqual(HttpStatusCode.OK, (await server.GetAsync("/notizie")).StatusCode); + } +} diff --git a/tests/Anubis.Tests/OverviewScreenTests.cs b/tests/Anubis.Tests/OverviewScreenTests.cs index f875548..35758fa 100644 --- a/tests/Anubis.Tests/OverviewScreenTests.cs +++ b/tests/Anubis.Tests/OverviewScreenTests.cs @@ -124,7 +124,7 @@ public sealed class OverviewScreenTests // 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, "La lettura delle notizie è spenta insieme ai dati di mercato."); StringAssert.Contains(home, "L'apprendimento non è ancora attivo."); var diary = await server.TextAsync("/diario"); StringAssert.Contains(diary, "Come sta il sistema"); diff --git a/tools/Anubis.Tasks/Program.cs b/tools/Anubis.Tasks/Program.cs index 25c9906..5e67d8f 100644 --- a/tools/Anubis.Tasks/Program.cs +++ b/tools/Anubis.Tasks/Program.cs @@ -141,7 +141,7 @@ int Screenshots(string[] pages) var folder = Path.Combine(root, "artifacts", "screenshots"); Directory.CreateDirectory(folder); - var targets = pages.Length > 0 ? pages : ["/", "/conti", "/diario", "/impostazioni"]; + var targets = pages.Length > 0 ? pages : ["/", "/conti", "/diario", "/notizie", "/impostazioni"]; using var shots = Shots.Start(browser); foreach (var page in targets) {