Coverage for src/copytrading_engine/execution/domain/orders.py: 95%

164 statements  

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

1"""Validated order terms and records.""" 

2 

3import datetime as dt 

4import hashlib 

5from collections.abc import Mapping 

6from decimal import ROUND_DOWN, Decimal 

7from typing import Literal, Self 

8 

9from pydantic import AwareDatetime, Field, model_validator 

10 

11from copytrading_engine.execution.domain.order_lifecycle import ( 

12 OrderStatus, 

13 is_pending, 

14 is_terminal, 

15 map_broker_status, 

16) 

17from copytrading_engine.execution.domain.sessions import Session 

18from copytrading_engine.execution.domain.values import Identifier, Positive, Quantity, Side, Value 

19from copytrading_engine.shared.symbols import is_crypto 

20 

21 

22class OrderTerms(Value): 

23 side: Side 

24 position_intent: Literal["buy_to_open", "sell_to_close"] 

25 type: Literal["limit", "market", "stop"] 

26 limit_price: Positive | None = None 

27 # A stop sells at the market once the price falls to this (ADR-0015). 

28 stop_price: Positive | None = None 

29 

30 @model_validator(mode="after") 

31 def valid_terms(self) -> Self: 

32 if self.position_intent != ("buy_to_open" if self.side == "buy" else "sell_to_close"): 

33 raise ValueError("Broker position intent does not match the order side") 

34 if (self.type == "limit") != (self.limit_price is not None): 

35 raise ValueError("Only limit orders require a limit price") 

36 if (self.type == "stop") != (self.stop_price is not None): 36 ↛ 37line 36 didn't jump to line 37 because the condition on line 36 was never true

37 raise ValueError("Only stop orders carry a stop price") 

38 if self.type == "market" and self.side != "sell": 

39 raise ValueError("Only exits may use market orders") 

40 if self.type == "stop" and self.side != "sell": 40 ↛ 41line 40 didn't jump to line 41 because the condition on line 40 was never true

41 raise ValueError("Only exits may use stop orders") 

42 return self 

43 

44 

45class OrderRequest(OrderTerms): 

46 symbol: Identifier 

47 qty: Positive 

48 client_order_id: str = Field(min_length=1, max_length=48) 

49 # A stock order lasts the day; Alpaca takes a coin's only as good-till-canceled, so a sell of 

50 # one rests at its floor until it fills (ADR-0014). 

51 time_in_force: Literal["day", "gtc"] 

52 # Never sent for a coin, which has no extended hours. 

53 extended_hours: bool | None 

54 

55 @model_validator(mode="after") 

56 def valid_session(self) -> Self: 

57 crypto = is_crypto(self.symbol) 

58 if crypto != (self.time_in_force == "gtc"): 

59 raise ValueError("A coin's order is good-till-canceled, and only a coin's") 

60 if crypto != (self.extended_hours is None): 

61 raise ValueError("Only a stock's order says whether it trades in extended hours") 

62 if self.type == "market" and self.extended_hours: 

63 raise ValueError("Market orders cannot execute in extended hours") 

64 if self.type == "stop" and (crypto or self.extended_hours): 64 ↛ 66line 64 didn't jump to line 66 because the condition on line 64 was never true

65 # Alpaca takes a stock's stop for the day, in the regular session only (ADR-0015). 

66 raise ValueError("A stop is a stock's, for the regular session") 

67 return self 

68 

69 @classmethod 

70 def for_plan( 

71 cls, plan: OrderPlan, client_order_id: str, *, extended_hours: bool 

72 ) -> OrderRequest: 

73 """The order Alpaca is sent for a plan: a stock's for the day, marked for extended hours 

74 as asked; a coin's good-till-canceled, with no hours at all.""" 

75 crypto = is_crypto(plan.symbol) 

76 return cls( 

77 symbol=plan.symbol, 

78 side=plan.side, 

79 position_intent=plan.position_intent, 

80 qty=plan.qty, 

81 type=plan.type, 

82 limit_price=plan.limit_price, 

83 stop_price=plan.stop_price, 

84 client_order_id=client_order_id, 

85 time_in_force="gtc" if crypto else "day", 

86 extended_hours=None if crypto else extended_hours, 

87 ) 

88 

89 

90_SIZE_TOLERANCE = Decimal("1.02") 

91# Fields a fresh quote recomputes; see OrderPlan.same_order_as. 

