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;
/// News, calendar and earnings only measured (ADR 0023): the page is an archive of what each rule would have done.
public bool Measured => Board.Measured;
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, board.Measured, 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);
}
/// The spending of the day in words (SPEC 13.6): what the language model read and what it cost, against the cap.
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> 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, bool measured,
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);
// Measured: no note is written, so the candidates come from the list the filter of the earnings reads, within the
// reach the notes would have had (ADR 0027).
var candidates = measured ? await NewsWatcher.WatchedStocksAsync(services.Db, cancellationToken).ConfigureAwait(false) : new HashSet();
var reach = NewsDesk.EarningsReach(now);
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)
|| (candidates.Contains(s) && Zones.DayIn(e.OccursAt, Zones.NewYork) <= reach)),
_ => false,
}).OrderBy(e => e.OccursAt).Take(CalendarRows);
return [.. shown.Select(e => Row(e, now, zone, switches, measured))];
}
private static CalendarRow Row(CalendarEvent e, DateTimeOffset now, TimeZoneInfo zone, NewsRuleSwitches switches, bool measured)
{
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 measured
? new CalendarRow(dayText + when, e.Title, $"Riguarda {e.Symbol}: con le regole attive niente mean reversion {until}. Solo registrato.", false)
: 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 (measured)
{
var start = TimeZoneInfo.ConvertTime(window.From, zone);
var end = TimeZoneInfo.ConvertTime(window.To, zone);
return new CalendarRow(whenText, e.Title, string.Create(_it, $"{impact}: con le regole attive nessun nuovo ingresso dalle {start:HH:mm} alle {end:HH:mm}. Solo registrato."), false);
}
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..];
}