| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126 |
- using Application.Abstractions.Data;
- using Application.Helpers;
- using Domain.Entities.Stocks;
- using Microsoft.EntityFrameworkCore;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Logging;
- using Microsoft.Extensions.Options;
- using SharedKernel;
- namespace Infrastructure.StockData;
- /// <summary>
- /// 채권지수 일별시세 수집 — KRX OpenAPI (idx/bon_dd_trd, AUTH_KEY 헤더).
- /// 응답 shape(총수익·순가격·재투자·시장가격 지수 + 듀레이션·컨벡시티·YTM)이 주식/파생 지수와 달라 IndexPriceSyncService 와 분리한다.
- /// 기본 18:35 KST 실행(지수 수집 18:30 뒤). 공용 KrxBackfill 로 최근 BackfillYears(기본 3)년치를 endDate(직전 영업일)부터
- /// 과거로 훑으며 미적재일만 채운다. quota 보호를 위해 1회 실행당 BackfillMaxPerRun(기본 60)일까지만 fetch →
- /// 여러 날에 걸쳐 3년치를 메우고 이후엔 최신만 유지한다. 각 날짜는 1개 엔드포인트를 수집해 BondIndexDailyPrice upsert
- /// (UQ = GroupName+TradeDate). ApiKey 미설정 시 로그만 남기고 skip (다른 KRX 배치와 동일 정책).
- /// </summary>
- internal sealed class BondIndexPriceSyncService(
- IServiceScopeFactory scopeFactory,
- IHttpClientFactory httpClientFactory,
- IOptions<AppSettings> settings,
- ILogger<BondIndexPriceSyncService> logger
- ) : DailyScheduledService(logger)
- {
- private const string EndpointPath = "/svc/apis/idx/bon_dd_trd";
- protected override string JobName => "BondIndexPriceSync";
- protected override TimeOnly TargetTime => ParseTime(settings.Value.KRXCoKr.BondIndexSyncTime, new TimeOnly(18, 35));
- protected override int MaxRetryCount => 2;
- protected override TimeSpan RetryDelay => TimeSpan.FromHours(2);
- protected override async Task<bool> RunOnceAsync(DateOnly todayKst, CancellationToken ct)
- {
- var cfg = settings.Value.KRXCoKr;
- if (string.IsNullOrWhiteSpace(cfg.ApiKey))
- {
- Logger.LogWarning("[{Job}] KRXCoKr:ApiKey 미설정 — 수집 skip", JobName);
- return true;
- }
- using var scope = scopeFactory.CreateScope();
- var db = scope.ServiceProvider.GetRequiredService<IAppDbContext>();
- var client = httpClientFactory.CreateClient(KrxCoKrHttp.ClientName);
- var endDate = await MarketCalendar.GetPreviousBusinessDayAsync(db, todayKst.AddDays(1), ct);
- var years = cfg.BackfillYears > 0 ? cfg.BackfillYears : 3;
- var startDate = todayKst.AddYears(-years);
- // 백필 창 전체의 휴장일을 한 번에 로드 (KrxBackfill 은 주말은 자동 제외, 휴장일만 필요)
- var holidays = (await db.MarketHoliday.AsNoTracking()
- .Where(c => c.Date >= startDate && c.Date <= endDate)
- .Select(c => c.Date)
- .ToListAsync(ct)).ToHashSet();
- var maxPerRun = cfg.BackfillMaxPerRun > 0 ? cfg.BackfillMaxPerRun : 60;
- var fetched = await KrxBackfill.RunAsync(
- existsForDate: (day, token) => db.BondIndexDailyPrice.AsNoTracking().AnyAsync(c => c.TradeDate == day, token),
- fetchAndUpsertForDate: (day, token) => FetchAndUpsertAsync(db, client, cfg.BaseUrl, cfg.ApiKey, day, token),
- startDate: startDate,
- endDate: endDate,
- holidays: holidays,
- maxPerRun: maxPerRun,
- delayMs: 300,
- ct: ct);
- Logger.LogInformation("[{Job}] 완료 — 창=[{Start}~{End}], 이번 실행 fetch={Fetched}일 (maxPerRun={Max})",
- JobName, startDate, endDate, fetched, maxPerRun);
- // 최신 영업일(endDate) 데이터가 이번 실행에서도 미적재면 false → 베이스가 RetryDelay 후 재시도 (KRX T+0 마감 데이터 미반영 대비)
- if (!await db.BondIndexDailyPrice.AsNoTracking().AnyAsync(c => c.TradeDate == endDate, ct))
- {
- Logger.LogWarning("[{Job}] 최신 영업일 {End} 데이터 미적재 — {Delay} 후 재시도 (최대 {Max}회)", JobName, endDate, RetryDelay, MaxRetryCount);
- return false;
- }
- return true;
- }
- /// <summary>한 날짜에 대해 채권지수 엔드포인트를 수집하고 BondIndexDailyPrice upsert.</summary>
- private async Task FetchAndUpsertAsync(IAppDbContext db, HttpClient client, string baseUrl, string apiKey, DateOnly day, CancellationToken ct)
- {
- var url = $"{baseUrl.TrimEnd('/')}{EndpointPath}?basDd={day:yyyyMMdd}";
- var json = await KrxCoKrHttp.GetStringWithRetryAsync(client, url, apiKey, Logger, ct);
- var rows = KrxBondIndexParser.ParseBondIndexPrices(json);
- Logger.LogInformation("[{Job}] basDd={Day} rows={Rows}", JobName, day, rows.Count);
- if (rows.Count == 0)
- {
- Logger.LogInformation("[{Job}] basDd={Day} 채권지수 미반영 (0건)", JobName, day);
- return;
- }
- var existing = await db.BondIndexDailyPrice.Where(c => c.TradeDate == day).ToListAsync(ct);
- var existingByKey = existing.ToDictionary(c => c.GroupName);
- var inserted = 0;
- var updated = 0;
- foreach (var row in rows)
- {
- if (existingByKey.TryGetValue(row.GroupName, out var price))
- {
- 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);
- updated++;
- }
- else
- {
- 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);
- await db.BondIndexDailyPrice.AddAsync(created, ct);
- existingByKey[row.GroupName] = created;
- inserted++;
- }
- }
- await db.SaveChangesAsync(ct);
- Logger.LogInformation("[{Job}] basDd={Day} 적재 — rows={Rows}, inserted={Inserted}, updated={Updated}",
- JobName, day, rows.Count, inserted, updated);
- }
- }
|