92_PRICED = frozenset( 

93 { 

94 "limit_price", 

95 "source_price", 

96 "entry_price", 

97 "qty", 

98 "requested_usd", 

99 "budget_usd", 

100 "limited_by", 

101 } 

102) 

103 

104 

105# Why CopyTrading asked Alpaca to cancel an order: it went unfilled for the account's order 

106# timeout, a sell of the same stock replaced a buy still waiting, or copying stopped. 

107def copy_client_id(message_key: str, part: int, attempt: int = 1) -> str: 

108 """The client order ID of a copied call: one per post and call, so a retried submit can't 

109 place it twice, and `-2`, `-3` after it for a sell sent again after an abort (ADR-0010).""" 

110 base = "copy-" + hashlib.sha256(f"{message_key}:{part}".encode()).hexdigest()[:40] 

111 return base if attempt == 1 else f"{base}-{attempt}" 

112 

113 

114# 

115# A stop order is cancelled to match its shares, as a later copied sell or a newer stop changes 

116# what it protects, or to leave its shares to a sell that needs them (ADR-0015). 

117type CancelReason = Literal[ 

118 "timeout", "replaced_by_sell", "copying_stopped", "stop_resized", "made_room_for_order" 

119] 

120# Statuses that say Alpaca has the order live on the market; an order's timeout runs from the first 

121# of them, not from when it was sent, since Alpaca can hold an order before it goes out. 

122LIVE_AT_BROKER = frozenset( 

123 { 

124 OrderStatus.NEW, 

125 OrderStatus.PARTIALLY_FILLED, 

126 OrderStatus.FILLED, 

127 } 

128) 

129 

130# What cut a buy below what its call asked for (risk.BuyLimit). 

131type BuyLimit = Literal["largest_single_buy", "symbol_exposure_cap", "total_exposure_cap"] 

132 

133 

134class OrderPlan(OrderTerms): 

135 symbol: Identifier 

136 qty: Positive 

137 source_price: Positive 

138 entry_tolerance_pct: Quantity 

139 lot_id: Identifier | None 

140 entry_price: Positive 

141 session: Session 

142 # A buy joins the guru's open lot of the stock (ADR-0010). 

143 joins_lot: Identifier | None = None 

144 # A sell takes from these buys in its lot, or from every buy when empty (ADR-0010). 

145 from_entries: tuple[Identifier, ...] = () 

146 # What the call asked for, what the account's limits allowed of it, and the limit that cut 

147 # it, if one did (ADR-0010). 

148 requested_usd: Positive | None = None 

149 budget_usd: Positive | None = None 

150 limited_by: BuyLimit | None = None 

151 

152 def still_allowed_by(self, fresh: OrderPlan) -> bool: 

153 """The approved order may still go out: the same order, and no larger than what the 

154 account's limits allow now. A price tick moves a buy's size a little, so a size within 

155 2% of today's passes; a real drop, such as buying power falling, does not.""" 

156 return self.same_order_as(fresh) and self.qty <= fresh.qty * _SIZE_TOLERANCE 

157 

158 def same_order_as(self, other: OrderPlan) -> bool: 

159 """The same order apart from prices, which a fresh quote recomputes every time. The 

160 owner approves a plan and that plan is sent; prices that tick meanwhile do not change 

161 which order it is.""" 

162 return self.model_dump(exclude=set(_PRICED)) == other.model_dump(exclude=set(_PRICED)) 

163 

164 @model_validator(mode="after") 

165 def valid_plan(self) -> Self: 

166 if self.side == "sell" and ( 

167 self.joins_lot is not None 

168 or self.requested_usd is not None 

169 or self.budget_usd is not None 

170 or self.limited_by is not None 

171 ): 

172 raise ValueError("Only buys join a lot or carry a requested amount") 

173 if self.side == "buy" and self.from_entries: 

174 raise ValueError("Only sells take from buys") 

175 if self.session == Session.CLOSED: 

176 raise ValueError("Cannot prepare an order in a closed session") 

177 if self.type == "market" and self.session not in { 

178 Session.REGULAR, 

179 Session.AROUND_THE_CLOCK, 

180 }: 

181 raise ValueError("Market exits require a regular session") 

182 if self.type == "stop" and self.session != Session.REGULAR: 182 ↛ 183line 182 didn't jump to line 183 because the condition on line 182 was never true

