Coverage for src/copytrading_engine/execution/application/lot_sales.py: 78%

149 statements  

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

1"""Preview and explicitly confirm the owner's sale of one copied lot.""" 

2 

3import datetime as dt 

4import hashlib 

5import logging 

6from collections.abc import Callable 

7from decimal import Decimal 

8from typing import Literal 

9 

10from copytrading_engine.execution.application.engine import CopyEngine 

11from copytrading_engine.execution.application.manual_commands import ( 

12 facts_digest, 

13 owner_order_reason, 

14 owner_order_status, 

15) 

16from copytrading_engine.execution.application.ports import BrokerError, QuoteBroker 

17from copytrading_engine.execution.domain.ledger_state import LedgerSnapshot 

18from copytrading_engine.execution.domain.lot_sales import ( 

19 LotSaleConfirmation, 

20 LotSalePreview, 

21 LotSalePreviewRequest, 

22 LotSaleRecord, 

23 LotSaleResult, 

24) 

25from copytrading_engine.execution.domain.manual_commands import ManualCheck 

26from copytrading_engine.execution.domain.market import Quote 

27from copytrading_engine.execution.domain.pricing import ( 

28 SELL_FLOOR_QUOTE_MAX_AGE_SECONDS, 

29 quote_problem, 

30) 

31from copytrading_engine.execution.domain.values import BrokerAccountNumber 

32from copytrading_engine.shared.signals import Instruction 

33 

34LOT_SALE_PREVIEW_TTL_SECONDS = 30 

35log = logging.getLogger(__name__) 

36 

37 

38class LotSaleApplication: 

39 """Account-local lot sales; every state change goes through TradingLedger. 

40 

41 A sale plans through the same decision as a copied exit, so it gets the same session, 

42 asset, position, and open-order checks, and it submits through the same guarded path. 

43 """ 

44 

45 def __init__( 

46 self, 

47 engine: CopyEngine, 

48 *, 

49 local_account_id: str, 

50 broker_account_id: BrokerAccountNumber, 

51 environment: Literal["paper", "live"], 

52 halted: Callable[[], bool], 

53 entry_block_reason: Callable[[], str | None], 

54 recovery_ready: Callable[[], bool], 

55 stopping: Callable[[], bool], 

56 ) -> None: 

57 self.engine = engine 

58 self.local_account_id = local_account_id 

59 self.broker_account_id = broker_account_id 

60 self.environment = environment 

61 self.halted = halted 

62 self.entry_block_reason = entry_block_reason 

63 self.recovery_ready = recovery_ready 

64 self.stopping = stopping 

65 

66 def preview(self, request: LotSalePreviewRequest, now: dt.datetime) -> LotSalePreview: 

67 existing = self.engine.ledger.state.lot_sale_previews.get(request.preview_id) 

68 if existing is not None: 68 ↛ 69line 68 didn't jump to line 69 because the condition on line 68 was never true

69 if existing.request != request: 

70 raise ValueError("Lot sale preview identity conflicts with another request") 

71 return existing.model_copy(deep=True) 

72 return self.engine.ledger.save_lot_sale_preview(self._evaluate(request, now)) 

73 

74 def confirm(self, request: LotSaleConfirmation, now: dt.datetime) -> LotSaleResult: 

75 snapshot = self.engine.ledger.state 

76 previous = snapshot.lot_sales.get(request.command_id) 

77 if previous is not None: 

78 if previous.request != request: 78 ↛ 79line 78 didn't jump to line 79 because the condition on line 78 was never true

79 raise ValueError("Lot sale identity conflicts with different content") 

80 self.engine.reconcile(now) 

81 return self.result(request.command_id) 

82 preview = snapshot.lot_sale_previews.get(request.preview_id) 

83 if preview is None or preview.request.account_id != request.account_id: 83 ↛ 84line 83 didn't jump to line 84 because the condition on line 83 was never true

84 raise ValueError("Lot sale preview is unavailable") 

85 

86 # Read prior broker outcomes before a second action; never resubmit a known intent. 

87 self.engine.reconcile(now) 

88 current = self._evaluate(preview.request, now) 

89 reason = self._confirmation_block(preview, current, now) 

90 if reason is not None: 

91 self.engine.ledger.reject_lot_sale( 

92 LotSaleRecord( 

93 request=request, 

94 lot_id=preview.request.lot_id, 

95 confirmed_at=now, 

96 state="rejected", 

97 reason=reason, 

98 ) 

99 ) 

100 return self.result(request.command_id) 

101 

102 assert preview.plan is not None 

103 client_id = "lotsale-" + hashlib.sha256(request.command_id.encode()).hexdigest()[:40] 

104 _, order = self.engine.ledger.prepare_lot_sale( 

105 LotSaleRecord( 

106 request=request, 

107 lot_id=preview.request.lot_id, 

108 confirmed_at=now, 

109 state="prepared", 

110 client_id=client_id, 

111 ), 

112 preview.plan, 

113 ) 

