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

118 statements  

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

1"""Typed immutable journal events committed by the execution ledger.""" 

2 

3from typing import Annotated, Literal 

4 

5from pydantic import AwareDatetime, ConfigDict, Field 

6 

7from copytrading_engine.execution.domain.ledger_state import CashAnchor, MessageStatus 

8from copytrading_engine.execution.domain.lifecycle import AccountControlResult 

9from copytrading_engine.execution.domain.lot_sales import LotSalePreview, LotSaleRecord 

10from copytrading_engine.execution.domain.manual_commands import ( 

11 ManualCommandRecord, 

12 ManualCorrectionRecord, 

13 ManualOrderPreview, 

14) 

15from copytrading_engine.execution.domain.market import Quote 

16from copytrading_engine.execution.domain.order_lifecycle import OrderStatus 

17from copytrading_engine.execution.domain.orders import CancelReason, OrderPlan 

18from copytrading_engine.execution.domain.ownership import ( 

19 ExternalPosition, 

20 OwnershipIncident, 

21 OwnershipResolution, 

22) 

23from copytrading_engine.execution.domain.progress import Exposure, SellWait 

24from copytrading_engine.execution.domain.recovery import ( 

25 IncidentClearanceEvidence, 

26 LateOrderIncident, 

27 ManualSale, 

28 ReleaseEvidence, 

29) 

30from copytrading_engine.execution.domain.sessions import Session 

31from copytrading_engine.execution.domain.sizing import DestinationTerms 

32from copytrading_engine.execution.domain.stops import StopRule 

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

34from copytrading_engine.shared.signals import Instruction, StopCall 

35 

36 

37class EventPayloadValue(Value): 

38 """Keep constructor defaults while requiring them in serialized JSON Schema.""" 

39 

40 model_config = ConfigDict(json_schema_serialization_defaults_required=True) 

41 

42 

43class AccountBound(EventPayloadValue): 

44 kind: Literal["account_bound"] = "account_bound" 

45 endpoint: Identifier 

46 

47 

48class AccountInventoried(EventPayloadValue): 

49 kind: Literal["account_inventoried"] = "account_inventoried" 

50 account_id: Identifier 

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

52 external_positions: dict[str, ExternalPosition] 

53 

54 

55class AccountControlChanged(EventPayloadValue): 

56 kind: Literal["account_control_changed"] = "account_control_changed" 

57 result: AccountControlResult 

58 

59 

60class LimitChange(Value): 

61 """One account limit the owner changed while copying: its policy name, before and after.""" 

62 

63 setting: Identifier 

64 before: str 

65 after: str 

66 

67 

68class LimitsChanged(EventPayloadValue): 

69 kind: Literal["limits_changed"] = "limits_changed" 

70 changes: tuple[LimitChange, ...] = Field(min_length=1) 

71 

72 

73class OwnershipIncidentOpened(EventPayloadValue): 

74 kind: Literal["ownership_incident_opened"] = "ownership_incident_opened" 

75 incident: OwnershipIncident 

76 

77 

78class OwnershipResolved(EventPayloadValue): 

79 kind: Literal["ownership_resolved"] = "ownership_resolved" 

80 resolution: OwnershipResolution 

81 

82 

83class SignalRejected(EventPayloadValue): 

84 kind: Literal["signal_rejected"] = "signal_rejected" 

85 payload_hash: str = Field(pattern=r"^[0-9a-f]{64}$") 

86 reason: Identifier 

87 

88 

89class Message(EventPayloadValue): 

90 kind: Literal["message"] = "message" 

91 message_id: Identifier 

92 status: MessageStatus 

93 parser_decision: Literal["trade", "ignore", "review"] 

94 parser_reason: Identifier 

95 parser_profile: str 

96 instructions: tuple[Instruction, ...] 

97 destination: DestinationTerms 

98 stops: tuple[StopCall, ...] = () 

99 

100 

101class CashAnchorRecorded(EventPayloadValue): 

102 kind: Literal["cash_anchor_recorded"] = "cash_anchor_recorded" 

103 anchor: CashAnchor 

104 

105 

106class Skipped(EventPayloadValue): 

107 kind: Literal["skipped"] = "skipped" 

108 message_id: Identifier 

109 part: int = Field(ge=0) 

110 reason: Identifier 

111 exposure: tuple[Exposure, ...] | None 

112 bought_at: AwareDatetime | None = None 

113 # The part is a stop of the post, not one of its instructions. 

114 stop: bool = False 

115 

116 

117class StopSet(EventPayloadValue): 

118 """The account follows a stop the guru posted: its price and the buys it protects.""" 

119 

120 kind: Literal["stop_set"] = "stop_set" 

121 message_id: Identifier 

122 rule: StopRule 

123 # Stops this one replaced, for the same buys. 

124 replaced: tuple[Identifier, ...] = () 

125 

126 

127class StopEnded(EventPayloadValue): 

128 """The account no longer follows a stop: nothing is left of its buys, or a newer stop took 

129 them all.""" 

130 

131 kind: Literal["stop_ended"] = "stop_ended" 

132 message_id: Identifier 

