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);
}
}
@@ -0,0 +1,59 @@
using FluentAssertions;
using IBKRTrader.Modules.Supervisor.Agent;
using IBKRTrader.Modules.Supervisor.Mcp;
namespace IBKRTrader.Tests.Modules.Supervisor;
[Trait("cat", "unit")]
public class McpJsonRpcTests
{
private static SupervisorToolRegistry Registry()
{
var reg = new SupervisorToolRegistry();
reg.Register(new SupervisorTool("echo", "Echo", """{"type":"object","properties":{"x":{"type":"string"}}}""",
args => SupervisorToolRegistry.GetString(args, "x") ?? ""));
return reg;
}
[Fact]
public void Initialize_ReturnsServerInfo()
{
var res = McpJsonRpc.Handle("""{"jsonrpc":"2.0","id":1,"method":"initialize"}""", Registry());
res.Should().Contain("ibkrtrader-supervisor").And.Contain("protocolVersion");
}
[Fact]
public void ToolsList_ListsTools()
{
var res = McpJsonRpc.Handle("""{"jsonrpc":"2.0","id":2,"method":"tools/list"}""", Registry());
res.Should().Contain("echo").And.Contain("inputSchema");
}
[Fact]
public void ToolsCall_ExecutesAndWrapsResult()
{
var res = McpJsonRpc.Handle(
"""{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"echo","arguments":{"x":"hi"}}}""",
Registry());
res.Should().Contain("\"text\":\"hi\"").And.Contain("\"isError\":false");
}
[Fact]
public void UnknownMethod_ReturnsMethodNotFound()
{
var res = McpJsonRpc.Handle("""{"jsonrpc":"2.0","id":4,"method":"nope"}""", Registry());
res.Should().Contain("-32601");
}
[Fact]
public void ParseError_ReturnsMinus32700()
{
McpJsonRpc.Handle("{ kaputt", Registry()).Should().Contain("-32700");
}
[Fact]
public void Notification_WithoutId_ReturnsNull()
{
McpJsonRpc.Handle("""{"jsonrpc":"2.0","method":"ping"}""", Registry()).Should().BeNull();
}
}
@@ -0,0 +1,55 @@
using FluentAssertions;
using IBKRTrader.Modules.Supervisor.Agent;
namespace IBKRTrader.Tests.Modules.Supervisor;
[Trait("cat", "unit")]
public class OpenRouterClientTests
{
private static SupervisorTool Tool() => new(
"get_kpis", "KPIs", """{"type":"object","properties":{"module":{"type":"string"}}}""", _ => "{}");
[Fact]
public void BuildRequestBody_IncludesModelMessagesAndTools()
{
var messages = new[] { ChatMessage.System("sys"), ChatMessage.User("frage?") };
var body = OpenRouterClient.BuildRequestBody("openrouter/auto", messages, new[] { Tool() });
body.Should().Contain("\"model\":\"openrouter/auto\"");
body.Should().Contain("\"role\":\"system\"");
body.Should().Contain("frage?");
body.Should().Contain("\"name\":\"get_kpis\"");
body.Should().Contain("\"parameters\"");
}
[Fact]
public void ParseResponse_ExtractsContentAndUsage()
{
const string json = """
{"choices":[{"message":{"content":"Antwort","role":"assistant"}}],
"usage":{"prompt_tokens":12,"completion_tokens":3}}
""";
var r = OpenRouterClient.ParseResponse(json);
r.Content.Should().Be("Antwort");
r.ToolCalls.Should().BeEmpty();
r.PromptTokens.Should().Be(12);
r.CompletionTokens.Should().Be(3);
}
[Fact]
public void ParseResponse_ExtractsToolCalls()
{
const string json = """
{"choices":[{"message":{"role":"assistant","content":null,
"tool_calls":[{"id":"call_1","type":"function","function":{"name":"get_kpis","arguments":"{\"module\":\"CT\"}"}}]}}]}
""";
var r = OpenRouterClient.ParseResponse(json);
r.ToolCalls.Should().HaveCount(1);
r.ToolCalls[0].Name.Should().Be("get_kpis");
r.ToolCalls[0].ArgumentsJson.Should().Contain("CT");
}
}
@@ -0,0 +1,75 @@
using FluentAssertions;
using IBKRTrader.Modules.Supervisor.Agent;
namespace IBKRTrader.Tests.Modules.Supervisor;
[Trait("cat", "unit")]
public class SupervisorAgentTests
{
/// <summary>Fake-Client: gibt vorab definierte Antworten der Reihe nach zurück.</summary>
private sealed class FakeChat : IChatCompletionClient
{
private readonly Queue<ChatResponse> _responses;
public List<string> SeenToolResults { get; } = new();
public FakeChat(params ChatResponse[] responses) => _responses = new(responses);
public Task<ChatResponse> CompleteAsync(string model, IReadOnlyList<ChatMessage> messages,
IReadOnlyList<SupervisorTool> tools, CancellationToken ct)
{
foreach (var m in messages)
if (m.Role == "tool" && m.Content != null) SeenToolResults.Add(m.Content);
return Task.FromResult(_responses.Dequeue());
}
}
private static SupervisorToolRegistry EchoRegistry()
{
var reg = new SupervisorToolRegistry();
reg.Register(new SupervisorTool("get_kpis", "KPIs", """{"type":"object"}""", _ => "{\"NetPnl\":42}"));
return reg;
}
[Fact]
public async Task RunsToolThenReturnsFinalAnswer()
{
var chat = new FakeChat(
new ChatResponse { ToolCalls = { new ToolCall("c1", "get_kpis", "{}") } },
new ChatResponse { Content = "Netto-PnL ist 42." });
var agent = new SupervisorAgent(chat, EchoRegistry());
var result = await agent.AskAsync("Wie ist die Performance?");
result.Answer.Should().Be("Netto-PnL ist 42.");
result.ToolInvocations.Should().ContainSingle();
result.ToolInvocations[0].Tool.Should().Be("get_kpis");
chat.SeenToolResults.Should().Contain(s => s.Contains("42")); // Tool-Ergebnis ging ans Modell zurück
}
[Fact]
public async Task ProfileFilter_DeniesUnlistedTool()
{
var chat = new FakeChat(
new ChatResponse { ToolCalls = { new ToolCall("c1", "get_kpis", "{}") } },
new ChatResponse { Content = "fertig" });
// Technik-Profil listet get_kpis NICHT → Ausführung verweigert.
var agent = new SupervisorAgent(chat, EchoRegistry());
var result = await agent.AskAsync("test", profile: SupervisorProfiles.Technik);
result.ToolInvocations[0].Result.Should().Contain("nicht freigegeben");
}
[Fact]
public async Task StopsAfterMaxIterations()
{
// Modell fordert IMMER ein Tool an → harte Iterationsgrenze greift.
var always = Enumerable.Range(0, SupervisorAgent.MaxIterations + 2)
.Select(_ => new ChatResponse { ToolCalls = { new ToolCall("c", "get_kpis", "{}") } })
.ToArray();
var agent = new SupervisorAgent(new FakeChat(always), EchoRegistry());
var result = await agent.AskAsync("Endlosschleife?");
result.Answer.Should().Contain("maximale Tool-Iterationen");
}
}
@@ -0,0 +1,47 @@
using FluentAssertions;
using IBKRTrader.Modules.Supervisor.Agent;
namespace IBKRTrader.Tests.Modules.Supervisor;
[Trait("cat", "unit")]
public class SupervisorToolRegistryTests
{
private static SupervisorToolRegistry WithEcho()
{
var reg = new SupervisorToolRegistry();
reg.Register(new SupervisorTool("echo", "Echo", """{"type":"object","properties":{"x":{"type":"string"}}}""",
args => SupervisorToolRegistry.GetString(args, "x") ?? "(leer)"));
return reg;
}
[Fact]
public void UnknownTool_ReturnsErrorText_DoesNotThrow()
{
var reg = WithEcho();
reg.Execute("nope", "{}").Should().StartWith("FEHLER: Unbekanntes Tool");
}
[Fact]
public void InvalidJsonArgs_ReturnsErrorText()
{
var reg = WithEcho();
reg.Execute("echo", "{ kaputt").Should().StartWith("FEHLER: Ungültige Tool-Argumente");
}
[Fact]
public void ExecutesRegisteredTool()
{
var reg = WithEcho();
reg.Execute("echo", """{"x":"hallo"}""").Should().Be("hallo");
}
[Fact]
public void ToolException_IsCaught_AsErrorText()
{
var reg = new SupervisorToolRegistry();
reg.Register(new SupervisorTool("boom", "Boom", """{"type":"object"}""",
_ => throw new InvalidOperationException("geplatzt")));
reg.Execute("boom", "{}").Should().Contain("geplatzt");
}
}