Slice 2 (Fable-Fixes): K2 – Neustart-Reconciliation

Ruhende GTC-Leiter-/MakerEntry-Orders ueberleben Neustarts auf dem CLOB, der
Verwaltungszustand (ExitLadders/ExitPending/PendingOrderTimestamps) ist transient.
Ohne Bereinigung liefe die Engine gegen Waisen-Orders (Doppel-Leiter, Kaskaden).

- StartupOrderReconciliationService (IHostedService): storniert beim Start je
  Live-Account alle offenen CLOB-Orders; danach entscheidet die Engine sauber neu.
  Registriert als ERSTER Modul-HostedService (nach Hydration, vor Monitor/Engine),
  pro Account fehlertolerant.
- GetOpenOrdersAsync: assetId jetzt optional (default "") -> ohne Filter ALLE
  offenen Orders des Accounts. Signaturneutral (HMAC geht ueber Pfad ohne Query),
  rueckwaertskompatibel fuer die bestehenden per-Asset-Aufrufer. IClobClient +
  FakeClobClient nachgezogen.

Hinweis: "/data/orders ohne asset_id = alle Orders" ist API-gated und im Zielland
live zu verifizieren (wie M6).

Tests: 3 neue (cancelt alle Orders je Live-Account, ueberspringt Demo/credential-los,
no-op ohne offene Orders). Build 0 Fehler, 218 Tests gruen, --smoke-ui ok.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Richard
2026-07-09 13:20:03 +02:00
co-authored by Claude Opus 4.8
parent 0200a726e7
commit 98109b78f6
6 changed files with 195 additions and 10 deletions
+5 -2
View File
@@ -25,8 +25,11 @@ namespace PolyTraderSharp.Services
/// <summary>Cancelt konfligierende offene Orders desselben Tokens vor dem Nachpreisen/Platzieren.</summary>
Task CancelConflictingOrdersAsync(AccountState acc, string assetId, decimal newPrice, string sideStr);
/// <summary>Liefert die offenen Orders (Id, Side, Price) für ein Asset.</summary>
Task<List<(string Id, string Side, decimal Price)>> GetOpenOrdersAsync(AccountState acc, string assetId);
/// <summary>
/// Liefert die offenen Orders (Id, Side, Price). Mit <paramref name="assetId"/> nur für dieses
/// Asset; ohne (leer) ALLE offenen Orders des Accounts genutzt von der Startup-Reconciliation.
/// </summary>
Task<List<(string Id, string Side, decimal Price)>> GetOpenOrdersAsync(AccountState acc, string assetId = "");
/// <summary>Cancelt eine einzelne Order per OrderId; true bei Erfolg.</summary>
Task<bool> CancelOrderAsync(AccountState acc, string orderId);
@@ -364,7 +364,7 @@ namespace PolyTraderSharp.Services
return 0;
}
public async Task<System.Collections.Generic.List<(string Id, string Side, decimal Price)>> GetOpenOrdersAsync(AccountState acc, string assetId)
public async Task<System.Collections.Generic.List<(string Id, string Side, decimal Price)>> GetOpenOrdersAsync(AccountState acc, string assetId = "")
{
var result = new System.Collections.Generic.List<(string Id, string Side, decimal Price)>();
if (string.IsNullOrEmpty(acc.ApiKey) || string.IsNullOrEmpty(acc.ApiSecret) || string.IsNullOrEmpty(acc.ApiPassphrase) || string.IsNullOrEmpty(acc.PrivateKey))
@@ -373,7 +373,10 @@ namespace PolyTraderSharp.Services
try
{
string endpoint = "/data/orders";
string requestUrl = $"{endpoint}?asset_id={assetId}";
// Ohne assetId: ALLE offenen Orders des Accounts (Startup-Reconciliation K2).
// Die HMAC-Signatur geht über den Pfad "/data/orders" ohne Query-String, daher ist
// das Weglassen des asset_id-Filters signaturneutral.
string requestUrl = string.IsNullOrEmpty(assetId) ? endpoint : $"{endpoint}?asset_id={assetId}";
string timestamp = GetClobTimestamp();
string signature = GenerateHmacSignature(acc.ApiSecret, timestamp, "GET", endpoint);
@@ -51,6 +51,15 @@ namespace PolyTrader.Modules.CopyTrading
// WSS-Infrastruktur (Core) wird nur vom Copytrading-Blockchain-Listener genutzt.
services.AddSingleton<IBlockchainWssClientFactory, AlchemyWssClientFactory>();
// IClobClient-Seam: Leiter/Reconciliation hängen am Interface (mockbar für Integrationstests);
// die Live-Instanz ist der eine PolymarketClobClient-Singleton aus dem App-Container.
services.AddSingleton<IClobClient>(sp => sp.GetRequiredService<PolymarketClobClient>());
// K2 Neustart-Reconciliation: MUSS als erster Modul-HostedService laufen (nach der
// State-Hydration, vor TraderMonitor/Engine), damit verwaiste CLOB-Orders vom vorherigen
// Lauf storniert sind, bevor das erste Signal verarbeitet wird.
services.AddHostedService<StartupOrderReconciliationService>();
// Modul-Services (Signalquelle, Ausführung, Analytics)
services.AddSingleton<TraderMonitorService>();
services.AddHostedService(sp => sp.GetRequiredService<TraderMonitorService>());
@@ -66,10 +75,6 @@ namespace PolyTrader.Modules.CopyTrading
services.AddHostedService<AlchemyWebsocketService>();
services.AddHostedService<PolymarketWssClient>();
// IClobClient-Seam: Leiter/Reconciliation hängen am Interface (mockbar für Integrationstests);
// die Live-Instanz ist der eine PolymarketClobClient-Singleton aus dem App-Container.
services.AddSingleton<IClobClient>(sp => sp.GetRequiredService<PolymarketClobClient>());
// Phase 0.1: SELL-Eskalationsleiter (preist offene Exit-Limits stufenweise nach).
// Singleton + Hosted, damit Engine und TraderMonitor StartLadderAsync aufrufen können.
services.AddSingleton<SellLadderService>();
@@ -0,0 +1,86 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using PolyTraderSharp;
namespace PolyTraderSharp.Services
{
/// <summary>
/// K2 (Fable-Fixes) Neustart-Reconciliation. Ruhende GTC-Orders der SELL-Eskalationsleiter
/// (und ruhende MakerEntry-BUYs) überleben einen Neustart auf dem CLOB, der zugehörige
/// Verwaltungszustand (ExitLadders, Position.ExitPending, PendingOrderTimestamps) ist aber
/// bewusst transient. Ohne Bereinigung liefe die Engine gegen Waisen-Orders (Doppel-Leiter auf
/// dieselben Shares, Fehlerkaskaden).
///
/// Deterministische Lösung: Beim Start je LIVE-Account alle offenen CLOB-Orders pauschal canceln.
/// Danach entscheidet die Engine sauber neu (Master-SELL/Profit-Target starten frische Leitern).
/// Bewusst blockierend als IHostedService, registriert VOR TraderMonitor/Engine, damit die
/// Bereinigung abgeschlossen ist, bevor das erste Signal verarbeitet wird. Pro Account
/// fehlertolerant ein Account-Fehler darf den Start nicht verhindern.
/// </summary>
public class StartupOrderReconciliationService : IHostedService
{
private readonly TradingState _state;
private readonly IClobClient _clob;
private readonly TerminalLogger _logger;
public StartupOrderReconciliationService(TradingState state, IClobClient clob, TerminalLogger logger)
{
_state = state;
_clob = clob;
_logger = logger;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
int accountsProcessed = 0, ordersCancelled = 0;
foreach (var acc in _state.Accounts.Values)
{
if (cancellationToken.IsCancellationRequested) break;
// Nur echte Live-Accounts mit CLOB-Credentials haben ruhende Orders.
if (acc.IsDemo) continue;
if (string.IsNullOrEmpty(acc.ApiKey) || string.IsNullOrEmpty(acc.ApiSecret)
|| string.IsNullOrEmpty(acc.ApiPassphrase) || string.IsNullOrEmpty(acc.PrivateKey)) continue;
try
{
var openOrders = await _clob.GetOpenOrdersAsync(acc); // ohne assetId = ALLE offenen Orders
if (openOrders.Count == 0)
{
_logger.Info($"🧹 [Startup-Reconciliation] {acc.Name}: keine offenen Orders.");
accountsProcessed++;
continue;
}
_logger.Warning($"🧹 [Startup-Reconciliation] {acc.Name}: {openOrders.Count} verwaiste Order(s) vom vorherigen Lauf storniere alle.");
foreach (var order in openOrders)
{
if (cancellationToken.IsCancellationRequested) break;
try
{
bool ok = await _clob.CancelOrderAsync(acc, order.Id);
if (ok) ordersCancelled++;
else _logger.Warning($"⚠️ [Startup-Reconciliation] {acc.Name}: Order {order.Id} konnte nicht storniert werden.");
}
catch (Exception ex)
{
_logger.Error($"[Startup-Reconciliation] {acc.Name}: Cancel {order.Id} fehlgeschlagen: {ex.Message}");
}
}
accountsProcessed++;
}
catch (Exception ex)
{
_logger.Error($"[Startup-Reconciliation] {acc.Name}: Abruf offener Orders fehlgeschlagen: {ex.Message}");
}
}
_logger.Info($"🧹 [Startup-Reconciliation] Abgeschlossen: {accountsProcessed} Live-Account(s) geprüft, {ordersCancelled} Order(s) storniert. Engine entscheidet jetzt sauber neu.");
}
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
}