133 rule_key: Identifier 

134 reason: Literal["nothing_left", "replaced"] 

135 

136 

137class SellWaiting(EventPayloadValue): 

138 """A sell that has no price to sell at yet: it waits, and asks again later.""" 

139 

140 kind: Literal["sell_waiting"] = "sell_waiting" 

141 message_id: Identifier 

142 part: int = Field(ge=0) 

143 reason: SellWait 

144 

145 

146class CryptoFeeCounted(EventPayloadValue): 

147 """Alpaca's fee on a coin's buys, counted from the coin it holds: the coin the account never 

148 received comes out of the buys' lot (ADR-0014).""" 

149 

150 kind: Literal["crypto_fee_counted"] = "crypto_fee_counted" 

151 symbol: Identifier 

152 # Each buy's fee, by its order, for the fill counted now. 

153 fees: dict[Identifier, Quantity] 

154 # The coin those buys filled since their fee was last counted. 

155 filled_qty: Positive 

156 

157 

158class ReadBackSummary(EventPayloadValue): 

159 """What came of the posts read back after CopyTrading was off, told to the owner once.""" 

160 

161 kind: Literal["read_back_summary"] = "read_back_summary" 

162 posts: int = Field(ge=1) 

163 sells_copied: int = Field(ge=0) 

164 buys_too_old: int = Field(ge=0) 

165 

166 

167class MessageDone(EventPayloadValue): 

168 kind: Literal["message_done"] = "message_done" 

169 message_id: Identifier 

170 

171 

172class OrderPrepared(EventPayloadValue): 

173 kind: Literal["order_prepared"] = "order_prepared" 

174 client_id: Identifier 

175 message_id: Identifier 

176 symbol: Identifier 

177 side: Side 

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

179 source_price: Positive 

180 entry_price: Positive 

181 qty: Positive 

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

183 limit_price: Positive | None 

184 entry_tolerance_pct: Quantity 

185 session: Session 

186 stop_price: Positive | None = None 

187 

188 

189class SubmitStarted(EventPayloadValue): 

190 kind: Literal["submit_started"] = "submit_started" 

191 client_id: Identifier 

192 message_id: Identifier 

193 submit_started_at: AwareDatetime 

194 

195 

196class SubmissionAborted(EventPayloadValue): 

197 kind: Literal["submission_aborted"] = "submission_aborted" 

198 client_id: Identifier 

199 message_id: Identifier 

200 reason: Identifier 

201 

202 

203class SendAborted(EventPayloadValue): 

204 """A copied sell stopped before it reached Alpaca (CopyTrading stopping, or the session 

205 changing): its call waits again, and its next attempt goes out under a new client ID.""" 

206 

207 kind: Literal["send_aborted"] = "send_aborted" 

208 client_id: Identifier 

209 message_id: Identifier 

210 part: int = Field(ge=0) 

211 reason: Identifier 

212 

213 

214class SubmissionUncertain(EventPayloadValue): 

215 kind: Literal["submission_uncertain"] = "submission_uncertain" 

216 client_id: Identifier 

217 message_id: Identifier 

218 

219 

220class BrokerAcknowledged(EventPayloadValue): 

221 kind: Literal["broker_acknowledged"] = "broker_acknowledged" 

222 client_id: Identifier 

223 message_id: Identifier 

224 

225 

226class CancelRequested(EventPayloadValue): 

227 kind: Literal["cancel_requested"] = "cancel_requested" 

228 client_id: Identifier 

229 message_id: Identifier 

230 # None for orders cancelled before the reason was recorded. 

231 reason: CancelReason | None = None 

232 

233 

234class QuoteUnavailable(EventPayloadValue): 

235 kind: Literal["quote_unavailable"] = "quote_unavailable" 

236 client_id: Identifier 

237 message_id: Identifier 

238 

239 

240class SubmitError(EventPayloadValue): 

241 kind: Literal["submit_error"] = "submit_error" 

242 client_id: Identifier 

243 message_id: Identifier 

244 status: OrderStatus 

245 http_status: int | None 

246 # Alpaca's own words for a refusal; absent in events recorded before it was kept. 

247 reason: str | None = None 

248 

249 

250class SubmissionQuote(EventPayloadValue): 

251 kind: Literal["submission_quote"] = "submission_quote" 

252 client_id: Identifier 

253 message_id: Identifier 

254 quote: Quote 

255 

256 

257class ManualSaleRecorded(EventPayloadValue): 

258 kind: Literal["manual_sale_recorded"] = "manual_sale_recorded" 

259 sale: ManualSale 

260 previous_remaining_qty: Quantity | None = None 

261 remaining_qty: Quantity | None = None 

262 ownership_incident: OwnershipIncident | None = None 

263 

264 

265class ManualCorrectionRecorded(EventPayloadValue): 

266 kind: Literal["manual_correction_recorded"] = "manual_correction_recorded" 

267 correction: ManualCorrectionRecord 

268 

269 

270class ManualOrderPreviewed(EventPayloadValue): 

271 kind: Literal["manual_order_previewed"] = "manual_order_previewed" 

272 preview: ManualOrderPreview 

