Handler.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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)
  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);
  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. IsuCode = c.IsuCode,
  43. IsuName = c.IsuName,
  44. RightType = c.RightType,
  45. StrikePrice = c.StrikePrice,
  46. Close = c.Close,
  47. ChangeAmount = c.ChangeAmount,
  48. ImpliedVolatility = c.ImpliedVolatility,
  49. Volume = c.Volume,
  50. TradeValue = c.TradeValue,
  51. OpenInterest = c.OpenInterest,
  52. ProductName = c.ProductName
  53. })
  54. .ToListAsync(ct);
  55. return new Response
  56. {
  57. Total = total,
  58. TradeDate = targetDate.Value,
  59. List = list
  60. };
  61. }
  62. }