183 raise ValueError("A stop is placed in the regular session") 

184 if is_crypto(self.symbol) != (self.session == Session.AROUND_THE_CLOCK): 

185 raise ValueError("A coin trades around the clock, and only a coin does") 

186 if (self.side == "sell") != (self.lot_id is not None): 

187 raise ValueError("Only sells must reference an owned lot") 

188 return self 

189 

190 

191class OrderRecord(OrderPlan): 

192 client_id: Identifier 

193 message_id: Identifier 

194 instruction_index: int = Field(ge=0) 

195 source_key: Identifier 

196 status: OrderStatus 

197 filled_qty: Quantity 

198 broker_id: str | None 

199 created_at: AwareDatetime 

200 day: dt.date 

201 raw_broker_status: Identifier | None = None 

202 submit_started_at: AwareDatetime | None = None 

203 filled_avg_price: Positive | None = None 

204 # When Alpaca first reported the order live on the market; its timeout runs from here. 

205 accepted_at: AwareDatetime | None = None 

206 # A coin bought arrives less Alpaca's fee, taken in the coin itself and reported only at the 

207 # day's end: `fee_qty` is the coin the account never received, counted from the broker's 

208 # holding once `fee_settled_qty` of the fill had been booked (ADR-0014). Zero for a stock. 

209 fee_qty: Quantity = Decimal(0) 

210 fee_settled_qty: Quantity = Decimal(0) 

211 # The stop this order is, one of the day orders the stop is placed as (domain/stops.py). 

212 stop_rule: Identifier | None = None 

213 

214 @property 

215 def received_qty(self) -> Decimal: 

216 """What the account holds from this order's fills: a coin's less its fee.""" 

217 return self.filled_qty - self.fee_qty 

218 

219 @property 

220 def unsettled_fee_qty(self) -> Decimal: 

221 """The coin a buy filled since its fee was last counted; a stock's fill, and a sale, pay 

222 no fee in what they receive.""" 

223 if self.side != "buy" or not is_crypto(self.symbol): 

224 return Decimal(0) 

225 return self.filled_qty - self.fee_settled_qty 

226 

227 @model_validator(mode="after") 

228 def valid_fill(self) -> Self: 

229 if (self.type == "stop") != (self.stop_rule is not None): 229 ↛ 230line 229 didn't jump to line 230 because the condition on line 229 was never true

230 raise ValueError("A stop order belongs to its stop, and only a stop order does") 

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

232 raise ValueError("Inconsistent recorded fill quantity") 

233 if self.fee_qty or self.fee_settled_qty: 

234 if self.side != "buy" or not is_crypto(self.symbol): 

235 raise ValueError("Only a coin's buy pays its fee in the coin") 

236 if not self.fee_qty <= self.fee_settled_qty <= self.filled_qty: 

237 raise ValueError("A fee is counted only on what has filled") 

238 if self.status == "aborted_before_submit" and (self.filled_qty or self.broker_id): 

239 raise ValueError("An order aborted before submission cannot have broker activity") 

240 if self.status == OrderStatus.UNRECOGNIZED: 

241 if ( 

242 self.raw_broker_status is None 

243 or map_broker_status(self.raw_broker_status) != self.status 

244 ): 

245 raise ValueError("An unrecognized order status must preserve its broker value") 

246 elif ( 

247 self.raw_broker_status is not None 

248 and map_broker_status(self.raw_broker_status) != self.status 

249 ): 

250 raise ValueError("Raw broker status does not match the internal order status") 

251 return self 

252 

253 @property 

254 def pending(self) -> bool: 

255 return is_pending(self.status) 

256 

257 @property 

258 def terminal(self) -> bool: 

259 return is_terminal(self.status) 

260 

261 

262# Shares are kept to the millionth, as Alpaca trades them. 

263SHARE_STEP = Decimal("0.000001") 

264 

265 

266class OwnedLot(Value): 

267 """Every buy of one stock from one guru, as one position (ADR-0010). The lot keeps each buy's 

268 remaining shares, so a sell can take from the buys at a named price, or from all of them.""" 

269 

270 symbol: Identifier 

271 entry_price: Positive 

272 source_key: Identifier 

273 original_qty: Positive 

274 remaining_qty: Quantity 

275 # What each share still held cost: every buy's remaining shares at that buy's own fill price. 

276 average_price: Positive 

