Handler.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using Application.Abstractions.Data;
  2. using Application.Abstractions.Messaging;
  3. using Microsoft.EntityFrameworkCore;
  4. namespace Application.Features.Api.Stocks.GetOptions;
  5. /// <summary>
  6. /// 옵션(일반/주식유가/주식코스닥) 목록 — 상품군·세션(기본 정규)별 지정일(미지정 시 최신 TradeDate) 행을 거래대금 내림차순으로 페이징 (KRX 파생상품 수집, 익명).
  7. /// </summary>
  8. internal sealed class Handler(IAppDbContext db) : IQueryHandler<Query, Response>
  9. {
  10. private const ushort MaxPerPage = 100;
  11. public async Task<Response> Handle(Query request, CancellationToken ct)
  12. {
  13. var page = request.Page < 1 ? 1 : request.Page;
  14. var perPage = request.PerPage is 0 or > MaxPerPage ? (ushort)20 : request.PerPage;
  15. var targetDate = request.Date;
  16. if (targetDate is null)
  17. {
  18. targetDate = await db.OptionsDailyTrade.AsNoTracking()
  19. .Where(c => c.OptionsKind == request.Kind && c.Session == request.Session)
  20. .OrderByDescending(c => c.TradeDate)
  21. .Select(c => (DateOnly?)c.TradeDate)
  22. .FirstOrDefaultAsync(ct);
  23. }
  24. if (targetDate is null)
  25. {
  26. return new Response
  27. {
  28. Total = 0,
  29. TradeDate = null,
  30. List = []
  31. };
  32. }
  33. var query = db.OptionsDailyTrade.AsNoTracking().Where(c => c.OptionsKind == request.Kind && c.TradeDate == targetDate.Value && c.Session == request.Session);
  34. var total = await query.CountAsync(ct);
  35. var list = await query
  36. .OrderByDescending(c => c.TradeValue).ThenBy(c => c.IsuCode)
  37. .Skip((page - 1) * perPage)
  38. .Take(perPage)
  39. .Select(c => new Response.Row
  40. {
  41. Kind = c.OptionsKind,
  42. Session = c.Session,
  43. IsuCode = c.IsuCode,
  44. IsuName = c.IsuName,
  45. RightType = c.RightType,
  46. StrikePrice = c.StrikePrice,
  47. Close = c.Close,
  48. ChangeAmount = c.ChangeAmount,
  49. ImpliedVolatility = c.ImpliedVolatility,
  50. Volume = c.Volume,
  51. TradeValue = c.TradeValue,
  52. OpenInterest = c.OpenInterest,
  53. ProductName = c.ProductName
  54. })
  55. .ToListAsync(ct);
  56. return new Response
  57. {
  58. Total = total,
  59. TradeDate = targetDate.Value,
  60. List = list
  61. };
  62. }
  63. }