Fix TradeReconciliationWorker: Fetch missing markets from API on demand before linking orphaned trades
This commit is contained in:
@@ -3,6 +3,7 @@ using Predictalytics.Infrastructure.Logging;
|
|||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.Extensions.Hosting;
|
using Microsoft.Extensions.Hosting;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
namespace Predictalytics.Worker.Services;
|
namespace Predictalytics.Worker.Services;
|
||||||
|
|
||||||
@@ -67,6 +68,39 @@ public class TradeReconciliationWorker : BackgroundService
|
|||||||
int reconciledCount = 0;
|
int reconciledCount = 0;
|
||||||
try
|
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<IEnumerable<IPlatformProvider>>();
|
||||||
|
var polyProvider = platformProviders.FirstOrDefault(p => p.Platform == Predictalytics.Domain.Enums.PlatformType.Polymarket);
|
||||||
|
var marketRepo = scope.ServiceProvider.GetRequiredService<IMarketRepository>();
|
||||||
|
|
||||||
|
if (polyProvider != null)
|
||||||
|
{
|
||||||
|
var newEvents = new List<Predictalytics.Domain.Entities.Event>();
|
||||||
|
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, @"
|
reconciledCount = await Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.ExecuteSqlRawAsync(db.Database, @"
|
||||||
UPDATE Trades t
|
UPDATE Trades t
|
||||||
INNER JOIN MarketOutcomes o ON t.AssetId = o.TokenId
|
INNER JOIN MarketOutcomes o ON t.AssetId = o.TokenId
|
||||||
|
|||||||
Reference in New Issue
Block a user