277 # Later buys of the stock from the same guru, in the order they joined. 

278 joined_entries: tuple[Identifier, ...] = () 

279 # What is left of each buy, keyed by its order, oldest first; it adds up to remaining_qty. 

280 entry_remaining: dict[Identifier, Quantity] 

281 # The guru's price for each buy, so a sell naming a price finds its buys. 

282 entry_prices: dict[Identifier, Positive] 

283 

284 def entries(self, key: str) -> tuple[str, ...]: 

285 """Every buy order in this lot: the one that opened it, which keys it, then the rest.""" 

286 return (key, *self.joined_entries) 

287 

288 def entries_at(self, price: Decimal) -> tuple[str, ...]: 

289 """The buys the guru made at exactly this price that still hold shares.""" 

290 return tuple( 

291 entry 

292 for entry, entry_price in self.entry_prices.items() 

293 if entry_price == price and self.entry_remaining.get(entry, Decimal(0)) > 0 

294 ) 

295 

296 def remaining_of(self, entries: tuple[str, ...]) -> Decimal: 

297 return sum((self.entry_remaining[entry] for entry in entries), Decimal(0)) 

298 

299 def priced(self, fills: Mapping[str, Decimal]) -> OwnedLot: 

300 """The lot with its average set from `fills`, each buy's fill price by its order. A buy 

301 that was partly sold weighs only what it has left, so a sale of one buy moves the average 

302 toward the others. A sold-out lot, or one missing a held buy's fill, keeps its average.""" 

303 held = {entry: left for entry, left in self.entry_remaining.items() if left > 0} 

304 if not held or any(entry not in fills for entry in held): 

305 return self 

306 cost = sum((left * fills[entry] for entry, left in held.items()), Decimal(0)) 

307 return self.model_copy(update={"average_price": cost / self.remaining_qty}) 

308 

309 def reduced(self, qty: Decimal, entries: tuple[str, ...] | None = None) -> OwnedLot: 

310 """The lot after selling `qty`, taken from `entries` (all buys when None) in proportion to 

311 what each has left; the rounding remainder comes from the oldest of them. A sale of whole 

312 shares from buys that hold whole shares, as every sale of a stock that trades only in 

313 whole shares is, splits in whole shares, so no buy is left a fraction it can't sell 

314 (ADR-0010).""" 

315 chosen = tuple( 

316 entry 

317 for entry in (entries or tuple(self.entry_remaining)) 

318 if self.entry_remaining.get(entry, Decimal(0)) > 0 

319 ) 

320 available = self.remaining_of(chosen) 

321 if qty > available: 

322 raise ValueError("A sale cannot take more than the buys it sells from hold") 

323 whole = all( 

324 amount == amount.to_integral_value() 

325 for amount in (qty, *(self.entry_remaining[entry] for entry in chosen)) 

326 ) 

327 step = Decimal(1) if whole else SHARE_STEP 

328 taken: dict[str, Decimal] = {} 

329 for entry in chosen: 

330 share = (qty * self.entry_remaining[entry] / available) if available else Decimal(0) 

331 taken[entry] = share.quantize(step, rounding=ROUND_DOWN) 

332 leftover = qty - sum(taken.values(), Decimal(0)) 

333 for entry in chosen: 

334 if leftover <= 0: 

335 break 

336 extra = min(leftover, self.entry_remaining[entry] - taken[entry]) 

337 taken[entry] += extra 

338 leftover -= extra 

339 return OwnedLot.model_validate( 

340 self.model_dump() 

341 | { 

342 "remaining_qty": self.remaining_qty - qty, 

343 "entry_remaining": { 

344 entry: left - taken.get(entry, Decimal(0)) 

345 for entry, left in self.entry_remaining.items() 

346 }, 

347 } 

348 ) 

349 

350 @model_validator(mode="after") 

351 def valid_remaining(self) -> Self: 

352 if self.remaining_qty > self.original_qty: 

353 raise ValueError("Remaining shares exceed the original lot") 

354 if sum(self.entry_remaining.values(), Decimal(0)) != self.remaining_qty: 

355 raise ValueError("A lot's buys must add up to its remaining shares") 

356 if set(self.entry_remaining) != set(self.entry_prices) or len(self.entry_remaining) != ( 

357 1 + len(self.joined_entries) 

358 ): 

359 raise ValueError("Every buy in a lot has its remaining shares and price") 

360 return self