KrxWarrantSyncService.cs 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. using Application.Abstractions.Data;
  2. using Domain.Entities.Stocks;
  3. using Domain.Entities.Stocks.ValueObject;
  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) — sw_bydd_trd(증권) + sr_bydd_trd(증서).
  12. /// 기본 18:25 KST 실행(장 마감 15:30 이후 확정, 증권상품 수집 18:20 뒤), basDd=직전 영업일 2개 엔드포인트 전량 수집 →
  13. /// WarrantDailyTrade upsert (UQ = WarrantType+Code+TradeDate). 미반영(0건)이면 2시간 간격 2회 재시도.
  14. /// 증서(sr)는 유상증자 시에만 상장되는 단기 상품이라 대부분의 영업일에 0건이 정상 — 두 엔드포인트 합계로 0 판정한다.
  15. /// ApiKey 미설정 시 로그만 남기고 skip (다른 KRX 배치와 동일 정책).
  16. /// </summary>
  17. internal sealed class KrxWarrantSyncService(
  18. IServiceScopeFactory scopeFactory,
  19. IHttpClientFactory httpClientFactory,
  20. IOptions<AppSettings> settings,
  21. ILogger<KrxWarrantSyncService> logger
  22. ) : DailyScheduledService(logger)
  23. {
  24. // (유형, 엔드포인트 경로) — 증권(sw)/증서(sr)
  25. private static readonly (WarrantType Type, string Path)[] Endpoints =
  26. [
  27. (WarrantType.SubscriptionWarrant, "/svc/apis/sto/sw_bydd_trd"),
  28. (WarrantType.SubscriptionRight, "/svc/apis/sto/sr_bydd_trd")
  29. ];
  30. protected override string JobName => "KrxWarrantSync";
  31. protected override TimeOnly TargetTime => ParseTime(settings.Value.KRXCoKr.WarrantSyncTime, new TimeOnly(18, 25));
  32. protected override int MaxRetryCount => 2;
  33. protected override TimeSpan RetryDelay => TimeSpan.FromHours(2);
  34. protected override async Task<bool> RunOnceAsync(DateOnly todayKst, CancellationToken ct)
  35. {
  36. var cfg = settings.Value.KRXCoKr;
  37. if (string.IsNullOrWhiteSpace(cfg.ApiKey))
  38. {
  39. Logger.LogWarning("[{Job}] KRXCoKr:ApiKey 미설정 — 수집 skip", JobName);
  40. return true;
  41. }
  42. using var scope = scopeFactory.CreateScope();
  43. var db = scope.ServiceProvider.GetRequiredService<IAppDbContext>();
  44. var client = httpClientFactory.CreateClient(KrxCoKrHttp.ClientName);
  45. var targetDate = await MarketCalendar.GetPreviousBusinessDayAsync(db, todayKst.AddDays(1), ct);
  46. var rows = new List<KrxWarrantParser.WarrantRow>();
  47. foreach (var (type, path) in Endpoints)
  48. {
  49. var url = $"{cfg.BaseUrl.TrimEnd('/')}{path}?basDd={targetDate:yyyyMMdd}";
  50. var json = await KrxCoKrHttp.GetStringWithRetryAsync(client, url, cfg.ApiKey, Logger, ct);
  51. var parsed = KrxWarrantParser.ParseDaily(json, type);
  52. Logger.LogInformation("[{Job}] {Type} basDd={TargetDate} rows={Rows}", JobName, type, targetDate, parsed.Count);
  53. rows.AddRange(parsed);
  54. }
  55. if (rows.Count == 0)
  56. {
  57. Logger.LogInformation("[{Job}] basDd={TargetDate} 신주인수권 미반영 (0건)", JobName, targetDate);
  58. return false;
  59. }
  60. var existing = await db.WarrantDailyTrade.Where(c => c.TradeDate == targetDate).ToListAsync(ct);
  61. var existingByKey = existing.ToDictionary(c => (c.WarrantType, c.Code));
  62. var inserted = 0;
  63. var updated = 0;
  64. foreach (var row in rows)
  65. {
  66. if (existingByKey.TryGetValue((row.WarrantType, row.Code), out var trade))
  67. {
  68. 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);
  69. updated++;
  70. }
  71. else
  72. {
  73. 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);
  74. await db.WarrantDailyTrade.AddAsync(created, ct);
  75. existingByKey[(row.WarrantType, row.Code)] = created;
  76. inserted++;
  77. }
  78. }
  79. await db.SaveChangesAsync(ct);
  80. Logger.LogInformation("[{Job}] 완료 — basDd={TargetDate}, rows={Rows}, inserted={Inserted}, updated={Updated}",
  81. JobName, targetDate, rows.Count, inserted, updated);
  82. return true;
  83. }
  84. }