DailyPriceSyncService.cs 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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. if (string.IsNullOrWhiteSpace(cfg.ServiceKey))
  31. {
  32. Logger.LogWarning("[{Job}] StockData:DataGoKr:ServiceKey 미설정 — 수집 skip", JobName);
  33. return true;
  34. }
  35. using var scope = scopeFactory.CreateScope();
  36. var db = scope.ServiceProvider.GetRequiredService<IAppDbContext>();
  37. var client = httpClientFactory.CreateClient(DataGoKrHttp.ClientName);
  38. var targetDate = await MarketCalendar.GetPreviousBusinessDayAsync(db, todayKst, ct);
  39. var rows = new List<DataGoKrStockParser.DailyPriceItem>();
  40. var totalCount = int.MaxValue;
  41. for (var pageNo = 1; pageNo <= MaxPages && rows.Count < totalCount; pageNo++)
  42. {
  43. var url = $"{cfg.BaseUrl.TrimEnd('/')}{ServicePath}?serviceKey={Uri.EscapeDataString(cfg.ServiceKey)}&resultType=json&numOfRows={cfg.PageSize}&pageNo={pageNo}&basDt={targetDate:yyyyMMdd}";
  44. var json = await DataGoKrHttp.GetStringWithRetryAsync(client, url, Logger, ct);
  45. var (items, total) = DataGoKrStockParser.ParseDailyPrices(json);
  46. totalCount = total;
  47. if (items.Count == 0)
  48. {
  49. break;
  50. }
  51. rows.AddRange(items);
  52. }
  53. if (rows.Count == 0)
  54. {
  55. Logger.LogInformation("[{Job}] basDt={TargetDate} 시세 미반영 (0건)", JobName, targetDate);
  56. return false;
  57. }
  58. var stockByCode = await db.Stock.ToDictionaryAsync(c => c.Code, ct);
  59. var existingByStockID = await db.StockDailyPrice.Where(c => c.TradingDate == targetDate).ToDictionaryAsync(c => c.StockID, ct);
  60. var inserted = 0;
  61. var updated = 0;
  62. var unknown = 0;
  63. foreach (var row in rows)
  64. {
  65. if (!stockByCode.TryGetValue(row.Code, out var stock))
  66. {
  67. // 마스터 미동기화 종목 — 다음 마스터 동기화 후 자연 반영
  68. unknown++;
  69. continue;
  70. }
  71. if (existingByStockID.TryGetValue(stock.ID, out var price))
  72. {
  73. price.Update(row.Open, row.High, row.Low, row.Close, row.Volume, row.TradingValue, row.ChangeAmount, row.ChangeRate, row.MarketCap, row.ListedShares);
  74. updated++;
  75. }
  76. else
  77. {
  78. 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);
  79. inserted++;
  80. }
  81. stock.UpdateLastPrice(row.TradingDate, row.Close, row.ChangeRate, row.MarketCap);
  82. }
  83. await db.SaveChangesAsync(ct);
  84. Logger.LogInformation("[{Job}] 완료 — basDt={TargetDate}, rows={Rows}, inserted={Inserted}, updated={Updated}, unknownCode={Unknown}",
  85. JobName, targetDate, rows.Count, inserted, updated, unknown);
  86. return true;
  87. }
  88. }