diff --git a/src/Anubis.Server/Components/Pages/Impostazioni.razor b/src/Anubis.Server/Components/Pages/Impostazioni.razor index a8a280d..feb7f12 100644 --- a/src/Anubis.Server/Components/Pages/Impostazioni.razor +++ b/src/Anubis.Server/Components/Pages/Impostazioni.razor @@ -319,6 +319,57 @@ }

Rapporto sulla qualità dei dati degli ultimi 30 giorni

+

Esportazione per la dichiarazione

+

Tutte le operazioni con il controvalore in euro al cambio della BCE del giorno di ciascuna, o l'ultimo precedente. È un elenco per te o per il tuo commercialista, non un calcolo delle tasse.

+ @if (Shell.IsDemo) + { +

Nella modalità dimostrativa non ci sono operazioni da esportare.

+ } + else + { +
+ + + + + + + @if (_taxChoices.Count == 0) + { +

Nessuna operazione da esportare finora.

+ } + @foreach (var (world, years) in _taxChoices) + { + var real = world == Anubis.Trading.Worlds.Real; +
+ + + + + +
+ } +
+ Cosa c'è e cosa non c'è +
    +
  • Il costo di ciò che vendi segue gli acquisti del solo bot su quel conto. Se sullo stesso conto compri o vendi anche a mano, il conto va rifatto insieme.
  • +
  • Il risultato può essere diverso da quello della pagina Operazioni, che usa il prezzo medio e non gli acquisti uno per uno.
  • +
  • I dividendi sono lordi e alla data di stacco. Ritenute e piccole commissioni di legge di Alpaca non sono nel registro: prendile dai documenti del broker.
  • +
  • Una riga senza cambio resta vuota e lo dice nella nota; un cambio provvisorio diventa definitivo appena la BCE pubblica quello del giorno.
  • +
  • Il capitale affidato e gli spostamenti fra strategie non sono operazioni e non ci sono.
  • +
+
+ } +
@@ -590,6 +641,8 @@ IReadOnlyList Strategies); private sealed record LimitField(string Key, string Label, string Value, bool ReadOnly); private readonly List _limits = []; + private SettingValue _taxMethod = new(Anubis.Trading.TaxExport.MethodSetting.Key, "lifo", false, null); + private IReadOnlyList<(string World, IReadOnlyList Years)> _taxChoices = []; private bool _anyLive; private string _pdt = "off"; private string _scenarios = ""; @@ -631,6 +684,8 @@ _history = await services.Settings.HistoryAsync(null, 50, ct); _meetings = await services.Settings.GetAsync(SettingsStore.CentralBankMeetings.Key, ct); _sources = await new Anubis.Data.SourceStateStore(services.Db, Clock).ListAsync(ct); + _taxMethod = await services.Settings.GetAsync(Anubis.Trading.TaxExport.MethodSetting.Key, ct); + _taxChoices = await Anubis.Trading.TaxExport.ChoicesAsync(services.Db, ct); foreach (var rule in Anubis.News.NewsRuleSettings.All) { _newsRules.Add(await services.Settings.GetAsync(rule.Key, ct)); @@ -864,6 +919,8 @@ "auto" => "Come il sistema", "light" => "Chiaro", "dark" => "Scuro", + "lifo" => "Ultimo comprato, primo venduto (LIFO)", + "fifo" => "Primo comprato, primo venduto (FIFO)", "EUR" => "Euro (EUR)", "USD" => "Dollaro (USD)", "active" => "Attivo", diff --git a/src/Anubis.Server/Endpoints.cs b/src/Anubis.Server/Endpoints.cs index cab78e4..81be6ad 100644 --- a/src/Anubis.Server/Endpoints.cs +++ b/src/Anubis.Server/Endpoints.cs @@ -191,6 +191,33 @@ internal static partial class Endpoints "text/csv; charset=utf-8", $"anubis-operazioni-{day}.csv"); }); + // The operations for the tax return (SPEC 4.6, 13.5): one world and one Italian year, or all of them. + api.MapGet("/dichiarazione.csv", async (AnubisHost host, IClock clock, string? anno, string? mondo, string? dettaglio, CancellationToken ct) => + { + int? year = null; + if (!string.IsNullOrEmpty(anno) && anno != "tutti") + { + if (!int.TryParse(anno, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var parsed) || parsed is < 1999 or > 9999) + { + return Error(StatusCodes.Status400BadRequest, "valore_non_valido", "L'anno non è valido."); + } + + year = parsed; + } + + if (mondo is not (null or "" or "reale" or "simulazione") || dettaglio is not (null or "" or "lotti")) + { + return Error(StatusCodes.Status400BadRequest, "valore_non_valido", "La scelta non è valida."); + } + + var world = mondo == "reale" ? Anubis.Trading.Worlds.Real : Anubis.Trading.Worlds.Simulated; + var services = host.Services!; + var method = Anubis.Trading.TaxExport.Method((await services.Settings.GetAsync(Anubis.Trading.TaxExport.MethodSetting.Key, ct).ConfigureAwait(false)).Value); + var report = await Anubis.Trading.TaxExport.LoadAsync(services.Db, world, year, method, ct).ConfigureAwait(false); + var name = $"anubis-dichiarazione-{year?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "tutti"}{(dettaglio == "lotti" ? "-lotti" : "")}{(world == Anubis.Trading.Worlds.Real ? "" : "-simulazione")}.csv"; + return Results.File(dettaglio == "lotti" ? report.LotsCsv() : report.Csv(), "text/csv; charset=utf-8", name); + }); + // The technical logs of the data folder as one zip (SPEC 13.6, "Diario e sistema"). They are redacted when // written (JsonLog); only the files the log writer names, read while it keeps writing the newest one. api.MapGet("/registri.zip", (AnubisHost host, ShellData shell, IClock clock) => diff --git a/src/Anubis.Server/Forms.cs b/src/Anubis.Server/Forms.cs index 7fc2e24..db0c407 100644 --- a/src/Anubis.Server/Forms.cs +++ b/src/Anubis.Server/Forms.cs @@ -273,7 +273,7 @@ internal static partial class Forms var back = Back(form, "/impostazioni"); var news = Anubis.News.NewsRuleSettings.All.Any(d => d.Key == key); var model = Anubis.News.NewsModelSettings.All.Any(d => d.Key == key); - if (key != SettingsStore.Theme.Key && key != SettingsStore.Currency.Key && key != SettingsStore.CentralBankMeetings.Key && key != SettingsStore.TelegramStatus.Key && + if (key != SettingsStore.Theme.Key && key != SettingsStore.Currency.Key && key != SettingsStore.CentralBankMeetings.Key && key != SettingsStore.TelegramStatus.Key && key != Anubis.Trading.TaxExport.MethodSetting.Key && !news && !model) { return Results.Redirect(With(back, "errore", "impostazione")); diff --git a/src/Anubis/Core/Format.cs b/src/Anubis/Core/Format.cs index fe7641f..a3ab409 100644 --- a/src/Anubis/Core/Format.cs +++ b/src/Anubis/Core/Format.cs @@ -206,7 +206,7 @@ public static class Format private static string CsvValue(object? cell) => cell switch { null => "", - decimal d => d.ToString(CultureInfo.InvariantCulture).Replace('.', ','), + decimal d => (d / 1.000000000000000000000000000000000m).ToString(CultureInfo.InvariantCulture).Replace('.', ','), double f => f.ToString("R", CultureInfo.InvariantCulture).Replace('.', ','), int or long => Convert.ToString(cell, CultureInfo.InvariantCulture)!, DateOnly date => date.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture), diff --git a/src/Anubis/Core/Settings.cs b/src/Anubis/Core/Settings.cs index dd78a1a..f07f721 100644 --- a/src/Anubis/Core/Settings.cs +++ b/src/Anubis/Core/Settings.cs @@ -45,7 +45,7 @@ public sealed class SettingsStore(Database db, IClock clock, EventBus bus, IRead public static readonly SettingDefinition TelegramStatus = new("telegram.status", "Stato periodico su Telegram", "never", ["never", "hourly", "daily"]); public static readonly IReadOnlyList All = - [Theme, Currency, BotState, CentralBankMeetings, TelegramStatus, .. Risk.RiskSettings.All, Risk.Scenarios.Setting, .. News.NewsRuleSettings.All, .. News.NewsModelSettings.All, .. Learning.LearningSettings.All]; + [Theme, Currency, BotState, CentralBankMeetings, TelegramStatus, Trading.TaxExport.MethodSetting, .. Risk.RiskSettings.All, Risk.Scenarios.Setting, .. News.NewsRuleSettings.All, .. News.NewsModelSettings.All, .. Learning.LearningSettings.All]; private readonly IReadOnlyDictionary _overrides = overrides ?? new Dictionary(); diff --git a/src/Anubis/Data/ReferenceSources.cs b/src/Anubis/Data/ReferenceSources.cs index 3f8c60d..ac42dea 100644 --- a/src/Anubis/Data/ReferenceSources.cs +++ b/src/Anubis/Data/ReferenceSources.cs @@ -47,13 +47,21 @@ public sealed class ReferenceSources( private readonly MoodStore _mood = new(db, clock); - /// Reference rates: the whole history the first time, the last 90 days after a pause, otherwise the day's file. + // The first answer after a start repairs what a past pause may have skipped. + private bool _fxRepaired; + + /// + /// Reference rates: the whole history the first time and after a long pause, the last 90 days when a working day is + /// missing or at the first reading after a start, otherwise the day's file. No day is ever skipped: the tax export + /// needs the rate of each one (SPEC 4.6). + /// public Task RefreshFxAsync(CancellationToken cancellationToken) => RunAsync(Ecb.Source, async () => { var latest = await _fx.LatestAsync("EUR", "USD", cancellationToken).ConfigureAwait(false); var today = DateOnly.FromDateTime(clock.UtcNow.UtcDateTime); IReadOnlyList rates; - if (latest is null) + var expected = today.AddDays(today.DayOfWeek switch { DayOfWeek.Monday => -3, DayOfWeek.Sunday => -2, _ => -1 }); + if (latest is null || latest.Date < today.AddDays(-85)) { var zip = await http.GetBytesAsync(Ecb.History, null, null, cancellationToken).ConfigureAwait(false) ?? throw new MarketDataException("BCE: archivio storico dei cambi non trovato.", retryable: true); @@ -61,11 +69,12 @@ public sealed class ReferenceSources( } else { - var url = latest.Date < today.AddDays(-4) ? Ecb.Last90Days : Ecb.Daily; + var url = !_fxRepaired || latest.Date < expected ? Ecb.Last90Days : Ecb.Daily; rates = Ecb.ParseXml(await http.GetStringAsync(url, null, null, cancellationToken).ConfigureAwait(false), Currencies); } await _fx.UpsertAsync(rates, cancellationToken).ConfigureAwait(false); + _fxRepaired = true; return $"{rates.Count} cambi"; }, cancellationToken); diff --git a/src/Anubis/Db/Migrations/0014_rates_and_candidates.sql b/src/Anubis/Db/Migrations/0014_rates_and_candidates.sql new file mode 100644 index 0000000..4382876 --- /dev/null +++ b/src/Anubis/Db/Migrations/0014_rates_and_candidates.sql @@ -0,0 +1,4 @@ +-- The reference exchange rate in force when an execution happened (SPEC 6.8): units of the instrument's currency for +-- one euro. Empty for prices in euro, for executions recorded before this migration and when no rate was known. + +ALTER TABLE fills ADD COLUMN fx_rate {money}; diff --git a/src/Anubis/Trading/Ledger.cs b/src/Anubis/Trading/Ledger.cs index ffc58f7..3c60fcd 100644 --- a/src/Anubis/Trading/Ledger.cs +++ b/src/Anubis/Trading/Ledger.cs @@ -107,6 +107,19 @@ public sealed class Ledger(Database db, IClock clock) /// Quantities below this are zero: decimal arithmetic on 18 decimals leaves nothing larger. public const decimal Dust = 0.000000000001m; + /// The executions Anubis writes by itself, which are not trades on the market: a residue written off, an alignment chosen by the user. + public const string ResiduePrefix = "ANURESIDUE"; + + public const string AdjustmentPrefix = "ANUADJUST"; + + private const string DividendWord = "Dividendo "; + + /// The note of a dividend: the only place that says which stock paid it, so it is written and read here. + public static string DividendNote(string symbol, decimal perShare) => $"{DividendWord}{symbol} {Format.Quantity(perShare)} per azione"; + + public static string? DividendSymbol(string? note) => + note is not null && note.StartsWith(DividendWord, StringComparison.Ordinal) ? note[DividendWord.Length..].Split(' ')[0] : null; + public LotMethod LotMethod { get; init; } = LotMethod.Lifo; /// Gives (positive) or takes back (negative) capital to a strategy. It counts as a flow, not a result. @@ -171,13 +184,16 @@ public sealed class Ledger(Database db, IClock clock) decimal? slippage = fill.ReferencePrice is > 0m ? DbValues.Money((fill.Side == OrderSide.Buy ? fill.Price - fill.ReferencePrice.Value : fill.ReferencePrice.Value - fill.Price) / fill.ReferencePrice.Value * 10_000m) : null; + // SPEC 6.8: the reference rate in force when it happened, as known now; the tax export uses the one published for its day. + var rate = quoteCurrency == "EUR" ? null : await s.FirstOrDefaultAsync("SELECT rate FROM fx_rates WHERE base = 'EUR' AND quote = @q AND rate_date <= @d ORDER BY rate_date DESC", + r => (decimal?)r.Money("rate"), ("q", quoteCurrency), ("d", Data.BarStore.DayText(Data.Zones.DayIn(fill.ExecutedAt, Data.Zones.Frankfurt)))).ConfigureAwait(false); var fillId = Ids.NewId(clock); await s.ExecuteAsync( - "INSERT INTO fills (id, account_id, order_id, instrument_id, execution_id, side, quantity, price, fee, fee_currency, executed_at, created_at, strategy, reference_price, slippage_bp) " + - "VALUES (@id, @a, @o, @i, @e, @side, @q, @p, @fee, @fc, @at, @now, @st, @ref, @slip)", cancellationToken, + "INSERT INTO fills (id, account_id, order_id, instrument_id, execution_id, side, quantity, price, fee, fee_currency, executed_at, created_at, strategy, reference_price, slippage_bp, fx_rate) " + + "VALUES (@id, @a, @o, @i, @e, @side, @q, @p, @fee, @fc, @at, @now, @st, @ref, @slip, @fx)", cancellationToken, ("id", fillId), ("a", fill.AccountId), ("o", fill.OrderId), ("i", fill.InstrumentId), ("e", fill.ExecutionId), ("side", Wire.Text(fill.Side)), ("q", fill.Quantity), ("p", fill.Price), ("fee", fill.Fee), ("fc", fill.FeeCurrency), ("at", fill.ExecutedAt), ("now", now), - ("st", fill.Strategy), ("ref", fill.ReferencePrice), ("slip", slippage)).ConfigureAwait(false); + ("st", fill.Strategy), ("ref", fill.ReferencePrice), ("slip", slippage), ("fx", rate)).ConfigureAwait(false); var trade = await OpenTradeAsync(s, fill.AccountId, fill.InstrumentId, fill.Strategy).ConfigureAwait(false); var feeValue = feeInKind ? DbValues.Money(fill.Fee * fill.Price) : quoteFee; @@ -268,7 +284,7 @@ public sealed class Ledger(Database db, IClock clock) } var (_, quote) = await CurrenciesAsync(s, instrumentId).ConfigureAwait(false); - var outcome = await RecordFillAsync(s, new LedgerFill(accountId, instrumentId, strategy, "ANURESIDUE" + Ids.NewId(clock).ToString("N"), OrderSide.Sell, + var outcome = await RecordFillAsync(s, new LedgerFill(accountId, instrumentId, strategy, ResiduePrefix + Ids.NewId(clock).ToString("N"), OrderSide.Sell, position.Quantity, price, 0m, quote, clock.UtcNow) { ExitReason = "residue" }, cancellationToken).ConfigureAwait(false); var value = DbValues.Money(position.Quantity * price); @@ -297,11 +313,11 @@ public sealed class Ledger(Database db, IClock clock) var (_, quote) = await CurrenciesAsync(s, instrumentId).ConfigureAwait(false); var side = delta > 0m ? OrderSide.Buy : OrderSide.Sell; - await RecordFillAsync(s, new LedgerFill(accountId, instrumentId, strategy, "ANUADJUST" + Ids.NewId(clock).ToString("N"), side, + var outcome = await RecordFillAsync(s, new LedgerFill(accountId, instrumentId, strategy, AdjustmentPrefix + Ids.NewId(clock).ToString("N"), side, Math.Abs(delta), price, 0m, quote, clock.UtcNow) { ExitReason = "adjustment" }, cancellationToken).ConfigureAwait(false); var value = DbValues.Money(delta * price); - await AddCashAsync(s, accountId, strategy, quote, value, LedgerKinds.Adjustment, null, note, clock.UtcNow, cancellationToken).ConfigureAwait(false); + await AddCashAsync(s, accountId, strategy, quote, value, LedgerKinds.Adjustment, outcome.FillId, note, clock.UtcNow, cancellationToken).ConfigureAwait(false); }, cancellationToken); /// diff --git a/src/Anubis/Trading/TaxExport.cs b/src/Anubis/Trading/TaxExport.cs new file mode 100644 index 0000000..8d0f475 --- /dev/null +++ b/src/Anubis/Trading/TaxExport.cs @@ -0,0 +1,429 @@ +using System.Globalization; +using Anubis.Backtest; +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; + +namespace Anubis.Trading; + +public enum TaxKind +{ + Split, + Purchase, + Sale, + Dividend, + Residue, + Adjustment, + Correction, +} + +/// An event of the ledgers as the tax export reads it. is the traded one; a split has only its ratio. +internal sealed record TaxEvent(Guid Account, Guid? Instrument, DateTimeOffset At, TaxKind Kind, string Id) +{ + public string Strategy { get; init; } = ""; + + public bool Entering { get; init; } + + public decimal Quantity { get; init; } + + public decimal Price { get; init; } + + public decimal Fee { get; init; } + + public string FeeCurrency { get; init; } = ""; + + /// Money of a dividend or of a correction; units per share of a split. + public decimal Amount { get; init; } + + public string Currency { get; init; } = ""; + + public string? Symbol { get; init; } + + public string Note { get; init; } = ""; +} + +internal sealed record TaxAccount(string Name, string Broker, string World); + +internal sealed record TaxInstrument(string Symbol, string Name, string AssetClass, string? Base, string Quote); + +/// A row of the export. Amounts in euro are null when no rate is known: never zero. +public sealed record TaxRow(string World, string Account, DateTimeOffset At, DateOnly Day, TaxKind Kind, string Symbol, string Name, string AssetClass, string Strategy, string Id) +{ + /// A sale or an incoming quantity, for the label of residues and adjustments. + public bool Entering { get; init; } + + public decimal? Quantity { get; init; } + + public decimal? Price { get; init; } + + public string Currency { get; init; } = ""; + + public decimal? Gross { get; init; } + + public decimal? Fee { get; init; } + + public string? FeeCurrency { get; init; } + + public decimal? Rate { get; init; } + + public DateOnly? RateDate { get; init; } + + public decimal? GrossEur { get; init; } + + public decimal? FeeEur { get; init; } + + public decimal? CostEur { get; init; } + + public decimal? ResultEur { get; init; } + + public decimal? FxEffectEur { get; init; } + + public bool MissingRate { get; init; } + + public bool Provisional { get; init; } + + public string Note { get; init; } = ""; +} + +/// A sale and one of the purchases it consumes: the detail behind . +public sealed record TaxLot(string World, string Account, string Symbol, DateOnly Bought, DateOnly Sold, decimal Quantity, decimal? CostEur, decimal? ProceedsEur, string SaleId) +{ + public decimal? ResultEur => ProceedsEur - CostEur; +} + +/// +/// The operations for the tax return (SPEC 4.6, 6.8, 7.5): each with its value in euro at the ECB rate of its own +/// Italian day, or the last one before it, and for sales the cost of what was sold. The costs are computed again from +/// the executions, in the order of the purchases and for the whole account: what a strategy bought and another sold is +/// one holding for the law. The stored lots are not used, so the method can be changed at any time (ADR 0020). +/// +public sealed record TaxReport(string World, int? Year, LotMethod Method, IReadOnlyList Rows, IReadOnlyList Lots) +{ + public int MissingRates => Rows.Count(r => r.MissingRate); + + public int Provisional => Rows.Count(r => r.Provisional); + + private string MethodName => Method == LotMethod.Lifo ? "LIFO" : "FIFO"; + + private static string WorldName(string world) => world == Worlds.Real ? "soldi veri" : "simulazione"; + + private static decimal? Cents(decimal? value) => value is { } v ? Math.Round(v, 2, MidpointRounding.AwayFromZero) : null; + + // Trailing zeros dropped, so both database engines give the same text. + private static decimal? Plain(decimal? value) => value is { } v ? v / 1.000000000000000000000000000000000m : null; + + public byte[] Csv() => Format.Csv( + ["Ambiente", "Conto", "Data", "Ora", "Operazione", "Strumento", "Nome", "Tipo", "Strategia", "Quantità", "Prezzo", "Valuta", "Controvalore", "Commissione", "Valuta commissione", + "Cambio EUR/USD BCE", "Data del cambio", "Controvalore EUR", "Commissione EUR", $"Costo EUR ({MethodName})", "Risultato EUR", "Effetto cambio EUR", "Identificativo", "Nota"], + Rows.Select(r => (IReadOnlyList) + [ + WorldName(r.World), r.Account, r.Day, TimeZoneInfo.ConvertTime(r.At, Zones.Rome).ToString("HH:mm:ss", CultureInfo.InvariantCulture), Operation(r), r.Symbol, r.Name, + r.AssetClass switch { "" => "", "crypto" => "crypto", _ => "azione" }, r.Strategy, Plain(r.Quantity), Plain(r.Price), r.Currency, Plain(r.Gross), Plain(r.Fee), r.FeeCurrency, + Plain(r.Rate), r.RateDate, Cents(r.GrossEur), Cents(r.FeeEur), Cents(r.CostEur), Cents(r.ResultEur), Cents(r.FxEffectEur), r.Id, r.Note, + ])); + + /// One row for each purchase consumed by a sale, with its own date and cost. + public byte[] LotsCsv() => Format.Csv( + ["Ambiente", "Conto", "Strumento", "Comprato il", "Venduto il", "Quantità", $"Costo EUR ({MethodName})", "Ricavo EUR", "Risultato EUR", "Vendita"], + Lots.Select(l => (IReadOnlyList) + [WorldName(l.World), l.Account, l.Symbol, l.Bought, l.Sold, Plain(l.Quantity), Cents(l.CostEur), Cents(l.ProceedsEur), Cents(l.ResultEur), l.SaleId])); + + private static string Operation(TaxRow r) => r.Kind switch + { + TaxKind.Purchase => "Acquisto", + TaxKind.Sale => "Vendita", + TaxKind.Dividend => "Dividendo", + TaxKind.Split => "Frazionamento", + TaxKind.Residue => "Residuo tolto dal registro", + TaxKind.Adjustment => r.Quantity is null ? "Allineamento della liquidità" : r.Entering ? "Allineamento in entrata" : "Allineamento in uscita", + _ => "Storno", + }; +} + +public static class TaxExport +{ + public static readonly SettingDefinition MethodSetting = new("tax.lot_method", "Metodo per il costo delle vendite", "lifo", ["lifo", "fifo"]); + + public static LotMethod Method(string value) => value == "fifo" ? LotMethod.Fifo : LotMethod.Lifo; + + /// The worlds with an operation and the Italian years of those operations, for the choices of the page. + public static async Task Years)>> ChoicesAsync(Database db, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(db); + var (accounts, _, events, _) = await ReadAsync(db, cancellationToken).ConfigureAwait(false); + return events.GroupBy(e => accounts[e.Account].World) + .Select(g => (g.Key, (IReadOnlyList)[.. g.Select(e => Zones.DayIn(e.At, Zones.Rome).Year).Distinct().OrderDescending()])) + .OrderBy(g => g.Key, StringComparer.Ordinal).ToList(); + } + + /// The report of a world, for one Italian year or (null) for all of them. The costs always come from the whole history. + public static async Task LoadAsync(Database db, string world, int? year, LotMethod method, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(db); + var (accounts, instruments, events, rates) = await ReadAsync(db, cancellationToken).ConfigureAwait(false); + var (rows, lots) = Build(events.Where(e => accounts[e.Account].World == world), accounts, instruments, rates, method); + return new TaxReport(world, year, method, [.. rows.Where(r => year is null || r.Day.Year == year)], [.. lots.Where(l => year is null || l.Sold.Year == year)]); + } + + private static Task<(Dictionary Accounts, Dictionary Instruments, List Events, List Rates)> ReadAsync( + Database db, CancellationToken cancellationToken) => + db.ReadAsync(async s => + { + var accounts = (await s.QueryAsync("SELECT id, name, broker, environment FROM accounts", + r => (Id: r.Id("id"), Account: new TaxAccount(r.Text("name"), r.Text("broker"), TradingEnvironments.World(r.Text("environment"))))).ConfigureAwait(false)) + .ToDictionary(a => a.Id, a => a.Account); + var instruments = (await s.QueryAsync("SELECT id, symbol, name, asset_class, base_currency, quote_currency FROM instruments", + r => (Id: r.Id("id"), Instrument: new TaxInstrument(r.Text("symbol"), r.TextOrNull("name") ?? "", r.Text("asset_class"), r.TextOrNull("base_currency"), r.Text("quote_currency")))) + .ConfigureAwait(false)).ToDictionary(i => i.Id, i => i.Instrument); + var events = (await s.QueryAsync( + "SELECT id, account_id, instrument_id, execution_id, side, quantity, price, fee, fee_currency, executed_at, strategy FROM fills ORDER BY executed_at, id", + r => new TaxEvent(r.Id("account_id"), r.Id("instrument_id"), r.Moment("executed_at"), + r.Text("execution_id") is var e && e.StartsWith(Ledger.ResiduePrefix, StringComparison.Ordinal) ? TaxKind.Residue + : e.StartsWith(Ledger.AdjustmentPrefix, StringComparison.Ordinal) ? TaxKind.Adjustment + : Wire.Side(r.Text("side")) == OrderSide.Buy ? TaxKind.Purchase : TaxKind.Sale, + e) + { + Strategy = r.TextOrNull("strategy") ?? "", + Entering = Wire.Side(r.Text("side")) == OrderSide.Buy, + Quantity = r.Money("quantity"), + Price = r.Money("price"), + Fee = r.Money("fee"), + FeeCurrency = r.Text("fee_currency"), + }).ConfigureAwait(false)).ToList(); + + // The counterpart of a quantity aligned by the user is already in its execution. Rows written before the + // link between the two existed are recognised by account, strategy, instant and value. + var aligned = events.Where(e => e.Kind == TaxKind.Adjustment).Select(e => (e.Account, e.Strategy, e.At.ToUnixTimeSeconds(), DbValues.Money(e.Entering ? e.Quantity * e.Price : -e.Quantity * e.Price))).ToHashSet(); + var cash = await s.QueryAsync( + "SELECT id, account_id, strategy, currency, amount, kind, fill_id, note, occurred_at FROM cash_ledger WHERE kind IN ('dividend', 'reversal', 'adjustment') ORDER BY occurred_at, id", + r => (Fill: r.IdOrNull("fill_id"), Event: new TaxEvent(r.Id("account_id"), null, r.Moment("occurred_at"), r.Text("kind") switch + { + LedgerKinds.Dividend => TaxKind.Dividend, + LedgerKinds.Adjustment => TaxKind.Adjustment, + _ => TaxKind.Correction, + }, r.Id("id").ToString("N")) + { + Strategy = r.TextOrNull("strategy") ?? "", + Amount = r.Money("amount"), + Currency = r.Text("currency"), + Note = r.TextOrNull("note") ?? "", + Symbol = r.Text("kind") == LedgerKinds.Dividend ? Ledger.DividendSymbol(r.TextOrNull("note")) : null, + })).ConfigureAwait(false); + events.AddRange(cash.Where(c => c.Event.Kind != TaxKind.Adjustment || + (c.Fill is null && !aligned.Contains((c.Event.Account, c.Event.Strategy, c.Event.At.ToUnixTimeSeconds(), c.Event.Amount)))).Select(c => c.Event)); + + var applied = await s.QueryAsync("SELECT a.account_id, a.source_key, c.symbol, c.ex_date, c.ratio FROM applied_actions a JOIN corporate_actions c ON c.source_key = a.source_key", + r => (Account: r.Id("account_id"), Key: r.Text("source_key"), Symbol: r.Text("symbol"), Day: BarStore.ParseDay(r.Text("ex_date")), Ratio: r.MoneyOrNull("ratio"))).ConfigureAwait(false); + foreach (var split in applied.Where(a => a.Ratio is > 0m)) + { + // The instrument of that account with this symbol: the one that was traded there. + foreach (var instrument in events.Where(e => e.Account == split.Account && e.Instrument is { } i && instruments[i].Symbol == split.Symbol).Select(e => e.Instrument!.Value).Distinct().ToList()) + { + events.Add(new TaxEvent(split.Account, instrument, new DateTimeOffset(split.Day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero), TaxKind.Split, split.Key) { Amount = split.Ratio!.Value }); + } + } + + var rates = await s.QueryAsync("SELECT base, quote, rate_date, rate, source FROM fx_rates WHERE base = 'EUR' ORDER BY quote, rate_date", + r => new FxRate(r.Text("base"), r.Text("quote"), BarStore.ParseDay(r.Text("rate_date")), r.Money("rate"), r.Text("source"))).ConfigureAwait(false); + return (accounts, instruments, events, rates.ToList()); + }, cancellationToken); + + private sealed class Lot(DateTimeOffset at, decimal units, decimal cost, decimal? costEur) + { + public DateTimeOffset At { get; } = at; + + public decimal Units { get; set; } = units; + + public decimal Cost { get; set; } = cost; + + public decimal? CostEur { get; set; } = costEur; + } + + internal static (List Rows, List Lots) Build(IEnumerable events, IReadOnlyDictionary accounts, + IReadOnlyDictionary instruments, IReadOnlyList rates, LotMethod method) + { + var byCurrency = rates.GroupBy(r => r.Quote, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.OrderBy(r => r.Date).ToList(), StringComparer.Ordinal); + var rows = new List(); + var details = new List(); + var held = new Dictionary<(Guid, Guid), List>(); + + // On a tie a split comes first (it is at midnight of the ex-date, before that day's trades), then purchases. + foreach (var e in events.OrderBy(e => e.At).ThenBy(e => e.Kind).ThenBy(e => e.Id, StringComparer.Ordinal)) + { + var account = accounts[e.Account]; + var instrument = e.Instrument is { } id ? instruments[id] : null; + var day = Zones.DayIn(e.At, Zones.Rome); + var row = new TaxRow(account.World, account.Name, e.At, day, e.Kind, instrument?.Symbol ?? e.Symbol ?? "", instrument?.Name ?? "", instrument?.AssetClass ?? "", e.Strategy, e.Id) + { + Entering = e.Entering, + }; + if (instrument is null) + { + rows.Add(Money(row, e, RateOf(e.Currency, day, byCurrency))); + continue; + } + + var key = (e.Account, e.Instrument!.Value); + if (!held.TryGetValue(key, out var lots)) + { + held[key] = lots = []; + } + + if (e.Kind == TaxKind.Split) + { + var before = lots.Sum(l => l.Units); + foreach (var lot in lots) + { + lot.Units *= e.Amount; + } + + if (before > Ledger.Dust) + { + rows.Add(row with { Quantity = before * (e.Amount - 1m), Note = $"ogni azione diventa {Format.Quantity(e.Amount)}: il costo totale non cambia" }); + } + + continue; + } + + rows.Add(Traded(row, e, instrument, RateOf(instrument.Quote, day, byCurrency), lots, method, details)); + } + + return (rows, details); + } + + private static TaxRow Money(TaxRow row, TaxEvent e, RateOn rate) + { + var note = e.Kind switch + { + TaxKind.Dividend => "lordo, alla data di stacco: ritenute e data di pagamento sono nei documenti del broker", + TaxKind.Adjustment => "correzione scelta dall'utente: non è un guadagno né una perdita", + _ => e.Note, + }; + return Rated(row with { Currency = e.Currency, Gross = e.Amount, GrossEur = rate.Eur(e.Amount) }, rate, note); + } + + private static TaxRow Traded(TaxRow row, TaxEvent e, TaxInstrument instrument, RateOn rate, List lots, LotMethod method, List details) + { + var coin = instrument.Base ?? (instrument.Symbol.Contains('-', StringComparison.Ordinal) ? instrument.Symbol.Split('-')[0] : null); + var inKind = coin is not null && e.FeeCurrency == coin ? e.Fee : 0m; + var quoteFee = e.FeeCurrency == instrument.Quote ? e.Fee : 0m; + var gross = e.Quantity * e.Price; + var notes = new List(); + if (e.Fee > 0m && inKind == 0m && quoteFee == 0m) + { + notes.Add($"commissione in {e.FeeCurrency}: non è nel costo, valutala a parte"); + } + + row = row with + { + Quantity = e.Quantity, + Price = e.Price, + Currency = instrument.Quote, + Gross = gross, + Fee = e.Fee, + FeeCurrency = e.Fee > 0m ? e.FeeCurrency : null, + GrossEur = rate.Eur(gross), + FeeEur = e.Fee == 0m ? 0m : inKind > 0m ? rate.Eur(inKind * e.Price) : quoteFee > 0m ? rate.Eur(quoteFee) : null, + }; + + if (e.Entering) + { + // A fee kept in the coin leaves fewer units for the same money. + lots.Add(new Lot(e.At, e.Quantity - inKind, gross + quoteFee, rate.Eur(gross + quoteFee))); + if (e.Kind == TaxKind.Adjustment) + { + notes.Add("quantità portata nel registro su scelta dell'utente, al prezzo di mercato: il costo vero va preso dai tuoi documenti"); + } + + return Rated(row, rate, notes); + } + + var selling = e.Kind == TaxKind.Sale; + var moved = e.Quantity + inKind; + var proceeds = gross - quoteFee; + var proceedsEur = rate.Eur(proceeds); + var left = moved; + var cost = 0m; + decimal? costEur = 0m; + foreach (var lot in method == LotMethod.Lifo ? Enumerable.Reverse(lots) : lots) + { + if (left <= Ledger.Dust) + { + break; + } + + var take = Math.Min(left, lot.Units); + var part = take / lot.Units; + var (lotCost, lotCostEur) = (lot.Cost * part, lot.CostEur * part); + cost += lotCost; + costEur += lotCostEur; + if (selling) + { + details.Add(new TaxLot(row.World, row.Account, row.Symbol, Zones.DayIn(lot.At, Zones.Rome), row.Day, take, lotCostEur, proceedsEur * (take / moved), e.Id)); + } + + (lot.Units, lot.Cost, lot.CostEur) = (lot.Units - take, lot.Cost - lotCost, lot.CostEur - lotCostEur); + left -= take; + } + + lots.RemoveAll(l => l.Units <= Ledger.Dust); + if (!selling) + { + notes.Add(e.Kind == TaxKind.Residue ? "resta sul conto, non è una vendita: nessun guadagno e nessuna perdita" : "tolto dal registro su scelta dell'utente: non è una vendita"); + return Rated(row, rate, notes); + } + + if (left > Ledger.Dust) + { + notes.Add("non trovo gli acquisti di tutta la quantità venduta: costo da calcolare a mano"); + return Rated(row, rate, notes); + } + + if (costEur is null) + { + notes.Add("manca il cambio di un acquisto: costo da calcolare a mano"); + } + + return Rated(row with + { + CostEur = costEur, + ResultEur = proceedsEur - costEur, + FxEffectEur = instrument.Quote == "EUR" ? null : proceedsEur - costEur - rate.Eur(proceeds - cost), + }, rate, notes); + } + + private static TaxRow Rated(TaxRow row, RateOn rate, params IEnumerable notes) + { + var all = notes.Where(n => n.Length > 0).ToList(); + if (rate.Missing) + { + all.Add($"cambio della BCE mancante per {row.Currency}: importi in euro da calcolare a mano"); + } + else if (rate.Provisional) + { + all.Add("cambio provvisorio: la BCE non ha ancora pubblicato quello del giorno"); + } + + return row with { Rate = rate.Rate, RateDate = rate.Date, MissingRate = rate.Missing, Provisional = rate.Provisional, Note = string.Join("; ", all) }; + } + + /// The rate of a day: euro needs none, an unknown one leaves the amounts empty. + private readonly record struct RateOn(decimal? Rate, DateOnly? Date, bool Missing, bool Provisional) + { + public decimal? Eur(decimal amount) => Missing ? null : Rate is { } r ? amount / r : amount; + } + + private static RateOn RateOf(string currency, DateOnly day, Dictionary> rates) + { + if (currency == "EUR") + { + return new RateOn(null, null, false, false); + } + + var known = rates.GetValueOrDefault(currency) ?? []; + var rate = known.LastOrDefault(r => r.Date <= day); + return rate is null || rate.Date < day.AddDays(-EuroHistory.MaxRateAgeDays) || rate.Rate <= 0m + ? new RateOn(null, null, true, false) + : new RateOn(rate.Rate, rate.Date, false, rate.Date < day && known[^1].Date <= day); + } +} diff --git a/src/Anubis/Trading/TradingService.cs b/src/Anubis/Trading/TradingService.cs index 50672db..d646536 100644 --- a/src/Anubis/Trading/TradingService.cs +++ b/src/Anubis/Trading/TradingService.cs @@ -885,7 +885,7 @@ public sealed partial class TradingService : IDisposable { var amount = Math.Round(quantity * action.CashAmount!.Value, 2, MidpointRounding.ToZero); await Ledger.RecordDividendAsync(account.AccountId, strategy, amount, currency, exDate, - $"Dividendo {action.Symbol} {Format.Quantity(action.CashAmount!.Value)} per azione", cancellationToken, appliedKey: key + ":" + strategy).ConfigureAwait(false); + Ledger.DividendNote(action.Symbol, action.CashAmount!.Value), cancellationToken, appliedKey: key + ":" + strategy).ConfigureAwait(false); } await MarkAppliedAsync(account.AccountId, key, cancellationToken).ConfigureAwait(false); diff --git a/tests/Anubis.Tests/TaxExportTests.cs b/tests/Anubis.Tests/TaxExportTests.cs new file mode 100644 index 0000000..79fb111 --- /dev/null +++ b/tests/Anubis.Tests/TaxExportTests.cs @@ -0,0 +1,335 @@ +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); + } + } +}