| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114 |
- using Application.Abstractions.Data;
- using Domain.Entities.Stocks;
- using Microsoft.EntityFrameworkCore;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Logging;
- using Microsoft.Extensions.Options;
- using SharedKernel;
- namespace Infrastructure.StockData;
- /// <summary>
- /// T+1 일별 시세 수집 — 금융위 주식시세정보 API (영업일+1 13시 이후 반영).
- /// 기본 13:10 KST 실행, basDt=직전 영업일 전량 수집 → StockDailyPrice upsert + Stock denorm(최근 종가/등락률/시총) 갱신.
- /// 미반영(0건)이면 2시간 간격 2회 재시도 (≈15시/17시). ServiceKey 미설정 시 로그만 남기고 skip.
- /// </summary>
- internal sealed class DailyPriceSyncService(
- IServiceScopeFactory scopeFactory,
- IHttpClientFactory httpClientFactory,
- IOptions<AppSettings> settings,
- ILogger<DailyPriceSyncService> logger
- ) : DailyScheduledService(logger)
- {
- private const string ServicePath = "/1160100/service/GetStockSecuritiesInfoService/getStockPriceInfo";
- private const int MaxPages = 50;
- protected override string JobName => "DailyPriceSync";
- protected override TimeOnly TargetTime => ParseTime(settings.Value.StockData.DailyPriceSyncTime, new TimeOnly(13, 10));
- protected override int MaxRetryCount => 2;
- protected override TimeSpan RetryDelay => TimeSpan.FromHours(2);
- protected override async Task<bool> RunOnceAsync(DateOnly todayKst, CancellationToken ct)
- {
- var cfg = settings.Value.StockData.DataGoKr;
- using var scope = scopeFactory.CreateScope();
- var collectorSettings = scope.ServiceProvider.GetRequiredService<ICollectorSettingsProvider>();
- if (!await collectorSettings.IsEnabledAsync(CollectorFlag.StockDataDailyPrice, ct))
- {
- return true;
- }
- cfg = cfg with { ServiceKey = await collectorSettings.GetKeyAsync(CollectorKey.DataGoKr, ct) ?? cfg.ServiceKey };
- if (string.IsNullOrWhiteSpace(cfg.ServiceKey))
- {
- Logger.LogWarning("[{Job}] StockData:DataGoKr:ServiceKey 미설정 — 수집 skip", JobName);
- return true;
- }
- var db = scope.ServiceProvider.GetRequiredService<IAppDbContext>();
- var client = httpClientFactory.CreateClient(DataGoKrHttp.ClientName);
- var targetDate = await MarketCalendar.GetPreviousBusinessDayAsync(db, todayKst, ct);
- var rows = new List<DataGoKrStockParser.DailyPriceItem>();
- var totalCount = int.MaxValue;
- for (var pageNo = 1; pageNo <= MaxPages && rows.Count < totalCount; pageNo++)
- {
- var url = $"{cfg.BaseUrl.TrimEnd('/')}{ServicePath}?serviceKey={Uri.EscapeDataString(cfg.ServiceKey)}&resultType=json&numOfRows={cfg.PageSize}&pageNo={pageNo}&basDt={targetDate:yyyyMMdd}";
- var json = await DataGoKrHttp.GetStringWithRetryAsync(client, url, Logger, ct);
- var (items, total) = DataGoKrStockParser.ParseDailyPrices(json);
- totalCount = total;
- if (items.Count == 0)
- {
- break;
- }
- rows.AddRange(items);
- }
- if (rows.Count == 0)
- {
- Logger.LogInformation("[{Job}] basDt={TargetDate} 시세 미반영 (0건)", JobName, targetDate);
- return false;
- }
- var stockByCode = await db.Stock.ToDictionaryAsync(c => c.Code, ct);
- var existingByStockID = await db.StockDailyPrice.Where(c => c.TradingDate == targetDate).ToDictionaryAsync(c => c.StockID, ct);
- var inserted = 0;
- var updated = 0;
- var unknown = 0;
- foreach (var row in rows)
- {
- if (!stockByCode.TryGetValue(row.Code, out var stock))
- {
- // 마스터 미동기화 종목 — 다음 마스터 동기화 후 자연 반영
- unknown++;
- continue;
- }
- if (existingByStockID.TryGetValue(stock.ID, out var price))
- {
- price.Update(row.Open, row.High, row.Low, row.Close, row.Volume, row.TradingValue, row.ChangeAmount, row.ChangeRate, row.MarketCap, row.ListedShares);
- updated++;
- }
- else
- {
- await db.StockDailyPrice.AddAsync(StockDailyPrice.Create(stock.ID, row.TradingDate, row.Open, row.High, row.Low, row.Close, row.Volume, row.TradingValue, row.ChangeAmount, row.ChangeRate, row.MarketCap, row.ListedShares), ct);
- inserted++;
- }
- stock.UpdateLastPrice(row.TradingDate, row.Close, row.ChangeRate, row.MarketCap);
- }
- await db.SaveChangesAsync(ct);
- Logger.LogInformation("[{Job}] 완료 — basDt={TargetDate}, rows={Rows}, inserted={Inserted}, updated={Updated}, unknownCode={Unknown}",
- JobName, targetDate, rows.Count, inserted, updated, unknown);
- return true;
- }
- }
|