IndexPriceSyncService.cs 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using Application.Abstractions.Data;
  2. using Domain.Entities.Stocks;
  3. using Domain.Entities.Stocks.ValueObject;
  4. using Microsoft.EntityFrameworkCore;
  5. using Microsoft.Extensions.DependencyInjection;
  6. using Microsoft.Extensions.Logging;
  7. using Microsoft.Extensions.Options;
  8. using SharedKernel;
  9. namespace Infrastructure.StockData;
  10. /// <summary>
  11. /// 지수(시장) 일별시세 수집 — KRX OpenAPI (KOSPI/KOSDAQ/KRX 시리즈, AUTH_KEY 헤더).
  12. /// 기본 18:30 KST 실행(장 마감 후 확정), basDd=직전 영업일 3개 엔드포인트 전량 수집 → IndexDailyPrice upsert (UQ = Series+IndexName+TradeDate).
  13. /// 미반영(0건)이면 2시간 간격 2회 재시도. ApiKey 미설정 시 로그만 남기고 skip (data.go.kr 배치와 동일 정책).
  14. /// </summary>
  15. internal sealed class IndexPriceSyncService(
  16. IServiceScopeFactory scopeFactory,
  17. IHttpClientFactory httpClientFactory,
  18. IOptions<AppSettings> settings,
  19. ILogger<IndexPriceSyncService> logger
  20. ) : DailyScheduledService(logger)
  21. {
  22. // (계열, 엔드포인트 경로)
  23. private static readonly (MarketIndexSeries Series, string Path)[] Endpoints =
  24. [
  25. (MarketIndexSeries.KOSPI, "/svc/apis/idx/kospi_dd_trd"),
  26. (MarketIndexSeries.KOSDAQ, "/svc/apis/idx/kosdaq_dd_trd"),
  27. (MarketIndexSeries.KRX, "/svc/apis/idx/krx_dd_trd")
  28. ];
  29. protected override string JobName => "IndexPriceSync";
  30. protected override TimeOnly TargetTime => ParseTime(settings.Value.KRXCoKr.IndexSyncTime, new TimeOnly(18, 30));
  31. protected override int MaxRetryCount => 2;
  32. protected override TimeSpan RetryDelay => TimeSpan.FromHours(2);
  33. protected override async Task<bool> RunOnceAsync(DateOnly todayKst, CancellationToken ct)
  34. {
  35. var cfg = settings.Value.KRXCoKr;
  36. if (string.IsNullOrWhiteSpace(cfg.ApiKey))
  37. {
  38. Logger.LogWarning("[{Job}] KRXCoKr:ApiKey 미설정 — 수집 skip", JobName);
  39. return true;
  40. }
  41. using var scope = scopeFactory.CreateScope();
  42. var db = scope.ServiceProvider.GetRequiredService<IAppDbContext>();
  43. var client = httpClientFactory.CreateClient(KrxCoKrHttp.ClientName);
  44. var targetDate = await MarketCalendar.GetPreviousBusinessDayAsync(db, todayKst.AddDays(1), ct);
  45. var rows = new List<KrxIndexParser.IndexRow>();
  46. foreach (var (series, path) in Endpoints)
  47. {
  48. var url = $"{cfg.BaseUrl.TrimEnd('/')}{path}?basDd={targetDate:yyyyMMdd}";
  49. var json = await KrxCoKrHttp.GetStringWithRetryAsync(client, url, cfg.ApiKey, Logger, ct);
  50. var parsed = KrxIndexParser.ParseIndexPrices(json, series);
  51. Logger.LogInformation("[{Job}] {Series} basDd={TargetDate} rows={Rows}", JobName, series, targetDate, parsed.Count);
  52. rows.AddRange(parsed);
  53. }
  54. if (rows.Count == 0)
  55. {
  56. Logger.LogInformation("[{Job}] basDd={TargetDate} 지수 미반영 (0건)", JobName, targetDate);
  57. return false;
  58. }
  59. var existing = await db.IndexDailyPrice.Where(c => c.TradeDate == targetDate).ToListAsync(ct);
  60. var existingByKey = existing.ToDictionary(c => (c.Series, c.IndexName));
  61. var inserted = 0;
  62. var updated = 0;
  63. foreach (var row in rows)
  64. {
  65. if (existingByKey.TryGetValue((row.Series, row.IndexName), out var price))
  66. {
  67. price.Update(row.Close, row.ChangeVal, row.FlucRateBp, row.Open, row.High, row.Low, row.Volume, row.Value, row.MarketCap);
  68. updated++;
  69. }
  70. else
  71. {
  72. var created = IndexDailyPrice.Create(row.Series, row.IndexName, row.TradeDate, row.Close, row.ChangeVal, row.FlucRateBp, row.Open, row.High, row.Low, row.Volume, row.Value, row.MarketCap);
  73. await db.IndexDailyPrice.AddAsync(created, ct);
  74. existingByKey[(row.Series, row.IndexName)] = created;
  75. inserted++;
  76. }
  77. }
  78. await db.SaveChangesAsync(ct);
  79. Logger.LogInformation("[{Job}] 완료 — basDd={TargetDate}, rows={Rows}, inserted={Inserted}, updated={Updated}",
  80. JobName, targetDate, rows.Count, inserted, updated);
  81. return true;
  82. }
  83. }