using System.Globalization;
using System.Text.Json;
using Anubis.Core;
using Anubis.Data;
using Anubis.Risk;
using Anubis.Trading;
namespace Anubis.Server;
/// The last 30 days of an account: the result net of flows and the daily values in euro for the small line.
internal sealed record AccountTrend(decimal Month, IReadOnlyList Points);
/// A news item of the "Notizie che contano" tile; when its effect is still on.
internal sealed record PanoramaNews(string When, string About, string Title, string Effect, bool Active);
/// The model at a glance: signals counted toward the 300, precision on unseen cases, training and next check.
internal sealed record PanoramaLearning(int Signals, int Needed, int Precision, string Trained, string NextCheck);
/// One of the four limits of the Panoramica (SPEC 13.6): value, threshold, share used and, for the fall, the worst so far.
internal sealed record PanoramaLimit(string Label, string Value, string Threshold, decimal Share, decimal? Worst = null);
/// A strategy at a glance: result, the bar against the best one, its stage in words and its trades.
internal sealed record PanoramaStrategy(string Name, string Color, decimal Result, decimal Bar, string Stage, string Trades);
///
/// Everything under the top block of the Panoramica (SPEC 13.6, mockup 01): accounts with their last 30 days, the
/// four main limits, positions, strategies, news, model and system. In demo mode the values of appendix F that
/// exist only as totals come from the aggregates (SPEC 13.1); outside it news and the model are not active yet.
///
internal sealed record PanoramaView(
AccountsView Accounts,
IReadOnlyDictionary Trends,
IReadOnlyList Limits,
bool LimitsKept,
IReadOnlyList Strategies,
bool AnyLive,
SystemView System,
IReadOnlyList? DemoMoves,
IReadOnlyList? DemoLast,
string? NextDecision,
IReadOnlyList? News,
PanoramaLearning? Learning,
DateTimeOffset? FractionStops)
{
private static readonly CultureInfo _it = CultureInfo.InvariantCulture;
public static async Task LoadAsync(AnubisHost host, ShellData shell, Overview overview, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(host);
ArgumentNullException.ThrowIfNull(shell);
ArgumentNullException.ThrowIfNull(overview);
var services = host.Services!;
var clock = host.Clock;
var risk = await RiskView.LoadAsync(services, clock, shell.Zone, cancellationToken).ConfigureAwait(false);
var accounts = await AccountsView.LoadAsync(services, clock, shell.Zone, cancellationToken).ConfigureAwait(false);
var strategies = await StrategiesView.LoadAsync(services, clock, false, cancellationToken).ConfigureAwait(false);
var system = await SystemView.LoadAsync(host, shell, cancellationToken).ConfigureAwait(false);
var trends = await TrendsAsync(services, accounts, shell.Now, shell.Zone, cancellationToken).ConfigureAwait(false);
// The four limits of the Panoramica, read from the same rows as the Rischio page.
var rows = risk.Rows.ToDictionary(r => r.Key);
var day = rows[RiskSettings.DailyLoss.Key];
var invested = rows[RiskSettings.MaxInvested.Key];
var biggest = rows[RiskSettings.MaxPosition.Key];
var fall = risk.Risk.Measures.Drawdown;
decimal? worst = risk.Drawdown.Count > 0 ? risk.Drawdown.Min(d => d.Drawdown) : null;
var stop = risk.Limits.DrawdownStop;
var limits = new List
{
new("Perdita di oggi", day.Now, day.Threshold, day.Usage ?? 0m),
new("Calo dal massimo", Format.Percent(fall * 100m, 2), Format.Percent(-stop * 100m, 2), stop <= 0m ? 0m : Math.Clamp(-fall / stop, 0m, 1m),
worst is { } w && stop > 0m ? Math.Clamp(-w / stop, 0m, 1m) : null),
new("Capitale investito", invested.Now, invested.Threshold, invested.Usage ?? 0m),
new("Posizione più grande" + (biggest.Detail is { } symbol ? $" ({symbol.Split('/')[0]})" : ""), biggest.Now, biggest.Threshold, biggest.Usage ?? 0m),
};
var kept = !risk.AnyBlock && risk.Rows.All(r => r.Usage is null or < 1m);
// Strategies: the bar compares each result with the best one; the stage says what is still missing.
var best = strategies.Cards.Select(c => Math.Abs(c.ResultEur)).DefaultIfEmpty(0m).Max();
var cards = strategies.Cards.Select(c => new PanoramaStrategy(c.Name, c.Color, c.ResultEur, best == 0m ? 0m : Math.Abs(c.ResultEur) / best, Stage(c), Trades(c))).ToList();
var anyLive = strategies.Cards.Any(c => StrategyStages.IsLive(c.Stage.Stage));
// The daily stops of the fractions come back with the orders after the open (SPEC 7.2).
DateTimeOffset? fractions = accounts.MarketOpen ? null : accounts.MarketNext + (services.Trading?.Engine.Options.OrdersAfterOpen ?? new LiveEngineOptions().OrdersAfterOpen);
using var aggregates = shell.Aggregates();
if (aggregates is null)
{
return new PanoramaView(accounts, trends, limits, kept, cards, anyLive, system, null, null, Decision(overview.NextDecision, shell.Now, shell.Zone), null, null, fractions);
}
var root = aggregates.RootElement;
var demo = root.GetProperty("panoramica");
var moves = demo.GetProperty("mosse").EnumerateArray().Select(m => new NextMove(m.GetProperty("ora").GetString()!, m.GetProperty("testo").GetString()!,
m.TryGetProperty("dove", out var where) ? where.GetString() : null, m.GetProperty("calendario").GetBoolean())).ToList();
var last = demo.GetProperty("ultime_azioni").EnumerateArray().Select(a => new LastAction(a.GetProperty("quando").GetString()!, a.GetProperty("testo").GetString()!)).ToList();
var news = root.GetProperty("notizie").GetProperty("panoramica").EnumerateArray().Select(n => new PanoramaNews(n.GetProperty("quando").GetString()!,
n.GetProperty("riguarda").GetString()!, n.GetProperty("titolo").GetString()!, n.GetProperty("effetto").GetString()!, n.GetProperty("in_corso").GetBoolean())).ToList();
var model = root.GetProperty("apprendimento");
var learning = new PanoramaLearning(model.GetProperty("segnali").GetInt32(), model.GetProperty("necessari").GetInt32(), model.GetProperty("precisione_pct").GetInt32(),
model.GetProperty("ultimo_addestramento").GetString()!, model.GetProperty("prossima_verifica").GetString()!);
// The 30-day results of appendix F.2: the generated daily series of each account only ends on its total.
var month = root.GetProperty("conti").EnumerateArray().ToDictionary(c => c.GetProperty("nome").GetString()!,
c => decimal.Parse(c.GetProperty("trenta_giorni").GetString()!, _it), StringComparer.Ordinal);
var demoTrends = accounts.Accounts.ToDictionary(a => a.Id,
a => new AccountTrend(month.GetValueOrDefault(a.Name, trends.GetValueOrDefault(a.Id)?.Month ?? 0m), trends.GetValueOrDefault(a.Id)?.Points ?? []));
return new PanoramaView(accounts, demoTrends, limits, kept, cards, anyLive, system, moves, last, demo.GetProperty("prossima_decisione").GetString(), news, learning, fractions);
}
private static async Task> TrendsAsync(AppServices services, AccountsView accounts, DateTimeOffset now, TimeZoneInfo zone,
CancellationToken cancellationToken)
{
var shown = accounts.Accounts.ToDictionary(a => a.Id);
var world = accounts.Accounts.Any(a => TradingEnvironments.World(a.Environment) == Worlds.Real) ? Worlds.Real : Worlds.Simulated;
var rows = await services.Db.ReadAsync(s => s.QueryAsync(
"SELECT taken_at, account_id, currency, equity, flows FROM equity_snapshots WHERE scope = 'account' AND world = @w AND taken_at >= @f ORDER BY taken_at, id",
r => (At: r.Moment("taken_at"), Account: r.IdOrNull("account_id"), Currency: r.TextOrNull("currency"), Equity: r.Money("equity"), Flows: r.MoneyOrNull("flows") ?? 0m),
("w", world), ("f", now.AddDays(-32))), cancellationToken).ConfigureAwait(false);
var result = new Dictionary();
foreach (var group in rows.Where(r => r.Account is { } id && shown.ContainsKey(id)).GroupBy(r => r.Account!.Value))
{
var account = shown[group.Key];
decimal Eur(decimal amount, string? currency) => currency == "USD" ? account.Eur(amount) : amount;
var daily = group.GroupBy(r => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(r.At, zone).DateTime)).Select(g => g.Last()).ToList();
var latest = daily[^1];
var latestDay = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(latest.At, zone).DateTime);
var start = daily.LastOrDefault(p => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(p.At, zone).DateTime) <= latestDay.AddDays(-30));
start = start == default ? daily[0] : start;
var month = Eur(latest.Equity, latest.Currency) - Eur(start.Equity, start.Currency) - (Eur(latest.Flows, latest.Currency) - Eur(start.Flows, start.Currency));
var points = daily.Where(p => p.At >= start.At).Select(p => Eur(p.Equity - p.Flows, p.Currency)).ToList();
result[group.Key] = new AccountTrend(month, points);
}
return result;
}
/// Where a strategy is on its path, with the requirement that is furthest away: "In simulazione, giorno 58 di 60".
private static string Stage(StrategyCard card)
{
var stage = card.Stage.Stage;
if (stage == StrategyStages.Observation)
{
return "In osservazione";
}
if (stage == StrategyStages.Real)
{
return "Con soldi veri";
}
var where = stage == StrategyStages.Reduced ? "In reale ridotto" : "In simulazione";
var missing = card.Requirements
.Where(r => !r.Met && r.Key is "days" or "trades")
.Select(r => (r.Key, Value: Whole(r.Value), Target: Whole(r.Target)))
.Where(r => r.Value is not null && r.Target is > 0)
.OrderBy(r => (decimal)r.Value!.Value / r.Target!.Value)
.FirstOrDefault();
return missing.Key switch
{
"days" => $"{where}, giorno {missing.Value} di {missing.Target}",
"trades" => $"{where}, {missing.Value} operazioni su {missing.Target}",
_ => where,
};
static int? Whole(string text)
{
var digits = new string(text.Where(char.IsAsciiDigit).ToArray());
return int.TryParse(digits, NumberStyles.None, _it, out var n) ? n : null;
}
}
private static string Trades(StrategyCard card)
{
var open = card.Open.Distinct().Count();
var positions = open switch
{
0 => "Nessuna posizione aperta",
1 => "1 posizione aperta",
_ => $"{open} posizioni aperte",
};
var closed = card.Closed switch
{
0 => "nessuna operazione chiusa",
1 => $"1 operazione chiusa ({(card.Winners == 1 ? "in guadagno" : "in perdita")})",
_ => $"{card.Closed} operazioni chiuse ({card.Winners} in guadagno)",
};
return positions + ", " + closed;
}
/// "Prossima decisione tra 7 ore e 14 minuti, alle 15:35."
private static string? Decision(DateTimeOffset? due, DateTimeOffset now, TimeZoneInfo zone)
{
if (due is not { } at || at <= now)
{
return null;
}
var wait = at - now;
var hours = (int)wait.TotalHours;
var minutes = wait.Minutes;
var span = (hours, minutes) switch
{
(0, <= 1) => "un minuto",
(0, _) => $"{minutes} minuti",
(1, 0) => "un'ora",
(_, 0) => $"{hours} ore",
(1, _) => $"un'ora e {minutes} minuti",
_ => $"{hours} ore e {minutes} minuti",
};
var time = TimeZoneInfo.ConvertTime(at, zone).ToString("HH:mm", _it);
return wait < TimeSpan.FromHours(24) ? $"Prossima decisione tra {span}, alle {time}." : $"Prossima decisione {Format.ShortDate(at, now, zone).ToLowerInvariant()}.";
}
}