114 self.engine.submit_manual_prepared( 

115 order, 

116 now, 

117 halted=self.halted, 

118 entry_block_reason=self.entry_block_reason, 

119 stopping=self.stopping, 

120 ) 

121 return self.result(request.command_id) 

122 

123 def result(self, command_id: str) -> LotSaleResult: 

124 return lot_sale_result_from_snapshot(self.engine.ledger.snapshot(), command_id) 

125 

126 def _confirmation_block( 

127 self, saved: LotSalePreview, fresh: LotSalePreview, now: dt.datetime 

128 ) -> str | None: 

129 if saved.expires_at <= now: 

130 return "preview_expired" 

131 if saved.request.account_id != self.local_account_id: 131 ↛ 132line 131 didn't jump to line 132 because the condition on line 131 was never true

132 return "account_changed" 

133 if saved.facts_sha256 != fresh.facts_sha256: 

134 return "account_facts_changed" 

135 if ( 135 ↛ 141line 135 didn't jump to line 141 because the condition on line 135 was never true

136 fresh.reasons 

137 or saved.plan is None 

138 or fresh.plan is None 

139 or not saved.plan.still_allowed_by(fresh.plan) 

140 ): 

141 return fresh.reasons[0] if fresh.reasons else "plan_changed" 

142 return None 

143 

144 def _evaluate(self, request: LotSalePreviewRequest, now: dt.datetime) -> LotSalePreview: 

145 snapshot = self.engine.ledger.state 

146 if request.account_id != self.local_account_id: 146 ↛ 147line 146 didn't jump to line 147 because the condition on line 146 was never true

147 raise ValueError("Lot sale account identity mismatch") 

148 if ( 148 ↛ 152line 148 didn't jump to line 152 because the condition on line 148 was never true

149 snapshot.account_id != self.broker_account_id 

150 or snapshot.environment != self.environment 

151 ): 

152 raise ValueError("Lot sale broker identity mismatch") 

153 lot = snapshot.lots.get(request.lot_id) 

154 buy = snapshot.orders.get(request.lot_id) 

155 if lot is None or buy is None or lot.remaining_qty <= 0: 

156 raise ValueError("Lot is unavailable") 

157 

158 checks: list[ManualCheck] = [] 

159 reasons: list[str] = [] 

160 account = self.engine.broker.account() 

161 if account.id != self.broker_account_id or not account.active: 161 ↛ 162line 161 didn't jump to line 162 because the condition on line 161 was never true

162 reasons.append("account_unavailable") 

163 checks.append( 

164 ManualCheck(name="account", status="blocked", reason="account_unavailable") 

165 ) 

166 else: 

167 checks.append(ManualCheck(name="account", status="passed")) 

168 

169 if self.recovery_ready(): 

170 checks.append(ManualCheck(name="permission", status="passed")) 

171 else: 

172 reasons.append("recovery_pending") 

173 checks.append( 

174 ManualCheck(name="permission", status="blocked", reason="recovery_pending") 

175 ) 

176 

177 if any( 177 ↛ 183line 177 didn't jump to line 183 because the condition on line 177 was never true

178 sale.lot_id == request.lot_id 

179 and sale.client_id is not None 

180 and self.engine.ledger.order(sale.client_id).pending 

181 for sale in snapshot.lot_sales.values() 

182 ): 

183 reasons.append("related_manual_action") 

184 checks.append( 

185 ManualCheck(name="prior_action", status="blocked", reason="related_manual_action") 

186 ) 

187 else: 

188 checks.append(ManualCheck(name="prior_action", status="passed")) 

189 

190 quote: Quote | None = None 

191 bid: Decimal | None = None 

192 quote_reason: str | None = None 

193 old_bid: str | None = None 

194 broker = self.engine.broker 

195 if not isinstance(broker, QuoteBroker): 195 ↛ 196line 195 didn't jump to line 196 because the condition on line 195 was never true

196 quote_reason = "quote_unavailable" 

197 else: 

198 try: 

199 quote = broker.quote(lot.symbol) 

200 bid = quote.bid 

201 # The bid only sets the sale's floor, so one up to six hours old will do, as for a 

202 # copied sell at the market (ADR-0007); a sale off an old one is only warned about. 

203 quote_reason = quote_problem(quote, bid, now, SELL_FLOOR_QUOTE_MAX_AGE_SECONDS) 

204 old_bid = quote_problem(quote, bid, now) 

205 except BrokerError: 

206 quote_reason = "quote_unavailable" 

207 except Exception as exc: # noqa: BLE001 - unexpected preview failures become a reason 

208 _report_unexpected_preview_failure("quote", exc) 

209 quote_reason = "preview_unavailable" 

210 if quote_reason is not None: 

211 quote, bid = (quote, bid) if bid is not None and bid > 0 else (None, None) 

