BondIndexPriceSyncService.cs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. using Application.Abstractions.Data;
  2. using Application.Helpers;
  3. using Domain.Entities.Stocks;
  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 (idx/bon_dd_trd, AUTH_KEY 헤더).
  12. /// 응답 shape(총수익·순가격·재투자·시장가격 지수 + 듀레이션·컨벡시티·YTM)이 주식/파생 지수와 달라 IndexPriceSyncService 와 분리한다.
  13. /// 기본 18:35 KST 실행(지수 수집 18:30 뒤). 공용 KrxBackfill 로 최근 BackfillYears(기본 3)년치를 endDate(직전 영업일)부터
  14. /// 과거로 훑으며 미적재일만 채운다. quota 보호를 위해 1회 실행당 BackfillMaxPerRun(기본 60)일까지만 fetch →
  15. /// 여러 날에 걸쳐 3년치를 메우고 이후엔 최신만 유지한다. 각 날짜는 1개 엔드포인트를 수집해 BondIndexDailyPrice upsert
  16. /// (UQ = GroupName+TradeDate). ApiKey 미설정 시 로그만 남기고 skip (다른 KRX 배치와 동일 정책).
  17. /// </summary>
  18. internal sealed class BondIndexPriceSyncService(
  19. IServiceScopeFactory scopeFactory,
  20. IHttpClientFactory httpClientFactory,
  21. IOptions<AppSettings> settings,
  22. ILogger<BondIndexPriceSyncService> logger
  23. ) : DailyScheduledService(logger)
  24. {
  25. private const string EndpointPath = "/svc/apis/idx/bon_dd_trd";
  26. protected override string JobName => "BondIndexPriceSync";
  27. protected override TimeOnly TargetTime => ParseTime(settings.Value.KRXCoKr.BondIndexSyncTime, new TimeOnly(18, 35));
  28. protected override int MaxRetryCount => 2;
  29. protected override TimeSpan RetryDelay => TimeSpan.FromHours(2);
  30. protected override async Task<bool> RunOnceAsync(DateOnly todayKst, CancellationToken ct)
  31. {
  32. var cfg = settings.Value.KRXCoKr;
  33. using var scope = scopeFactory.CreateScope();
  34. var collectorSettings = scope.ServiceProvider.GetRequiredService<ICollectorSettingsProvider>();
  35. if (!await collectorSettings.IsEnabledAsync(CollectorFlag.KrxBondIndex, ct))
  36. {
  37. return true;
  38. }
  39. cfg = cfg with { ApiKey = await collectorSettings.GetKeyAsync(CollectorKey.Krx, ct) ?? cfg.ApiKey };
  40. var db = scope.ServiceProvider.GetRequiredService<IAppDbContext>();
  41. if (string.IsNullOrWhiteSpace(cfg.ApiKey))
  42. {
  43. Logger.LogWarning("[{Job}] KRXCoKr:ApiKey 미설정 — 수집 skip", JobName);
  44. return true;
  45. }
  46. var client = httpClientFactory.CreateClient(KrxCoKrHttp.ClientName);
  47. var endDate = await MarketCalendar.GetPreviousBusinessDayAsync(db, todayKst.AddDays(1), ct);
  48. var years = cfg.BackfillYears > 0 ? cfg.BackfillYears : 3;
  49. var startDate = todayKst.AddYears(-years);
  50. // 백필 창 전체의 휴장일을 한 번에 로드 (KrxBackfill 은 주말은 자동 제외, 휴장일만 필요)
  51. var holidays = (await db.MarketHoliday.AsNoTracking()
  52. .Where(c => c.Date >= startDate && c.Date <= endDate)
  53. .Select(c => c.Date)
  54. .ToListAsync(ct)).ToHashSet();
  55. var maxPerRun = cfg.BackfillMaxPerRun > 0 ? cfg.BackfillMaxPerRun : 60;
  56. var fetched = await KrxBackfill.RunAsync(
  57. existsForDate: (day, token) => db.BondIndexDailyPrice.AsNoTracking().AnyAsync(c => c.TradeDate == day, token),
  58. fetchAndUpsertForDate: (day, token) => FetchAndUpsertAsync(db, client, cfg.BaseUrl, cfg.ApiKey, day, token),
  59. startDate: startDate,
  60. endDate: endDate,
  61. holidays: holidays,
  62. maxPerRun: maxPerRun,
  63. delayMs: 300,
  64. ct: ct);
  65. Logger.LogInformation("[{Job}] 완료 — 창=[{Start}~{End}], 이번 실행 fetch={Fetched}일 (maxPerRun={Max})",
  66. JobName, startDate, endDate, fetched, maxPerRun);
  67. // 최신 영업일(endDate) 데이터가 이번 실행에서도 미적재면 false → 베이스가 RetryDelay 후 재시도 (KRX T+0 마감 데이터 미반영 대비)
  68. if (!await db.BondIndexDailyPrice.AsNoTracking().AnyAsync(c => c.TradeDate == endDate, ct))
  69. {
  70. Logger.LogWarning("[{Job}] 최신 영업일 {End} 데이터 미적재 — {Delay} 후 재시도 (최대 {Max}회)", JobName, endDate, RetryDelay, MaxRetryCount);
  71. return false;
  72. }
  73. return true;
  74. }
  75. /// <summary>한 날짜에 대해 채권지수 엔드포인트를 수집하고 BondIndexDailyPrice upsert.</summary>
  76. private async Task FetchAndUpsertAsync(IAppDbContext db, HttpClient client, string baseUrl, string apiKey, DateOnly day, CancellationToken ct)
  77. {
  78. var url = $"{baseUrl.TrimEnd('/')}{EndpointPath}?basDd={day:yyyyMMdd}";
  79. var json = await KrxCoKrHttp.GetStringWithRetryAsync(client, url, apiKey, Logger, ct);
  80. var rows = KrxBondIndexParser.ParseBondIndexPrices(json);
  81. Logger.LogInformation("[{Job}] basDd={Day} rows={Rows}", JobName, day, rows.Count);
  82. if (rows.Count == 0)
  83. {
  84. Logger.LogInformation("[{Job}] basDd={Day} 채권지수 미반영 (0건)", JobName, day);
  85. return;
  86. }
  87. var existing = await db.BondIndexDailyPrice.Where(c => c.TradeDate == day).ToListAsync(ct);
  88. var existingByKey = existing.ToDictionary(c => c.GroupName);
  89. var inserted = 0;
  90. var updated = 0;
  91. foreach (var row in rows)
  92. {
  93. if (existingByKey.TryGetValue(row.GroupName, out var price))
  94. {
  95. price.Update(row.TotalEarningIndex, row.TotalEarningChange, row.NetPriceIndex, row.NetPriceChange, row.ZeroReinvestIndex, row.ZeroReinvestChange, row.CallReinvestIndex, row.CallReinvestChange, row.MarketPriceIndex, row.MarketPriceChange, row.AvgDuration, row.AvgConvexity, row.AvgYield);
  96. updated++;
  97. }
  98. else
  99. {
  100. var created = BondIndexDailyPrice.Create(row.GroupName, row.TradeDate, row.TotalEarningIndex, row.TotalEarningChange, row.NetPriceIndex, row.NetPriceChange, row.ZeroReinvestIndex, row.ZeroReinvestChange, row.CallReinvestIndex, row.CallReinvestChange, row.MarketPriceIndex, row.MarketPriceChange, row.AvgDuration, row.AvgConvexity, row.AvgYield);
  101. await db.BondIndexDailyPrice.AddAsync(created, ct);
  102. existingByKey[row.GroupName] = created;
  103. inserted++;
  104. }
  105. }
  106. await db.SaveChangesAsync(ct);
  107. Logger.LogInformation("[{Job}] basDd={Day} 적재 — rows={Rows}, inserted={Inserted}, updated={Updated}",
  108. JobName, day, rows.Count, inserted, updated);
  109. }
  110. }