BondIndexPriceSyncService.cs 4.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. /// 채권지수 일별시세 수집 — KRX OpenAPI (idx/bon_dd_trd, AUTH_KEY 헤더).
  11. /// 응답 shape(총수익·순가격·재투자·시장가격 지수 + 듀레이션·컨벡시티·YTM)이 주식/파생 지수와 달라 IndexPriceSyncService 와 분리한다.
  12. /// 기본 18:35 KST 실행(지수 수집 18:30 뒤), basDd=직전 영업일 1개 엔드포인트 전량 수집 → BondIndexDailyPrice upsert (UQ = GroupName+TradeDate).
  13. /// 미반영(0건)이면 2시간 간격 2회 재시도. ApiKey 미설정 시 로그만 남기고 skip (다른 KRX 배치와 동일 정책).
  14. /// </summary>
  15. internal sealed class BondIndexPriceSyncService(
  16. IServiceScopeFactory scopeFactory,
  17. IHttpClientFactory httpClientFactory,
  18. IOptions<AppSettings> settings,
  19. ILogger<BondIndexPriceSyncService> logger
  20. ) : DailyScheduledService(logger)
  21. {
  22. private const string EndpointPath = "/svc/apis/idx/bon_dd_trd";
  23. protected override string JobName => "BondIndexPriceSync";
  24. protected override TimeOnly TargetTime => ParseTime(settings.Value.KRXCoKr.BondIndexSyncTime, new TimeOnly(18, 35));
  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.KRXCoKr;
  30. if (string.IsNullOrWhiteSpace(cfg.ApiKey))
  31. {
  32. Logger.LogWarning("[{Job}] KRXCoKr:ApiKey 미설정 — 수집 skip", JobName);
  33. return true;
  34. }
  35. using var scope = scopeFactory.CreateScope();
  36. var db = scope.ServiceProvider.GetRequiredService<IAppDbContext>();
  37. var client = httpClientFactory.CreateClient(KrxCoKrHttp.ClientName);
  38. var targetDate = await MarketCalendar.GetPreviousBusinessDayAsync(db, todayKst.AddDays(1), ct);
  39. var url = $"{cfg.BaseUrl.TrimEnd('/')}{EndpointPath}?basDd={targetDate:yyyyMMdd}";
  40. var json = await KrxCoKrHttp.GetStringWithRetryAsync(client, url, cfg.ApiKey, Logger, ct);
  41. var rows = KrxBondIndexParser.ParseBondIndexPrices(json);
  42. Logger.LogInformation("[{Job}] basDd={TargetDate} rows={Rows}", JobName, targetDate, rows.Count);
  43. if (rows.Count == 0)
  44. {
  45. Logger.LogInformation("[{Job}] basDd={TargetDate} 채권지수 미반영 (0건)", JobName, targetDate);
  46. return false;
  47. }
  48. var existing = await db.BondIndexDailyPrice.Where(c => c.TradeDate == targetDate).ToListAsync(ct);
  49. var existingByKey = existing.ToDictionary(c => c.GroupName);
  50. var inserted = 0;
  51. var updated = 0;
  52. foreach (var row in rows)
  53. {
  54. if (existingByKey.TryGetValue(row.GroupName, out var price))
  55. {
  56. 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);
  57. updated++;
  58. }
  59. else
  60. {
  61. 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);
  62. await db.BondIndexDailyPrice.AddAsync(created, ct);
  63. existingByKey[row.GroupName] = created;
  64. inserted++;
  65. }
  66. }
  67. await db.SaveChangesAsync(ct);
  68. Logger.LogInformation("[{Job}] 완료 — basDd={TargetDate}, rows={Rows}, inserted={Inserted}, updated={Updated}",
  69. JobName, targetDate, rows.Count, inserted, updated);
  70. return true;
  71. }
  72. }