R8: Accounting- + Supervisor-Modul + Core-Datenfundament (S-0)

Portierung der beiden fehlenden Grundbausteine aus PolytraderSharp (voller Ausbau).

Core S-0 (Datenfundament fuer Analyse/Forensik):
- core_decision_journal + core_order_events (+ ReasonCode/Decision/OrderEvent-Enums),
  IDecisionJournal/IOrderEventLog mit fehlertoleranten EF-Impls (Handel bricht nie).
- SignalId-Durchreichung TradeSignal -> ExecutionService -> core_trade_history;
  ExecutionService schreibt an jeder Verzweigung Journal/Order-Events.
- JSONL-Log-Sink (LogJson + Dual-Sink), pure Analytik: RealizedPnlEngine (FIFO),
  TradeAnalytics, DossierBuilder. Migration AddAnalysisFoundation.

Accounting-Modul (acc_): unabhaengiger IBKR-Kontoauszug (Activity Flex Query) hinter
Interfaces mit Offline-Null-Stubs -> append-only Ledger + Periodenabrechnung/BWA + FX
(USD/EUR) + CSV/PDF (PDFsharp/MigraDoc). Steuerschicht bewusst offen (Platzhalter-Tab).
Kein Handel. Migration InitialAccounting.

Supervisor-Modul (sup_): read-only OpenRouter-Agent (Function-Calling-Loop) + read-only
Tool-Registry (8 Tools) + Profile + Dossier-Browser + Counterfactual-Job (Stub) +
Tagesbericht/MCP-Light (opt-in). Migration InitialSupervisor.

Verdrahtung: Program.cs (beide Module + Icons), slnx/App/Tests-Referenzen,
provision-db.ps1, AppSettings-Sektionen, docs/konzepte, README.

