using Application.Abstractions.Data;
using Application.Helpers;
using Domain.Entities.Stocks;
using Domain.Entities.Stocks.ValueObject;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SharedKernel;
namespace Infrastructure.StockData;
///
/// 신주인수권증권/증서 일별매매 수집 (KRX OpenAPI) — sw_bydd_trd(증권) + sr_bydd_trd(증서).
/// 기본 18:25 KST 실행(장 마감 15:30 이후 확정, 증권상품 수집 18:20 뒤). 공용 KrxBackfill 로 최근 BackfillYears(기본 3)년치를
/// endDate(직전 영업일)부터 과거로 훑으며 미적재일만 채운다. quota 보호를 위해 1회 실행당 BackfillMaxPerRun(기본 60)일까지만 fetch →
/// 여러 날에 걸쳐 3년치를 메우고 이후엔 최신만 유지한다. 각 날짜는 2개 유형 엔드포인트를 모두 수집해 WarrantDailyTrade upsert
/// (UQ = WarrantType+Code+TradeDate).
/// 증서(sr)는 유상증자 시에만 상장되는 단기 상품이라 대부분의 영업일에 0건이 정상 — 두 엔드포인트 합계로 0 판정하고,
/// existsForDate 도 유형 구분 없이 그날 한 건이라도 있으면 적재됨으로 간주(증서 0건 날의 영구 재수집 방지).
/// ApiKey 미설정 시 로그만 남기고 skip (다른 KRX 배치와 동일 정책).
///
internal sealed class KrxWarrantSyncService(
IServiceScopeFactory scopeFactory,
IHttpClientFactory httpClientFactory,
IOptions settings,
ILogger logger
) : DailyScheduledService(logger)
{
// (유형, 엔드포인트 경로) — 증권(sw)/증서(sr)
private static readonly (WarrantType Type, string Path)[] Endpoints =
[
(WarrantType.SubscriptionWarrant, "/svc/apis/sto/sw_bydd_trd"),
(WarrantType.SubscriptionRight, "/svc/apis/sto/sr_bydd_trd")
];
protected override string JobName => "KrxWarrantSync";
protected override TimeOnly TargetTime => ParseTime(settings.Value.KRXCoKr.WarrantSyncTime, new TimeOnly(18, 25));
protected override int MaxRetryCount => 2;
protected override TimeSpan RetryDelay => TimeSpan.FromHours(2);
protected override async Task 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();
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.WarrantDailyTrade.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);
// fetch 가 0 이어도(이미 최신까지 적재됨) 정상 완료 — 재시도 불필요
return true;
}
/// 한 날짜에 대해 2개 유형 엔드포인트를 모두 수집하고 WarrantDailyTrade upsert.
private async Task FetchAndUpsertAsync(IAppDbContext db, HttpClient client, string baseUrl, string apiKey, DateOnly day, CancellationToken ct)
{
var rows = new List();
foreach (var (type, path) in Endpoints)
{
var url = $"{baseUrl.TrimEnd('/')}{path}?basDd={day:yyyyMMdd}";
var json = await KrxCoKrHttp.GetStringWithRetryAsync(client, url, apiKey, Logger, ct);
var parsed = KrxWarrantParser.ParseDaily(json, type);
Logger.LogInformation("[{Job}] {Type} basDd={Day} rows={Rows}", JobName, type, day, parsed.Count);
rows.AddRange(parsed);
}
if (rows.Count == 0)
{
Logger.LogInformation("[{Job}] basDd={Day} 신주인수권 미반영 (0건)", JobName, day);
return;
}
var existing = await db.WarrantDailyTrade.Where(c => c.TradeDate == day).ToListAsync(ct);
var existingByKey = existing.ToDictionary(c => (c.WarrantType, c.Code));
var inserted = 0;
var updated = 0;
foreach (var row in rows)
{
if (existingByKey.TryGetValue((row.WarrantType, row.Code), out var trade))
{
trade.Update(row.Name, row.Market, row.Close, row.Open, row.High, row.Low, row.ChangeAmount, row.ChangeRate, row.Volume, row.TradeValue, row.MarketCap, row.ListedShares, row.TargetStockCode, row.TargetStockName, row.TargetStockPrice, row.ExercisePrice, row.ExerciseStartDate, row.ExerciseEndDate, row.IssuePrice, row.DelistDate);
updated++;
}
else
{
var created = WarrantDailyTrade.Create(row.WarrantType, row.Code, row.Name, row.Market, row.TradeDate, row.Close, row.Open, row.High, row.Low, row.ChangeAmount, row.ChangeRate, row.Volume, row.TradeValue, row.MarketCap, row.ListedShares, row.TargetStockCode, row.TargetStockName, row.TargetStockPrice, row.ExercisePrice, row.ExerciseStartDate, row.ExerciseEndDate, row.IssuePrice, row.DelistDate);
await db.WarrantDailyTrade.AddAsync(created, ct);
existingByKey[(row.WarrantType, row.Code)] = created;
inserted++;
}
}
await db.SaveChangesAsync(ct);
Logger.LogInformation("[{Job}] basDd={Day} 적재 — rows={Rows}, inserted={Inserted}, updated={Updated}",
JobName, day, rows.Count, inserted, updated);
}
}