using System.Net; using System.Text; using Anubis.Brokers; using Anubis.Core; using Anubis.Data; using Anubis.Db; using Anubis.Trading; namespace Anubis.Tests; /// The export for the tax return (issue #73, SPEC 4.6, 6.8, 7.5, 13.3). [TestClass] public sealed class TaxExportTests { private static readonly CancellationToken _none = CancellationToken.None; private static readonly Guid _account = Guid.Parse("00000000-0000-0000-0000-00000000000a"); private static readonly Guid _other = Guid.Parse("00000000-0000-0000-0000-00000000000b"); private static readonly Guid _aapl = Guid.Parse("00000000-0000-0000-0000-000000000001"); private static readonly Guid _btc = Guid.Parse("00000000-0000-0000-0000-000000000002"); private static readonly Dictionary _accounts = new() { [_account] = new("Alpaca", Venues.Alpaca, Worlds.Real), [_other] = new("Alpaca due", Venues.Alpaca, Worlds.Real), }; private static readonly Dictionary _instruments = new() { [_aapl] = new("AAPL", "Apple", "us_equity", null, "USD"), [_btc] = new("BTC-EUR", "Bitcoin", "crypto", "BTC", "EUR"), }; private static readonly FxRate[] _rates = [ Rate(2026, 3, 2, 1.25m), Rate(2026, 3, 3, 1.20m), Rate(2026, 3, 6, 1.10m), Rate(2026, 12, 30, 1.00m), Rate(2027, 1, 4, 1.05m), ]; private static FxRate Rate(int year, int month, int day, decimal rate) => new("EUR", "USD", new DateOnly(year, month, day), rate, "ecb"); private static DateTimeOffset At(int year, int month, int day, int hour = 15, int minute = 0) => new(year, month, day, hour, minute, 0, TimeSpan.Zero); private static TaxEvent Trade(TaxKind kind, DateTimeOffset at, decimal quantity, decimal price, decimal fee = 0m, string feeCurrency = "USD", Guid? instrument = null, string strategy = "s", Guid? account = null) => new(account ?? _account, instrument ?? _aapl, at, kind, $"{at:yyyyMMddHHmmss}-{kind}-{strategy}") { Entering = kind == TaxKind.Purchase, Quantity = quantity, Price = price, Fee = fee, FeeCurrency = feeCurrency, Strategy = strategy, }; private static (List Rows, List Lots) Build(LotMethod method, params TaxEvent[] events) => TaxExport.Build(events, _accounts, _instruments, _rates, method); // ---- costs and rates ---- [TestMethod] [TestCategory(Category.Unit)] public void TheCostFollowsTheMethodAndEachPurchaseKeepsItsOwnRate() { // 10 at 100 on 2 March (1.25): 800 euro. 10 at 120 on 3 March (1.20): 1,000 euro. 15 sold at 132 on 6 March (1.10): 1,800 euro. TaxEvent[] events = [ Trade(TaxKind.Purchase, At(2026, 3, 2), 10m, 100m), Trade(TaxKind.Purchase, At(2026, 3, 3), 10m, 120m), Trade(TaxKind.Sale, At(2026, 3, 6), 15m, 132m), ]; var (rows, lots) = Build(LotMethod.Lifo, events); var sale = rows[2]; Assert.AreEqual(1800m, sale.GrossEur); Assert.AreEqual(1400m, sale.CostEur, "The 10 of 3 March and 5 of 2 March."); Assert.AreEqual(400m, sale.ResultEur); Assert.AreEqual(Math.Round(400m - (280m / 1.10m), 10), Math.Round(sale.FxEffectEur!.Value, 10), "280 dollars of gain at the rate of the sale; the rest is the exchange rate."); CollectionAssert.AreEqual(new[] { (new DateOnly(2026, 3, 3), 10m), (new DateOnly(2026, 3, 2), 5m) }, lots.Select(l => (l.Bought, l.Quantity)).ToList()); Assert.AreEqual(400m, Math.Round(lots.Sum(l => l.ResultEur!.Value), 10)); var fifo = Build(LotMethod.Fifo, events).Rows[2]; Assert.AreEqual(1300m, fifo.CostEur, "The 10 of 2 March and 5 of 3 March."); Assert.AreEqual(500m, fifo.ResultEur); Assert.AreEqual(800m, rows[0].GrossEur); Assert.AreEqual((1.25m, new DateOnly(2026, 3, 2)), (rows[0].Rate, rows[0].RateDate)); } [TestMethod] [TestCategory(Category.Unit)] public void FeesEnterTheCostAndTheProceeds() { var (rows, _) = Build(LotMethod.Lifo, Trade(TaxKind.Purchase, At(2026, 3, 2), 10m, 100m, 5m), Trade(TaxKind.Sale, At(2026, 3, 3), 10m, 120m, 6m)); Assert.AreEqual(4m, rows[0].FeeEur); Assert.AreEqual(804m, rows[1].CostEur); Assert.AreEqual(995m - 804m, rows[1].ResultEur); Assert.AreEqual(1000m, rows[1].GrossEur, "The value is gross."); // A fee kept in the coin: fewer coins for the same money, and it is not subtracted twice. (rows, _) = Build(LotMethod.Lifo, Trade(TaxKind.Purchase, At(2026, 3, 2), 0.01m, 60000m, 0.0001m, "BTC", _btc), Trade(TaxKind.Sale, At(2026, 3, 3), 0.0099m, 70000m, 0.7m, "EUR", _btc)); Assert.AreEqual(6m, rows[0].FeeEur); Assert.AreEqual(600m, rows[1].CostEur); Assert.AreEqual(693m - 0.7m - 600m, rows[1].ResultEur); Assert.IsNull(rows[1].Rate); Assert.IsNull(rows[1].FxEffectEur); // Also on a sale: the coin of the fee leaves too. (rows, var lots) = Build(LotMethod.Lifo, Trade(TaxKind.Purchase, At(2026, 3, 2), 1m, 100m, 0m, "EUR", _btc), Trade(TaxKind.Sale, At(2026, 3, 3), 0.4m, 100m, 0.1m, "BTC", _btc)); Assert.AreEqual(50m, rows[1].CostEur); Assert.AreEqual(0.5m, lots.Single().Quantity); // A fee in another currency is shown and never counted as zero. (rows, _) = Build(LotMethod.Lifo, Trade(TaxKind.Purchase, At(2026, 3, 2), 10m, 100m, 3m, "BNB")); Assert.AreEqual((3m, "BNB"), (rows[0].Fee, rows[0].FeeCurrency)); Assert.IsNull(rows[0].FeeEur); StringAssert.Contains(rows[0].Note, "BNB"); } [TestMethod] [TestCategory(Category.Unit)] public void ADayWithoutARateUsesTheOneBeforeAndAnUnknownOneLeavesTheCellsEmpty() { // Sunday 8 March: the rate of Friday 6. var (rows, _) = Build(LotMethod.Lifo, Trade(TaxKind.Purchase, At(2026, 3, 8), 10m, 110m)); Assert.AreEqual((1.10m, new DateOnly(2026, 3, 6), 1000m, false), (rows[0].Rate, rows[0].RateDate, rows[0].GrossEur, rows[0].Provisional)); // A hole of more than a week, or a currency nobody publishes: nothing is invented. (rows, _) = Build(LotMethod.Lifo, Trade(TaxKind.Purchase, At(2026, 5, 4), 10m, 110m), Trade(TaxKind.Sale, At(2026, 12, 30), 10m, 120m)); Assert.IsNull(rows[0].GrossEur); Assert.IsTrue(rows[0].MissingRate); StringAssert.Contains(rows[0].Note, "mancante"); Assert.AreEqual(1200m, rows[1].GrossEur); Assert.IsNull(rows[1].CostEur, "Its purchase has no rate."); Assert.IsNull(rows[1].ResultEur); StringAssert.Contains(rows[1].Note, "a mano"); Assert.AreEqual(1, new TaxReport(Worlds.Real, null, LotMethod.Lifo, rows, []).MissingRates); // After the last rate published: provisional until the next one. (rows, _) = Build(LotMethod.Lifo, Trade(TaxKind.Purchase, At(2027, 1, 5), 10m, 105m)); Assert.IsTrue(rows[0].Provisional); Assert.AreEqual(1000m, rows[0].GrossEur); StringAssert.Contains(rows[0].Note, "provvisorio"); } [TestMethod] [TestCategory(Category.Unit)] public void TheDayIsTheItalianOne() { var (rows, _) = Build(LotMethod.Lifo, Trade(TaxKind.Purchase, At(2026, 12, 31, 22, 59), 1m, 100m), Trade(TaxKind.Purchase, At(2026, 12, 31, 23, 30), 1m, 100m), Trade(TaxKind.Purchase, At(2026, 7, 1, 22, 30), 1m, 100m)); CollectionAssert.AreEqual(new[] { new DateOnly(2026, 7, 2), new DateOnly(2026, 12, 31), new DateOnly(2027, 1, 1) }, rows.Select(r => r.Day).ToList()); } [TestMethod] [TestCategory(Category.Unit)] public void TwoStrategiesShareTheHoldingAndTwoAccountsDoNot() { var (rows, _) = Build(LotMethod.Lifo, Trade(TaxKind.Purchase, At(2026, 3, 2), 10m, 100m, strategy: "a"), Trade(TaxKind.Purchase, At(2026, 3, 3), 10m, 120m, strategy: "b"), Trade(TaxKind.Sale, At(2026, 3, 6), 10m, 110m, strategy: "a")); Assert.AreEqual(1000m, rows[2].CostEur, "The last bought of the account, whichever strategy bought it."); (rows, _) = Build(LotMethod.Lifo, Trade(TaxKind.Purchase, At(2026, 3, 2), 10m, 100m), Trade(TaxKind.Purchase, At(2026, 3, 3), 10m, 120m, account: _other), Trade(TaxKind.Sale, At(2026, 3, 6), 10m, 110m)); Assert.AreEqual(800m, rows[2].CostEur); } [TestMethod] [TestCategory(Category.Unit)] public void ASplitMultipliesWhatWasBoughtBeforeAndKeepsItsDateAndCost() { var split = new TaxEvent(_account, _aapl, At(2026, 3, 3, 0), TaxKind.Split, "split") { Amount = 4m }; var (rows, lots) = Build(LotMethod.Lifo, Trade(TaxKind.Sale, At(2026, 3, 6), 45m, 33m), Trade(TaxKind.Purchase, At(2026, 3, 2), 10m, 100m), split, Trade(TaxKind.Purchase, At(2026, 3, 3), 10m, 30m)); Assert.AreEqual((TaxKind.Split, 30m), (rows[1].Kind, rows[1].Quantity)); Assert.IsNull(rows[1].GrossEur); Assert.AreEqual(250m + (800m * 35m / 40m), rows[3].CostEur, "All 10 new shares, then 35 of the 40 old ones."); CollectionAssert.AreEqual(new[] { new DateOnly(2026, 3, 3), new DateOnly(2026, 3, 2) }, lots.Select(l => l.Bought).ToList()); } [TestMethod] [TestCategory(Category.Unit)] public void ResiduesAndAlignmentsAreNotSalesAndASaleWithoutItsPurchasesSaysSo() { var (rows, lots) = Build(LotMethod.Lifo, Trade(TaxKind.Purchase, At(2026, 3, 2), 10m, 100m), Trade(TaxKind.Residue, At(2026, 3, 3), 1m, 120m), Trade(TaxKind.Sale, At(2026, 3, 6), 9m, 110m)); Assert.IsNull(rows[1].ResultEur); Assert.IsNull(rows[1].CostEur); Assert.AreEqual(720m, rows[2].CostEur, "The residue took its part of the cost away."); Assert.HasCount(1, lots); (rows, _) = Build(LotMethod.Lifo, Trade(TaxKind.Purchase, At(2026, 3, 2), 5m, 100m), Trade(TaxKind.Sale, At(2026, 3, 3), 9m, 110m)); Assert.IsNull(rows[1].ResultEur); StringAssert.Contains(rows[1].Note, "a mano"); } // ---- from the ledger ---- [TestMethod] [TestCategory(Category.Integration)] public async Task TheReportReadsTheLedgerAndKeepsSimulationApart() { await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); await new FxStore(rig.Db, rig.Clock).UpsertAsync([new("EUR", "USD", new DateOnly(2026, 11, 9), 1.25m, "ecb")], _none).ConfigureAwait(false); var simulated = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Simulation).ConfigureAwait(false); var real = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Live, "Alpaca vero").ConfigureAwait(false); var stock = await rig.InstrumentAsync(TradingRig.Stock("MSFT") with { Name = "=HYPERLINK(\"x\")" }).ConfigureAwait(false); const string strategy = StrategyNames.EquityMomentum; await rig.Ledger.RecordCapitalAsync(simulated.AccountId, strategy, 10000m, "USD", "test", _none).ConfigureAwait(false); await rig.Ledger.RecordFillAsync(rig.Fill(simulated, stock, strategy, OrderSide.Buy, 10m, 100m, 1m), _none).ConfigureAwait(false); await rig.Ledger.RecordFillAsync(rig.Fill(real, stock, strategy, OrderSide.Buy, 2m, 100m), _none).ConfigureAwait(false); rig.Clock.Advance(TimeSpan.FromMinutes(1)); await rig.Ledger.RecordFillAsync(rig.Fill(simulated, stock, strategy, OrderSide.Sell, 4m, 110m), _none).ConfigureAwait(false); await rig.Ledger.RecordDividendAsync(simulated.AccountId, strategy, 2.5m, "USD", rig.Clock.UtcNow, Ledger.DividendNote("MSFT", 0.25m), _none).ConfigureAwait(false); rig.Clock.Advance(TimeSpan.FromMinutes(1)); await rig.Ledger.AdjustQuantityAsync(simulated.AccountId, stock.Id, strategy, 1m, 100m, "allineamento", _none).ConfigureAwait(false); await rig.Ledger.AdjustCashAsync(simulated.AccountId, strategy, -7m, "USD", "allineamento", _none).ConfigureAwait(false); await rig.Ledger.WriteOffResidueAsync(simulated.AccountId, stock.Id, strategy, 100m, "residuo", _none).ConfigureAwait(false); var choices = await TaxExport.ChoicesAsync(rig.Db, _none).ConfigureAwait(false); CollectionAssert.AreEqual(new[] { Worlds.Real, Worlds.Simulated }, choices.Select(c => c.World).ToList()); CollectionAssert.AreEqual(new[] { 2026 }, choices[0].Years.ToList()); Assert.IsEmpty((await TaxExport.LoadAsync(rig.Db, Worlds.Simulated, 2025, LotMethod.Lifo, _none).ConfigureAwait(false)).Rows); var report = await TaxExport.LoadAsync(rig.Db, Worlds.Simulated, 2026, LotMethod.Lifo, _none).ConfigureAwait(false); CollectionAssert.AreEquivalent(new[] { TaxKind.Purchase, TaxKind.Sale, TaxKind.Dividend, TaxKind.Adjustment, TaxKind.Adjustment, TaxKind.Residue }, report.Rows.Select(r => r.Kind).ToList(), "The counterpart of the aligned quantity is not a second row; the capital is not an operation."); var sale = report.Rows.Single(r => r.Kind == TaxKind.Sale); Assert.AreEqual((352m, 320.32m), (sale.GrossEur, Math.Round(sale.CostEur!.Value, 2))); Assert.AreEqual(("MSFT", 2m), (report.Rows.Single(r => r.Kind == TaxKind.Dividend).Symbol, report.Rows.Single(r => r.Kind == TaxKind.Dividend).GrossEur)); Assert.AreEqual(-5.6m, report.Rows.Single(r => r.Kind == TaxKind.Adjustment && r.Quantity is null).GrossEur); Assert.HasCount(1, (await TaxExport.LoadAsync(rig.Db, Worlds.Real, 2026, LotMethod.Lifo, _none).ConfigureAwait(false)).Rows); // SPEC 6.8: each execution keeps the reference rate in force when it happened. var saved = await rig.QueryAsync("SELECT fx_rate FROM fills", r => r.MoneyOrNull("fx_rate")).ConfigureAwait(false); Assert.IsTrue(saved.All(r => r == 1.25m)); // The file of SPEC 13.3: BOM, semicolons, decimal comma, Italian headers, nothing a spreadsheet would compute. var bytes = report.Csv(); CollectionAssert.AreEqual(new byte[] { 0xEF, 0xBB, 0xBF }, bytes[..3]); var lines = Encoding.UTF8.GetString(bytes[3..]).Split("\r\n", StringSplitOptions.RemoveEmptyEntries); StringAssert.StartsWith(lines[0], "Ambiente;Conto;Data;Ora;Operazione;Strumento;Nome;Tipo;Strategia;Quantità;Prezzo;"); StringAssert.Contains(lines[0], "Costo EUR (LIFO)"); var sold = lines.Single(l => l.Contains(";Vendita;", StringComparison.Ordinal)); StringAssert.StartsWith(sold, "simulazione;"); StringAssert.Contains(sold, ";10/11/2026;16:01:00;Vendita;MSFT;\"'=HYPERLINK(\"\"x\"\")\";azione;"); StringAssert.Contains(sold, ";4;110;USD;440;0;;1,25;09/11/2026;352;0;320,32;31,68;"); StringAssert.StartsWith(Encoding.UTF8.GetString(report.LotsCsv()[3..]).Split("\r\n")[1], "simulazione;"); } [TestMethod] [TestCategory(Category.Integration)] public async Task TheExportHoldsWhatTheLedgerHolds() { // Random purchases and sales, one strategy: the purchases left by the export are those left by the ledger. await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); var account = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false); var btc = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false); const string strategy = StrategyNames.CryptoTrend; await rig.Ledger.RecordCapitalAsync(account.AccountId, strategy, 1_000_000m, "EUR", "test", _none).ConfigureAwait(false); var random = new Random(73); var held = 0m; for (var i = 0; i < 60; i++) { rig.Clock.Advance(TimeSpan.FromMinutes(7)); var buy = held < 0.01m || random.Next(2) == 0; var quantity = buy ? random.Next(1, 500) / 10000m : Math.Round(held * random.Next(10, 100) / 100m, 8); var fee = buy ? quantity * 0.001m : Math.Round(quantity * 60000m * 0.001m, 4); var outcome = await rig.Ledger.RecordFillAsync(rig.Fill(account, btc, strategy, buy ? OrderSide.Buy : OrderSide.Sell, quantity, 60000m + random.Next(-5000, 5000), fee, buy ? "BTC" : "EUR"), _none) .ConfigureAwait(false); held = outcome.Quantity; } foreach (var method in new[] { LotMethod.Lifo, LotMethod.Fifo }) { var report = await TaxExport.LoadAsync(rig.Db, Worlds.Simulated, null, method, _none).ConfigureAwait(false); var bought = report.Rows.Where(r => r.Kind == TaxKind.Purchase).Sum(r => r.Quantity!.Value - r.Fee!.Value); Assert.AreEqual(Math.Round(held, 10), Math.Round(bought - report.Lots.Sum(l => l.Quantity), 10), method.ToString()); var sales = report.Rows.Where(r => r.Kind == TaxKind.Sale).ToList(); Assert.IsTrue(sales.All(s => s.ResultEur is not null)); Assert.AreEqual(Math.Round(sales.Sum(s => s.ResultEur!.Value), 6), Math.Round(report.Lots.Sum(l => l.ResultEur!.Value), 6)); } // With the method of the ledger, each sale consumed the same purchases. var lifo = await TaxExport.LoadAsync(rig.Db, Worlds.Simulated, null, LotMethod.Lifo, _none).ConfigureAwait(false); var ledger = await rig.QueryAsync("SELECT f.execution_id AS sale, l.quantity FROM lots l JOIN fills f ON f.id = l.fill_id WHERE l.closes_id IS NOT NULL", r => (Sale: r.Text("sale"), Quantity: -r.Money("quantity"))).ConfigureAwait(false); CollectionAssert.AreEquivalent(ledger.Select(l => (l.Sale, Math.Round(l.Quantity, 10))).ToList(), lifo.Lots.Select(l => (l.SaleId, Math.Round(l.Quantity, 10))).ToList()); } // ---- the rates ---- [TestMethod] [TestCategory(Category.Integration)] [DataRow("2026-11-09", "eurofxref-hist-90d.xml", "eurofxref-daily.xml", DisplayName = "after a start the last 90 days, then the day's file")] [DataRow("2026-11-05", "eurofxref-hist-90d.xml", "eurofxref-daily.xml", DisplayName = "a working day is missing")] [DataRow("2026-08-01", "eurofxref-hist.zip", "eurofxref-daily.xml", DisplayName = "after months the whole history")] public async Task NoWorkingDayIsSkipped(string latest, string first, string second) { var clock = new FastClock(new DateTimeOffset(2026, 11, 10, 8, 0, 0, TimeSpan.Zero)); await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false); await new FxStore(test.Db, clock).UpsertAsync([new("EUR", "USD", DateOnly.ParseExact(latest, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture), 1.1m, "ecb")], _none).ConfigureAwait(false); var day = Fixture.Text("free/ecb-daily.xml"); var http = new FakeHttp().OnBytes("eurofxref-hist.zip", ReferenceSourcesTests.Zip("eurofxref-hist.csv", Fixture.Text("free/ecb-hist.csv"))) .On("eurofxref-hist-90d.xml", day).On("eurofxref-daily.xml", day); var sources = new ReferenceSources(new ApiHttp(http.Client(), clock, "reference"), test.Db, clock, new SettingsStore(test.Db, clock, new EventBus()), (_, _) => Task.FromResult(null)); Assert.IsTrue(await sources.RefreshFxAsync(_none).ConfigureAwait(false)); clock.Advance(TimeSpan.FromHours(1)); Assert.IsTrue(await sources.RefreshFxAsync(_none).ConfigureAwait(false)); CollectionAssert.AreEqual(new[] { first, second }, http.Urls.Select(u => u.Segments[^1]).ToList()); } // ---- the page ---- [TestMethod] [TestCategory(Category.Integration)] public async Task ThePageExportsAndChangesTheMethod() { await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite()); using (var refused = await server.Http.GetAsync(new Uri("/api/dichiarazione.csv?anno=2026", UriKind.Relative))) { Assert.AreNotEqual(HttpStatusCode.OK, refused.StatusCode); } await server.SignInFirstTimeAsync(); var page = await server.TextAsync("/impostazioni"); StringAssert.Contains(page, "Esportazione per la dichiarazione"); StringAssert.Contains(page, "Nessuna operazione da esportare finora"); using (var saved = await server.PostFormAsync("/impostazioni", "/azioni/impostazioni/" + TaxExport.MethodSetting.Key, ("valore", "fifo"), ("ritorno", "/impostazioni#dichiarazione"))) { Assert.AreEqual("/impostazioni#dichiarazione", ServerHarness.Location(saved)); } using var file = await server.Http.GetAsync(new Uri("/api/dichiarazione.csv?anno=2026&mondo=simulazione", UriKind.Relative)); Assert.AreEqual(HttpStatusCode.OK, file.StatusCode); Assert.AreEqual("text/csv", file.Content.Headers.ContentType!.MediaType); Assert.AreEqual("anubis-dichiarazione-2026-simulazione.csv", file.Content.Headers.ContentDisposition!.FileName!.Trim('"')); StringAssert.Contains(await file.Content.ReadAsStringAsync(), "Costo EUR (FIFO)"); foreach (var wrong in new[] { "anno=duemila", "anno=1", "mondo=altro", "dettaglio=x" }) { using var bad = await server.Http.GetAsync(new Uri("/api/dichiarazione.csv?" + wrong, UriKind.Relative)); Assert.AreEqual(HttpStatusCode.BadRequest, bad.StatusCode, wrong); } } }