Supervisor S-1: Dossier-Generator + Modul-Skelett mit Dossier-Browser + Journal-Nachverdrahtung
Neues Modul PolyTrader.Modules.Supervisor (IPolyTraderModule, Name=Supervisor, DbPrefix=sup_, nur Core-Referenz, strikt read-only): - DossierBuilder (Core/Analytics, pur+getestet): TradeDossier aus Entscheidungen + Order-Events + Trades + Log-Zeilen, chronologisch, mit Markdown-Rendering (Tabellen, Pipe-Escaping). - DossierService (Modul): beschafft Journal/Events/Trade-Log per SignalId + JSONL-Zeilen per CID (nur Tagesdateien im Ereignis-Zeitfenster +-1 Tag); RecentSignals-Uebersicht (Journal gruppiert). - SupervisorMainForm: Dossier-Browser - links juengste Signale, rechts Markdown-Dossier; SignalId-Suche; Analyse-Chat (OpenRouter) folgt in S-2. In Launcher/Smoke registriert. Journal-Nachverdrahtung (S-0-Vervollstaendigung): - TraderMonitor: Profit-Target erzeugt eigene SignalId -> Leiter + Journal (ProfitTargetTriggered); Stale-Cleanup-Cancels als OrderEvents (StaleCleanupCancel). - StartupOrderReconciliation: K2-Cancels als OrderEvents (StartupReconcileCancel). - RF: Demo-Einstiege (DemoFilled, eigene SignalId) + Resolution-Closes (SystemResolutionClose) im Journal - damit sind ALLE Module im Entscheidungsjournal vertreten. Tests: +3 DossierBuilder; 4 Service-Builder auf neue Ctors. Build 0 Fehler, 344 Tests gruen, --smoke-ui: [OK] supervisor.main (alle 5 Views gruen). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
ca00977ea3
commit
c75a958e36
@@ -89,6 +89,7 @@
|
|||||||
<ProjectReference Include="src\PolyTrader.Core\PolyTrader.Core.csproj" />
|
<ProjectReference Include="src\PolyTrader.Core\PolyTrader.Core.csproj" />
|
||||||
<ProjectReference Include="src\PolyTrader.Modules.CopyTrading\PolyTrader.Modules.CopyTrading.csproj" />
|
<ProjectReference Include="src\PolyTrader.Modules.CopyTrading\PolyTrader.Modules.CopyTrading.csproj" />
|
||||||
<ProjectReference Include="src\PolyTrader.Modules.ResolutionFarming\PolyTrader.Modules.ResolutionFarming.csproj" />
|
<ProjectReference Include="src\PolyTrader.Modules.ResolutionFarming\PolyTrader.Modules.ResolutionFarming.csproj" />
|
||||||
|
<ProjectReference Include="src\PolyTrader.Modules.Supervisor\PolyTrader.Modules.Supervisor.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
@@ -23,6 +23,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PolyTrader.Tests", "tests\P
|
|||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PolyTrader.Modules.ResolutionFarming", "src\PolyTrader.Modules.ResolutionFarming\PolyTrader.Modules.ResolutionFarming.csproj", "{98C70A7B-DC3D-48E3-BE5D-03F867E9BFA8}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PolyTrader.Modules.ResolutionFarming", "src\PolyTrader.Modules.ResolutionFarming\PolyTrader.Modules.ResolutionFarming.csproj", "{98C70A7B-DC3D-48E3-BE5D-03F867E9BFA8}"
|
||||||
EndProject
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PolyTrader.Modules.Supervisor", "src\PolyTrader.Modules.Supervisor\PolyTrader.Modules.Supervisor.csproj", "{63F8B9B4-6F56-4A6B-BEBE-53DE49F913D1}"
|
||||||
|
EndProject
|
||||||
Global
|
Global
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
Debug|Any CPU = Debug|Any CPU
|
Debug|Any CPU = Debug|Any CPU
|
||||||
@@ -105,6 +107,18 @@ Global
|
|||||||
{98C70A7B-DC3D-48E3-BE5D-03F867E9BFA8}.Release|x64.Build.0 = Release|Any CPU
|
{98C70A7B-DC3D-48E3-BE5D-03F867E9BFA8}.Release|x64.Build.0 = Release|Any CPU
|
||||||
{98C70A7B-DC3D-48E3-BE5D-03F867E9BFA8}.Release|x86.ActiveCfg = Release|Any CPU
|
{98C70A7B-DC3D-48E3-BE5D-03F867E9BFA8}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
{98C70A7B-DC3D-48E3-BE5D-03F867E9BFA8}.Release|x86.Build.0 = Release|Any CPU
|
{98C70A7B-DC3D-48E3-BE5D-03F867E9BFA8}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{63F8B9B4-6F56-4A6B-BEBE-53DE49F913D1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{63F8B9B4-6F56-4A6B-BEBE-53DE49F913D1}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{63F8B9B4-6F56-4A6B-BEBE-53DE49F913D1}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{63F8B9B4-6F56-4A6B-BEBE-53DE49F913D1}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{63F8B9B4-6F56-4A6B-BEBE-53DE49F913D1}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{63F8B9B4-6F56-4A6B-BEBE-53DE49F913D1}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{63F8B9B4-6F56-4A6B-BEBE-53DE49F913D1}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{63F8B9B4-6F56-4A6B-BEBE-53DE49F913D1}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{63F8B9B4-6F56-4A6B-BEBE-53DE49F913D1}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{63F8B9B4-6F56-4A6B-BEBE-53DE49F913D1}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{63F8B9B4-6F56-4A6B-BEBE-53DE49F913D1}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{63F8B9B4-6F56-4A6B-BEBE-53DE49F913D1}.Release|x86.Build.0 = Release|Any CPU
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
GlobalSection(SolutionProperties) = preSolution
|
||||||
HideSolutionNode = FALSE
|
HideSolutionNode = FALSE
|
||||||
@@ -116,6 +130,7 @@ Global
|
|||||||
{FA3FC57B-EA9D-4703-B643-2874C8C0461E} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
{FA3FC57B-EA9D-4703-B643-2874C8C0461E} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||||
{E361C601-CC50-409F-8298-FD753DB4F6FF} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
|
{E361C601-CC50-409F-8298-FD753DB4F6FF} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
|
||||||
{98C70A7B-DC3D-48E3-BE5D-03F867E9BFA8} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
{98C70A7B-DC3D-48E3-BE5D-03F867E9BFA8} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||||
|
{63F8B9B4-6F56-4A6B-BEBE-53DE49F913D1} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||||
SolutionGuid = {60AA6BCF-B17E-4D52-A290-14154A3E97CF}
|
SolutionGuid = {60AA6BCF-B17E-4D52-A290-14154A3E97CF}
|
||||||
|
|||||||
+4
-2
@@ -16,6 +16,7 @@ using PolyTrader.Core.Modularity;
|
|||||||
using PolyTrader.Modules.CopyTrading;
|
using PolyTrader.Modules.CopyTrading;
|
||||||
using PolyTrader.Modules.CopyTrading.Persistence;
|
using PolyTrader.Modules.CopyTrading.Persistence;
|
||||||
using PolyTrader.Modules.ResolutionFarming;
|
using PolyTrader.Modules.ResolutionFarming;
|
||||||
|
using PolyTrader.Modules.Supervisor;
|
||||||
using PolyTraderSharp.Models;
|
using PolyTraderSharp.Models;
|
||||||
using PolyTraderSharp.Services;
|
using PolyTraderSharp.Services;
|
||||||
|
|
||||||
@@ -63,7 +64,8 @@ internal static class Program
|
|||||||
var modules = new System.Collections.Generic.List<IPolyTraderModule>
|
var modules = new System.Collections.Generic.List<IPolyTraderModule>
|
||||||
{
|
{
|
||||||
new CopyTradingModule(),
|
new CopyTradingModule(),
|
||||||
new ResolutionFarmingModule()
|
new ResolutionFarmingModule(),
|
||||||
|
new SupervisorModule()
|
||||||
};
|
};
|
||||||
|
|
||||||
AppHost = Host.CreateDefaultBuilder()
|
AppHost = Host.CreateDefaultBuilder()
|
||||||
@@ -381,7 +383,7 @@ internal static class Program
|
|||||||
{
|
{
|
||||||
ApplicationConfiguration.Initialize();
|
ApplicationConfiguration.Initialize();
|
||||||
|
|
||||||
var modules = new System.Collections.Generic.List<IPolyTraderModule> { new CopyTradingModule(), new ResolutionFarmingModule() };
|
var modules = new System.Collections.Generic.List<IPolyTraderModule> { new CopyTradingModule(), new ResolutionFarmingModule(), new SupervisorModule() };
|
||||||
|
|
||||||
using var host = Host.CreateDefaultBuilder()
|
using var host = Host.CreateDefaultBuilder()
|
||||||
.UseContentRoot(AppContext.BaseDirectory)
|
.UseContentRoot(AppContext.BaseDirectory)
|
||||||
|
|||||||
@@ -0,0 +1,132 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using PolyTraderSharp.Models;
|
||||||
|
using PolyTraderSharp.Services;
|
||||||
|
|
||||||
|
namespace PolyTrader.Core.Analytics
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Das „Trade-Dossier" (S-1, Supervisor-Konzept): alles, was zu einem Signal gehört —
|
||||||
|
/// Entscheidungen, Order-Events, abgeschlossene Trades, Log-Zeilen — als eine Einheit.
|
||||||
|
/// Grundlage für den Dossier-Browser (Mensch) und die KI-Analyse (S-2).
|
||||||
|
/// </summary>
|
||||||
|
public sealed class TradeDossier
|
||||||
|
{
|
||||||
|
public string SignalId { get; init; } = string.Empty;
|
||||||
|
public string ModuleName { get; init; } = string.Empty;
|
||||||
|
public int AccountId { get; init; }
|
||||||
|
public string TokenId { get; init; } = string.Empty;
|
||||||
|
public string MarketQuestion { get; init; } = string.Empty;
|
||||||
|
public string Side { get; init; } = string.Empty;
|
||||||
|
|
||||||
|
public List<DecisionRecord> Decisions { get; init; } = new();
|
||||||
|
public List<OrderEventRecord> OrderEvents { get; init; } = new();
|
||||||
|
public List<TradeRecord> ClosedTrades { get; init; } = new();
|
||||||
|
public List<LogJson.ParsedLogLine> LogLines { get; init; } = new();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Reiner Zusammenbau + Markdown-Rendering eines Dossiers. Seiteneffektfrei und unit-getestet;
|
||||||
|
/// die Datenbeschaffung (Repos/JSONL) macht der DossierService des Supervisor-Moduls.
|
||||||
|
/// </summary>
|
||||||
|
public static class DossierBuilder
|
||||||
|
{
|
||||||
|
/// <summary>Baut das Dossier aus bereits auf die SignalId gescopten Daten (sortiert chronologisch).</summary>
|
||||||
|
public static TradeDossier Build(
|
||||||
|
string signalId,
|
||||||
|
IEnumerable<DecisionRecord> decisions,
|
||||||
|
IEnumerable<OrderEventRecord> orderEvents,
|
||||||
|
IEnumerable<TradeRecord> closedTrades,
|
||||||
|
IEnumerable<LogJson.ParsedLogLine>? logLines = null)
|
||||||
|
{
|
||||||
|
var dec = decisions.OrderBy(d => d.Timestamp).ToList();
|
||||||
|
var ev = orderEvents.OrderBy(e => e.Timestamp).ToList();
|
||||||
|
var trades = closedTrades.OrderBy(t => t.ClosedAt).ToList();
|
||||||
|
var first = dec.FirstOrDefault();
|
||||||
|
|
||||||
|
return new TradeDossier
|
||||||
|
{
|
||||||
|
SignalId = signalId,
|
||||||
|
ModuleName = first?.ModuleName ?? trades.FirstOrDefault()?.ModuleName ?? string.Empty,
|
||||||
|
AccountId = first?.AccountId ?? trades.FirstOrDefault()?.AccountId ?? 0,
|
||||||
|
TokenId = first?.TokenId ?? trades.FirstOrDefault()?.TokenId ?? string.Empty,
|
||||||
|
MarketQuestion = first?.MarketQuestion ?? trades.FirstOrDefault()?.MarketQuestion ?? string.Empty,
|
||||||
|
Side = first?.Side ?? string.Empty,
|
||||||
|
Decisions = dec,
|
||||||
|
OrderEvents = ev,
|
||||||
|
ClosedTrades = trades,
|
||||||
|
LogLines = (logLines ?? Enumerable.Empty<LogJson.ParsedLogLine>()).ToList()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Menschenlesbare Markdown-Fassung (Dossier-Browser; auch als KI-Input geeignet).</summary>
|
||||||
|
public static string ToMarkdown(TradeDossier d)
|
||||||
|
{
|
||||||
|
var sb = new StringBuilder();
|
||||||
|
sb.AppendLine($"# Dossier {ShortId(d.SignalId)}");
|
||||||
|
sb.AppendLine();
|
||||||
|
sb.AppendLine($"- **Markt:** {d.MarketQuestion}");
|
||||||
|
sb.AppendLine($"- **Modul:** {d.ModuleName} **Konto:** {d.AccountId} **Side:** {d.Side}");
|
||||||
|
sb.AppendLine($"- **TokenId:** {d.TokenId}");
|
||||||
|
sb.AppendLine($"- **SignalId:** {d.SignalId}");
|
||||||
|
|
||||||
|
decimal pnl = d.ClosedTrades.Sum(t => t.RealizedPnl);
|
||||||
|
sb.AppendLine($"- **Ergebnis:** {d.ClosedTrades.Count} Trade(s), realisierter PnL {pnl:F2} USDC");
|
||||||
|
sb.AppendLine();
|
||||||
|
|
||||||
|
if (d.Decisions.Count > 0)
|
||||||
|
{
|
||||||
|
sb.AppendLine("## Entscheidungen");
|
||||||
|
sb.AppendLine();
|
||||||
|
sb.AppendLine("| Zeit (UTC) | Entscheidung | Grund | Details |");
|
||||||
|
sb.AppendLine("|---|---|---|---|");
|
||||||
|
foreach (var x in d.Decisions)
|
||||||
|
sb.AppendLine($"| {x.Timestamp:dd.MM. HH:mm:ss} | {x.Decision} | {x.Reason} | {Escape(x.Message)} {(string.IsNullOrEmpty(x.ContextJson) ? "" : "`" + x.ContextJson + "`")} |");
|
||||||
|
sb.AppendLine();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (d.OrderEvents.Count > 0)
|
||||||
|
{
|
||||||
|
sb.AppendLine("## Order-Events");
|
||||||
|
sb.AppendLine();
|
||||||
|
sb.AppendLine("| Zeit (UTC) | Event | Side | Preis | USDC | Antwort |");
|
||||||
|
sb.AppendLine("|---|---|---|---|---|---|");
|
||||||
|
foreach (var x in d.OrderEvents)
|
||||||
|
sb.AppendLine($"| {x.Timestamp:dd.MM. HH:mm:ss} | {x.EventType} | {x.Side} | {x.Price:F3} | {x.AmountUsd:F2} | {Escape(x.Response)} |");
|
||||||
|
sb.AppendLine();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (d.ClosedTrades.Count > 0)
|
||||||
|
{
|
||||||
|
sb.AppendLine("## Abgeschlossene Trades");
|
||||||
|
sb.AppendLine();
|
||||||
|
sb.AppendLine("| Geschlossen (UTC) | Entry | Exit | Size | PnL | Grund |");
|
||||||
|
sb.AppendLine("|---|---|---|---|---|---|");
|
||||||
|
foreach (var t in d.ClosedTrades)
|
||||||
|
sb.AppendLine($"| {t.ClosedAt:dd.MM. HH:mm:ss} | {t.EntryPrice:F3} | {t.ExitPrice:F3} | {t.Size:F2} | {t.RealizedPnl:F2} | {Escape(t.ExitReason)} |");
|
||||||
|
sb.AppendLine();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (d.LogLines.Count > 0)
|
||||||
|
{
|
||||||
|
sb.AppendLine("## Log-Auszug");
|
||||||
|
sb.AppendLine();
|
||||||
|
foreach (var l in d.LogLines)
|
||||||
|
sb.AppendLine($"- `{l.Time}` **{l.Level}** {Escape(l.Message)}");
|
||||||
|
sb.AppendLine();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (d.Decisions.Count == 0 && d.OrderEvents.Count == 0 && d.ClosedTrades.Count == 0)
|
||||||
|
sb.AppendLine("*Keine Daten zu dieser SignalId gefunden.*");
|
||||||
|
|
||||||
|
return sb.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string ShortId(string id) => string.IsNullOrEmpty(id) ? "(ohne SignalId)" : id[..Math.Min(8, id.Length)];
|
||||||
|
|
||||||
|
private static string Escape(string s) =>
|
||||||
|
(s ?? string.Empty).Replace("|", "\\|").Replace("\r\n", " ").Replace("\n", " ");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,7 +2,9 @@ using System;
|
|||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Microsoft.Extensions.Hosting;
|
using Microsoft.Extensions.Hosting;
|
||||||
|
using PolyTrader.Core.Persistence;
|
||||||
using PolyTraderSharp;
|
using PolyTraderSharp;
|
||||||
|
using PolyTraderSharp.Models;
|
||||||
|
|
||||||
namespace PolyTraderSharp.Services
|
namespace PolyTraderSharp.Services
|
||||||
{
|
{
|
||||||
@@ -24,12 +26,14 @@ namespace PolyTraderSharp.Services
|
|||||||
private readonly TradingState _state;
|
private readonly TradingState _state;
|
||||||
private readonly IClobClient _clob;
|
private readonly IClobClient _clob;
|
||||||
private readonly TerminalLogger _logger;
|
private readonly TerminalLogger _logger;
|
||||||
|
private readonly IOrderEventLog _orderEvents;
|
||||||
|
|
||||||
public StartupOrderReconciliationService(TradingState state, IClobClient clob, TerminalLogger logger)
|
public StartupOrderReconciliationService(TradingState state, IClobClient clob, TerminalLogger logger, IOrderEventLog orderEvents)
|
||||||
{
|
{
|
||||||
_state = state;
|
_state = state;
|
||||||
_clob = clob;
|
_clob = clob;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
|
_orderEvents = orderEvents;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task StartAsync(CancellationToken cancellationToken)
|
public async Task StartAsync(CancellationToken cancellationToken)
|
||||||
@@ -64,6 +68,16 @@ namespace PolyTraderSharp.Services
|
|||||||
bool ok = await _clob.CancelOrderAsync(acc, order.Id);
|
bool ok = await _clob.CancelOrderAsync(acc, order.Id);
|
||||||
if (ok) ordersCancelled++;
|
if (ok) ordersCancelled++;
|
||||||
else _logger.Warning($"⚠️ [Startup-Reconciliation] {acc.Name}: Order {order.Id} konnte nicht storniert werden.");
|
else _logger.Warning($"⚠️ [Startup-Reconciliation] {acc.Name}: Order {order.Id} konnte nicht storniert werden.");
|
||||||
|
_orderEvents.Write(new OrderEventRecord
|
||||||
|
{
|
||||||
|
ModuleName = "CopyTrading",
|
||||||
|
AccountId = acc.AccountId,
|
||||||
|
EventType = OrderEventType.StartupReconcileCancel,
|
||||||
|
Side = order.Side,
|
||||||
|
Price = order.Price,
|
||||||
|
Response = ok ? "OK" : "Cancel fehlgeschlagen",
|
||||||
|
DetailsJson = $"{{\"orderId\":\"{order.Id}\"}}"
|
||||||
|
});
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -27,6 +27,8 @@ namespace PolyTraderSharp.Services
|
|||||||
private readonly IPositionRepository _positionRepo;
|
private readonly IPositionRepository _positionRepo;
|
||||||
private readonly IMarketRepository _marketRepo;
|
private readonly IMarketRepository _marketRepo;
|
||||||
private readonly SellLadderService _sellLadder;
|
private readonly SellLadderService _sellLadder;
|
||||||
|
private readonly IDecisionJournal _journal;
|
||||||
|
private readonly IOrderEventLog _orderEvents;
|
||||||
|
|
||||||
// Prevents duplicates. Fast O(1) lookup cache to prevent DB spam.
|
// Prevents duplicates. Fast O(1) lookup cache to prevent DB spam.
|
||||||
private readonly ConcurrentDictionary<string, DateTime> _processedTxHashes = new();
|
private readonly ConcurrentDictionary<string, DateTime> _processedTxHashes = new();
|
||||||
@@ -55,8 +57,12 @@ namespace PolyTraderSharp.Services
|
|||||||
IPositionRepository positionRepo,
|
IPositionRepository positionRepo,
|
||||||
IMarketRepository marketRepo,
|
IMarketRepository marketRepo,
|
||||||
ICopyTradeLogRepository tradeLog,
|
ICopyTradeLogRepository tradeLog,
|
||||||
SellLadderService sellLadder)
|
SellLadderService sellLadder,
|
||||||
|
IDecisionJournal journal,
|
||||||
|
IOrderEventLog orderEvents)
|
||||||
{
|
{
|
||||||
|
_journal = journal;
|
||||||
|
_orderEvents = orderEvents;
|
||||||
_state = state;
|
_state = state;
|
||||||
_copyState = copyState;
|
_copyState = copyState;
|
||||||
_api = api;
|
_api = api;
|
||||||
@@ -1127,7 +1133,25 @@ namespace PolyTraderSharp.Services
|
|||||||
|
|
||||||
_logger.Trade($"🎯 [PROFIT TARGET] {acc.Name} | {pos.MarketQuestion}\n" +
|
_logger.Trade($"🎯 [PROFIT TARGET] {acc.Name} | {pos.MarketQuestion}\n" +
|
||||||
$" Aktuell {pos.CurrentPrice:F3} ≥ Entry {pos.EntryPrice:F3} × (1+{s.ProfitTarget:F0}%). Starte Exit-Leiter.");
|
$" Aktuell {pos.CurrentPrice:F3} ≥ Entry {pos.EntryPrice:F3} × (1+{s.ProfitTarget:F0}%). Starte Exit-Leiter.");
|
||||||
await _sellLadder.StartLadderAsync(acc, pos, pos.CurrentPrice, pos.SourceTraderId, isHf, s.MaxPriceDifference, s.SellFloorPct, isNegRisk, "Profit Target");
|
// S-0: eigener Korrelations-Kontext für den Profit-Target-Exit (kein Master-Signal).
|
||||||
|
string ptSignalId = Guid.NewGuid().ToString("N");
|
||||||
|
bool ptOk = await _sellLadder.StartLadderAsync(acc, pos, pos.CurrentPrice, pos.SourceTraderId, isHf, s.MaxPriceDifference, s.SellFloorPct, isNegRisk, "Profit Target", ptSignalId);
|
||||||
|
_journal.Write(new DecisionRecord
|
||||||
|
{
|
||||||
|
SignalId = ptSignalId,
|
||||||
|
ModuleName = "CopyTrading",
|
||||||
|
AccountId = acc.AccountId,
|
||||||
|
IsDemo = acc.IsDemo,
|
||||||
|
SourceTraderId = pos.SourceTraderId,
|
||||||
|
TokenId = pos.TokenId,
|
||||||
|
MarketSlug = pos.MarketSlug,
|
||||||
|
MarketQuestion = pos.MarketQuestion,
|
||||||
|
Side = "SELL",
|
||||||
|
SignalPrice = pos.CurrentPrice,
|
||||||
|
Decision = ptOk ? TradeDecision.Executed : TradeDecision.Failed,
|
||||||
|
Reason = DecisionReason.ProfitTargetTriggered,
|
||||||
|
Message = $"Take-Profit: {pos.CurrentPrice:F3} ≥ Entry {pos.EntryPrice:F3} × (1+{s.ProfitTarget:F0}%)"
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1171,7 +1195,18 @@ namespace PolyTraderSharp.Services
|
|||||||
foreach (var order in openOrders)
|
foreach (var order in openOrders)
|
||||||
{
|
{
|
||||||
_logger.Warning($"⏰ [{account.Name}] Stale Order Timeout ({ageMinutes:F0} min > {timeoutMinutes} min). Storniere Order {order.Id} für {tokenId.Substring(0, Math.Min(10, tokenId.Length))}...");
|
_logger.Warning($"⏰ [{account.Name}] Stale Order Timeout ({ageMinutes:F0} min > {timeoutMinutes} min). Storniere Order {order.Id} für {tokenId.Substring(0, Math.Min(10, tokenId.Length))}...");
|
||||||
await _clob.CancelOrderAsync(account, order.Id);
|
bool cancelled = await _clob.CancelOrderAsync(account, order.Id);
|
||||||
|
_orderEvents.Write(new OrderEventRecord
|
||||||
|
{
|
||||||
|
ModuleName = "CopyTrading",
|
||||||
|
AccountId = account.AccountId,
|
||||||
|
TokenId = tokenId,
|
||||||
|
EventType = OrderEventType.StaleCleanupCancel,
|
||||||
|
Side = order.Side,
|
||||||
|
Price = order.Price,
|
||||||
|
Response = cancelled ? "OK" : "Cancel fehlgeschlagen",
|
||||||
|
DetailsJson = $"{{\"orderId\":\"{order.Id}\",\"ageMinutes\":{(int)ageMinutes},\"timeoutMinutes\":{timeoutMinutes}}}"
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,10 +4,12 @@ using System.Linq;
|
|||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Microsoft.Extensions.Hosting;
|
using Microsoft.Extensions.Hosting;
|
||||||
|
using PolyTrader.Core.Persistence;
|
||||||
using PolyTrader.Modules.ResolutionFarming.Logic;
|
using PolyTrader.Modules.ResolutionFarming.Logic;
|
||||||
using PolyTrader.Modules.ResolutionFarming.Models;
|
using PolyTrader.Modules.ResolutionFarming.Models;
|
||||||
using PolyTrader.Modules.ResolutionFarming.Persistence;
|
using PolyTrader.Modules.ResolutionFarming.Persistence;
|
||||||
using PolyTraderSharp;
|
using PolyTraderSharp;
|
||||||
|
using PolyTraderSharp.Models;
|
||||||
using PolyTraderSharp.Services;
|
using PolyTraderSharp.Services;
|
||||||
|
|
||||||
namespace PolyTrader.Modules.ResolutionFarming.Services
|
namespace PolyTrader.Modules.ResolutionFarming.Services
|
||||||
@@ -31,10 +33,12 @@ namespace PolyTrader.Modules.ResolutionFarming.Services
|
|||||||
private readonly IRfPositionRepository _positionRepo;
|
private readonly IRfPositionRepository _positionRepo;
|
||||||
private readonly IRfClosedTradeRepository _closedRepo;
|
private readonly IRfClosedTradeRepository _closedRepo;
|
||||||
private readonly TerminalLogger _logger;
|
private readonly TerminalLogger _logger;
|
||||||
|
private readonly IDecisionJournal _journal;
|
||||||
|
|
||||||
public FarmingExecutionService(
|
public FarmingExecutionService(
|
||||||
TradingState state, IRfSettingsRepository settingsRepo, IRfCandidateRepository candidateRepo,
|
TradingState state, IRfSettingsRepository settingsRepo, IRfCandidateRepository candidateRepo,
|
||||||
IRfPositionRepository positionRepo, IRfClosedTradeRepository closedRepo, TerminalLogger logger)
|
IRfPositionRepository positionRepo, IRfClosedTradeRepository closedRepo, TerminalLogger logger,
|
||||||
|
IDecisionJournal journal)
|
||||||
{
|
{
|
||||||
_state = state;
|
_state = state;
|
||||||
_settingsRepo = settingsRepo;
|
_settingsRepo = settingsRepo;
|
||||||
@@ -42,6 +46,7 @@ namespace PolyTrader.Modules.ResolutionFarming.Services
|
|||||||
_positionRepo = positionRepo;
|
_positionRepo = positionRepo;
|
||||||
_closedRepo = closedRepo;
|
_closedRepo = closedRepo;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
|
_journal = journal;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||||
@@ -119,6 +124,25 @@ namespace PolyTrader.Modules.ResolutionFarming.Services
|
|||||||
};
|
};
|
||||||
_positionRepo.Upsert(pos);
|
_positionRepo.Upsert(pos);
|
||||||
opened.Add(pos);
|
opened.Add(pos);
|
||||||
|
|
||||||
|
// S-0: Entscheidung strukturiert journalisieren (Rejects stehen bereits in rf_candidates).
|
||||||
|
_journal.Write(new DecisionRecord
|
||||||
|
{
|
||||||
|
SignalId = Guid.NewGuid().ToString("N"),
|
||||||
|
ModuleName = "ResolutionFarming",
|
||||||
|
AccountId = accountId,
|
||||||
|
IsDemo = true,
|
||||||
|
TokenId = c.TokenId,
|
||||||
|
MarketSlug = c.MarketSlug,
|
||||||
|
MarketQuestion = c.MarketQuestion,
|
||||||
|
Side = "BUY",
|
||||||
|
SignalPrice = c.Ask,
|
||||||
|
MarketEndDate = c.EndDate,
|
||||||
|
Decision = TradeDecision.Executed,
|
||||||
|
Reason = DecisionReason.DemoFilled,
|
||||||
|
Message = $"RF-Demo-Einstieg {shares:F2} Shares @ {c.Ask:F3} (Score {c.Score:F2})",
|
||||||
|
ContextJson = System.Text.Json.JsonSerializer.Serialize(new { shares, sizeUsd, score = c.Score, netEdgePct = c.NetEdgePct, cluster = c.ClusterKey })
|
||||||
|
});
|
||||||
}
|
}
|
||||||
return opened;
|
return opened;
|
||||||
}
|
}
|
||||||
|
|||||||
+20
-1
@@ -30,10 +30,12 @@ namespace PolyTrader.Modules.ResolutionFarming.Services
|
|||||||
private readonly IMarketResolutionSource _resolution;
|
private readonly IMarketResolutionSource _resolution;
|
||||||
private readonly ITradeLogRepository _coreLog;
|
private readonly ITradeLogRepository _coreLog;
|
||||||
private readonly TerminalLogger _logger;
|
private readonly TerminalLogger _logger;
|
||||||
|
private readonly IDecisionJournal _journal;
|
||||||
|
|
||||||
public FarmingResolutionMonitorService(
|
public FarmingResolutionMonitorService(
|
||||||
TradingState state, IRfPositionRepository positionRepo, IRfClosedTradeRepository closedRepo,
|
TradingState state, IRfPositionRepository positionRepo, IRfClosedTradeRepository closedRepo,
|
||||||
IMarketResolutionSource resolution, ITradeLogRepository coreLog, TerminalLogger logger)
|
IMarketResolutionSource resolution, ITradeLogRepository coreLog, TerminalLogger logger,
|
||||||
|
IDecisionJournal journal)
|
||||||
{
|
{
|
||||||
_state = state;
|
_state = state;
|
||||||
_positionRepo = positionRepo;
|
_positionRepo = positionRepo;
|
||||||
@@ -41,6 +43,7 @@ namespace PolyTrader.Modules.ResolutionFarming.Services
|
|||||||
_resolution = resolution;
|
_resolution = resolution;
|
||||||
_coreLog = coreLog;
|
_coreLog = coreLog;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
|
_journal = journal;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||||
@@ -100,6 +103,22 @@ namespace PolyTrader.Modules.ResolutionFarming.Services
|
|||||||
});
|
});
|
||||||
|
|
||||||
_logger.Trade($"🏆 [RF] {pos.MarketQuestion} aufgelöst ({(isWinner ? "Gewinner" : "Verlierer")}) – PnL {trade.RealizedPnl:F2} USDC.");
|
_logger.Trade($"🏆 [RF] {pos.MarketQuestion} aufgelöst ({(isWinner ? "Gewinner" : "Verlierer")}) – PnL {trade.RealizedPnl:F2} USDC.");
|
||||||
|
_journal.Write(new DecisionRecord
|
||||||
|
{
|
||||||
|
SignalId = Guid.NewGuid().ToString("N"),
|
||||||
|
ModuleName = "ResolutionFarming",
|
||||||
|
AccountId = pos.AccountId,
|
||||||
|
IsDemo = pos.IsDemo,
|
||||||
|
TokenId = pos.TokenId,
|
||||||
|
MarketSlug = pos.MarketSlug,
|
||||||
|
MarketQuestion = pos.MarketQuestion,
|
||||||
|
Side = "SELL",
|
||||||
|
SignalPrice = trade.ExitPrice,
|
||||||
|
Decision = TradeDecision.Executed,
|
||||||
|
Reason = DecisionReason.SystemResolutionClose,
|
||||||
|
Message = $"RF-Resolution ({(isWinner ? "Gewinner" : "Verlierer")}), PnL {trade.RealizedPnl:F2}",
|
||||||
|
ContextJson = System.Text.Json.JsonSerializer.Serialize(new { isWinner, realizedPnl = trade.RealizedPnl, size = pos.Size })
|
||||||
|
});
|
||||||
result.Add(trade);
|
result.Add(trade);
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\PolyTrader.Core\PolyTrader.Core.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<!-- Erlaubt dem Testprojekt, interne Methoden zu testen. -->
|
||||||
|
<ItemGroup>
|
||||||
|
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute">
|
||||||
|
<_Parameter1>PolyTrader.Tests</_Parameter1>
|
||||||
|
</AssemblyAttribute>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net8.0-windows</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<!-- Modul trägt eigene WinForms-UI bei (Dossier-Browser, später Analyse-Chat). -->
|
||||||
|
<UseWindowsForms>true</UseWindowsForms>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using PolyTrader.Core.Analytics;
|
||||||
|
using PolyTrader.Core.Persistence;
|
||||||
|
using PolyTraderSharp.Services;
|
||||||
|
|
||||||
|
namespace PolyTrader.Modules.Supervisor.Services
|
||||||
|
{
|
||||||
|
/// <summary>Kopfzeile eines Signals für die Übersichtsliste des Dossier-Browsers.</summary>
|
||||||
|
public sealed record SignalSummary(
|
||||||
|
string SignalId, DateTime FirstSeen, string ModuleName, int AccountId,
|
||||||
|
string Side, string MarketQuestion, string LastDecision, string LastReason, int DecisionCount);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Beschafft die Daten für Trade-Dossiers (S-1): Entscheidungsjournal + Order-Events +
|
||||||
|
/// Core-Trade-Log + JSONL-Log-Zeilen (per CorrelationId), Zusammenbau/Rendering pur im
|
||||||
|
/// <see cref="DossierBuilder"/> (Core). Read-only — der Supervisor ist Beobachter.
|
||||||
|
/// </summary>
|
||||||
|
public class DossierService
|
||||||
|
{
|
||||||
|
private readonly IDecisionJournal _journal;
|
||||||
|
private readonly IOrderEventLog _orderEvents;
|
||||||
|
private readonly ITradeLogRepository _tradeLog;
|
||||||
|
private readonly string _logsDirectory;
|
||||||
|
|
||||||
|
public DossierService(IDecisionJournal journal, IOrderEventLog orderEvents, ITradeLogRepository tradeLog)
|
||||||
|
{
|
||||||
|
_journal = journal;
|
||||||
|
_orderEvents = orderEvents;
|
||||||
|
_tradeLog = tradeLog;
|
||||||
|
_logsDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Jüngste Signale (gruppiert über das Entscheidungsjournal), neueste zuerst.</summary>
|
||||||
|
public List<SignalSummary> RecentSignals(int limit = 200)
|
||||||
|
{
|
||||||
|
var decisions = _journal.Query(d => d.SignalId != "", limit * 5);
|
||||||
|
return decisions
|
||||||
|
.GroupBy(d => d.SignalId)
|
||||||
|
.Select(g =>
|
||||||
|
{
|
||||||
|
var ordered = g.OrderBy(d => d.Timestamp).ToList();
|
||||||
|
var first = ordered[0];
|
||||||
|
var last = ordered[^1];
|
||||||
|
return new SignalSummary(g.Key, first.Timestamp, first.ModuleName, first.AccountId,
|
||||||
|
first.Side, first.MarketQuestion, last.Decision.ToString(), last.Reason.ToString(), ordered.Count);
|
||||||
|
})
|
||||||
|
.OrderByDescending(s => s.FirstSeen)
|
||||||
|
.Take(limit)
|
||||||
|
.ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Baut das komplette Dossier zu einer SignalId (inkl. Log-Zeilen aus den JSONL-Tagesdateien).</summary>
|
||||||
|
public TradeDossier BuildForSignal(string signalId)
|
||||||
|
{
|
||||||
|
var decisions = _journal.Query(d => d.SignalId == signalId);
|
||||||
|
var events = _orderEvents.Query(e => e.SignalId == signalId);
|
||||||
|
var trades = _tradeLog.Find(t => t.SignalId == signalId);
|
||||||
|
var logLines = ReadLogLines(signalId, decisions.Select(d => d.Timestamp).Concat(events.Select(e => e.Timestamp)));
|
||||||
|
return DossierBuilder.Build(signalId, decisions, events, trades, logLines);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Liest JSONL-Zeilen mit passender CorrelationId — nur aus den Tagesdateien im Zeitfenster der
|
||||||
|
/// bekannten Ereignisse (±1 Tag), statt alle Logs zu scannen. Fehlertolerant (fehlende Dateien = leer).
|
||||||
|
/// </summary>
|
||||||
|
private List<LogJson.ParsedLogLine> ReadLogLines(string signalId, IEnumerable<DateTime> eventTimes)
|
||||||
|
{
|
||||||
|
var result = new List<LogJson.ParsedLogLine>();
|
||||||
|
var times = eventTimes.ToList();
|
||||||
|
if (times.Count == 0 || string.IsNullOrEmpty(signalId)) return result;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var from = times.Min().Date.AddDays(-1);
|
||||||
|
var to = times.Max().Date.AddDays(1);
|
||||||
|
for (var day = from; day <= to; day = day.AddDays(1))
|
||||||
|
{
|
||||||
|
string path = Path.Combine(_logsDirectory, $"{day:yyyy-MM-dd}.jsonl");
|
||||||
|
if (!File.Exists(path)) continue;
|
||||||
|
foreach (var line in File.ReadLines(path))
|
||||||
|
{
|
||||||
|
var p = LogJson.ParseLine(line);
|
||||||
|
if (p != null && p.Cid == signalId) result.Add(p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch { /* Log-Auszug ist Beiwerk – Dossier bleibt auch ohne nutzbar */ }
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using PolyTrader.Core.Modularity;
|
||||||
|
using PolyTrader.Modules.Supervisor.Services;
|
||||||
|
|
||||||
|
namespace PolyTrader.Modules.Supervisor
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Supervisor-Modul (docs/konzepte/KONZEPT-Modul-Supervisor.md): Analyse/Forensik über ALLE
|
||||||
|
/// Module — strikt read-only (kein Handel). S-1: Dossier-Browser über Entscheidungsjournal,
|
||||||
|
/// Order-Events, Trade-Log und JSONL-Logs. S-2 (OpenRouter-Agent + Tool-Registry), S-3
|
||||||
|
/// (Profile/Berichte/Counterfactual/Predictalytics) und S-4 (MCP-Light) folgen.
|
||||||
|
/// </summary>
|
||||||
|
public class SupervisorModule : IPolyTraderModule
|
||||||
|
{
|
||||||
|
public string Name => "Supervisor";
|
||||||
|
public string DbPrefix => "sup_";
|
||||||
|
|
||||||
|
public void RegisterServices(IServiceCollection services, IConfiguration configuration)
|
||||||
|
{
|
||||||
|
// S-1: reine Beschaffung/Aufbereitung. Eigene sup_-Persistenz (Berichte/Konversationen)
|
||||||
|
// folgt mit S-2/S-3.
|
||||||
|
services.AddSingleton<DossierService>();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void RegisterUi(IModuleUiHost host, System.IServiceProvider services)
|
||||||
|
{
|
||||||
|
host.RegisterView(new ModuleView
|
||||||
|
{
|
||||||
|
Id = "supervisor.main",
|
||||||
|
Title = "Supervisor",
|
||||||
|
Group = "Supervisor",
|
||||||
|
Order = 300,
|
||||||
|
CreateForm = () =>
|
||||||
|
{
|
||||||
|
var form = new Ui.SupervisorMainForm();
|
||||||
|
form.Initialize(services);
|
||||||
|
return form;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task StartAsync(CancellationToken cancellationToken) => Task.CompletedTask;
|
||||||
|
|
||||||
|
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Windows.Forms;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using PolyTrader.Core.Analytics;
|
||||||
|
using PolyTrader.Modules.Supervisor.Services;
|
||||||
|
|
||||||
|
namespace PolyTrader.Modules.Supervisor.Ui
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Hauptfenster des Supervisor-Moduls (S-1): Dossier-Browser — links die jüngsten Signale
|
||||||
|
/// (aus dem Entscheidungsjournal), rechts das komplette Dossier (Markdown). Der Analyse-Chat
|
||||||
|
/// (OpenRouter-Agent) folgt in S-2 als weiterer Tab. Code-only konstruiert (Muster RF-Modul);
|
||||||
|
/// DB-Zugriffe defensiv, damit die UI auch bei leerer/nicht erreichbarer DB bedienbar bleibt.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class SupervisorMainForm : Form
|
||||||
|
{
|
||||||
|
private DossierService? _dossiers;
|
||||||
|
|
||||||
|
private readonly ToolStrip _toolStrip = new();
|
||||||
|
private readonly ToolStripButton _btnRefresh = new() { Text = "Aktualisieren", DisplayStyle = ToolStripItemDisplayStyle.Text };
|
||||||
|
private readonly ToolStripLabel _lblSearch = new() { Text = "SignalId:" };
|
||||||
|
private readonly ToolStripTextBox _tbSignalId = new() { AutoSize = false, Width = 220 };
|
||||||
|
private readonly ToolStripButton _btnOpen = new() { Text = "Dossier öffnen", DisplayStyle = ToolStripItemDisplayStyle.Text };
|
||||||
|
|
||||||
|
private readonly SplitContainer _split = new() { Dock = DockStyle.Fill, SplitterDistance = 420 };
|
||||||
|
private readonly DataGridView _grid = new()
|
||||||
|
{
|
||||||
|
Dock = DockStyle.Fill, ReadOnly = true, AllowUserToAddRows = false, AllowUserToDeleteRows = false,
|
||||||
|
AutoGenerateColumns = true, SelectionMode = DataGridViewSelectionMode.FullRowSelect,
|
||||||
|
RowHeadersVisible = false, MultiSelect = false
|
||||||
|
};
|
||||||
|
private readonly TextBox _dossierText = new()
|
||||||
|
{
|
||||||
|
Dock = DockStyle.Fill, Multiline = true, ReadOnly = true, ScrollBars = ScrollBars.Both,
|
||||||
|
Font = new System.Drawing.Font("Consolas", 9.5f), WordWrap = false
|
||||||
|
};
|
||||||
|
private readonly Label _status = new() { Dock = DockStyle.Bottom, Height = 22, Padding = new Padding(6, 2, 6, 2), Text = "" };
|
||||||
|
|
||||||
|
public SupervisorMainForm()
|
||||||
|
{
|
||||||
|
Text = "Supervisor";
|
||||||
|
Width = 1250;
|
||||||
|
Height = 700;
|
||||||
|
StartPosition = FormStartPosition.CenterScreen;
|
||||||
|
|
||||||
|
_toolStrip.Items.AddRange(new ToolStripItem[] { _btnRefresh, new ToolStripSeparator(), _lblSearch, _tbSignalId, _btnOpen });
|
||||||
|
_split.Panel1.Controls.Add(_grid);
|
||||||
|
_split.Panel2.Controls.Add(_dossierText);
|
||||||
|
|
||||||
|
Controls.Add(_split);
|
||||||
|
Controls.Add(_toolStrip);
|
||||||
|
Controls.Add(_status);
|
||||||
|
_toolStrip.Dock = DockStyle.Top;
|
||||||
|
|
||||||
|
_btnRefresh.Click += (_, _) => LoadSignals();
|
||||||
|
_btnOpen.Click += (_, _) => OpenDossier(_tbSignalId.Text.Trim());
|
||||||
|
_grid.SelectionChanged += (_, _) => OpenSelected();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Initialize(IServiceProvider services)
|
||||||
|
{
|
||||||
|
_dossiers = services.GetRequiredService<DossierService>();
|
||||||
|
LoadSignals();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void LoadSignals()
|
||||||
|
{
|
||||||
|
if (_dossiers == null) return;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
List<SignalSummary> signals = _dossiers.RecentSignals(200);
|
||||||
|
_grid.DataSource = signals;
|
||||||
|
_status.Text = signals.Count == 0
|
||||||
|
? "Noch keine Journal-Einträge (Entscheidungen entstehen, sobald Signale verarbeitet werden)."
|
||||||
|
: $"{signals.Count} Signale.";
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_status.Text = $"Journal nicht lesbar: {ex.Message}";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OpenSelected()
|
||||||
|
{
|
||||||
|
if (_grid.CurrentRow?.DataBoundItem is SignalSummary s)
|
||||||
|
OpenDossier(s.SignalId);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OpenDossier(string signalId)
|
||||||
|
{
|
||||||
|
if (_dossiers == null || string.IsNullOrWhiteSpace(signalId)) return;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var dossier = _dossiers.BuildForSignal(signalId);
|
||||||
|
_dossierText.Text = DossierBuilder.ToMarkdown(dossier).Replace("\n", Environment.NewLine);
|
||||||
|
_tbSignalId.Text = signalId;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_dossierText.Text = $"Dossier konnte nicht geladen werden: {ex.Message}";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
using System;
|
||||||
|
using System.Linq;
|
||||||
|
using PolyTrader.Core.Analytics;
|
||||||
|
using PolyTraderSharp.Models;
|
||||||
|
using PolyTraderSharp.Services;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace PolyTrader.Tests
|
||||||
|
{
|
||||||
|
/// <summary>Sicherheitsnetz für den reinen Dossier-Zusammenbau + das Markdown-Rendering (S-1).</summary>
|
||||||
|
public class DossierBuilderTests
|
||||||
|
{
|
||||||
|
private static readonly DateTime T0 = new(2026, 7, 16, 10, 0, 0, DateTimeKind.Utc);
|
||||||
|
private const string Sig = "sig-abc123";
|
||||||
|
|
||||||
|
private static TradeDossier SampleDossier()
|
||||||
|
{
|
||||||
|
var decisions = new[]
|
||||||
|
{
|
||||||
|
new DecisionRecord { SignalId = Sig, Timestamp = T0.AddSeconds(2), ModuleName = "CopyTrading",
|
||||||
|
AccountId = 1, TokenId = "tok", MarketQuestion = "Frage?", Side = "SELL",
|
||||||
|
Decision = TradeDecision.Executed, Reason = DecisionReason.LadderStarted, Message = "Leiter" },
|
||||||
|
new DecisionRecord { SignalId = Sig, Timestamp = T0, ModuleName = "CopyTrading",
|
||||||
|
AccountId = 1, TokenId = "tok", MarketQuestion = "Frage?", Side = "SELL",
|
||||||
|
Decision = TradeDecision.Skipped, Reason = DecisionReason.SellSpamBlock, Message = "Spam | Test" }
|
||||||
|
};
|
||||||
|
var events = new[]
|
||||||
|
{
|
||||||
|
new OrderEventRecord { SignalId = Sig, Timestamp = T0.AddSeconds(3),
|
||||||
|
EventType = OrderEventType.LadderStart, Side = "SELL", Price = 0.48m, AmountUsd = 48m, Response = "OK" }
|
||||||
|
};
|
||||||
|
var trades = new[]
|
||||||
|
{
|
||||||
|
new TradeRecord { SignalId = Sig, ClosedAt = T0.AddMinutes(5), ModuleName = "CopyTrading",
|
||||||
|
AccountId = 1, TokenId = "tok", MarketQuestion = "Frage?", EntryPrice = 0.40m,
|
||||||
|
ExitPrice = 0.48m, Size = 100m, RealizedPnl = 8m, ExitReason = "Master Trader Sold" }
|
||||||
|
};
|
||||||
|
var logs = new[] { new LogJson.ParsedLogLine("2026-07-16T10:00:01", "Trade", Sig, "Logzeile") };
|
||||||
|
|
||||||
|
return DossierBuilder.Build(Sig, decisions, events, trades, logs);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Build_sorts_chronologically_and_derives_header()
|
||||||
|
{
|
||||||
|
var d = SampleDossier();
|
||||||
|
|
||||||
|
Assert.Equal(Sig, d.SignalId);
|
||||||
|
Assert.Equal("CopyTrading", d.ModuleName);
|
||||||
|
Assert.Equal(1, d.AccountId);
|
||||||
|
Assert.Equal("tok", d.TokenId);
|
||||||
|
Assert.Equal(2, d.Decisions.Count);
|
||||||
|
Assert.Equal(DecisionReason.SellSpamBlock, d.Decisions[0].Reason); // früheste zuerst
|
||||||
|
Assert.Single(d.OrderEvents);
|
||||||
|
Assert.Single(d.ClosedTrades);
|
||||||
|
Assert.Single(d.LogLines);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Markdown_contains_all_sections_and_escapes_pipes()
|
||||||
|
{
|
||||||
|
string md = DossierBuilder.ToMarkdown(SampleDossier());
|
||||||
|
|
||||||
|
Assert.Contains("## Entscheidungen", md);
|
||||||
|
Assert.Contains("## Order-Events", md);
|
||||||
|
Assert.Contains("## Abgeschlossene Trades", md);
|
||||||
|
Assert.Contains("## Log-Auszug", md);
|
||||||
|
Assert.Contains("8,00 USDC", md.Replace("8.00", "8,00")); // PnL-Summe (kulturneutral geprüft)
|
||||||
|
Assert.Contains("Spam \\| Test", md); // Pipe im Text escaped (Tabelle bleibt intakt)
|
||||||
|
Assert.Contains("LadderStart", md);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Markdown_for_empty_dossier_says_no_data()
|
||||||
|
{
|
||||||
|
var d = DossierBuilder.Build("sig-x",
|
||||||
|
Enumerable.Empty<DecisionRecord>(), Enumerable.Empty<OrderEventRecord>(), Enumerable.Empty<TradeRecord>());
|
||||||
|
Assert.Contains("Keine Daten", DossierBuilder.ToMarkdown(d));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ using System.Linq;
|
|||||||
using PolyTrader.Modules.ResolutionFarming.Models;
|
using PolyTrader.Modules.ResolutionFarming.Models;
|
||||||
using PolyTrader.Modules.ResolutionFarming.Persistence.Ef;
|
using PolyTrader.Modules.ResolutionFarming.Persistence.Ef;
|
||||||
using PolyTrader.Modules.ResolutionFarming.Services;
|
using PolyTrader.Modules.ResolutionFarming.Services;
|
||||||
|
using PolyTrader.Tests.Fakes;
|
||||||
using PolyTrader.Tests.TestSupport;
|
using PolyTrader.Tests.TestSupport;
|
||||||
using PolyTraderSharp;
|
using PolyTraderSharp;
|
||||||
using PolyTraderSharp.Services;
|
using PolyTraderSharp.Services;
|
||||||
@@ -25,7 +26,7 @@ namespace PolyTrader.Tests
|
|||||||
var posRepo = new EfRfPositionRepository(factory);
|
var posRepo = new EfRfPositionRepository(factory);
|
||||||
var closedRepo = new EfRfClosedTradeRepository(factory);
|
var closedRepo = new EfRfClosedTradeRepository(factory);
|
||||||
var settingsRepo = new EfRfSettingsRepository(factory);
|
var settingsRepo = new EfRfSettingsRepository(factory);
|
||||||
var svc = new FarmingExecutionService(new TradingState(), settingsRepo, candRepo, posRepo, closedRepo, new TerminalLogger());
|
var svc = new FarmingExecutionService(new TradingState(), settingsRepo, candRepo, posRepo, closedRepo, new TerminalLogger(), new FakeDecisionJournal());
|
||||||
return (svc, posRepo, candRepo);
|
return (svc, posRepo, candRepo);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ namespace PolyTrader.Tests
|
|||||||
var resolution = new FakeResolution(new() { ["a"] = (true, true) }); // nur a aufgelöst (Gewinner)
|
var resolution = new FakeResolution(new() { ["a"] = (true, true) }); // nur a aufgelöst (Gewinner)
|
||||||
var coreLog = new FakeCoreTradeLogRepository();
|
var coreLog = new FakeCoreTradeLogRepository();
|
||||||
var state = new TradingState();
|
var state = new TradingState();
|
||||||
var svc = new FarmingResolutionMonitorService(state, posRepo, closedRepo, resolution, coreLog, new TerminalLogger());
|
var svc = new FarmingResolutionMonitorService(state, posRepo, closedRepo, resolution, coreLog, new TerminalLogger(), new FakeDecisionJournal());
|
||||||
|
|
||||||
var closed = await svc.CheckAndCloseAsync(CancellationToken.None);
|
var closed = await svc.CheckAndCloseAsync(CancellationToken.None);
|
||||||
|
|
||||||
@@ -58,7 +58,7 @@ namespace PolyTrader.Tests
|
|||||||
posRepo.Upsert(new RfPosition { AccountId = 1, TokenId = "a", MarketSlug = "m-a", Size = 100m, EntryPrice = 0.95m, AmountUsd = 95m });
|
posRepo.Upsert(new RfPosition { AccountId = 1, TokenId = "a", MarketSlug = "m-a", Size = 100m, EntryPrice = 0.95m, AmountUsd = 95m });
|
||||||
|
|
||||||
var svc = new FarmingResolutionMonitorService(new TradingState(), posRepo, closedRepo,
|
var svc = new FarmingResolutionMonitorService(new TradingState(), posRepo, closedRepo,
|
||||||
new FakeResolution(new()), new FakeCoreTradeLogRepository(), new TerminalLogger());
|
new FakeResolution(new()), new FakeCoreTradeLogRepository(), new TerminalLogger(), new FakeDecisionJournal());
|
||||||
|
|
||||||
var closed = await svc.CheckAndCloseAsync(CancellationToken.None);
|
var closed = await svc.CheckAndCloseAsync(CancellationToken.None);
|
||||||
|
|
||||||
|
|||||||
@@ -20,6 +20,7 @@
|
|||||||
<ProjectReference Include="..\..\src\PolyTrader.Core\PolyTrader.Core.csproj" />
|
<ProjectReference Include="..\..\src\PolyTrader.Core\PolyTrader.Core.csproj" />
|
||||||
<ProjectReference Include="..\..\src\PolyTrader.Modules.CopyTrading\PolyTrader.Modules.CopyTrading.csproj" />
|
<ProjectReference Include="..\..\src\PolyTrader.Modules.CopyTrading\PolyTrader.Modules.CopyTrading.csproj" />
|
||||||
<ProjectReference Include="..\..\src\PolyTrader.Modules.ResolutionFarming\PolyTrader.Modules.ResolutionFarming.csproj" />
|
<ProjectReference Include="..\..\src\PolyTrader.Modules.ResolutionFarming\PolyTrader.Modules.ResolutionFarming.csproj" />
|
||||||
|
<ProjectReference Include="..\..\src\PolyTrader.Modules.Supervisor\PolyTrader.Modules.Supervisor.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ namespace PolyTrader.Tests
|
|||||||
clob.AllOpenOrders.Add(("o1", "SELL", 0.40m));
|
clob.AllOpenOrders.Add(("o1", "SELL", 0.40m));
|
||||||
clob.AllOpenOrders.Add(("o2", "BUY", 0.55m));
|
clob.AllOpenOrders.Add(("o2", "BUY", 0.55m));
|
||||||
|
|
||||||
var svc = new StartupOrderReconciliationService(state, clob, new TerminalLogger());
|
var svc = new StartupOrderReconciliationService(state, clob, new TerminalLogger(), new FakeOrderEventLog());
|
||||||
await svc.StartAsync(CancellationToken.None);
|
await svc.StartAsync(CancellationToken.None);
|
||||||
|
|
||||||
Assert.Equal(new[] { "o1", "o2" }, clob.CanceledOrderIds);
|
Assert.Equal(new[] { "o1", "o2" }, clob.CanceledOrderIds);
|
||||||
@@ -59,7 +59,7 @@ namespace PolyTrader.Tests
|
|||||||
var clob = new FakeClobClient();
|
var clob = new FakeClobClient();
|
||||||
clob.AllOpenOrders.Add(("x", "SELL", 0.40m));
|
clob.AllOpenOrders.Add(("x", "SELL", 0.40m));
|
||||||
|
|
||||||
var svc = new StartupOrderReconciliationService(state, clob, new TerminalLogger());
|
var svc = new StartupOrderReconciliationService(state, clob, new TerminalLogger(), new FakeOrderEventLog());
|
||||||
await svc.StartAsync(CancellationToken.None);
|
await svc.StartAsync(CancellationToken.None);
|
||||||
|
|
||||||
Assert.Empty(clob.CanceledOrderIds); // weder Demo noch credential-lose Accounts angefasst
|
Assert.Empty(clob.CanceledOrderIds); // weder Demo noch credential-lose Accounts angefasst
|
||||||
@@ -74,7 +74,7 @@ namespace PolyTrader.Tests
|
|||||||
|
|
||||||
var clob = new FakeClobClient(); // AllOpenOrders leer
|
var clob = new FakeClobClient(); // AllOpenOrders leer
|
||||||
|
|
||||||
var svc = new StartupOrderReconciliationService(state, clob, new TerminalLogger());
|
var svc = new StartupOrderReconciliationService(state, clob, new TerminalLogger(), new FakeOrderEventLog());
|
||||||
await svc.StartAsync(CancellationToken.None);
|
await svc.StartAsync(CancellationToken.None);
|
||||||
|
|
||||||
Assert.Empty(clob.CanceledOrderIds);
|
Assert.Empty(clob.CanceledOrderIds);
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ namespace PolyTrader.Tests
|
|||||||
var closedCh = Channel.CreateUnbounded<ClosedTrade>();
|
var closedCh = Channel.CreateUnbounded<ClosedTrade>();
|
||||||
|
|
||||||
var svc = new TraderMonitorService(state, copy, api, clob, signalCh.Writer, closedCh.Writer,
|
var svc = new TraderMonitorService(state, copy, api, clob, signalCh.Writer, closedCh.Writer,
|
||||||
logger, posRepo, marketRepo, tradeLog, ladder);
|
logger, posRepo, marketRepo, tradeLog, ladder, new FakeDecisionJournal(), new FakeOrderEventLog());
|
||||||
|
|
||||||
state.Accounts[1] = new AccountState { AccountId = 1, Name = "Live", IsDemo = false };
|
state.Accounts[1] = new AccountState { AccountId = 1, Name = "Live", IsDemo = false };
|
||||||
return (svc, state, copy, clob);
|
return (svc, state, copy, clob);
|
||||||
|
|||||||
Reference in New Issue
Block a user