Tests: 79 -> 117 gruen (FIFO/KPIs/Dossier/JSONL, Classifier/Engine/FX/Idempotenz,
OpenRouter/Registry/Agent/MCP, STA-Konstruktion beider neuen Fenster).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Richard
2026-07-31 09:25:18 +02:00
co-authored by Claude Opus 4.8
parent cbbedb2e0e
commit 2a312ca035
86 changed files with 6880 additions and 22 deletions
@@ -0,0 +1,58 @@
using FluentAssertions;
using IBKRTrader.Modules.Accounting.Logic;
using IBKRTrader.Modules.Accounting.Models;
namespace IBKRTrader.Tests.Modules.Accounting;
[Trait("cat", "unit")]
public class AccountingClassifierTests
{
[Fact]
public void ClassifyExecution_Buy_CostsGrossPlusFee()
{
var e = new RawExecution { AccountId = "U1", TradeId = "T1", Side = "BUY", GrossBase = 1000m, FeeBase = 1m, Quantity = 10, Currency = "USD" };
var entry = AccountingClassifier.ClassifyExecution(e, 5);
entry.EventType.Should().Be(LedgerEventType.TradeBuy);
entry.NetBase.Should().Be(-1001m);
entry.IdempotencyKey.Should().Be("TRD|TradeBuy|T1");
entry.IngestBatchId.Should().Be(5);
}
[Fact]
public void ClassifyExecution_Sell_BringsGrossMinusFee()
{
var e = new RawExecution { AccountId = "U1", TradeId = "T2", Side = "SELL", GrossBase = 1300m, FeeBase = 1m };
var entry = AccountingClassifier.ClassifyExecution(e, 1);
entry.EventType.Should().Be(LedgerEventType.TradeSell);
entry.NetBase.Should().Be(1299m);
}
[Theory]
[InlineData("Dividends", LedgerEventType.Dividend)]
[InlineData("Withholding Tax", LedgerEventType.TaxWithholding)]
[InlineData("Broker Interest Received", LedgerEventType.Interest)]
[InlineData("Deposit", LedgerEventType.Deposit)]
[InlineData("Withdrawal", LedgerEventType.Withdrawal)]
public void MapCashType_MapsKnownTypes(string ibkrType, LedgerEventType expected)
{
AccountingClassifier.MapCashType(ibkrType).Should().Be(expected);
}
[Fact]
public void ClassifyCashTransaction_KeepsReportedSign()
{
var div = new RawCashTransaction { AccountId = "U1", TransactionId = "C1", Type = "Dividends", AmountBase = 50m };
var tax = new RawCashTransaction { AccountId = "U1", TransactionId = "C2", Type = "Withholding Tax", AmountBase = -7.5m };
AccountingClassifier.ClassifyCashTransaction(div, 1).NetBase.Should().Be(50m);
var t = AccountingClassifier.ClassifyCashTransaction(tax, 1);
t.EventType.Should().Be(LedgerEventType.TaxWithholding);
t.NetBase.Should().Be(-7.5m);
t.GrossBase.Should().Be(7.5m);
t.IdempotencyKey.Should().Be("CASH|TaxWithholding|C2");
}
}
@@ -0,0 +1,75 @@
using FluentAssertions;
using IBKRTrader.Modules.Accounting.Logic;
using IBKRTrader.Modules.Accounting.Models;
namespace IBKRTrader.Tests.Modules.Accounting;
[Trait("cat", "unit")]
public class AccountingEngineTests
{
private static LedgerEntry E(LedgerEventType type, decimal net, decimal gross, int day, decimal fee = 0m) =>
new()
{
AccountId = "U1", EventType = type, NetBase = net, GrossBase = gross, FeeBase = fee,
Timestamp = new DateTime(2026, 3, day, 12, 0, 0, DateTimeKind.Utc)
};
[Fact]
public void Statement_SatisfiesBalanceInvariant()
{
var entries = new[]
{
E(LedgerEventType.Deposit, 1000m, 1000m, 1),
E(LedgerEventType.TradeBuy, -500m, 499m, 2, fee: 1m),
E(LedgerEventType.TradeSell, 650m, 651m, 3, fee: 1m),
E(LedgerEventType.Dividend, 20m, 20m, 4),
E(LedgerEventType.Withdrawal, -200m, 200m, 5)
};
var s = AccountingEngine.BuildStatement(entries, new DateTime(2026, 3, 1, 0, 0, 0, DateTimeKind.Utc),
new DateTime(2026, 3, 31, 23, 59, 59, DateTimeKind.Utc), "U1");
// Invariante: Endsaldo Anfang = Ergebnis + Einzahlungen Auszahlungen
s.BalanceChange.Should().Be(s.NetTradingResult + s.Deposits - s.Withdrawals);
s.Deposits.Should().Be(1000m);
s.Withdrawals.Should().Be(200m);
s.Dividends.Should().Be(20m);
s.Fees.Should().Be(2m);
s.TradeCount.Should().Be(2);
s.ClosingBalance.Should().Be(970m); // 1000 -500 +650 +20 -200
}
[Fact]
public void OpeningBalance_AccumulatesEntriesBeforeFrom()
{
var entries = new[]
{
E(LedgerEventType.Deposit, 500m, 500m, 1), // vor dem Zeitraum
E(LedgerEventType.Dividend, 30m, 30m, 20) // im Zeitraum
};
var s = AccountingEngine.BuildStatement(entries, new DateTime(2026, 3, 10, 0, 0, 0, DateTimeKind.Utc),
new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc), "U1");
s.OpeningBalance.Should().Be(500m);
s.ClosingBalance.Should().Be(530m);
}
[Fact]
public void MonthlyBreakdown_ChainsOpeningBalances()
{
var entries = new[]
{
E(LedgerEventType.Deposit, 100m, 100m, 1), // März
E(LedgerEventType.Dividend, 10m, 10m, 5)
};
var monthly = AccountingEngine.BuildMonthlyBreakdown(entries,
new DateTime(2026, 3, 1, 0, 0, 0, DateTimeKind.Utc),
new DateTime(2026, 4, 30, 0, 0, 0, DateTimeKind.Utc), "U1");
monthly.Should().HaveCount(2);
monthly[0].From.Month.Should().Be(3);
monthly[1].OpeningBalance.Should().Be(monthly[0].ClosingBalance); // April startet mit März-Endsaldo
}
}
@@ -0,0 +1,101 @@
using FluentAssertions;
using IBKRTrader.Core.Logging;
using IBKRTrader.Modules.Accounting.Models;
using IBKRTrader.Modules.Accounting.Persistence;
using IBKRTrader.Modules.Accounting.Services;
using Microsoft.EntityFrameworkCore;
namespace IBKRTrader.Tests.Modules.Accounting;
/// <summary>Ingest-Kern gegen EF-InMemory: Idempotenz (Doppel-Ingest bucht nicht doppelt) + Balance-Anker.</summary>
[Trait("cat", "unit")]
public class AccountingIngestServiceTests
{
private sealed class Factory(DbContextOptions<AccountingDbContext> options) : IDbContextFactory<AccountingDbContext>
{
public AccountingDbContext CreateDbContext() => new(options);
}
private sealed class FakeStatement : IStatementSource
{
public IReadOnlyList<RawExecution> Executions = Array.Empty<RawExecution>();
public IReadOnlyList<RawCashTransaction> Cash = Array.Empty<RawCashTransaction>();
public Task<IReadOnlyList<RawExecution>> GetExecutionsAsync(string a, DateTime? s, CancellationToken ct) => Task.FromResult(Executions);
public Task<IReadOnlyList<RawCashTransaction>> GetCashTransactionsAsync(string a, DateTime? s, CancellationToken ct) => Task.FromResult(Cash);
}
private sealed class FakeBalance(decimal? v) : IBalanceAnchorSource
{
public Task<decimal?> GetBalanceAsync(string a, CancellationToken ct) => Task.FromResult(v);
}
private static (AccountingIngestService svc, ILedgerRepository ledger) Build(FakeStatement stmt, decimal? anchor = null)
{
var opts = new DbContextOptionsBuilder<AccountingDbContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString()).Options;
var dbf = new Factory(opts);
var ledger = new EfLedgerRepository(dbf);
var svc = new AccountingIngestService(
new NullAccountSource(), ledger, new EfIngestRunRepository(dbf), new EfRawSnapshotRepository(dbf),
stmt, new FakeBalance(anchor), new LoggingService());
return (svc, ledger);
}
[Fact]
public async Task DoubleIngest_IsIdempotent()
{
var stmt = new FakeStatement
{
Executions = new[]
{
new RawExecution { AccountId = "U1", TradeId = "T1", Side = "BUY", GrossBase = 1000m, FeeBase = 1m,
Timestamp = new DateTime(2026, 1, 1, 10, 0, 0, DateTimeKind.Utc) }
},
Cash = new[]
{
new RawCashTransaction { AccountId = "U1", TransactionId = "C1", Type = "Dividends", AmountBase = 20m,
Timestamp = new DateTime(2026, 1, 2, 10, 0, 0, DateTimeKind.Utc) }
}
};
var (svc, ledger) = Build(stmt);
var run1 = await svc.IngestAccountAsync("U1", backfill: true, CancellationToken.None);
var run2 = await svc.IngestAccountAsync("U1", backfill: true, CancellationToken.None);
run1.NewEntries.Should().Be(2);
run1.DuplicateEntries.Should().Be(0);
run2.NewEntries.Should().Be(0); // zweiter Lauf bucht nichts neu
run2.DuplicateEntries.Should().Be(2);
ledger.Count("U1").Should().Be(2);
}
[Fact]
public async Task ComputesBalanceDelta_AgainstAnchor()
{
var stmt = new FakeStatement
{
Cash = new[]
{
new RawCashTransaction { AccountId = "U1", TransactionId = "D1", Type = "Deposit", AmountBase = 1000m,
Timestamp = new DateTime(2026, 1, 1, 10, 0, 0, DateTimeKind.Utc) }
}
};
var (svc, _) = Build(stmt, anchor: 1000m);
var run = await svc.IngestAccountAsync("U1", backfill: true, CancellationToken.None);
run.LedgerNetBase.Should().Be(1000m);
run.BalanceAnchorBase.Should().Be(1000m);
run.BalanceDeltaBase.Should().Be(0m); // vollständig
}
[Fact]
public async Task NoAccounts_IngestAll_DoesNothing()
{
var (svc, ledger) = Build(new FakeStatement());
await svc.IngestAllAsync(backfill: false, CancellationToken.None);
ledger.DistinctAccounts().Should().BeEmpty();
}
}
@@ -0,0 +1,59 @@
using FluentAssertions;
using IBKRTrader.Modules.Accounting.Logic;
using IBKRTrader.Modules.Accounting.Models;
namespace IBKRTrader.Tests.Modules.Accounting;
[Trait("cat", "unit")]
public class CsvExporterTests
{
[Fact]
public void Ledger_HasHeader_AndInvariantFormatting()
{
var entries = new[]
{
new LedgerEntry
{
AccountId = "U1", EventType = LedgerEventType.TradeSell, Side = "SELL", Symbol = "AAPL",
Currency = "USD", Quantity = 10m, PriceNative = 130.5m, GrossBase = 1305m, FeeBase = 1m,
NetBase = 1304m, TransactionId = "T1", Source = "ibkr-flex",
Timestamp = new DateTime(2026, 1, 2, 15, 4, 5, DateTimeKind.Utc)
}
};
var csv = CsvExporter.Ledger(entries);
csv.Should().StartWith("Timestamp,AccountId,EventType,Side,Symbol");
csv.Should().Contain("2026-01-02 15:04:05");
csv.Should().Contain("130.5"); // Punkt-Dezimal, kulturinvariant
csv.Should().Contain("TradeSell");
}
[Fact]
public void Quote_EscapesCommasAndQuotes()
{
var entries = new[]
{
new LedgerEntry { AccountId = "U1", Symbol = "A,B\"C", EventType = LedgerEventType.Other, TransactionId = "X" }
};
var csv = CsvExporter.Ledger(entries);
csv.Should().Contain("\"A,B\"\"C\"");
}
[Fact]
public void Statement_ListsKeyMetrics()
{
var s = new PeriodStatement("U1", DateTime.UtcNow.AddDays(-30), DateTime.UtcNow,
OpeningBalance: 100m, ClosingBalance: 150m, Deposits: 50m, Withdrawals: 0m,
TradeVolume: 200m, Dividends: 5m, Interest: 0m, Fees: 2m, TaxWithheld: 1m,
NetTradingResult: 0m, TradeCount: 3, EntryCount: 6);
var csv = CsvExporter.Statement(s, "USD");
csv.Should().Contain("Kennzahl,USD");
csv.Should().Contain("Anfangssaldo,100");
csv.Should().Contain("Endsaldo,150");
}
}
@@ -0,0 +1,39 @@
using FluentAssertions;
using IBKRTrader.Modules.Accounting.Logic;
using IBKRTrader.Modules.Accounting.Models;
namespace IBKRTrader.Tests.Modules.Accounting;
[Trait("cat", "unit")]
public class FxConverterTests
{
private static FxRate R(int day, decimal rate) =>
new() { Date = new DateTime(2026, 5, day), UsdToEur = rate, Source = "ECB" };
[Fact]
public void UsesNearestRateOnOrBefore()
{
var conv = new FxConverter(new[] { R(1, 0.90m), R(10, 0.92m) });
conv.UsdToEurOn(new DateTime(2026, 5, 5)).Should().Be(0.90m); // zwischen 1. und 10. → 0.90
conv.UsdToEurOn(new DateTime(2026, 5, 10)).Should().Be(0.92m); // exakt
conv.UsdToEurOn(new DateTime(2026, 5, 20)).Should().Be(0.92m); // nach letztem → letzter
}
[Fact]
public void ReturnsNull_WhenNoRateBeforeDate()
{
var conv = new FxConverter(new[] { R(10, 0.92m) });
conv.UsdToEurOn(new DateTime(2026, 5, 1)).Should().BeNull();
conv.UsdToEur(100m, new DateTime(2026, 5, 1)).Should().BeNull();
}
[Fact]
public void ConvertsAndRounds()
{
var conv = new FxConverter(new[] { R(1, 0.9123m) });
conv.UsdToEur(100m, new DateTime(2026, 5, 2)).Should().Be(91.23m);
}
}