DailyPriceSyncService.cs 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. using Application.Abstractions.Data;
  2. using Domain.Entities.Stocks;
  3. using Microsoft.EntityFrameworkCore;
  4. using Microsoft.Extensions.DependencyInjection;
  5. using Microsoft.Extensions.Logging;
  6. using Microsoft.Extensions.Options;
  7. using SharedKernel;
  8. namespace Infrastructure.StockData;
  9. /// <summary>
  10. /// T+1 일별 시세 수집 — 금융위 주식시세정보 API (영업일+1 13시 이후 반영).
  11. /// 기본 13:10 KST 실행, basDt=직전 영업일 전량 수집 → StockDailyPrice upsert + Stock denorm(최근 종가/등락률/시총) 갱신.
  12. /// 미반영(0건)이면 2시간 간격 2회 재시도 (≈15시/17시). ServiceKey 미설정 시 로그만 남기고 skip.
  13. /// </summary>
  14. internal sealed class DailyPriceSyncService(
  15. IServiceScopeFactory scopeFactory,
  16. IHttpClientFactory httpClientFactory,
  17. IOptions<AppSettings> settings,
  18. ILogger<DailyPriceSyncService> logger
  19. ) : DailyScheduledService(logger)
  20. {
  21. private const string ServicePath = "/1160100/service/GetStockSecuritiesInfoService/getStockPriceInfo";
  22. private const int MaxPages = 50;
  23. protected override string JobName => "DailyPriceSync";
  24. protected override TimeOnly TargetTime => ParseTime(settings.Value.StockData.DailyPriceSyncTime, new TimeOnly(13, 10));
  25. protected override int MaxRetryCount => 2;
  26. protected override TimeSpan RetryDelay => TimeSpan.FromHours(2);
  27. protected override async Task<bool> RunOnceAsync(DateOnly todayKst, CancellationToken ct)
  28. {
  29. var cfg = settings.Value.StockData.DataGoKr;
  30. using var scope = scopeFactory.CreateScope();
  31. var collectorSettings = scope.ServiceProvider.GetRequiredService<ICollectorSettingsProvider>();
  32. if (!await collectorSettings.IsEnabledAsync(CollectorFlag.StockDataDailyPrice, ct))
  33. {
  34. return true;
  35. }
  36. cfg = cfg with { ServiceKey = await collectorSettings.GetKeyAsync(CollectorKey.DataGoKr, ct) ?? cfg.ServiceKey };
  37. if (string.IsNullOrWhiteSpace(cfg.ServiceKey))
  38. {
  39. Logger.LogWarning("[{Job}] StockData:DataGoKr:ServiceKey 미설정 — 수집 skip", JobName);
  40. return true;
  41. }
  42. var db = scope.ServiceProvider.GetRequiredService<IAppDbContext>();
  43. var client = httpClientFactory.CreateClient(DataGoKrHttp.ClientName);
  44. var targetDate = await MarketCalendar.GetPreviousBusinessDayAsync(db, todayKst, ct);
  45. var rows = new List<DataGoKrStockParser.DailyPriceItem>();
  46. var totalCount = int.MaxValue;
  47. for (var pageNo = 1; pageNo <= MaxPages && rows.Count < totalCount; pageNo++)
  48. {
  49. var url = $"{cfg.BaseUrl.TrimEnd('/')}{ServicePath}?serviceKey={Uri.EscapeDataString(cfg.ServiceKey)}&resultType=json&numOfRows={cfg.PageSize}&pageNo={pageNo}&basDt={targetDate:yyyyMMdd}";
  50. var json = await DataGoKrHttp.GetStringWithRetryAsync(client, url, Logger, ct);
  51. var (items, total) = DataGoKrStockParser.ParseDailyPrices(json);
  52. totalCount = total;
  53. if (items.Count == 0)
  54. {
  55. break;
  56. }
  57. rows.AddRange(items);
  58. }
  59. if (rows.Count == 0)
  60. {
  61. Logger.LogInformation("[{Job}] basDt={TargetDate} 시세 미반영 (0건)", JobName, targetDate);
  62. return false;
  63. }
  64. var stockByCode = await db.Stock.ToDictionaryAsync(c => c.Code, ct);
  65. var existingByStockID = await db.StockDailyPrice.Where(c => c.TradingDate == targetDate).ToDictionaryAsync(c => c.StockID, ct);
  66. var inserted = 0;
  67. var updated = 0;
  68. var unknown = 0;
  69. foreach (var row in rows)
  70. {
  71. if (!stockByCode.TryGetValue(row.Code, out var stock))
  72. {
  73. // 마스터 미동기화 종목 — 다음 마스터 동기화 후 자연 반영
  74. unknown++;
  75. continue;
  76. }
  77. if (existingByStockID.TryGetValue(stock.ID, out var price))
  78. {
  79. price.Update(row.Open, row.High, row.Low, row.Close, row.Volume, row.TradingValue, row.ChangeAmount, row.ChangeRate, row.MarketCap, row.ListedShares);
  80. updated++;
  81. }
  82. else
  83. {
  84. 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);
  85. inserted++;
  86. }
  87. stock.UpdateLastPrice(row.TradingDate, row.Close, row.ChangeRate, row.MarketCap);
  88. }
  89. await db.SaveChangesAsync(ct);
  90. Logger.LogInformation("[{Job}] 완료 — basDt={TargetDate}, rows={Rows}, inserted={Inserted}, updated={Updated}, unknownCode={Unknown}",
  91. JobName, targetDate, rows.Count, inserted, updated, unknown);
  92. return true;
  93. }
  94. }