Coverage for src/copytrading_engine/execution/domain/market.py: 100%

58 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-16 16:55 +0000

1import datetime as dt 

2from typing import Annotated, ClassVar, Literal, Self 

3 

4from pydantic import AwareDatetime, Field, model_validator 

5 

6from copytrading_engine.execution.domain.values import ( 

7 BrokerAccountId, 

8 Identifier, 

9 Money, 

10 Positive, 

11 Quantity, 

12 Side, 

13 Value, 

14) 

15 

16 

17class Account(Value): 

18 id: BrokerAccountId 

19 status: Identifier 

20 cash: Money 

21 buying_power: Money 

22 equity: Money 

23 last_equity: Money 

24 trading_blocked: bool 

25 account_blocked: bool 

26 trade_suspended_by_user: bool 

27 currency: str 

28 

29 @property 

30 def active(self) -> bool: 

31 return self.status == "ACTIVE" and not ( 

32 self.trading_blocked or self.account_blocked or self.trade_suspended_by_user 

33 ) 

34 

35 def standing(self) -> dict[str, object]: 

36 """Whether and how this account may trade. Balances move with every tick, so a review 

37 that compares accounts must not include them.""" 

38 return self.model_dump( 

39 mode="json", exclude={"cash", "buying_power", "equity", "last_equity"} 

40 ) 

41 

42 

43class Asset(Value): 

44 symbol: Identifier 

45 asset_class: str 

46 status: str 

47 tradable: bool 

48 fractionable: bool 

49 attributes: tuple[str, ...] = () 

50 overnight_tradable: bool = False 

51 overnight_halted: bool = False 

52 # A coin's trading steps, which Alpaca gives only for crypto: the smallest order in coins, the 

53 # step a quantity moves in, and the step a price moves in. 

54 min_order_size: Positive | None = None 

55 min_trade_increment: Positive | None = None 

56 price_increment: Positive | None = None 

57 

58 @property 

59 def crypto(self) -> bool: 

60 return self.asset_class == "crypto" 

61 

62 

63class Position(Value): 

64 """A broker position: what is held, and the broker's own valuation of it.""" 

65 

66 symbol: Identifier 

67 qty: Money 

68 market_value: Money | None = None 

69 currency: str | None = None 

70 asset_class: str | None = None 

71 avg_entry_price: Money | None = None 

72 current_price: Money | None = None 

73 unrealized_pl: Money | None = None 

74 unrealized_plpc: Money | None = None 

75 

76 #: The broker's valuation, which moves with every tick and every outside fill. 

77 VALUATION: ClassVar[frozenset[str]] = frozenset( 

78 {"market_value", "avg_entry_price", "current_price", "unrealized_pl", "unrealized_plpc"} 

79 ) 

80 

81 def holding(self) -> dict[str, object]: 

82 """What is held, without its valuation.""" 

83 return self.model_dump(mode="json", exclude=set(self.VALUATION)) 

84 

85 

86class CalendarDay(Value): 

87 date: dt.date 

88 open: dt.time 

89 close: dt.time 

90 session_open: dt.time = dt.time(4) 

91 session_close: dt.time | None = None 

92 

93 

94class BrokerOrder(Value): 

95 id: Identifier 

96 client_order_id: Identifier 

97 symbol: Identifier 

98 side: Side 

99 qty: Positive 

100 filled_qty: Quantity 

101 filled_avg_price: Positive | None 

102 status: Identifier 

103 position_intent: Literal["buy_to_open", "sell_to_close"] | None = None 

104 

105 @model_validator(mode="after") 

106 def consistent_fill(self) -> Self: 

107 if self.filled_qty > self.qty or (self.status == "filled" and self.filled_qty != self.qty): 

108 raise ValueError("Inconsistent broker fill quantity") 

109 if self.filled_qty > 0 and self.filled_avg_price is None: 

110 raise ValueError("A fill requires its average price") 

111 return self 

112 

113 

114# Stock feeds by the hour (adapters.alpaca.broker.quote_feeds), and Alpaca's crypto feed. 

115type QuoteFeed = Literal["iex", "delayed_sip", "overnight", "crypto"] 

116 

117 

118class Quote(Value): 

119 feed: QuoteFeed 

120 bid: Quantity | None 

121 ask: Quantity | None 

122 timestamp: AwareDatetime | None 

123 

124 

125class Bar(Value): 

126 """One five-minute bar of a symbol's session: what it opened at and closed at.""" 

127 

128 at: AwareDatetime 

129 open: Quantity 

130 close: Quantity 

131 

132 

133class DailyBar(Value): 

134 """One trading day of a symbol: its open, high, low and close, and the shares traded.""" 

135 

136 at: AwareDatetime 

137 open: Quantity 

138 high: Quantity 

139 low: Quantity 

140 close: Quantity 

141 volume: Annotated[int, Field(ge=0)] 

142 

143 

144type DailyRange = Literal["month", "six_months", "year"] 

145 

146 

147class EquityPoint(Value): 

148 at: AwareDatetime 

149 equity: Money 

150 

151 

152type HistoryRange = Literal["day", "week", "month", "three_months", "year"] 

153 

154 

155class HistoryWindow(Value): 

156 """A stretch of the broker's equity curve: a range ending now, or one chosen trading day.""" 

157 

158 range: HistoryRange 

159 day: dt.date | None = None 

160 

161 @model_validator(mode="after") 

162 def day_names_only_a_day(self) -> Self: 

163 if self.day is not None and self.range != "day": 

164 raise ValueError("Only the day range names a date") 

165 return self 

166 

167 

168class EquityHistory(Value): 

169 """The broker's equity curve for one window, oldest point first.""" 

170 

171 window: HistoryWindow 

172 base_value: Money | None 

173 points: tuple[EquityPoint, ...]