Files
Anubis/src/Anubis.Server/TradesView.cs
T
Alby96andClaude Opus 5.5 0b0f4a5e75
ci / test (postgres) (push) Successful in 6m37s
ci / test (sqlite) (push) Successful in 7m51s
ci / test (postgres) (pull_request) Successful in 5m40s
ci / test (sqlite) (pull_request) Successful in 7m31s
ci / image (push) Successful in 2m29s
ci / image (pull_request) Successful in 59s
Fix what the independent review of Phase 8 found and close the phase
Two reviewers with a clean context read the engine and the screens. The
isotonic calibration took its floor from the first step, even of two cases, so
with few winners it flattened every estimate: the first model is rebuilt with
the fix. Learning failures no longer forget the multiplier an operation was
born with, nor stop a decision or the nightly check; recovered decisions read
the outside world as it was when due; models estimate only the strategies they
studied; a newer history does not repeat what was lived. The screens count
examples instead of verifications, show the next threshold and never round an
alarm to 50%; two forms now check the antiforgery token.

Each defect has its test, on both engines. ADR 0018 point 17 has the list.

refs #67

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 13:36:26 +01:00

207 lines
14 KiB
C#

using System.Globalization;
using System.Text;
using Anubis.Core;
using Anubis.Data;
using Anubis.Trading;
namespace Anubis.Server;
/// <summary>The filters of the Operazioni screen, read from the address so a filtered page can be bookmarked.</summary>
internal sealed record TradeFilter(string? Search, Guid? Account, string? Strategy, string? Result, string Period, int Page)
{
public const int PageSize = 20;
public static readonly IReadOnlyList<(string Key, string Label)> Periods = [("avvio", "Dall'avvio"), ("7", "Ultimi 7 giorni"), ("30", "Ultimi 30 giorni"), ("90", "Ultimi 90 giorni")];
public static readonly IReadOnlyList<(string Key, string Label)> Results = [("", "Guadagni e perdite"), ("guadagni", "Solo guadagni"), ("perdite", "Solo perdite")];
public static TradeFilter Parse(string? search, string? account, string? strategy, string? result, string? period, string? page) => new(
string.IsNullOrWhiteSpace(search) ? null : search.Trim(),
Guid.TryParse(account, out var a) ? a : null,
string.IsNullOrWhiteSpace(strategy) ? null : strategy,
result is "guadagni" or "perdite" ? result : null,
Periods.Any(p => p.Key == period) ? period! : "avvio",
int.TryParse(page, NumberStyles.None, CultureInfo.InvariantCulture, out var p) && p > 0 ? p : 1);
/// <summary>The query string of this filter with one value changed.</summary>
public string Query(int? page = null)
{
var parts = new List<string>();
void Add(string key, string? value)
{
if (!string.IsNullOrEmpty(value))
{
parts.Add(key + "=" + Uri.EscapeDataString(value));
}
}
Add("cerca", Search);
Add("conto", Account?.ToString());
Add("strategia", Strategy);
Add("esito", Result);
Add("periodo", Period == "avvio" ? null : Period);
var p = page ?? Page;
Add("pagina", p > 1 ? p.ToString(CultureInfo.InvariantCulture) : null);
return parts.Count == 0 ? "" : "?" + string.Join('&', parts);
}
}
/// <summary>A step of the "why" card: a stage of a decision in plain Italian.</summary>
internal sealed record WhyLine(string Text, bool Good);
/// <summary>A closed trade of the Operazioni screen, in its own currency and in euro.</summary>
internal sealed record TradeRow(Guid Id, string Symbol, string Name, string Strategy, string Account, string Currency, DateTimeOffset OpenedAt, DateTimeOffset ClosedAt,
decimal Quantity, decimal EntryPrice, decimal ExitPrice, decimal Realized, decimal RealizedEur, decimal Fees, string ExitReason, string? ExitCode,
IReadOnlyList<WhyLine> Bought, IReadOnlyList<WhyLine> Sold, decimal? EntrySlipBp, decimal? ExitSlipBp)
{
public decimal Percent => EntryPrice * Quantity == 0m ? 0m : Realized / (EntryPrice * Quantity) * 100m;
}
/// <summary>
/// The Operazioni screen (SPEC 13.6, mockup 03): closed trades with their figures, filters, the result of each
/// trade as bars, and for each one the "why" card built from the rows of the decisions table (SPEC 5.2).
/// </summary>
internal sealed record TradesView(
IReadOnlyList<TradeRow> Rows,
int Matching,
int Total,
DateTimeOffset? Since,
decimal Gains,
decimal Losses,
int Winners,
decimal Fees,
IReadOnlyList<(DateTimeOffset At, decimal Eur, string Symbol)> Bars,
IReadOnlyList<(Guid Id, string Name)> Accounts,
IReadOnlyList<string> Strategies)
{
public int Losers => Matching - Winners;
/// <summary>Euro gained for each euro lost: null while nothing was lost.</summary>
public decimal? PerEuroLost => Losses < 0m ? Gains / -Losses : null;
public decimal Net => Gains + Losses;
public static async Task<TradesView> LoadAsync(AppServices services, IClock clock, TradeFilter filter, int? limit, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(filter);
var rate = (await new FxStore(services.Db, clock).LatestAsync("EUR", "USD", cancellationToken).ConfigureAwait(false))?.Rate ?? 0m;
var (accounts, trades) = await services.Db.ReadAsync(async s =>
{
var a = await s.QueryAsync("SELECT id, name, environment, base_currency FROM accounts ORDER BY broker DESC, created_at",
r => (Id: r.Id("id"), Name: r.Text("name"), Environment: r.Text("environment"), Currency: r.Text("base_currency"))).ConfigureAwait(false);
var t = await s.QueryAsync(
"SELECT t.id, t.account_id, t.instrument_id, t.strategy, t.opened_at, t.closed_at, t.bought_quantity, t.bought_value, t.sold_quantity, t.sold_value, t.fees, t.realized, " +
"t.exit_reason, i.symbol, i.name FROM trades t JOIN instruments i ON i.id = t.instrument_id WHERE t.status = 'closed' ORDER BY t.closed_at DESC, t.id",
r => new Closed(r.Id("id"), r.Id("account_id"), r.Id("instrument_id"), r.Text("strategy"), r.Moment("opened_at"), r.Moment("closed_at"), r.Money("bought_quantity"),
r.Money("bought_value"), r.Money("sold_quantity"), r.Money("sold_value"), r.Money("fees"), r.Money("realized"), r.TextOrNull("exit_reason"), r.Text("symbol"),
r.TextOrNull("name") ?? "")).ConfigureAwait(false);
return (a, t);
}, cancellationToken).ConfigureAwait(false);
// One world only, as on the Conti screen: real accounts when there are any, so finto and vero never add up.
var world = accounts.Any(a => TradingEnvironments.World(a.Environment) == Worlds.Real) ? Worlds.Real : Worlds.Simulated;
var shown = accounts.Where(a => TradingEnvironments.World(a.Environment) == world).ToDictionary(a => a.Id);
decimal Eur(Guid account, decimal amount) => shown[account].Currency == "USD" ? (rate > 0m ? amount / rate : 0m) : amount;
var all = trades.Where(t => shown.ContainsKey(t.Account)).ToList();
var from = filter.Period switch
{
"7" => clock.UtcNow.AddDays(-7),
"30" => clock.UtcNow.AddDays(-30),
"90" => clock.UtcNow.AddDays(-90),
_ => (DateTimeOffset?)null,
};
var matching = all.Where(t =>
(filter.Account is null || t.Account == filter.Account) &&
(filter.Strategy is null || t.Strategy == filter.Strategy) &&
(from is null || t.ClosedAt >= from) &&
(filter.Result is null || (filter.Result == "guadagni" ? t.Realized >= 0m : t.Realized < 0m)) &&
(filter.Search is null || t.Symbol.Contains(filter.Search, StringComparison.OrdinalIgnoreCase) || t.Name.Contains(filter.Search, StringComparison.OrdinalIgnoreCase)))
.ToList();
var page = limit is { } n ? matching.Take(n).ToList() : matching.Skip((filter.Page - 1) * TradeFilter.PageSize).Take(TradeFilter.PageSize).ToList();
var rows = new List<TradeRow>();
foreach (var t in page)
{
var (bought, sold, entrySlip, exitSlip, code) = await WhyAsync(services, t, cancellationToken).ConfigureAwait(false);
var quantity = t.BoughtQuantity;
rows.Add(new TradeRow(t.Id, t.Symbol, t.Name, t.Strategy, shown[t.Account].Name, shown[t.Account].Currency, t.OpenedAt, t.ClosedAt, quantity,
quantity == 0m ? 0m : t.BoughtValue / quantity, t.SoldQuantity == 0m ? 0m : t.SoldValue / t.SoldQuantity, t.Realized,
Math.Round(Eur(t.Account, t.Realized), 2, MidpointRounding.AwayFromZero), t.Fees, ReasonTexts.Exit(code ?? t.ExitReason), code ?? t.ExitReason, bought, sold, entrySlip,
exitSlip));
}
var bars = matching.OrderBy(t => t.ClosedAt).Select(t => (t.ClosedAt, Math.Round(Eur(t.Account, t.Realized), 2, MidpointRounding.AwayFromZero), t.Symbol)).ToList();
return new TradesView(rows, matching.Count, all.Count, all.Count > 0 ? all.Min(t => t.ClosedAt) : null,
bars.Where(b => b.Item2 >= 0m).Sum(b => b.Item2), bars.Where(b => b.Item2 < 0m).Sum(b => b.Item2), bars.Count(b => b.Item2 >= 0m),
matching.Sum(t => Math.Round(Eur(t.Account, t.Fees), 2, MidpointRounding.AwayFromZero)), bars,
[.. shown.Values.Select(a => (a.Id, a.Name))], [.. all.Select(t => t.Strategy).Distinct().Order(StringComparer.Ordinal)]);
}
/// <summary>The trades as CSV for an Italian spreadsheet: semicolons, decimal commas, one row per closed trade.</summary>
public string Csv()
{
var text = new StringBuilder("chiusa_il;aperta_il;strumento;nome;strategia;conto;quantita;prezzo_entrata;prezzo_uscita;valuta;risultato;risultato_eur;commissioni;motivo\n");
foreach (var r in Rows)
{
text.Append(string.Join(';', Moment(r.ClosedAt), Moment(r.OpenedAt), Clean(r.Symbol), Clean(r.Name), r.Strategy, Clean(r.Account), Number(r.Quantity), Number(r.EntryPrice),
Number(r.ExitPrice), r.Currency, Number(r.Realized), Number(r.RealizedEur), Number(r.Fees), Clean(r.ExitReason))).Append('\n');
}
return text.ToString();
static string Moment(DateTimeOffset at) => at.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture);
static string Number(decimal value) => (Math.Round(value, 8) / 1.000000000000000000000000000000000m).ToString(CultureInfo.InvariantCulture).Replace('.', ',');
static string Clean(string value) => value.Replace(';', ',').Replace('\n', ' ');
}
private sealed record Closed(Guid Id, Guid Account, Guid Instrument, string Strategy, DateTimeOffset OpenedAt, DateTimeOffset ClosedAt, decimal BoughtQuantity, decimal BoughtValue,
decimal SoldQuantity, decimal SoldValue, decimal Fees, decimal Realized, string? ExitReason, string Symbol, string Name);
/// <summary>
/// The decisions behind a trade: the first purchase and the last sale of its executions, matched to their decision
/// through the order key (the hash of the decision id), and every stage of those decisions in words.
/// </summary>
private static async Task<(List<WhyLine> Bought, List<WhyLine> Sold, decimal? EntrySlip, decimal? ExitSlip, string? ExitCode)> WhyAsync(AppServices services, Closed t,
CancellationToken cancellationToken)
{
var (executions, decisions, earlier) = await services.Db.ReadAsync(async s =>
{
var e = await s.QueryAsync(
"SELECT side, order_key, reference_price, purpose, started_at FROM executions WHERE account_id = @a AND instrument_id = @i AND strategy = @s AND started_at >= @f AND started_at <= @t " +
"ORDER BY started_at, id",
r => (Side: r.Text("side"), Key: r.Text("order_key"), Reference: r.MoneyOrNull("reference_price"), Purpose: r.Text("purpose")),
("a", t.Account), ("i", t.Instrument), ("s", t.Strategy), ("f", t.OpenedAt.AddMinutes(-5)), ("t", t.ClosedAt)).ConfigureAwait(false);
var d = await s.QueryAsync(
"SELECT decision_id, stage, outcome, reasons, data FROM decisions WHERE strategy = @s AND symbol = @sym AND created_at >= @f AND created_at <= @t ORDER BY created_at, id",
r => (Id: r.Id("decision_id"), Stage: r.Text("stage"), Outcome: r.Text("outcome"), Reasons: r.Text("reasons"), Data: r.TextOrNull("data")),
("s", t.Strategy), ("sym", t.Symbol), ("f", t.OpenedAt.AddDays(-1)), ("t", t.ClosedAt.AddMinutes(5))).ConfigureAwait(false);
// The example may be older than the purchase: proposed, held back, and bought days later. Same example, same estimate.
var m = d.Any(x => x.Stage == DecisionStages.Model) ? [] : await s.QueryAsync(
"SELECT d.outcome, d.data FROM decisions d JOIN ml_features f ON f.decision_id = d.decision_id AND f.symbol = d.symbol LEFT JOIN ml_labels l ON l.feature_id = f.id " +
"WHERE d.stage = @st AND d.strategy = @s AND d.symbol = @sym AND d.created_at <= @t AND (l.closed_day IS NULL OR l.closed_day > @o) ORDER BY d.created_at DESC LIMIT 1",
r => (Outcome: r.Text("outcome"), Data: r.TextOrNull("data")), ("st", DecisionStages.Model), ("s", t.Strategy), ("sym", t.Symbol), ("t", t.OpenedAt.AddMinutes(5)),
("o", DateOnly.FromDateTime(t.OpenedAt.UtcDateTime).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture))).ConfigureAwait(false);
return (e, d, m);
}, cancellationToken).ConfigureAwait(false);
var byKey = decisions.GroupBy(d => d.Id).ToDictionary(g => ClientOrderIds.Key(g.Key), g => g.ToList(), StringComparer.Ordinal);
List<WhyLine> Lines(string? key) => key is not null && byKey.TryGetValue(key, out var rows)
? [.. rows.SelectMany(r => ReasonTexts.Stage(r.Stage, r.Outcome, System.Text.Json.JsonSerializer.Deserialize<List<string>>(r.Reasons) ?? [], r.Data))]
: [];
var buy = executions.FirstOrDefault(e => e.Side == "buy");
var sell = executions.LastOrDefault(e => e.Side == "sell");
var sold = Lines(sell.Key);
var code = sell.Key is not null && byKey.TryGetValue(sell.Key, out var exitRows)
? exitRows.Where(r => r.Stage == DecisionStages.Strategy).SelectMany(r => System.Text.Json.JsonSerializer.Deserialize<List<string>>(r.Reasons) ?? []).FirstOrDefault()
: sell.Purpose is "stop" or "protective" ? "stop" : null;
decimal? entrySlip = buy.Reference is > 0m && t.BoughtQuantity > 0m ? Math.Round(((t.BoughtValue / t.BoughtQuantity) / buy.Reference.Value - 1m) * 10_000m, 1) : null;
decimal? exitSlip = sell.Reference is > 0m && t.SoldQuantity > 0m ? Math.Round((1m - (t.SoldValue / t.SoldQuantity) / sell.Reference.Value) * 10_000m, 1) : null;
List<WhyLine> bought = [.. Lines(buy.Key), .. earlier.SelectMany(m => ReasonTexts.Stage(DecisionStages.Model, m.Outcome, [], m.Data))];
return (bought, sold, entrySlip, exitSlip, code);
}
}