273 

274 

275class ManualCommandRejected(EventPayloadValue): 

276 kind: Literal["manual_command_rejected"] = "manual_command_rejected" 

277 command: ManualCommandRecord 

278 

279 

280class ManualCommandPrepared(EventPayloadValue): 

281 kind: Literal["manual_command_prepared"] = "manual_command_prepared" 

282 command: ManualCommandRecord 

283 plan: OrderPlan 

284 

285 

286class LotSalePreviewed(EventPayloadValue): 

287 kind: Literal["lot_sale_previewed"] = "lot_sale_previewed" 

288 preview: LotSalePreview 

289 

290 

291class LotSaleRejected(EventPayloadValue): 

292 kind: Literal["lot_sale_rejected"] = "lot_sale_rejected" 

293 sale: LotSaleRecord 

294 

295 

296class LotSalePrepared(EventPayloadValue): 

297 kind: Literal["lot_sale_prepared"] = "lot_sale_prepared" 

298 sale: LotSaleRecord 

299 plan: OrderPlan 

300 

301 

302class OrderIntentReleased(EventPayloadValue): 

303 kind: Literal["order_intent_released"] = "order_intent_released" 

304 client_id: Identifier 

305 message_id: Identifier 

306 previous_status: Literal["uncertain"] 

307 status: Literal["released_unsubmitted"] 

308 evidence: ReleaseEvidence 

309 entry_halted: bool 

310 

311 

312class LateOrderIncidentCleared(EventPayloadValue): 

313 kind: Literal["late_order_incident_cleared"] = "late_order_incident_cleared" 

314 client_id: Identifier 

315 message_id: Identifier 

316 broker_id: Identifier 

317 order_symbol: Identifier 

318 evidence: IncidentClearanceEvidence 

319 entry_halted: bool 

320 

321 

322class OrderUpdate(EventPayloadValue): 

323 kind: Literal["order_update"] = "order_update" 

324 client_id: Identifier 

325 message_id: Identifier 

326 status: OrderStatus 

327 raw_broker_status: Identifier 

328 filled_qty: Quantity 

329 filled_avg_price: Positive | None 

330 applied_fill_qty: Quantity | None 

331 unapplied_fill_qty: Quantity | None 

332 late_order_incident_ids: tuple[Identifier, ...] | None 

333 entry_halted: bool 

334 late_order_incident: LateOrderIncident | None 

335 

336 

337class LateOrderIncidentOpened(EventPayloadValue): 

338 kind: Literal["late_order_incident_opened"] = "late_order_incident_opened" 

339 client_id: Identifier 

340 message_id: Identifier 

341 status: OrderStatus 

342 raw_broker_status: Identifier 

343 filled_qty: Quantity 

344 filled_avg_price: Positive | None 

345 applied_fill_qty: Quantity | None 

346 unapplied_fill_qty: Quantity | None 

347 late_order_incident_ids: tuple[Identifier, ...] | None 

348 entry_halted: bool 

349 late_order_incident: LateOrderIncident 

350 

351 

352class LateOrderIncidentReopened(EventPayloadValue): 

353 kind: Literal["late_order_incident_reopened"] = "late_order_incident_reopened" 

354 client_id: Identifier 

355 message_id: Identifier 

356 status: OrderStatus 

357 raw_broker_status: Identifier 

358 filled_qty: Quantity 

359 filled_avg_price: Positive | None 

360 applied_fill_qty: Quantity | None 

361 unapplied_fill_qty: Quantity | None 

362 late_order_incident_ids: tuple[Identifier, ...] | None 

363 entry_halted: bool 

364 late_order_incident: LateOrderIncident 

365 

366 

367type EventPayload = Annotated[ 

368 AccountBound 

369 | AccountInventoried 

370 | AccountControlChanged 

371 | LimitsChanged 

372 | OwnershipIncidentOpened 

373 | OwnershipResolved 

374 | SignalRejected 

375 | Message 

376 | CashAnchorRecorded 

377 | Skipped 

378 | StopSet 

379 | StopEnded 

380 | SellWaiting 

381 | CryptoFeeCounted 

382 | ReadBackSummary 

383 | MessageDone 

384 | OrderPrepared 

385 | SubmitStarted 

386 | SubmissionAborted 

387 | SendAborted 

388 | SubmissionUncertain 

389 | BrokerAcknowledged 

390 | CancelRequested 

391 | QuoteUnavailable 

392 | SubmitError 

393 | SubmissionQuote 

394 | ManualSaleRecorded 

395 | ManualCorrectionRecorded 

396 | ManualOrderPreviewed 

397 | ManualCommandRejected 

398 | ManualCommandPrepared 

399 | LotSalePreviewed 

400 | LotSaleRejected 

401 | LotSalePrepared 

402 | OrderIntentReleased 

403 | LateOrderIncidentCleared 

404 | OrderUpdate 

405 | LateOrderIncidentOpened 

406 | LateOrderIncidentReopened, 

407 Field(discriminator="kind"), 

408] 

409 

410 

411class JournalEvent(Value): 

412 at: AwareDatetime 

413 payload: EventPayload