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,44 @@
using FluentAssertions;
using IBKRTrader.Core.Analytics;
using IBKRTrader.Core.Logging;
using IBKRTrader.Core.Persistence.Entities;
namespace IBKRTrader.Tests.Analytics;
[Trait("cat", "unit")]
public class DossierBuilderTests
{
[Fact]
public void Build_OrdersEverythingChronologically()
{
var decisions = new[]
{
new CoreDecisionRecord { SignalId = "s", Timestamp = new DateTime(2026,1,1,0,2,0,DateTimeKind.Utc), Decision = TradeDecision.Executed },
new CoreDecisionRecord { SignalId = "s", Timestamp = new DateTime(2026,1,1,0,1,0,DateTimeKind.Utc), Decision = TradeDecision.Skipped }
};
var dossier = DossierBuilder.Build("s", decisions,
Array.Empty<CoreOrderEvent>(), Array.Empty<CoreTrade>(), Array.Empty<LogJson.ParsedLogLine>());
dossier.Decisions[0].Decision.Should().Be(TradeDecision.Skipped); // frühester zuerst
dossier.Decisions[1].Decision.Should().Be(TradeDecision.Executed);
}
[Fact]
public void ToMarkdown_And_ToJson_ContainSignalId_AndData()
{
var decisions = new[]
{
new CoreDecisionRecord { SignalId = "sig-9", Module = "CT", Symbol = "AAPL", Side = "BUY",
Decision = TradeDecision.Rejected, Reason = DecisionReason.RiskRejected, Message = "Limit überschritten" }
};
var dossier = DossierBuilder.Build("sig-9", decisions,
Array.Empty<CoreOrderEvent>(), Array.Empty<CoreTrade>(), Array.Empty<LogJson.ParsedLogLine>());
var md = DossierBuilder.ToMarkdown(dossier);
md.Should().Contain("sig-9").And.Contain("RiskRejected").And.Contain("Limit überschritten");
var json = DossierBuilder.ToJson(dossier);
json.Should().Contain("sig-9").And.Contain("RiskRejected");
}
}
@@ -0,0 +1,85 @@
using FluentAssertions;
using IBKRTrader.Core.Analytics;
using IBKRTrader.Core.Persistence.Entities;
namespace IBKRTrader.Tests.Analytics;
[Trait("cat", "unit")]
public class RealizedPnlEngineTests
{
private static CoreTrade Fill(string action, decimal qty, decimal price, int minute, string symbol = "AAPL") =>
new()
{
Module = "CT", Symbol = symbol, Action = action,
Quantity = qty, Price = price, TotalValue = qty * price,
TradedAt = new DateTime(2026, 1, 1, 0, minute, 0, DateTimeKind.Utc)
};
[Fact]
public void BuyThenSellAll_RealizesFullPnl()
{
var fills = new[] { Fill("BUY", 10, 100m, 0), Fill("SELL", 10, 130m, 1) };
var realized = RealizedPnlEngine.Match(fills);
realized.Should().HaveCount(1);
realized[0].RealizedPnl.Should().Be(300m); // (130-100)*10
}
[Fact]
public void Sell_MatchesOldestLotsFirst_Fifo()
{
var fills = new[]
{
Fill("BUY", 10, 100m, 0),
Fill("BUY", 10, 120m, 1),
Fill("SELL", 15, 130m, 2) // 10 gegen 100er-Lot, 5 gegen 120er-Lot
};
var realized = RealizedPnlEngine.Match(fills);
realized.Should().HaveCount(2);
realized[0].RealizedPnl.Should().Be((130m - 100m) * 10m); // 300
realized[1].RealizedPnl.Should().Be((130m - 120m) * 5m); // 50
RealizedPnlEngine.TotalRealized(fills).Should().Be(350m);
}
[Fact]
public void PartialSell_LeavesRemainderOpen()
{
var fills = new[] { Fill("BUY", 10, 100m, 0), Fill("SELL", 4, 130m, 1) };
var realized = RealizedPnlEngine.Match(fills);
realized.Should().HaveCount(1);
realized[0].Quantity.Should().Be(4m);
realized[0].RealizedPnl.Should().Be(120m);
}
[Fact]
public void SellExceedingHoldings_IgnoresSurplus_NoShort()
{
var fills = new[] { Fill("BUY", 5, 100m, 0), Fill("SELL", 8, 130m, 1) };
var realized = RealizedPnlEngine.Match(fills);
realized.Should().HaveCount(1);
realized[0].Quantity.Should().Be(5m); // nur die gehaltenen 5 realisiert
}
[Fact]
public void SeparatesBySymbol()
{
var fills = new[]
{
Fill("BUY", 10, 100m, 0, "AAPL"),
Fill("BUY", 10, 50m, 1, "MSFT"),
Fill("SELL", 10, 130m, 2, "AAPL")
};
var realized = RealizedPnlEngine.Match(fills);
realized.Should().HaveCount(1);
realized[0].Symbol.Should().Be("AAPL");
}
}
@@ -0,0 +1,65 @@
using FluentAssertions;
using IBKRTrader.Core.Analytics;
using IBKRTrader.Core.Persistence.Entities;
namespace IBKRTrader.Tests.Analytics;
[Trait("cat", "unit")]
public class TradeAnalyticsTests
{
private static CoreTrade Fill(string module, string action, decimal qty, decimal price, int minute, string symbol = "AAPL") =>
new()
{
Module = module, Symbol = symbol, Action = action,
Quantity = qty, Price = price, TotalValue = qty * price,
TradedAt = new DateTime(2026, 1, 1, 0, minute, 0, DateTimeKind.Utc)
};
[Fact]
public void EmptyInput_YieldsZeroKpis()
{
var k = TradeAnalytics.ComputeKpis(Array.Empty<CoreTrade>());
k.TradeCount.Should().Be(0);
k.NetPnl.Should().Be(0m);
k.WinRatePct.Should().Be(0d);
}
[Fact]
public void ComputesWinRateAndProfitFactor()
{
var fills = new[]
{
Fill("CT", "BUY", 10, 100m, 0),
Fill("CT", "SELL", 10, 130m, 1), // +300 Gewinner
Fill("CT", "BUY", 10, 100m, 2, "MSFT"),
Fill("CT", "SELL", 10, 90m, 3, "MSFT") // -100 Verlierer
};
var k = TradeAnalytics.ComputeKpis(fills);
k.TradeCount.Should().Be(2);
k.NetPnl.Should().Be(200m);
k.WinRatePct.Should().Be(50d);
k.ProfitFactor.Should().Be(3d); // 300 / 100
}
[Fact]
public void PnlByModule_GroupsAndSorts()
{
var fills = new[]
{
Fill("A", "BUY", 10, 100m, 0),
Fill("A", "SELL", 10, 130m, 1), // +300
Fill("B", "BUY", 10, 100m, 2, "MSFT"),
Fill("B", "SELL", 10, 90m, 3, "MSFT") // -100
};
var buckets = TradeAnalytics.PnlByModule(fills);
buckets.Should().HaveCount(2);
buckets[0].Key.Should().Be("A");
buckets[0].Pnl.Should().Be(300m);
buckets[1].Key.Should().Be("B");
}
}
@@ -24,6 +24,8 @@
<ItemGroup>
<ProjectReference Include="..\..\src\IBKRTrader.Core\IBKRTrader.Core.csproj" />
<ProjectReference Include="..\..\src\IBKRTrader.Modules.CongressTrading\IBKRTrader.Modules.CongressTrading.csproj" />
<ProjectReference Include="..\..\src\IBKRTrader.Modules.Accounting\IBKRTrader.Modules.Accounting.csproj" />
<ProjectReference Include="..\..\src\IBKRTrader.Modules.Supervisor\IBKRTrader.Modules.Supervisor.csproj" />
</ItemGroup>
<ItemGroup>
@@ -0,0 +1,43 @@
using FluentAssertions;
using IBKRTrader.Core.Logging;
namespace IBKRTrader.Tests.Logging;
[Trait("cat", "unit")]
public class LogJsonTests
{
[Fact]
public void RoundTrip_PreservesFields()
{
var ts = new DateTime(2026, 7, 30, 12, 34, 56, DateTimeKind.Utc);
var line = LogJson.WriteLine(ts, AppLogLevel.Warn, "CT", "Kurs fehlt für AAPL", "sig-123");
var parsed = LogJson.ParseLine(line);
parsed.Should().NotBeNull();
parsed!.Ts.Should().Be(ts);
parsed.Level.Should().Be("Warn");
parsed.Source.Should().Be("CT");
parsed.Cid.Should().Be("sig-123");
parsed.Message.Should().Be("Kurs fehlt für AAPL");
}
[Fact]
public void WriteLine_OmitsCid_WhenNull()
{
var line = LogJson.WriteLine(DateTime.UtcNow, AppLogLevel.Info, "Core", "hello", null);
line.Should().NotContain("cid");
LogJson.ParseLine(line)!.Cid.Should().BeNull();
}
[Theory]
[InlineData("")]
[InlineData(" ")]
[InlineData("nicht json")]
[InlineData("{ kaputt")]
public void ParseLine_ReturnsNull_OnGarbage(string input)
{
LogJson.ParseLine(input).Should().BeNull();
}
}
@@ -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");
}
}
@@ -0,0 +1,72 @@
using FluentAssertions;
using IBKRTrader.Core.Logging;
using IBKRTrader.Core.Persistence.Ef;
using IBKRTrader.Core.Persistence.Entities;
using Microsoft.EntityFrameworkCore;
namespace IBKRTrader.Tests.Persistence;
/// <summary>Entscheidungsjournal + Order-Event-Log gegen EF-InMemory, inkl. Robustheits-Garantie.</summary>
[Trait("cat", "unit")]
public class AnalysisJournalsTests
{
private sealed class Factory<T>(DbContextOptions<T> options) : IDbContextFactory<T> where T : DbContext
{
public T CreateDbContext() => (T)Activator.CreateInstance(typeof(T), options)!;
}
/// <summary>Factory, die immer wirft simuliert einen DB-Ausfall.</summary>
private sealed class ThrowingFactory : IDbContextFactory<CoreDbContext>
{
public CoreDbContext CreateDbContext() => throw new InvalidOperationException("DB weg");
}
private static Factory<CoreDbContext> InMemory() =>
new(new DbContextOptionsBuilder<CoreDbContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString()).Options);
[Fact]
public void DecisionJournal_WritesAndQueriesBack()
{
var journal = new EfDecisionJournal(InMemory(), new LoggingService());
journal.Write(new CoreDecisionRecord
{
SignalId = "sig-1", Module = "CT", Symbol = "AAPL", Side = "BUY",
Decision = TradeDecision.Rejected, Reason = DecisionReason.RiskRejected, Message = "Limit"
});
var rows = journal.Query(d => d.SignalId == "sig-1");
rows.Should().HaveCount(1);
rows[0].Reason.Should().Be(DecisionReason.RiskRejected);
}
[Fact]
public void OrderEventLog_WritesAndQueriesBack()
{
var log = new EfOrderEventLog(InMemory(), new LoggingService());
log.Write(new CoreOrderEvent
{
SignalId = "sig-2", Module = "CT", Symbol = "AAPL",
EventType = OrderEventType.Filled, Side = "BUY", Quantity = 5, Price = 100m, Response = "OK"
});
var rows = log.Query(e => e.SignalId == "sig-2");
rows.Should().HaveCount(1);
rows[0].EventType.Should().Be(OrderEventType.Filled);
}
[Fact]
public void Write_NeverThrows_OnDbFailure()
{
var journal = new EfDecisionJournal(new ThrowingFactory(), new LoggingService());
var log = new EfOrderEventLog(new ThrowingFactory(), new LoggingService());
var writeJournal = () => journal.Write(new CoreDecisionRecord { SignalId = "x" });
var writeEvent = () => log.Write(new CoreOrderEvent { SignalId = "x" });
writeJournal.Should().NotThrow();
writeEvent.Should().NotThrow();
}
}
@@ -1,5 +1,6 @@
using FluentAssertions;
using IBKRTrader.Core.Logging;
using IBKRTrader.Core.Persistence;
using IBKRTrader.Core.Settings;
using IBKRTrader.Core.Trading;
using NSubstitute;
@@ -13,9 +14,11 @@ public class ExecutionServiceTests
private readonly IRiskService _risk = Substitute.For<IRiskService>();
private readonly IPortfolioService _portfolio = Substitute.For<IPortfolioService>();
private readonly SettingsService _settings = new();
private readonly IDecisionJournal _journal = Substitute.For<IDecisionJournal>();
private readonly IOrderEventLog _orderLog = Substitute.For<IOrderEventLog>();
private ExecutionService CreateSut() =>
new(_broker, _risk, _portfolio, _settings, new LoggingService());
new(_broker, _risk, _portfolio, _settings, new LoggingService(), _journal, _orderLog);
private static readonly TradeSignal BuySignal = new()
{
@@ -92,7 +95,7 @@ public class ExecutionServiceTests
result.Executed.Should().BeTrue();
result.Order!.OrderId.Should().Be("O1");
await _portfolio.Received(1).RecordFillAsync(
"CT", "AAPL", TradeSide.Buy, 5, 100m, "O1", Arg.Any<CancellationToken>());
"CT", "AAPL", TradeSide.Buy, 5, 100m, "O1", Arg.Any<string?>(), Arg.Any<CancellationToken>());
}
[Fact]
@@ -107,6 +110,34 @@ public class ExecutionServiceTests
Arg.Any<CancellationToken>());
}
[Fact]
public async Task TradingDisabled_WritesSkippedDecision()
{
await CreateSut().ExecuteAsync(BuySignal);
_journal.Received().Write(Arg.Is<IBKRTrader.Core.Persistence.Entities.CoreDecisionRecord>(
d => d.Decision == IBKRTrader.Core.Persistence.Entities.TradeDecision.Skipped &&
d.Reason == IBKRTrader.Core.Persistence.Entities.DecisionReason.TradingDisabled));
}
[Fact]
public async Task HappyPath_PropagatesSignalId_AndJournalsExecuted()
{
ArrangeHappyPath();
var signal = new TradeSignal { Symbol = "AAPL", Side = TradeSide.Buy, SourceModule = "CT", SignalId = "sig-abc" };
await CreateSut().ExecuteAsync(signal);
await _portfolio.Received(1).RecordFillAsync(
"CT", "AAPL", TradeSide.Buy, 5, 100m, "O1", "sig-abc", Arg.Any<CancellationToken>());
_journal.Received().Write(Arg.Is<IBKRTrader.Core.Persistence.Entities.CoreDecisionRecord>(
d => d.SignalId == "sig-abc" &&
d.Decision == IBKRTrader.Core.Persistence.Entities.TradeDecision.Executed));
_orderLog.Received().Write(Arg.Is<IBKRTrader.Core.Persistence.Entities.CoreOrderEvent>(
e => e.SignalId == "sig-abc" &&
e.EventType == IBKRTrader.Core.Persistence.Entities.OrderEventType.Filled));
}
[Fact]
public async Task OrderFails_ReturnsError_AndDoesNotBook()
{
@@ -120,6 +151,6 @@ public class ExecutionServiceTests
result.Reason.Should().Contain("Broker abgelehnt");
await _portfolio.DidNotReceive().RecordFillAsync(
Arg.Any<string>(), Arg.Any<string>(), Arg.Any<TradeSide>(),
Arg.Any<int>(), Arg.Any<decimal>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
Arg.Any<int>(), Arg.Any<decimal>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,87 @@
using FluentAssertions;
using IBKRTrader.Core.Logging;
using IBKRTrader.Core.Persistence;
using IBKRTrader.Core.Persistence.Ef;
using IBKRTrader.Modules.Accounting.Persistence;
using IBKRTrader.Modules.Accounting.Services;
using IBKRTrader.Modules.Accounting.Ui;
using IBKRTrader.Modules.Supervisor.Agent;
using IBKRTrader.Modules.Supervisor.Persistence;
using IBKRTrader.Modules.Supervisor.Services;
using IBKRTrader.Modules.Supervisor.Ui;
using Microsoft.EntityFrameworkCore;
namespace IBKRTrader.Tests;
/// <summary>
/// Konstruiert die neuen Modul-Fenster mit In-Memory-/Stub-Abhängigkeiten gleichwertig zum
/// Headless-Smoke-UI-Check (`--smoke-ui`), aber ohne die laufende App/DB. Forms bauen im Konstruktor
/// nur Controls (DB-Zugriff erst auf Interaktion), daher genügt Instanziierbarkeit der Services.
/// </summary>
[Trait("cat", "unit")]
public class UiConstructionTests
{
private sealed class Factory<T>(DbContextOptions<T> options) : IDbContextFactory<T> where T : DbContext
{
public T CreateDbContext() => (T)Activator.CreateInstance(typeof(T), options)!;
}
private static Factory<T> InMemory<T>() where T : DbContext =>
new(new DbContextOptionsBuilder<T>().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options);
private sealed class NoChat : IChatCompletionClient
{
public Task<ChatResponse> CompleteAsync(string m, IReadOnlyList<ChatMessage> msgs,
IReadOnlyList<SupervisorTool> tools, CancellationToken ct) => Task.FromResult(new ChatResponse());
}
private static Exception? ConstructOnSta(Action action)
{
Exception? captured = null;
var t = new Thread(() => { try { action(); } catch (Exception ex) { captured = ex; } });
t.SetApartmentState(ApartmentState.STA);
t.Start();
t.Join();
return captured;
}
[Fact]
public void AccountingMainForm_Constructs()
{
var ex = ConstructOnSta(() =>
{
var logger = new LoggingService();
var accDbf = InMemory<AccountingDbContext>();
var ledger = new EfLedgerRepository(accDbf);
var runs = new EfIngestRunRepository(accDbf);
var report = new AccountingReportService(ledger, new EfFxRateRepository(accDbf));
var ingest = new AccountingIngestService(
new NullAccountSource(), ledger, runs, new EfRawSnapshotRepository(accDbf),
new NullStatementSource(), new NullBalanceAnchorSource(), logger);
using var form = new AccountingMainForm(ledger, runs, report, ingest, logger);
form.Text.Should().Be("Accounting");
});
ex.Should().BeNull();
}
[Fact]
public void SupervisorMainForm_Constructs()
{
var ex = ConstructOnSta(() =>
{
var logger = new LoggingService();
var coreDbf = InMemory<CoreDbContext>();
var supDbf = InMemory<SupervisorDbContext>();
IDecisionJournal journal = new EfDecisionJournal(coreDbf, logger);
IOrderEventLog orderLog = new EfOrderEventLog(coreDbf, logger);
var dossiers = new DossierService(journal, orderLog, new TradeLogReader(coreDbf));
var agent = new SupervisorAgent(new NoChat(), new SupervisorToolRegistry());
var reports = new EfSupervisorReportRepository(supDbf, logger);
using var form = new SupervisorMainForm(agent, dossiers, reports, logger);
form.Text.Should().Be("Supervisor");
});
ex.Should().BeNull();
}
}