using System.Reflection;
using Anubis.Core;
using Anubis.Data;
using Anubis.Trading;
namespace Anubis.Tests;
/// The diary from reason codes and the "senza bot" comparison (issue #50, SPEC 5.2, 7.5, appendix B and F.10).
[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
{
[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 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];
}