PaperPosition.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. using System.ComponentModel.DataAnnotations;
  2. using System.ComponentModel.DataAnnotations.Schema;
  3. namespace Domain.Entities.Paper;
  4. /// <summary>
  5. /// 모의투자 보유 포지션 — (AccountID, StockCode) UNIQUE. StockCode 는 FK 없이 denorm 보관 (d0 §2.1).
  6. /// ReservedQuantity 로 이중 매도를 차단한다.
  7. /// </summary>
  8. public class PaperPosition
  9. {
  10. [ForeignKey(nameof(AccountID))]
  11. public virtual PaperAccount Account { get; private set; } = null!;
  12. [Key]
  13. public int ID { get; private set; }
  14. public int AccountID { get; private set; }
  15. /// <summary>단축코드 (char 6)</summary>
  16. public string StockCode { get; private set; } = default!;
  17. /// <summary>보유 수량</summary>
  18. public int Quantity { get; private set; }
  19. /// <summary>매도 주문으로 예약된 수량</summary>
  20. public int ReservedQuantity { get; private set; }
  21. /// <summary>평균 단가 (18,4) — 매수 체결 시 평균단가법 갱신</summary>
  22. public decimal AvgPrice { get; private set; }
  23. public DateTime UpdatedAt { get; private set; } = DateTime.UtcNow;
  24. [Timestamp]
  25. public byte[] RowVersion { get; private set; } = default!;
  26. private PaperPosition() { }
  27. public static PaperPosition Create(int accountID, string stockCode, int quantity, decimal avgPrice)
  28. {
  29. if (accountID <= 0)
  30. {
  31. throw new ArgumentOutOfRangeException(nameof(accountID));
  32. }
  33. if (stockCode is not { Length: 6 })
  34. {
  35. throw new ArgumentException("stockCode must be 6 chars", nameof(stockCode));
  36. }
  37. if (quantity < 0)
  38. {
  39. throw new ArgumentOutOfRangeException(nameof(quantity));
  40. }
  41. return new PaperPosition
  42. {
  43. AccountID = accountID,
  44. StockCode = stockCode,
  45. Quantity = quantity,
  46. ReservedQuantity = 0,
  47. AvgPrice = avgPrice
  48. };
  49. }
  50. /// <summary>매도 주문 접수 시 수량 예약 — 가용 수량(Quantity - ReservedQuantity) 부족 시 실패.</summary>
  51. public void ReserveSell(int quantity)
  52. {
  53. if (quantity <= 0)
  54. {
  55. throw new ArgumentOutOfRangeException(nameof(quantity));
  56. }
  57. if (Quantity - ReservedQuantity < quantity)
  58. {
  59. throw new InvalidOperationException("매도 가능한 수량이 부족합니다.");
  60. }
  61. ReservedQuantity += quantity;
  62. UpdatedAt = DateTime.UtcNow;
  63. }
  64. /// <summary>매도 예약 환원 (주문 취소·거부).</summary>
  65. public void ReleaseSellReserve(int quantity)
  66. {
  67. if (quantity <= 0)
  68. {
  69. throw new ArgumentOutOfRangeException(nameof(quantity));
  70. }
  71. if (ReservedQuantity < quantity)
  72. {
  73. throw new InvalidOperationException("환원할 예약 수량이 부족합니다.");
  74. }
  75. ReservedQuantity -= quantity;
  76. UpdatedAt = DateTime.UtcNow;
  77. }
  78. }