212 reasons.append(quote_reason) 

213 checks.append(ManualCheck(name="quote", status="blocked", reason=quote_reason)) 

214 elif old_bid is not None: 

215 checks.append(ManualCheck(name="quote", status="warning", reason=old_bid)) 

216 else: 

217 checks.append(ManualCheck(name="quote", status="passed")) 

218 

219 decision = None 

220 decision_failure: str | None = None 

221 if bid is not None and bid > 0: 221 ↛ 245line 221 didn't jump to line 245 because the condition on line 221 was always true

222 instruction = Instruction( 

223 action="close", 

224 symbol=lot.symbol, 

225 price=bid, 

226 entry_price=lot.entry_price, 

227 fraction=Decimal(1), 

228 ) 

229 try: 

230 decision = self.engine.decide( 

231 instruction, 

232 buy.message_id, 

233 lot.source_key, 

234 now, 

235 halted=self.halted(), 

236 manual=True, 

237 chosen_lot=request.lot_id, 

238 chosen_qty=request.qty, 

239 ) 

240 except BrokerError: 

241 decision_failure = "market_facts_unavailable" 

242 except Exception as exc: # noqa: BLE001 - unexpected preview failures become a reason 

243 _report_unexpected_preview_failure("decision", exc) 

244 decision_failure = "preview_unavailable" 

245 if decision_failure is not None: 245 ↛ 246line 245 didn't jump to line 246 because the condition on line 245 was never true

246 reasons.append(decision_failure) 

247 elif decision is not None and decision.plan is None: 247 ↛ 248line 247 didn't jump to line 248 because the condition on line 247 was never true

248 reasons.append(decision.reason) 

249 ready = decision is not None and decision.plan is not None 

250 checks.append( 

251 ManualCheck( 

252 name="risk", 

253 status="passed" if ready else "blocked", 

254 reason=None 

255 if ready 

256 else ( 

257 decision.reason if decision is not None else decision_failure or quote_reason 

258 ), 

259 ) 

260 ) 

261 

262 plan = decision.plan if decision is not None and not reasons else None 

263 session = decision.plan.session if decision is not None and decision.plan else None 

264 facts = { 

265 "account": account.standing(), 

266 "positions": [item.holding() for item in broker.positions()], 

267 "open_orders": [item.model_dump(mode="json") for item in broker.open_orders()], 

268 "lot": lot.model_dump(mode="json"), 

269 "pending": [item.model_dump(mode="json") for item in self.engine.pending()], 

270 "control": snapshot.control.model_dump(mode="json"), 

271 "external_positions": { 

272 key: item.model_dump(mode="json") 

273 for key, item in snapshot.external_positions.items() 

274 }, 

275 "ownership_incidents": sorted( 

276 key for key, item in snapshot.ownership_incidents.items() if not item.resolved 

277 ), 

278 "late_order_incidents": sorted( 

279 key for key, item in snapshot.late_order_incidents.items() if item.unresolved 

280 ), 

281 "session": session.value if session is not None else None, 

282 "reasons": sorted(set(reasons)), 

283 } 

284 return LotSalePreview( 

285 request=request, 

286 broker_account_id=self.broker_account_id, 

287 environment=self.environment, 

288 symbol=lot.symbol, 

289 lot_remaining_qty=lot.remaining_qty, 

290 created_at=now, 

291 expires_at=now + dt.timedelta(seconds=LOT_SALE_PREVIEW_TTL_SECONDS), 

292 session=session, 

293 quote=quote, 

294 fresh_price=bid, 

295 plan=plan, 

296 checks=tuple(checks), 

297 reasons=tuple(sorted(set(reasons))), 

298 facts_sha256=facts_digest(facts), 

299 ) 

300 

301 

302def lot_sale_result_from_snapshot(snapshot: LedgerSnapshot, command_id: str) -> LotSaleResult: 

303 """Project one durable lot sale and its latest order evidence into the read contract.""" 

304 sale = snapshot.lot_sales[command_id] 

305 if sale.state == "rejected": 

306 return LotSaleResult(sale=sale, status="rejected", reason=sale.reason) 

307 assert sale.client_id is not None 

308 order = snapshot.orders[sale.client_id] 

309 status = owner_order_status(order) 

310 return LotSaleResult( 

311 sale=sale, 

312 status=status, 

313 reason=owner_order_reason(status), 

314 client_id=order.client_id, 

315 broker_order_id=order.broker_id, 

316 order_status=order.status, 

317 filled_qty=order.filled_qty, 

318 filled_avg_price=order.filled_avg_price, 

319 ) 

320 

321 

322def _report_unexpected_preview_failure(stage: str, error: Exception) -> None: 

323 """Log only static context and the exception type; never expose its text.""" 

324 log.error( 

325 "Unexpected lot sale preview failure (stage=%s, error_type=%s)", 

326 stage, 

327 type(error).__name__, 

328 )