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.
+ }
+ @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