diff --git a/src/Predictalytics.Worker/Services/TradeReconciliationWorker.cs b/src/Predictalytics.Worker/Services/TradeReconciliationWorker.cs index b75b68e..fbf5315 100644 --- a/src/Predictalytics.Worker/Services/TradeReconciliationWorker.cs +++ b/src/Predictalytics.Worker/Services/TradeReconciliationWorker.cs @@ -3,6 +3,7 @@ using Predictalytics.Infrastructure.Logging; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; +using Microsoft.EntityFrameworkCore; namespace Predictalytics.Worker.Services; @@ -67,6 +68,39 @@ public class TradeReconciliationWorker : BackgroundService int reconciledCount = 0; try { + // 1. Fetch missing markets on demand + var missingMarketIds = await db.Trades + .Where(t => t.MarketOutcomeId == null && !string.IsNullOrEmpty(t.MarketId) && !db.Markets.Any(m => m.ConditionId == t.MarketId)) + .Select(t => t.MarketId) + .Distinct() + .Take(50) // Limit to avoid rate limits + .ToListAsync(ct); + + if (missingMarketIds.Count > 0) + { + var platformProviders = scope.ServiceProvider.GetRequiredService>(); + var polyProvider = platformProviders.FirstOrDefault(p => p.Platform == Predictalytics.Domain.Enums.PlatformType.Polymarket); + var marketRepo = scope.ServiceProvider.GetRequiredService(); + + if (polyProvider != null) + { + var newEvents = new List(); + foreach (var marketId in missingMarketIds) + { + var market = await polyProvider.GetMarketAsync(marketId, ct); + if (market != null && market.Event != null) + { + newEvents.Add(market.Event); + } + } + if (newEvents.Count > 0) + { + await marketRepo.AddOrUpdateEventsAsync(newEvents, ct); + } + } + } + + // 2. Bulk update orphaned trades reconciledCount = await Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.ExecuteSqlRawAsync(db.Database, @" UPDATE Trades t INNER JOIN MarketOutcomes o ON t.AssetId = o.TokenId