using Application.Abstractions.Data; using Domain.Entities.Stocks; using Domain.Entities.Stocks.ValueObject; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using SharedKernel; namespace Infrastructure.StockData; /// /// 증권상품(ETF/ETN/ELW) 일별매매 수집 (KRX OpenAPI) — etf_bydd_trd + etn_bydd_trd + elw_bydd_trd. "KRX 증권상품(ETF/ETN/ELW) 수집". /// 기본 18:20 KST 실행(장 마감 15:30 이후 확정, 주식 수집 18:10 뒤), basDd=직전 영업일 3개 엔드포인트 전량 수집 → /// EtpDailyTrade upsert (UQ = EtpType+Code+TradeDate). 미반영(0건)이면 2시간 간격 2회 재시도. /// ApiKey 미설정 시 로그만 남기고 skip (다른 KRX 배치와 동일 정책). /// internal sealed class KrxEtpSyncService( IServiceScopeFactory scopeFactory, IHttpClientFactory httpClientFactory, IOptions settings, ILogger logger ) : DailyScheduledService(logger) { // (유형, 엔드포인트 경로) — ETF/ETN/ELW private static readonly (EtpType Type, string Path)[] Endpoints = [ (EtpType.ETF, "/svc/apis/etp/etf_bydd_trd"), (EtpType.ETN, "/svc/apis/etp/etn_bydd_trd"), (EtpType.ELW, "/svc/apis/etp/elw_bydd_trd") ]; protected override string JobName => "KrxEtpSync"; protected override TimeOnly TargetTime => ParseTime(settings.Value.KRXCoKr.EtpSyncTime, new TimeOnly(18, 20)); protected override int MaxRetryCount => 2; protected override TimeSpan RetryDelay => TimeSpan.FromHours(2); protected override async Task RunOnceAsync(DateOnly todayKst, CancellationToken ct) { var cfg = settings.Value.KRXCoKr; if (string.IsNullOrWhiteSpace(cfg.ApiKey)) { Logger.LogWarning("[{Job}] KRXCoKr:ApiKey 미설정 — 수집 skip", JobName); return true; } using var scope = scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var client = httpClientFactory.CreateClient(KrxCoKrHttp.ClientName); var targetDate = await MarketCalendar.GetPreviousBusinessDayAsync(db, todayKst.AddDays(1), ct); var rows = new List(); foreach (var (type, path) in Endpoints) { var url = $"{cfg.BaseUrl.TrimEnd('/')}{path}?basDd={targetDate:yyyyMMdd}"; var json = await KrxCoKrHttp.GetStringWithRetryAsync(client, url, cfg.ApiKey, Logger, ct); var parsed = KrxEtpParser.ParseDaily(json, type); Logger.LogInformation("[{Job}] {Type} basDd={TargetDate} rows={Rows}", JobName, type, targetDate, parsed.Count); rows.AddRange(parsed); } if (rows.Count == 0) { Logger.LogInformation("[{Job}] basDd={TargetDate} 증권상품 미반영 (0건)", JobName, targetDate); return false; } var existing = await db.EtpDailyTrade.Where(c => c.TradeDate == targetDate).ToListAsync(ct); var existingByKey = existing.ToDictionary(c => (c.EtpType, c.Code)); var inserted = 0; var updated = 0; foreach (var row in rows) { if (existingByKey.TryGetValue((row.EtpType, row.Code), out var trade)) { trade.Update(row.Name, row.Close, row.Open, row.High, row.Low, row.ChangeAmount, row.ChangeRate, row.Volume, row.TradeValue, row.MarketCap, row.ListedShares, row.Nav, row.NetAssetTotal, row.BaseIndexName, row.BaseIndexClose, row.Underlying, row.UnderlyingClose); updated++; } else { var created = EtpDailyTrade.Create(row.EtpType, row.Code, row.Name, row.TradeDate, row.Close, row.Open, row.High, row.Low, row.ChangeAmount, row.ChangeRate, row.Volume, row.TradeValue, row.MarketCap, row.ListedShares, row.Nav, row.NetAssetTotal, row.BaseIndexName, row.BaseIndexClose, row.Underlying, row.UnderlyingClose); await db.EtpDailyTrade.AddAsync(created, ct); existingByKey[(row.EtpType, row.Code)] = created; inserted++; } } await db.SaveChangesAsync(ct); Logger.LogInformation("[{Job}] 완료 — basDd={TargetDate}, rows={Rows}, inserted={Inserted}, updated={Updated}", JobName, targetDate, rows.Count, inserted, updated); return true; } }