Write the diary from fixed templates and add the "senza bot" comparison (refs #50)

The diary needs sentences in the tone of appendix B, built only from what
happened. DiaryText holds the templates the live engine will use: fills
with the result of the trade they close, raised stops, the daily crypto
close, the stock signals, observation signals, recovery and absence. The
reason-code sentences move from the server into the library
(ReasonCatalog) so the engine and the screens share them; a test checks
that every reason constant has its sentence. The diary gets the kinds of
the Diario screen: Ordini, Decisioni, Sistema, Notizie, Apprendimento.

The comparison of SPEC 7.5 invests each capital flow on its day, 40% in
BTC/EUR and 60% in SPY adjusted and converted at the ECB rate, and never
touches it; a withdrawal sells both in the proportion they reached. Prices
are the closes of the day before, so a deposit is never a gain. Without
the SPY history (no Alpaca keys) the photograph leaves it empty rather
than show half a comparison. The Panoramica now takes the flows out of
the "Senza bot" result, as it already did for the bot.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-11 17:46:28 +01:00
1 parent e3c9eae65b
commit 98ee504dab
9 files changed
+636 -72

No files matched your search

+6 -2
View File
@@ -95,9 +95,13 @@ internal sealed record Overview(
}; };
var series = daily.Where(p => p.Day >= start.Day).ToList(); var series = daily.Where(p => p.Day >= start.Day).ToList();
var cells = new List<PeriodResult> { Between("Oggi", Since(1)), Between("Ultimi 7 giorni", Since(7)), Between("Ultimi 30 giorni", Since(30)) }; var cells = new List<PeriodResult> { Between("Oggi", Since(1)), Between("Ultimi 7 giorni", Since(7)), Between("Ultimi 30 giorni", Since(30)) };
if (daily[0].Benchmark is { } firstBenchmark && latest.Benchmark is { } lastBenchmark && firstBenchmark != 0) // "Senza bot" since the first day it is known, with the same flows taken out as for the bot (SPEC 7.5).
if (daily.FirstOrDefault(p => p.Benchmark is not null) is { Benchmark: { } firstBenchmark } first && latest.Benchmark is { } lastBenchmark)
{ {
cells.Add(new PeriodResult("Senza bot", lastBenchmark - firstBenchmark, (lastBenchmark - firstBenchmark) / firstBenchmark * 100m)); var flows = latest.Flows - first.Flows;
var amount = lastBenchmark - firstBenchmark - flows;
var basis = firstBenchmark + flows;
cells.Add(new PeriodResult("Senza bot", amount, basis == 0m ? 0m : amount / basis * 100m));
} }
return new Overview(daily, series, Between("", start), start.Day, start.Equity, cells, (int)positions, (int)withoutStop, (int)orders, next, last, capitalSet); return new Overview(daily, series, Between("", start), start.Day, start.Equity, cells, (int)positions, (int)withoutStop, (int)orders, next, last, capitalSet);
+1 -58
View File
@@ -12,63 +12,6 @@ namespace Anubis.Server;
/// </summary> /// </summary>
internal static class ReasonTexts internal static class ReasonTexts
{ {
private static readonly Dictionary<string, string> Texts = new(StringComparer.Ordinal)
{
// Strategies.
["trend_entry"] = "La chiusura ha superato i massimi recenti su almeno un orizzonte: è iniziata una tendenza al rialzo.",
["trend_increase"] = "Più orizzonti erano d'accordo sulla tendenza: il peso è salito.",
["trend_reduce"] = "La tendenza si è indebolita, o la moneta è diventata più agitata: il peso è sceso.",
["trend_exit"] = "La tendenza si è interrotta: il prezzo è finito sotto lo stop mobile.",
["trend_stop"] = "Lo stop mobile è salito con il prezzo.",
["momentum_entry"] = "Era tra i titoli più forti degli ultimi mesi, con il mercato in salita.",
["momentum_increase"] = "Il peso obiettivo è salito alla revisione settimanale.",
["momentum_reduce"] = "Il peso obiettivo è sceso alla revisione settimanale.",
["momentum_exit_rank"] = "Non era più tra i 30 titoli più forti.",
["momentum_exit_trend"] = "Il mercato nel suo insieme è girato al ribasso: niente più azioni.",
["momentum_stop"] = "Lo stop di protezione è stato aggiornato.",
["meanrev_entry"] = "Era sceso per qualche seduta di fila ma restava sopra la sua media a 200 giorni: un ribasso breve di un titolo che nel lungo periodo sale.",
["meanrev_exit_average"] = "Il prezzo è tornato sopra la media a 5 giorni: il rimbalzo cercato è arrivato.",
["meanrev_exit_rsi"] = "L'indicatore di forza è tornato alto: il rimbalzo è avvenuto.",
["meanrev_exit_earnings"] = "Uscita prima della trimestrale.",
["meanrev_exit_time"] = "Tempo scaduto: nessun rimbalzo in 5 sedute.",
// Exits recorded on the trade.
["stop"] = "Stop di protezione raggiunto.",
["exit"] = "Uscita decisa dalla strategia.",
["signal"] = "Uscita sul segnale della strategia.",
["residue"] = "Resto troppo piccolo per essere venduto, tolto dal registro.",
["adjustment"] = "Rettifica dopo l'allineamento con il conto.",
// Correctives.
["crypto_regime_below_average"] = "Il mercato crypto era sotto la sua media: acquisti ridotti.",
["crypto_regime_high_volatility"] = "Il mercato crypto era molto agitato: acquisti ridotti.",
["calendar_event"] = "Un dato economico importante era vicino: niente nuove posizioni in quell'ora.",
// Risk.
["risk_reduction"] = "Ordine rimpicciolito dai limiti di rischio.",
["daily_loss_block"] = "Perdita del giorno oltre il limite: niente nuovi ingressi per 24 ore.",
["switch_tripped"] = "Interruttore scattato: il bot aspetta la tua conferma.",
["bot_paused"] = "Bot in pausa: niente nuovi ingressi.",
["bot_stopped"] = "Bot fermato con \"Ferma tutto\".",
["invested_limit"] = "Capitale investito al limite: niente soldi presi in prestito.",
["position_limit"] = "Ridotto al peso massimo di una posizione.",
["crypto_limit"] = "Quota delle crypto sul totale al limite.",
["trade_risk_limit"] = "Ridotto perché il rischio dell'operazione restasse entro il limite.",
["stop_above_price"] = "Stop sopra il prezzo: ordine rifiutato.",
["stale_price"] = "Prezzo troppo vecchio: niente acquisti finché i dati non tornano freschi.",
["price_gap"] = "Prezzo dell'ordine troppo lontano dall'ultimo prezzo.",
["clock_skew"] = "Orologio non allineato con quello del broker.",
["owned_by_other_strategy"] = "La posizione appartiene a un'altra strategia.",
["no_short_selling"] = "Niente vendite allo scoperto: venduto solo quanto posseduto.",
["no_leverage"] = "Niente leva: l'ordine sta nella liquidità disponibile.",
["not_owned_by_bot"] = "La posizione non è del bot: non la tocca.",
["live_not_confirmed"] = "Soldi veri non confermati per questa strategia.",
["exit_only"] = "Strategia in sola uscita: niente nuovi acquisti.",
["live_not_allowed"] = "Soldi veri non permessi dalla configurazione d'avvio.",
["observation"] = "Strategia in osservazione: produce segnali, nessun ordine.",
["orders_per_minute"] = "Troppi ordini in un minuto: il bot si è fermato.",
["pdt_guard"] = "Guardia sulle operazioni in giornata: niente posizioni in più oggi.",
["no_fx_rate"] = "Manca il cambio euro-dollaro: niente acquisti in dollari.",
["unknown_instrument"] = "Strumento sconosciuto.",
};
// The exits in the few words of a table column; the full sentence stays for the "why" card. // The exits in the few words of a table column; the full sentence stays for the "why" card.
private static readonly Dictionary<string, string> ShortExits = new(StringComparer.Ordinal) private static readonly Dictionary<string, string> ShortExits = new(StringComparer.Ordinal)
{ {
@@ -85,7 +28,7 @@ internal static class ReasonTexts
/// <summary>Why a trade was closed, in a short sentence.</summary> /// <summary>Why a trade was closed, in a short sentence.</summary>
public static string Exit(string? code) => code is null ? "Chiusa" : ShortExits.TryGetValue(code, out var text) ? text : Text(code).TrimEnd('.'); public static string Exit(string? code) => code is null ? "Chiusa" : ShortExits.TryGetValue(code, out var text) ? text : Text(code).TrimEnd('.');
public static string Text(string code) => Texts.TryGetValue(code, out var text) ? text : code; public static string Text(string code) => ReasonCatalog.Text(code);
/// <summary>The lines of one stage of a decision. <paramref name="data"/> is the JSON of the numbers the stage used.</summary> /// <summary>The lines of one stage of a decision. <paramref name="data"/> is the JSON of the numbers the stage used.</summary>
public static IEnumerable<WhyLine> Stage(string stage, string outcome, IReadOnlyList<string> reasons, string? data) public static IEnumerable<WhyLine> Stage(string stage, string outcome, IReadOnlyList<string> reasons, string? data)
+5
View File
@@ -8,7 +8,12 @@ namespace Anubis.Trading;
public static class DiaryKinds public static class DiaryKinds
{ {
public const string Orders = "Ordini"; public const string Orders = "Ordini";
public const string Decisions = "Decisioni";
public const string System = "Sistema"; public const string System = "Sistema";
public const string News = "Notizie";
public const string Learning = "Apprendimento";
public static readonly IReadOnlyList<string> All = [Orders, Decisions, System, News, Learning];
} }
/// <summary> /// <summary>
+237
View File
@@ -0,0 +1,237 @@
using Anubis.Core;
using Anubis.Data;
namespace Anubis.Trading;
/// <summary>
/// The fixed templates of the diary (SPEC 5.2, 13.3, appendix B): one main sentence and, when it helps, a second
/// one with the reason. Short form without a subject for what was done ("Alzato lo stop di BTC/EUR"), first person
/// for what the bot does or did ("Sono stato fermo"). Never free text written at decision time.
/// </summary>
public static class DiaryText
{
/// <summary>A symbol as the user reads it: <c>BTC/EUR</c> for the pair <c>BTC-EUR</c>, <c>AAPL</c> as it is.</summary>
public static string Shown(string symbol)
{
ArgumentNullException.ThrowIfNull(symbol);
return symbol.Replace('-', '/');
}
/// <summary>The coin of a pair: <c>BTC</c> for <c>BTC-EUR</c>.</summary>
public static string Coin(string symbol)
{
ArgumentNullException.ThrowIfNull(symbol);
var dash = symbol.IndexOf('-', StringComparison.Ordinal);
return dash > 0 ? symbol[..dash] : symbol;
}
/// <summary>"BTC, ETH e SOL".</summary>
public static string List(IEnumerable<string> items)
{
ArgumentNullException.ThrowIfNull(items);
var list = items.ToList();
return list.Count switch
{
0 => "",
1 => list[0],
_ => string.Join(", ", list.Take(list.Count - 1)) + " e " + list[^1],
};
}
/// <summary>A stop or a price level in a sentence: no decimals from 1,000 up (65.400 €), the price's own below.</summary>
public static string Level(decimal value, string currency) =>
Math.Abs(value) >= 1000m ? Format.Money(value, currency, decimals: 0) : Format.Number(value, Math.Abs(value) >= 1m ? 2 : 4) + " " + Format.CurrencySymbol(currency);
/// <summary>
/// A fill: "Comprate 2 AAPL a 259,80 $." and, for a sale that closes the trade, its result: "Venduta 1 MSFT a
/// 522,14 $: +9,84 $ in 3 giorni." <paramref name="reason"/> is the second sentence, from a reason code.
/// </summary>
public static string Fill(OrderSide side, decimal quantity, string symbol, bool crypto, decimal price, string currency, string? reason = null, ClosedTrade? closed = null)
{
var buy = side == OrderSide.Buy;
var one = quantity == 1m;
var verb = (buy, crypto, one) switch
{
(true, true, true) => "Comprato",
(true, true, false) => "Comprati",
(true, false, true) => "Comprata",
(true, false, false) => "Comprate",
(false, true, true) => "Venduto",
(false, true, false) => "Venduti",
(false, false, true) => "Venduta",
(false, false, false) => "Vendute",
};
var text = $"{verb} {Format.Quantity(quantity)} {Shown(symbol)} a {Format.Price(price)} {Format.CurrencySymbol(currency)}";
if (closed is not null)
{
text += $": {Format.Money(closed.Result, currency, withSign: true)} {Days(closed.Days)}";
}
return text + "." + (string.IsNullOrWhiteSpace(reason) ? "" : " " + reason.Trim());
}
/// <summary>"in 3 giorni", "in 1 giorno", "in giornata".</summary>
public static string Days(int days) => days switch
{
<= 0 => "in giornata",
1 => "in 1 giorno",
_ => $"in {days} giorni",
};
public static string StopRaised(string symbol, decimal from, decimal to, string currency) =>
$"Alzato lo stop di {Shown(symbol)} da {Level(from, currency)} a {Level(to, currency)}. Lo stop segue il prezzo quando sale.";
public static string StopsReplaced(int count) => count == 1
? "Rimesso 1 stop giornaliero sulle frazioni di azione."
: $"Rimessi {count} stop giornalieri sulle frazioni di azione.";
/// <summary>
/// The daily crypto close (SPEC 5.5): what changes, what stays in trend, what stays out. "Chiusura giornaliera
/// crypto: nessun cambio. BTC, ETH e SOL restano in tendenza. Le altre 7 monete restano fuori: nessuna ha segnato
/// nuovi massimi."
/// </summary>
public static string CryptoClose(DecisionSummary summary)
{
ArgumentNullException.ThrowIfNull(summary);
var head = "Chiusura giornaliera crypto: " + Changes(summary, Coin) + ".";
var staying = summary.Held.Select(Coin).ToList();
if (staying.Count > 0)
{
head += staying.Count == 1 ? $" {staying[0]} resta in tendenza." : $" {List(staying)} restano in tendenza.";
}
if (summary.Outside > 0)
{
head += summary.Outside == 1
? " L'altra moneta resta fuori: non ha segnato nuovi massimi."
: $" {(staying.Count + summary.Bought.Count > 0 ? "Le altre" : "Le")} {summary.Outside} monete restano fuori: nessuna ha segnato nuovi massimi.";
}
return head;
}
/// <summary>
/// The stock signals after the close: "Azioni: nessun nuovo acquisto. AAPL resta aperta." or "Azioni: domani
/// compro AAPL e MSFT, vendo JPM."
/// </summary>
public static string StockSignals(DecisionSummary summary)
{
ArgumentNullException.ThrowIfNull(summary);
var head = summary.HasChanges ? "Azioni: domani " + Changes(summary, s => s) + "." : "Azioni: nessun nuovo acquisto.";
if (summary.Held.Count > 0)
{
head += summary.Held.Count == 1 ? $" {summary.Held[0]} resta aperta." : $" {List(summary.Held)} restano aperte.";
}
return head;
}
/// <summary>A strategy in observation: the signal is recorded, no order leaves (SPEC 12.3).</summary>
public static string Observed(string strategy, DecisionSummary summary)
{
ArgumentNullException.ThrowIfNull(summary);
var label = StrategyNames.Label(strategy, withMarket: true);
return summary.HasChanges
? $"{label}, in osservazione: avrei {Conditional(summary)}. Nessun ordine: registro solo il segnale."
: $"{label}, in osservazione: nessun cambio. Registro solo il segnale.";
}
/// <summary>A strategy whose decision could not be made: the data was missing, nothing was bought.</summary>
public static string NoData(string strategy, string what) =>
$"{StrategyNames.Label(strategy, withMarket: true)}: nessuna decisione oggi. Mancano {what}: non apro nuove posizioni.";
/// <summary>A missed job done at the restart (SPEC 5.6).</summary>
public static string Recovered(string what, DateTimeOffset due, TimeZoneInfo zone) =>
$"Recuperato un lavoro saltato: {what} (previsto alle {TimeZoneInfo.ConvertTime(due, zone):HH:mm}).";
/// <summary>A missed job left out at the restart, with its reason (SPEC 5.6).</summary>
public static string Skipped(string what, string reason) => $"Saltato: {what}. {reason}";
/// <summary>An entry left out because the price moved too far from the planned one (SPEC 5.6).</summary>
public static string EntryDropped(string symbol, decimal movedPercent, decimal limitPercent) =>
$"Scartato l'acquisto di {Shown(symbol)}: il prezzo si è mosso del {Format.Percent(movedPercent, 1)} dall'orario previsto, oltre il limite del {Format.Percent(limitPercent, 0)}.";
/// <summary>The restart after an absence (SPEC 5.6, 9.4).</summary>
public static string Absence(TimeSpan absence) => $"Sono stato fermo per {Duration(absence)}. Ho ripreso i lavori saltati con le regole del recupero.";
/// <summary>"3 ore e 5 minuti", "2 giorni e 4 ore", "12 minuti".</summary>
public static string Duration(TimeSpan span)
{
static string Unit(int n, string one, string many) => n == 1 ? $"1 {one}" : $"{n} {many}";
if (span.TotalDays >= 1)
{
var days = (int)span.TotalDays;
return span.Hours > 0 ? $"{Unit(days, "giorno", "giorni")} e {Unit(span.Hours, "ora", "ore")}" : Unit(days, "giorno", "giorni");
}
if (span.TotalHours >= 1)
{
var hours = (int)span.TotalHours;
return span.Minutes > 0 ? $"{Unit(hours, "ora", "ore")} e {Unit(span.Minutes, "minuto", "minuti")}" : Unit(hours, "ora", "ore");
}
return Unit(Math.Max(1, (int)Math.Round(span.TotalMinutes)), "minuto", "minuti");
}
private static string Changes(DecisionSummary s, Func<string, string> name)
{
var parts = new List<string>();
if (s.Bought.Count > 0)
{
parts.Add("compro " + List(s.Bought.Select(name)));
}
if (s.Increased.Count > 0)
{
parts.Add("aumento " + List(s.Increased.Select(name)));
}
if (s.Reduced.Count > 0)
{
parts.Add("riduco " + List(s.Reduced.Select(name)));
}
if (s.Sold.Count > 0)
{
parts.Add("vendo " + List(s.Sold.Select(name)));
}
return parts.Count == 0 ? "nessun cambio" : string.Join(", ", parts);
}
private static string Conditional(DecisionSummary s)
{
var parts = new List<string>();
if (s.Bought.Count > 0)
{
parts.Add("comprato " + List(s.Bought.Select(Shown)));
}
if (s.Increased.Count > 0)
{
parts.Add("aumentato " + List(s.Increased.Select(Shown)));
}
if (s.Reduced.Count > 0)
{
parts.Add("ridotto " + List(s.Reduced.Select(Shown)));
}
if (s.Sold.Count > 0)
{
parts.Add("venduto " + List(s.Sold.Select(Shown)));
}
return string.Join(", ", parts);
}
}
/// <summary>The result of a trade a sale has just closed: for the diary line of the fill.</summary>
public sealed record ClosedTrade(decimal Result, int Days);
/// <summary>What one decision changes, by symbol: the material of the diary's decision lines.</summary>
public sealed record DecisionSummary(IReadOnlyList<string> Bought, IReadOnlyList<string> Increased, IReadOnlyList<string> Reduced, IReadOnlyList<string> Sold,
IReadOnlyList<string> Held, int Outside)
{
public bool HasChanges => Bought.Count + Increased.Count + Reduced.Count + Sold.Count > 0;
}
+36 -8
View File
@@ -55,7 +55,10 @@ public static class Returns
public sealed class EquityBook(Database db, IClock clock, Ledger ledger, FxStore fx) public sealed class EquityBook(Database db, IClock clock, Ledger ledger, FxStore fx)
{ {
private sealed record Shot(string Scope, string World, Guid? AccountId, string? Strategy, string Currency, decimal Equity, decimal Cash, decimal Invested, decimal Flows, private sealed record Shot(string Scope, string World, Guid? AccountId, string? Strategy, string Currency, decimal Equity, decimal Cash, decimal Invested, decimal Flows,
decimal? FxEffect); decimal? FxEffect)
{
public decimal? Benchmark { get; init; }
}
public async Task<int> TakeAsync(CancellationToken cancellationToken) public async Task<int> TakeAsync(CancellationToken cancellationToken)
{ {
@@ -84,10 +87,13 @@ public sealed class EquityBook(Database db, IClock clock, Ledger ledger, FxStore
} }
var rate = await UsdRateAsync(DateOnly.FromDateTime(now.UtcDateTime), cancellationToken).ConfigureAwait(false); var rate = await UsdRateAsync(DateOnly.FromDateTime(now.UtcDateTime), cancellationToken).ConfigureAwait(false);
var flowRows = await db.ReadAsync(s => s.QueryAsync("SELECT account_id, kind, amount, currency, created_at FROM cash_ledger WHERE strategy IS NOT NULL", var flowRows = await db.ReadAsync(s => s.QueryAsync("SELECT account_id, strategy, kind, amount, currency, created_at FROM cash_ledger WHERE strategy IS NOT NULL",
r => (Account: r.Id("account_id"), Kind: r.Text("kind"), Amount: r.Money("amount"), Currency: r.Text("currency"), At: r.Moment("created_at"))), cancellationToken) r => (Account: r.Id("account_id"), Strategy: r.Text("strategy"), Kind: r.Text("kind"), Amount: r.Money("amount"), Currency: r.Text("currency"), At: r.Moment("created_at"))), cancellationToken)
.ConfigureAwait(false); .ConfigureAwait(false);
foreach (var world in shots.Where(s => s.Scope == "account").GroupBy(s => s.World)) Func<DateOnly, (decimal Bitcoin, decimal Stock)?>? prices = null;
var pricesLoaded = false;
var today = DateOnly.FromDateTime(now.UtcDateTime);
foreach (var world in shots.Where(s => s.Scope == "account").GroupBy(s => s.World).ToList())
{ {
var usd = world.Where(s => s.Currency == "USD").ToList(); var usd = world.Where(s => s.Currency == "USD").ToList();
if (usd.Count > 0 && rate is null) if (usd.Count > 0 && rate is null)
@@ -102,11 +108,33 @@ public sealed class EquityBook(Database db, IClock clock, Ledger ledger, FxStore
usdFlows.Add((row.Amount, await UsdRateAsync(DateOnly.FromDateTime(row.At.UtcDateTime), cancellationToken).ConfigureAwait(false) ?? rate!.Value)); usdFlows.Add((row.Amount, await UsdRateAsync(DateOnly.FromDateTime(row.At.UtcDateTime), cancellationToken).ConfigureAwait(false) ?? rate!.Value));
} }
// The "senza bot" comparison gets the same flows, each on its day and in euro at that day's rate (SPEC 7.5).
var included = shots.Where(s => s.Scope == "strategy" && s.World == world.Key && !twins.Contains((s.Strategy!, s.AccountId!.Value)))
.Select(s => (s.AccountId!.Value, s.Strategy!)).ToHashSet();
var dated = new List<(DateOnly Day, decimal AmountEur)>();
foreach (var row in flowRows.Where(f => LedgerKinds.IsFlow(f.Kind) && included.Contains((f.Account, f.Strategy))))
{
var day = DateOnly.FromDateTime(row.At.UtcDateTime);
var amount = row.Currency == "USD"
? row.Amount / (await UsdRateAsync(day, cancellationToken).ConfigureAwait(false) ?? rate!.Value)
: row.Amount;
dated.Add((day, amount));
}
if (!pricesLoaded && dated.Count > 0)
{
pricesLoaded = true;
prices = await NoBot.PricesAsync(db, clock, dated.Min(d => d.Day), today, cancellationToken).ConfigureAwait(false);
}
var benchmark = prices is null ? null : NoBot.Value(dated, prices, today);
decimal ToEur(Shot s, decimal value) => s.Currency == "USD" ? value / rate!.Value : value; decimal ToEur(Shot s, decimal value) => s.Currency == "USD" ? value / rate!.Value : value;
var eurFlows = world.Where(s => s.Currency != "USD").Sum(s => s.Flows) + usdFlows.Sum(f => f.AmountUsd / f.Rate); var eurFlows = world.Where(s => s.Currency != "USD").Sum(s => s.Flows) + usdFlows.Sum(f => f.AmountUsd / f.Rate);
shots.Add(new Shot("total", world.Key, null, null, "EUR", shots.Add(new Shot("total", world.Key, null, null, "EUR",
DbValues.Money(world.Sum(s => ToEur(s, s.Equity))), DbValues.Money(world.Sum(s => ToEur(s, s.Cash))), DbValues.Money(world.Sum(s => ToEur(s, s.Invested))), DbValues.Money(world.Sum(s => ToEur(s, s.Equity))), DbValues.Money(world.Sum(s => ToEur(s, s.Cash))), DbValues.Money(world.Sum(s => ToEur(s, s.Invested))),
DbValues.Money(eurFlows), usd.Count > 0 ? DbValues.Money(Returns.FxEffect(usdFlows, rate!.Value)) : null)); DbValues.Money(eurFlows), usd.Count > 0 ? DbValues.Money(Returns.FxEffect(usdFlows, rate!.Value)) : null)
{ Benchmark = benchmark });
} }
await db.WriteAsync(async s => await db.WriteAsync(async s =>
@@ -119,10 +147,10 @@ public sealed class EquityBook(Database db, IClock clock, Ledger ledger, FxStore
var peak = Math.Max(previous?.Peak ?? index, index); var peak = Math.Max(previous?.Peak ?? index, index);
var drawdown = peak <= 0m ? 0m : Math.Round((index / peak - 1m) * 100m, 4, MidpointRounding.AwayFromZero); var drawdown = peak <= 0m ? 0m : Math.Round((index / peak - 1m) * 100m, 4, MidpointRounding.AwayFromZero);
await s.ExecuteAsync( await s.ExecuteAsync(
"INSERT INTO equity_snapshots (id, taken_at, scope, account_id, strategy, equity, cash, invested, drawdown_pct, created_at, world, currency, flows, twr_index, peak_index, fx_effect) " + "INSERT INTO equity_snapshots (id, taken_at, scope, account_id, strategy, equity, cash, invested, drawdown_pct, created_at, world, currency, flows, twr_index, peak_index, fx_effect, benchmark) " +
"VALUES (@id, @now, @sc, @a, @st, @e, @c, @i, @d, @now, @w, @cur, @f, @x, @p, @fx)", cancellationToken, "VALUES (@id, @now, @sc, @a, @st, @e, @c, @i, @d, @now, @w, @cur, @f, @x, @p, @fx, @b)", cancellationToken,
("id", Ids.NewId(clock)), ("now", now), ("sc", shot.Scope), ("a", shot.AccountId), ("st", shot.Strategy), ("e", shot.Equity), ("c", shot.Cash), ("i", shot.Invested), ("id", Ids.NewId(clock)), ("now", now), ("sc", shot.Scope), ("a", shot.AccountId), ("st", shot.Strategy), ("e", shot.Equity), ("c", shot.Cash), ("i", shot.Invested),
("d", drawdown), ("w", shot.World), ("cur", shot.Currency), ("f", shot.Flows), ("x", index), ("p", peak), ("fx", shot.FxEffect)).ConfigureAwait(false); ("d", drawdown), ("w", shot.World), ("cur", shot.Currency), ("f", shot.Flows), ("x", index), ("p", peak), ("fx", shot.FxEffect), ("b", shot.Benchmark)).ConfigureAwait(false);
} }
}, cancellationToken).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false);
return shots.Count; return shots.Count;
+113
View File
@@ -0,0 +1,113 @@
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
namespace Anubis.Trading;
/// <summary>
/// The "senza bot" comparison (SPEC 7.5): the same capital, with the same flows, put 40% in Bitcoin (BTC/EUR) and
/// 60% in the S&amp;P 500 (SPY adjusted for dividends and splits, in euro at the ECB rate) and never touched. Every
/// deposit buys the two in that proportion on its day; a withdrawal sells both in the proportion they have reached.
/// Prices are the daily closes of the days before: a deposit on Tuesday buys at Monday's close, and the value on
/// Wednesday uses Tuesday's. A close is final only when its day is over, so the comparison moves once a day.
/// </summary>
public static class NoBot
{
public const decimal BitcoinShare = 0.40m;
public const decimal StockShare = 0.60m;
public const string BitcoinSymbol = "BTC-EUR";
public const string StockSymbol = "SPY";
/// <summary>
/// The value in euro on <paramref name="today"/> of the untouched portfolio. Null when there are no flows or a
/// price is missing on a day that needs it: a comparison with a hole would not be honest.
/// </summary>
public static decimal? Value(IEnumerable<(DateOnly Day, decimal AmountEur)> flows, Func<DateOnly, (decimal Bitcoin, decimal Stock)?> prices, DateOnly today)
{
ArgumentNullException.ThrowIfNull(flows);
ArgumentNullException.ThrowIfNull(prices);
decimal bitcoin = 0m, stock = 0m;
var any = false;
foreach (var (day, amount) in flows.Where(f => f.AmountEur != 0m).OrderBy(f => f.Day))
{
if (prices(day) is not { Bitcoin: > 0m, Stock: > 0m } p)
{
return null;
}
any = true;
if (amount > 0m)
{
bitcoin += BitcoinShare * amount / p.Bitcoin;
stock += StockShare * amount / p.Stock;
continue;
}
var value = bitcoin * p.Bitcoin + stock * p.Stock;
var keep = value <= 0m ? 0m : Math.Max(0m, 1m + amount / value);
bitcoin *= keep;
stock *= keep;
}
return any && prices(today) is { Bitcoin: > 0m, Stock: > 0m } now ? DbValues.Money(bitcoin * now.Bitcoin + stock * now.Stock) : null;
}
/// <summary>
/// The daily closes the comparison needs, from the database: BTC-EUR on OKX, SPY on Alpaca with its corporate
/// actions, the ECB rate. Null when one of the series is missing (no Alpaca keys means no SPY history).
/// </summary>
public static async Task<Func<DateOnly, (decimal Bitcoin, decimal Stock)?>?> PricesAsync(Database db, IClock clock, DateOnly from, DateOnly to, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(db);
var catalog = new InstrumentCatalog(db, clock);
var bars = new BarStore(db, clock);
var btc = await catalog.FindAsync(Venues.Okx, BitcoinSymbol, cancellationToken).ConfigureAwait(false);
var spy = await catalog.FindAsync(Venues.Alpaca, StockSymbol, cancellationToken).ConfigureAwait(false);
if (btc is null || spy is null)
{
return null;
}
// A week before the first flow: a deposit on a Monday uses Friday's close.
var start = from.AddDays(-10);
var bitcoin = (await bars.DailyAsync(btc.Id, start, to, cancellationToken).ConfigureAwait(false)).Select(b => (b.Day, Close: (decimal)b.Close)).ToList();
var rawStock = await bars.DailyAsync(spy.Id, start, to, cancellationToken).ConfigureAwait(false);
var actions = await new CorporateActionStore(db, clock).ForSymbolAsync(StockSymbol, cancellationToken).ConfigureAwait(false);
var stock = rawStock.Count == 0 ? [] : Adjustments.Anchored(rawStock, actions, rawStock[^1].Day).Select(b => (b.Day, Close: (decimal)(b.Adjusted?.Close ?? b.Close))).ToList();
var rates = await db.ReadAsync(s => s.QueryAsync("SELECT rate_date, rate FROM fx_rates WHERE base = 'EUR' AND quote = 'USD' AND rate_date >= @f AND rate_date <= @t ORDER BY rate_date",
r => (Day: BarStore.ParseDay(r.Text("rate_date")), Rate: r.Money("rate")), ("f", BarStore.DayText(start.AddDays(-10))), ("t", BarStore.DayText(to))), cancellationToken).ConfigureAwait(false);
if (bitcoin.Count == 0 || stock.Count == 0 || rates.Count == 0)
{
return null;
}
var rateSeries = rates.Select(x => (x.Day, x.Rate)).ToList();
return day =>
{
var known = day.AddDays(-1);
var b = OnOrBefore(bitcoin, known);
var s = OnOrBefore(stock, known);
var r = OnOrBefore(rateSeries, known);
return b is null || s is null || r is not > 0m ? null : (b.Value, s.Value / r.Value);
};
}
private static decimal? OnOrBefore(List<(DateOnly Day, decimal Value)> series, DateOnly day)
{
decimal? found = null;
foreach (var (d, v) in series)
{
if (d > day)
{
break;
}
found = v;
}
return found;
}
}
+19 -4
View File
@@ -766,10 +766,25 @@ public sealed partial class OrderManager : IDisposable
recorded++; recorded++;
var instrument = await _instruments(row.InstrumentId, cancellationToken).ConfigureAwait(false); var instrument = await _instruments(row.InstrumentId, cancellationToken).ConfigureAwait(false);
await _db.WriteAsync(s => Diary.WriteAsync(s, _clock, DiaryKinds.Orders, "fill", await _db.WriteAsync(async s =>
string.Create(CultureInfo.InvariantCulture, {
$"{(fill.Side == OrderSide.Buy ? "Comprati" : "Venduti")} {Format.Quantity(fill.Quantity)} {instrument?.Symbol} a {Format.Price(fill.Price)} su {_account.Name}."), // A sale that closes the trade says its result (appendix F.10: "Venduta 1 MSFT a 522,14 $: +9,84 $ in 3 giorni").
new { fill.ExecutionId, row.ClientOrderId, outcome.SlippageBp }, cancellationToken), cancellationToken).ConfigureAwait(false); ClosedTrade? closed = null;
if (outcome.TradeClosed && outcome.TradeId is { } tradeId)
{
var trade = await s.FirstOrDefaultAsync("SELECT realized, opened_at, closed_at FROM trades WHERE id = @id",
r => (Realized: r.Money("realized"), Opened: r.Moment("opened_at"), Closed: r.MomentOrNull("closed_at")), ("id", tradeId)).ConfigureAwait(false);
if (trade.Closed is { } closedAt)
{
closed = new ClosedTrade(trade.Realized, (DateOnly.FromDateTime(closedAt.UtcDateTime).DayNumber - DateOnly.FromDateTime(trade.Opened.UtcDateTime).DayNumber));
}
}
var reason = fill.Side == OrderSide.Sell && row.Purpose is OrderPurpose.Stop or OrderPurpose.Protective ? ReasonCatalog.Text("stop") : null;
await Diary.WriteAsync(s, _clock, DiaryKinds.Orders, "fill",
DiaryText.Fill(fill.Side, fill.Quantity, instrument?.Symbol ?? "?", instrument?.IsCrypto ?? false, fill.Price, _account.Currency, reason, closed),
new { fill.ExecutionId, row.ClientOrderId, outcome.SlippageBp, outcome.TradeId, Account = _account.Name }, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
if (row.Purpose == OrderPurpose.Stop && outcome.Quantity > 0m && instrument is not null) if (row.Purpose == OrderPurpose.Stop && outcome.Quantity > 0m && instrument is not null)
{ {
// A stop that fired only in part, or one of Alpaca's two stops: the rest is sold at once (SPEC 7.2). // A stop that fired only in part, or one of Alpaca's two stops: the rest is sold at once (SPEC 7.2).
+83
View File
@@ -0,0 +1,83 @@
namespace Anubis.Trading;
/// <summary>
/// The fixed sentences of the reason codes of the decisions table (SPEC 5.2): the "why" card of a trade and the
/// diary use these, never free text written at decision time. An unknown code is shown as it is, so nothing is ever
/// hidden.
/// </summary>
public static class ReasonCatalog
{
private static readonly Dictionary<string, string> Texts = new(StringComparer.Ordinal)
{
// Strategies.
["trend_entry"] = "La chiusura ha superato i massimi recenti su almeno un orizzonte: è iniziata una tendenza al rialzo.",
["trend_increase"] = "Più orizzonti erano d'accordo sulla tendenza: il peso è salito.",
["trend_reduce"] = "La tendenza si è indebolita, o la moneta è diventata più agitata: il peso è sceso.",
["trend_exit"] = "La tendenza si è interrotta: il prezzo è finito sotto lo stop mobile.",
["trend_stop"] = "Lo stop mobile è salito con il prezzo.",
["momentum_entry"] = "Era tra i titoli più forti degli ultimi mesi, con il mercato in salita.",
["momentum_increase"] = "Il peso obiettivo è salito alla revisione settimanale.",
["momentum_reduce"] = "Il peso obiettivo è sceso alla revisione settimanale.",
["momentum_exit_rank"] = "Non era più tra i 30 titoli più forti.",
["momentum_exit_trend"] = "Il mercato nel suo insieme è girato al ribasso: niente più azioni.",
["momentum_stop"] = "Lo stop di protezione è stato aggiornato.",
["meanrev_entry"] = "Era sceso per qualche seduta di fila ma restava sopra la sua media a 200 giorni: un ribasso breve di un titolo che nel lungo periodo sale.",
["meanrev_exit_average"] = "Il prezzo è tornato sopra la media a 5 giorni: il rimbalzo cercato è arrivato.",
["meanrev_exit_rsi"] = "L'indicatore di forza è tornato alto: il rimbalzo è avvenuto.",
["meanrev_exit_earnings"] = "Uscita prima della trimestrale.",
["meanrev_exit_time"] = "Tempo scaduto: nessun rimbalzo in 5 sedute.",
// Exits recorded on the trade.
["stop"] = "Stop di protezione raggiunto.",
["exit"] = "Uscita decisa dalla strategia.",
["signal"] = "Uscita sul segnale della strategia.",
["residue"] = "Resto troppo piccolo per essere venduto, tolto dal registro.",
["adjustment"] = "Rettifica dopo l'allineamento con il conto.",
// Correctives.
["crypto_regime_below_average"] = "Il mercato crypto era sotto la sua media: acquisti ridotti.",
["crypto_regime_high_volatility"] = "Il mercato crypto era molto agitato: acquisti ridotti.",
["calendar_event"] = "Un dato economico importante era vicino: niente nuove posizioni in quell'ora.",
// Risk.
["risk_reduction"] = "Ordine rimpicciolito dai limiti di rischio.",
["daily_loss_block"] = "Perdita del giorno oltre il limite: niente nuovi ingressi per 24 ore.",
["switch_tripped"] = "Interruttore scattato: il bot aspetta la tua conferma.",
["bot_paused"] = "Bot in pausa: niente nuovi ingressi.",
["bot_stopped"] = "Bot fermato con \"Ferma tutto\".",
["invested_limit"] = "Capitale investito al limite: niente soldi presi in prestito.",
["position_limit"] = "Ridotto al peso massimo di una posizione.",
["crypto_limit"] = "Quota delle crypto sul totale al limite.",
["trade_risk_limit"] = "Ridotto perché il rischio dell'operazione restasse entro il limite.",
["stop_above_price"] = "Stop sopra il prezzo: ordine rifiutato.",
["stale_price"] = "Prezzo troppo vecchio: niente acquisti finché i dati non tornano freschi.",
["price_gap"] = "Prezzo dell'ordine troppo lontano dall'ultimo prezzo.",
["clock_skew"] = "Orologio non allineato con quello del broker.",
["owned_by_other_strategy"] = "La posizione appartiene a un'altra strategia.",
["no_short_selling"] = "Niente vendite allo scoperto: venduto solo quanto posseduto.",
["no_leverage"] = "Niente leva: l'ordine sta nella liquidità disponibile.",
["not_owned_by_bot"] = "La posizione non è del bot: non la tocca.",
["live_not_confirmed"] = "Soldi veri non confermati per questa strategia.",
["exit_only"] = "Strategia in sola uscita: niente nuovi acquisti.",
["live_not_allowed"] = "Soldi veri non permessi dalla configurazione d'avvio.",
["observation"] = "Strategia in osservazione: produce segnali, nessun ordine.",
["orders_per_minute"] = "Troppi ordini in un minuto: il bot si è fermato.",
["pdt_guard"] = "Guardia sulle operazioni in giornata: niente posizioni in più oggi.",
["no_fx_rate"] = "Manca il cambio euro-dollaro: niente acquisti in dollari.",
["unknown_instrument"] = "Strumento sconosciuto.",
["unknown_symbol"] = "Strumento sconosciuto.",
// Orders.
["zero_quantity"] = "Quantità troppo piccola: nessun ordine.",
["below_min_size"] = "Sotto la quantità minima del broker: nessun ordine.",
["below_min_notional"] = "Sotto l'importo minimo del broker: nessun ordine.",
["no_price"] = "Nessun prezzo recente: nessun ordine.",
["instrument_not_live"] = "Lo strumento non si può negoziare in questo momento.",
["account_prudent"] = "Conto in modalità prudente: niente nuovi ingressi.",
["not_ours"] = "L'ordine non è del bot: non lo tocca.",
["no_cash"] = "Liquidità insufficiente per l'acquisto.",
["stop_gap"] = "Il prezzo ha aperto sotto lo stop: venduto all'apertura.",
["residue_written_off"] = "Resto troppo piccolo per essere venduto, tolto dal registro.",
["dividend"] = "Dividendo accreditato.",
};
public static string Text(string code) => Texts.TryGetValue(code, out var text) ? text : code;
public static bool Has(string code) => Texts.ContainsKey(code);
}
+136
View File
@@ -0,0 +1,136 @@
using System.Reflection;
using Anubis.Core;
using Anubis.Data;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>The diary from reason codes and the "senza bot" comparison (issue #50, SPEC 5.2, 7.5, appendix B and F.10).</summary>
[TestClass]
public sealed class DiaryTests
{
private static readonly CancellationToken _none = CancellationToken.None;
// The appendix writes plain spaces; the bot puts a non-breaking one between a number and its currency.
private static string Plain(string text) => text.Replace(' ', ' ');
[TestMethod]
public void TheTemplatesWriteTheSentencesOfTheAppendix()
{
Assert.AreEqual("Alzato lo stop di BTC/EUR da 65.400 € a 66.180 €. Lo stop segue il prezzo quando sale.",
Plain(DiaryText.StopRaised("BTC-EUR", 65400m, 66180m, "EUR")));
Assert.AreEqual(
"Chiusura giornaliera crypto: nessun cambio. BTC, ETH e SOL restano in tendenza. Le altre 7 monete restano fuori: nessuna ha segnato nuovi massimi.",
DiaryText.CryptoClose(new DecisionSummary([], [], [], [], ["BTC-EUR", "ETH-EUR", "SOL-EUR"], 7)));
Assert.AreEqual("Venduta 1 MSFT a 522,14 $: +9,84 $ in 3 giorni.",
Plain(DiaryText.Fill(OrderSide.Sell, 1m, "MSFT", crypto: false, 522.14m, "USD", closed: new ClosedTrade(9.84m, 3))));
Assert.AreEqual("Comprate 2 AAPL a 259,80 $. Mean reversion: tre sedute di ribasso, titolo sopra la media a 200 giorni.",
Plain(DiaryText.Fill(OrderSide.Buy, 2m, "AAPL", crypto: false, 259.80m, "USD", "Mean reversion: tre sedute di ribasso, titolo sopra la media a 200 giorni.")));
Assert.AreEqual("Rimessi 6 stop giornalieri sulle frazioni di azione.", DiaryText.StopsReplaced(6));
Assert.AreEqual("Azioni: nessun nuovo acquisto. AAPL resta aperta.", DiaryText.StockSignals(new DecisionSummary([], [], [], [], ["AAPL"], 0)));
// Changes, coins and agreement.
Assert.AreEqual("Chiusura giornaliera crypto: compro ETH, vendo SOL. BTC resta in tendenza. Le altre 7 monete restano fuori: nessuna ha segnato nuovi massimi.",
DiaryText.CryptoClose(new DecisionSummary(["ETH-EUR"], [], [], ["SOL-EUR"], ["BTC-EUR"], 7)));
Assert.AreEqual("Azioni: domani compro AAPL e MSFT, vendo JPM.", DiaryText.StockSignals(new DecisionSummary(["AAPL", "MSFT"], [], [], ["JPM"], [], 0)));
Assert.AreEqual("Comprati 0,0512 BTC/EUR a 66.180,00 €.", Plain(DiaryText.Fill(OrderSide.Buy, 0.0512m, "BTC-EUR", crypto: true, 66180m, "EUR")));
Assert.AreEqual("Venduto 1 ETH/EUR a 3.010,50 €: −42,10 € in giornata. Stop di protezione raggiunto.",
Plain(DiaryText.Fill(OrderSide.Sell, 1m, "ETH-EUR", crypto: true, 3010.50m, "EUR", ReasonCatalog.Text("stop"), new ClosedTrade(-42.10m, 0))));
Assert.AreEqual("Trend crypto, in osservazione: avrei comprato BTC/EUR. Nessun ordine: registro solo il segnale.",
DiaryText.Observed(StrategyNames.CryptoTrend, new DecisionSummary(["BTC-EUR"], [], [], [], [], 0)));
Assert.AreEqual("3 ore", DiaryText.Duration(TimeSpan.FromHours(3)));
Assert.AreEqual("20 ore e 5 minuti", DiaryText.Duration(new TimeSpan(20, 5, 0)));
Assert.AreEqual("3 giorni", DiaryText.Duration(TimeSpan.FromDays(3)));
Assert.AreEqual("1 giorno e 1 ora", DiaryText.Duration(TimeSpan.FromHours(25)));
// No jargon and no exclamation marks (appendix B).
foreach (var sentence in new[] { DiaryText.Absence(TimeSpan.FromHours(20)), DiaryText.EntryDropped("AAPL", 1.4m, 1m), DiaryText.NoData(StrategyNames.EquityMomentum, "le barre di chiusura") })
{
Assert.DoesNotContain("!", sentence);
Assert.DoesNotContain("stop loss", sentence, StringComparison.OrdinalIgnoreCase);
}
}
[TestMethod]
public void EveryReasonCodeHasItsSentence()
{
// Every code a strategy, a corrective, the risk engine or the order rules can write: the diary never shows a bare code.
var holders = typeof(DiaryText).Assembly.GetTypes().Where(t => t.Name == "Reasons" || (t.Name.EndsWith("Reasons", StringComparison.Ordinal) && t.IsAbstract && t.IsSealed));
var codes = holders.SelectMany(t => t.GetFields(BindingFlags.Public | BindingFlags.Static))
.Where(f => f.IsLiteral && f.FieldType == typeof(string) && !f.Name.EndsWith("Prefix", StringComparison.Ordinal))
.Select(f => (string)f.GetRawConstantValue()!)
.ToList();
Assert.IsGreaterThan(40, codes.Count, "The reason classes were found.");
var missing = codes.Where(c => !ReasonCatalog.Has(c)).ToList();
Assert.IsEmpty(missing, "Codes without a sentence: " + string.Join(", ", missing));
Assert.IsTrue(codes.All(c => !ReasonCatalog.Text(c).Contains('!', StringComparison.Ordinal)));
}
[TestMethod]
public void TheComparisonInvestsEveryFlowOnItsDayAndNeverTouchesIt()
{
var d1 = new DateOnly(2026, 1, 5);
var d2 = new DateOnly(2026, 2, 2);
var d3 = new DateOnly(2026, 3, 2);
var prices = new Dictionary<DateOnly, (decimal Bitcoin, decimal Stock)>
{
[d1] = (50000m, 500m),
[d2] = (60000m, 500m),
[d3] = (60000m, 550m),
};
(decimal Bitcoin, decimal Stock)? At(DateOnly day) => prices.TryGetValue(day, out var p) ? p : null;
// 10,000 € on day 1: 4,000 in Bitcoin, 6,000 in the S&P 500. Bitcoin +20%: 4,800 + 6,000.
Assert.AreEqual(10800m, NoBot.Value([(d1, 10000m)], At, d2));
// A deposit of 1,000 € on day 2 buys at day 2's prices: it is not a gain. S&P +10% on day 3.
// Units: 0.08 + 0.0066667 BTC = 0.0866667 × 60,000 = 5,200; 12 + 1.2 SPY = 13.2 × 550 = 7,260.
Assert.AreEqual(12460m, NoBot.Value([(d1, 10000m), (d2, 1000m)], At, d3));
// A withdrawal sells both in the proportion they reached: half of 10,800 out leaves 5,400, then S&P +10%.
Assert.AreEqual(5700m, NoBot.Value([(d1, 10000m), (d2, -5400m)], At, d3));
// No flows, or a missing price: no comparison rather than a wrong one.
Assert.IsNull(NoBot.Value([], At, d3));
Assert.IsNull(NoBot.Value([(new DateOnly(2025, 12, 1), 10000m)], At, d3));
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ThePhotographOfTheTotalCarriesTheComparisonOnlyWithBothSeries()
{
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
var fx = new FxStore(rig.Db, rig.Clock);
var okx = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false);
await rig.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at, share) VALUES (@id, @s, @a, 'observation', 0, @j, @now, @now, 1)",
_none, ("id", Ids.NewId(rig.Clock)), ("s", StrategyNames.CryptoTrend), ("a", okx.AccountId), ("j", new Anubis.Db.DbJson("{}")), ("now", rig.Clock.UtcNow)), _none).ConfigureAwait(false);
var today = DateOnly.FromDateTime(rig.Clock.UtcNow.UtcDateTime);
var capital = new Capital(rig.Db, rig.Clock, rig.Ledger, fx);
await fx.UpsertAsync([new FxRate("EUR", "USD", today.AddDays(-3), 1.10m, "ecb")], _none).ConfigureAwait(false);
await capital.SetAsync(Venues.Okx, 10000m, "test", _none).ConfigureAwait(false);
var book = new EquityBook(rig.Db, rig.Clock, rig.Ledger, fx);
// Without the SPY history (no Alpaca keys) there is no comparison: null, never a half one.
await book.TakeAsync(_none).ConfigureAwait(false);
Assert.IsNull(await BenchmarkAsync(rig).ConfigureAwait(false));
// With both: BTC-EUR on OKX, SPY on Alpaca in dollars at 1.10 $/€.
var btc = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false);
var spy = await rig.InstrumentAsync(TradingRig.Stock("SPY")).ConfigureAwait(false);
var bars = new BarStore(rig.Db, rig.Clock);
await bars.UpsertDailyAsync(btc.Id, [new DailyBar(today.AddDays(-1), 50000, 50000, 50000, 50000, 1)], "test", _none).ConfigureAwait(false);
await bars.UpsertDailyAsync(spy.Id, [new DailyBar(today.AddDays(-1), 550, 550, 550, 550, 1)], "test", _none).ConfigureAwait(false);
rig.Clock.Advance(TimeSpan.FromMinutes(5));
await book.TakeAsync(_none).ConfigureAwait(false);
Assert.AreEqual(10000m, await BenchmarkAsync(rig).ConfigureAwait(false), "Invested today at today's prices: worth what was put in.");
// The next day Bitcoin is up 10%: 4,000 € become 4,400 €.
rig.Clock.Advance(TimeSpan.FromDays(1));
await bars.UpsertDailyAsync(btc.Id, [new DailyBar(today, 55000, 55000, 55000, 55000, 1)], "test", _none).ConfigureAwait(false);
await book.TakeAsync(_none).ConfigureAwait(false);
Assert.AreEqual(10400m, await BenchmarkAsync(rig).ConfigureAwait(false));
}
private static async Task<decimal?> BenchmarkAsync(TradingRig rig) =>
(await rig.QueryAsync("SELECT benchmark FROM equity_snapshots WHERE scope = 'total' ORDER BY taken_at DESC, id DESC LIMIT 1", r => r.MoneyOrNull("benchmark")).ConfigureAwait(false))[0];
}