BondIndexPriceSyncService.cs 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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. if (string.IsNullOrWhiteSpace(cfg.ApiKey))
  34. {
  35. Logger.LogWarning("[{Job}] KRXCoKr:ApiKey 미설정 — 수집 skip", JobName);
  36. return true;
  37. }
  38. using var scope = scopeFactory.CreateScope();
  39. var db = scope.ServiceProvider.GetRequiredService<IAppDbContext>();
  40. var client = httpClientFactory.CreateClient(KrxCoKrHttp.ClientName);
  41. var endDate = await MarketCalendar.GetPreviousBusinessDayAsync(db, todayKst.AddDays(1), ct);
  42. var years = cfg.BackfillYears > 0 ? cfg.BackfillYears : 3;
  43. var startDate = todayKst.AddYears(-years);
  44. // 백필 창 전체의 휴장일을 한 번에 로드 (KrxBackfill 은 주말은 자동 제외, 휴장일만 필요)
  45. var holidays = (await db.MarketHoliday.AsNoTracking()
  46. .Where(c => c.Date >= startDate && c.Date <= endDate)
  47. .Select(c => c.Date)
  48. .ToListAsync(ct)).ToHashSet();
  49. var maxPerRun = cfg.BackfillMaxPerRun > 0 ? cfg.BackfillMaxPerRun : 60;
  50. var fetched = await KrxBackfill.RunAsync(
  51. existsForDate: (day, token) => db.BondIndexDailyPrice.AsNoTracking().AnyAsync(c => c.TradeDate == day, token),
  52. fetchAndUpsertForDate: (day, token) => FetchAndUpsertAsync(db, client, cfg.BaseUrl, cfg.ApiKey, day, token),
  53. startDate: startDate,
  54. endDate: endDate,
  55. holidays: holidays,
  56. maxPerRun: maxPerRun,
  57. delayMs: 300,
  58. ct: ct);
  59. Logger.LogInformation("[{Job}] 완료 — 창=[{Start}~{End}], 이번 실행 fetch={Fetched}일 (maxPerRun={Max})",
  60. JobName, startDate, endDate, fetched, maxPerRun);
  61. // fetch 가 0 이어도(이미 최신까지 적재됨) 정상 완료 — 재시도 불필요
  62. return true;
  63. }
  64. /// <summary>한 날짜에 대해 채권지수 엔드포인트를 수집하고 BondIndexDailyPrice upsert.</summary>
  65. private async Task FetchAndUpsertAsync(IAppDbContext db, HttpClient client, string baseUrl, string apiKey, DateOnly day, CancellationToken ct)
  66. {
  67. var url = $"{baseUrl.TrimEnd('/')}{EndpointPath}?basDd={day:yyyyMMdd}";
  68. var json = await KrxCoKrHttp.GetStringWithRetryAsync(client, url, apiKey, Logger, ct);
  69. var rows = KrxBondIndexParser.ParseBondIndexPrices(json);
  70. Logger.LogInformation("[{Job}] basDd={Day} rows={Rows}", JobName, day, rows.Count);
  71. if (rows.Count == 0)
  72. {
  73. Logger.LogInformation("[{Job}] basDd={Day} 채권지수 미반영 (0건)", JobName, day);
  74. return;
  75. }
  76. var existing = await db.BondIndexDailyPrice.Where(c => c.TradeDate == day).ToListAsync(ct);
  77. var existingByKey = existing.ToDictionary(c => c.GroupName);
  78. var inserted = 0;
  79. var updated = 0;
  80. foreach (var row in rows)
  81. {
  82. if (existingByKey.TryGetValue(row.GroupName, out var price))
  83. {
  84. 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);
  85. updated++;
  86. }
  87. else
  88. {
  89. 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);
  90. await db.BondIndexDailyPrice.AddAsync(created, ct);
  91. existingByKey[row.GroupName] = created;
  92. inserted++;
  93. }
  94. }
  95. await db.SaveChangesAsync(ct);
  96. Logger.LogInformation("[{Job}] basDd={Day} 적재 — rows={Rows}, inserted={Inserted}, updated={Updated}",
  97. JobName, day, rows.Count, inserted, updated);
  98. }
  99. }