Coverage for src/copytrading_engine/execution/domain/ledger_state.py: 82%
285 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-16 16:55 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-16 16:55 +0000
1"""Canonical progress and aggregate state for the execution ledger."""
3from decimal import Decimal
4from typing import Literal, Self
6from pydantic import AwareDatetime, ConfigDict, Field, model_validator
8from copytrading_engine.execution.domain.lifecycle import AccountControl
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.order_lifecycle import (
16 OrderStatus,
17 is_pending,
18 map_broker_status,
19)
20from copytrading_engine.execution.domain.orders import (
21 OrderPlan,
22 OrderRecord,
23 OwnedLot,
24 copy_client_id,
25)
26from copytrading_engine.execution.domain.ownership import (
27 ExternalPosition,
28 OwnershipIncident,
29 OwnershipResolution,
30)
31from copytrading_engine.execution.domain.positions import expected_holdings
32from copytrading_engine.execution.domain.progress import (
33 InstructionProgress,
34 OrderLinked,
35 Pending,
36 Skipped,
37)
38from copytrading_engine.execution.domain.recovery import (
39 LateOrderIncident,
40 ManualSale,
41 QuarantinedFill,
42 ReleaseEvidence,
43)
44from copytrading_engine.execution.domain.sizing import DestinationTerms
45from copytrading_engine.execution.domain.stops import StopRule
46from copytrading_engine.execution.domain.values import BrokerAccountId, Identifier, Quantity, Value
47from copytrading_engine.shared.signals import StockSignal
49MessageStatus = Literal[
50 "queued",
51 "done",
52 "stale",
53 "out_of_order",
54 "ignored",
55 "review_required",
56]
59class EarlierLedgerVersion(ValueError):
60 """A ledger an earlier CopyTrading wrote; its format is never migrated."""
63class CashAnchor(Value):
64 """First observed funds for a message, committed before any buy intent.
66 A later broker balance has no freshness marker. The lower of that balance and
67 this anchor less known order commitments bounds every later entry in the message.
68 """
70 account_id: Identifier
71 message_id: Identifier
72 observed_at: AwareDatetime
73 cash: Quantity
74 buying_power: Quantity
77# Skips that hold a call back for the owner rather than refuse it: an account that approves every
78# order, and a sell naming a buy price none of its buys has (ADR-0010).
79HELD_FOR_OWNER = frozenset({"approval_required", "named_buy_not_held"})
82class MessageRecord(StockSignal):
83 model_config = ConfigDict(frozen=True, extra="ignore", hide_input_in_errors=True)
84 source_key: Identifier
85 destination: DestinationTerms
86 parts: tuple[InstructionProgress, ...]
87 status: MessageStatus
88 cash_anchor: CashAnchor | None = None
89 # How each stop the guru posted went, beside its instructions' `parts`. The orders of a stop
90 # are numbered after the instructions' (`stop_order_index`).
91 stop_parts: tuple[InstructionProgress, ...] = ()
93 @model_validator(mode="after")
94 def valid_progress(self) -> Self:
95 if len(self.parts) != len(self.instructions): 95 ↛ 96line 95 didn't jump to line 96 because the condition on line 95 was never true
96 raise ValueError("Every instruction requires a progress slot")
97 if len(self.stop_parts) != len(self.stops): 97 ↛ 98line 97 didn't jump to line 98 because the condition on line 97 was never true
98 raise ValueError("Every stop requires a progress slot")
99 if self.source_key != f"{self.source}:{self.channel_id}": 99 ↛ 100line 99 didn't jump to line 100 because the condition on line 99 was never true
100 raise ValueError("Message source identity mismatch")
101 if self.status == "done" and any(
102 isinstance(part, Pending) for part in (*self.parts, *self.stop_parts)
103 ):
104 raise ValueError("Completed message still has Pending instructions")
105 return self
107 def stop_order_index(self, stop_index: int) -> int:
108 """The `instruction_index` of an order a stop places, which follows the instructions'."""
109 return len(self.instructions) + stop_index
111 @property
112 def key(self) -> str:
113 return f"{self.source_key}:{self.id}"
115 @property
116 def waits_for_owner(self) -> bool:
117 """The account will not act on this post by itself (ADR-0007): it waits for review, or it
118 finished and held a call back for the owner. Only such a post can be copied by hand, so a
119 copy never doubles an order the account already sent."""
120 return self.status == "review_required" or (
121 self.status == "done"
122 and any(
123 isinstance(part, Skipped) and part.reason in HELD_FOR_OWNER for part in self.parts
124 )
125 )
128class LedgerSnapshot(Value):
129 schema_version: Literal[10] = 10
130 account_id: BrokerAccountId | None = None
131 control: AccountControl = Field(default_factory=AccountControl)
132 environment: Literal["paper", "live"] | None = None
133 messages: dict[str, MessageRecord] = Field(default_factory=dict)
134 orders: dict[str, OrderRecord] = Field(default_factory=dict)
135 lots: dict[str, OwnedLot] = Field(default_factory=dict)
136 manual_sales: dict[str, ManualSale] = Field(default_factory=dict)
137 release_evidence: dict[str, ReleaseEvidence] = Field(default_factory=dict)
138 late_order_incidents: dict[str, LateOrderIncident] = Field(default_factory=dict)
139 quarantined_fills: dict[str, QuarantinedFill] = Field(default_factory=dict)
140 external_positions: dict[str, ExternalPosition] = Field(default_factory=dict)
141 ownership_incidents: dict[str, OwnershipIncident] = Field(default_factory=dict)
142 ownership_resolutions: dict[str, OwnershipResolution] = Field(default_factory=dict)
143 manual_corrections: dict[str, ManualCorrectionRecord] = Field(default_factory=dict)
144 manual_previews: dict[str, ManualOrderPreview] = Field(default_factory=dict)
145 manual_commands: dict[str, ManualCommandRecord] = Field(default_factory=dict)
146 lot_sale_previews: dict[str, LotSalePreview] = Field(default_factory=dict)
147 lot_sales: dict[str, LotSaleRecord] = Field(default_factory=dict)
148 # The stops the account follows now, by key (domain/stops.py); an older ledger has none.
149 stops: dict[str, StopRule] = Field(default_factory=dict)
151 @property
152 def entry_halted(self) -> bool:
153 # Quarantined fills stay as audit evidence after a matched clearance;
154 # their linked late-order incident determines whether activity is unresolved.
155 return any(incident.unresolved for incident in self.late_order_incidents.values())
157 @property
158 def buy_halted(self) -> bool:
159 return self.entry_halted
161 @property
162 def expected_holdings(self) -> dict[str, Decimal]:
163 """The shares the broker should hold of each stock (positions.expected_holdings)."""
164 return expected_holdings(self.lots.values(), self.external_positions.values())
166 @property
167 def has_outstanding_work(self) -> bool:
168 """A call still to act on, or an order still open: work a clock decides, such as an
169 order timeout or a call waiting for the market to open, so its account checks often."""
170 return (
171 any(message.status == "queued" for message in self.messages.values())
172 or any(order.pending for order in self.orders.values())
173 # A stop is placed again at each open, so the account looks often enough to catch it.
174 or bool(self.stops)
175 )
177 @model_validator(mode="after")
178 def validate_references(self) -> Self:
179 has_state = (
180 self.orders
181 or self.lots
182 or self.release_evidence
183 or self.late_order_incidents
184 or self.quarantined_fills
185 or self.external_positions
186 or self.ownership_incidents
187 or self.ownership_resolutions
188 or self.manual_corrections
189 or self.manual_previews
190 or self.manual_commands
191 or self.lot_sale_previews
192 or self.lot_sales
193 )
194 if has_state and not self.account_id: 194 ↛ 195line 194 didn't jump to line 195 because the condition on line 194 was never true
195 raise ValueError("An active ledger requires an account identity")
196 if self.environment is not None and self.account_id is None: 196 ↛ 197line 196 didn't jump to line 197 because the condition on line 196 was never true
197 raise ValueError("A ledger environment requires an account identity")
198 for key, position in self.external_positions.items():
199 if key != position.symbol:
200 raise ValueError("External position symbol identity mismatch")
201 for key, incident in self.ownership_incidents.items():
202 if key != incident.incident_id: 202 ↛ 203line 202 didn't jump to line 203 because the condition on line 202 was never true
203 raise ValueError("Ownership incident identity mismatch")
204 if incident.resolved_by is not None:
205 resolution = self.ownership_resolutions.get(incident.resolved_by)
206 if resolution is None or resolution.request.incident_id != key: 206 ↛ 207line 206 didn't jump to line 207 because the condition on line 206 was never true
207 raise ValueError("Resolved ownership incident has no matching resolution")
208 for key, resolution in self.ownership_resolutions.items():
209 request = resolution.request
210 incident = self.ownership_incidents.get(request.incident_id)
211 if (
212 key != request.resolution_id
213 or request.account_id != self.account_id
214 or incident is None
215 or incident.symbol != request.symbol
216 or incident.resolved_by != key
217 ):
218 raise ValueError("Ownership resolution identity or allocation mismatch")
219 if any( 219 ↛ 223line 219 didn't jump to line 223 because the condition on line 219 was never true
220 lot_id not in self.lots or self.lots[lot_id].symbol != request.symbol
221 for lot_id in request.lot_remaining
222 ):
223 raise ValueError("Ownership resolution refers to an unknown owned lot")
224 if set(resolution.lot_reductions) != set(request.lot_remaining):
225 raise ValueError("Ownership resolution lot allocation is incomplete")
226 if resolution.checked_at <= incident.observed_at: 226 ↛ 227line 226 didn't jump to line 227 because the condition on line 226 was never true
227 raise ValueError("Ownership resolution evidence predates the incident")
228 allocation_revisions: dict[str, dict[int, OwnershipResolution]] = {}
229 for resolution in self.ownership_resolutions.values():
230 symbol = resolution.request.symbol
231 revisions = allocation_revisions.setdefault(symbol, {})
232 if resolution.allocation_revision in revisions: 232 ↛ 233line 232 didn't jump to line 233 because the condition on line 232 was never true
233 raise ValueError("Duplicate ownership allocation revision")
234 revisions[resolution.allocation_revision] = resolution
235 for symbol, position in self.external_positions.items():
236 revisions = allocation_revisions.get(symbol, {})
237 if set(revisions) != set(range(1, len(revisions) + 1)): 237 ↛ 238line 237 didn't jump to line 238 because the condition on line 237 was never true
238 raise ValueError("Ownership allocation revisions are incomplete")
239 latest = revisions.get(len(revisions))
240 if position.allocation_revision != len(revisions) or (
241 latest is not None and position.qty != latest.request.external_qty
242 ):
243 raise ValueError("External position does not match latest ownership allocation")
244 if any(symbol not in self.external_positions for symbol in allocation_revisions): 244 ↛ 245line 244 didn't jump to line 245 because the condition on line 244 was never true
245 raise ValueError("Ownership allocation has no current external position")
246 if any(key != message.key for key, message in self.messages.items()): 246 ↛ 247line 246 didn't jump to line 247 because the condition on line 246 was never true
247 raise ValueError("Snapshot message identity mismatch")
248 for message_key, message in self.messages.items():
249 anchor = message.cash_anchor
250 if anchor is not None and (
251 anchor.account_id != self.account_id or anchor.message_id != message_key
252 ):
253 raise ValueError("Cash anchor does not match its message and account")
254 for instruction_index, progress in enumerate(message.parts):
255 if isinstance(progress, OrderLinked):
256 order = self.orders.get(progress.client_id)
257 if order is None or (order.message_id, order.instruction_index) != (
258 message_key,
259 instruction_index,
260 ):
261 raise ValueError("Order link does not match its message instruction")
262 for stop_index, progress in enumerate(message.stop_parts):
263 if isinstance(progress, OrderLinked):
264 order = self.orders.get(progress.client_id)
265 if order is None or (order.message_id, order.instruction_index) != ( 265 ↛ 269line 265 didn't jump to line 269 because the condition on line 265 was never true
266 message_key,
267 message.stop_order_index(stop_index),
268 ):
269 raise ValueError("Order link does not match its message stop")
270 for key, rule in self.stops.items():
271 lot = self.lots.get(rule.lot_id)
272 if ( 272 ↛ 279line 272 didn't jump to line 279 because the condition on line 272 was never true
273 key != rule.key
274 or lot is None
275 or lot.symbol != rule.symbol
276 or any(entry not in lot.entry_remaining for entry in rule.entries)
277 or rule.message_id not in self.messages
278 ):
279 raise ValueError("A stop does not match the lot and post it protects")
280 for order in self.orders.values():
281 if order.stop_rule is not None and not ( 281 ↛ 284line 281 didn't jump to line 284 because the condition on line 281 was never true
282 order.side == "sell" and order.message_id in self.messages
283 ):
284 raise ValueError("A stop order is a sell placed for a post")
285 correction_revisions: set[tuple[str, int]] = set()
286 for key, correction in self.manual_corrections.items():
287 message = self.messages.get(correction.source_id)
288 accepted = (
289 StockSignal.model_validate(
290 {name: getattr(message, name) for name in StockSignal.model_fields}
291 )
292 if message is not None
293 else None
294 )
295 revision_key = (correction.source_id, correction.revision)
296 if ( 296 ↛ 306line 296 didn't jump to line 306 because the condition on line 296 was never true
297 key != correction.correction_id
298 or revision_key in correction_revisions
299 or message is None
300 or not message.waits_for_owner
301 or accepted != correction.accepted_interpretation
302 or correction.source_text != message.text
303 or correction.source_at != message.timestamp
304 or message.destination.connection.account_id not in correction.selected_account_ids
305 ):
306 raise ValueError("Manual correction does not match reviewed source evidence")
307 correction_revisions.add(revision_key)
308 for key, preview in self.manual_previews.items():
309 correction = self.manual_corrections.get(preview.request.correction_id)
310 instruction_index = preview.request.instruction_index
311 if ( 311 ↛ 322line 311 didn't jump to line 322 because the condition on line 311 was never true
312 key != preview.request.preview_id
313 or correction is None
314 or preview.request.account_id not in correction.selected_account_ids
315 or preview.broker_account_id != self.account_id
316 or preview.environment != self.environment
317 or preview.correction_revision != correction.revision
318 or instruction_index >= len(correction.instructions)
319 or preview.source_at != correction.source_at
320 or preview.instruction != correction.instructions[instruction_index]
321 ):
322 raise ValueError("Manual preview does not match its correction and owner")
323 if preview.plan is not None:
324 instruction = correction.instructions[instruction_index]
325 expected_side = "buy" if instruction.action == "buy" else "sell"
326 expected_entry = (
327 instruction.price
328 if expected_side == "buy"
329 else instruction.entry_price
330 if instruction.entry_price is not None
331 else preview.plan.entry_price
332 )
333 if ( 333 ↛ 342line 333 didn't jump to line 342 because the condition on line 333 was never true
334 preview.plan.side,
335 preview.plan.symbol,
336 preview.plan.entry_price,
337 ) != (
338 expected_side,
339 instruction.symbol,
340 expected_entry,
341 ) or instruction.price not in (None, preview.plan.source_price):
342 raise ValueError("Manual preview plan differs from corrected instruction")
343 manual_order_ids: set[str] = set()
344 for key, command in self.manual_commands.items():
345 preview = self.manual_previews.get(command.request.preview_id)
346 correction = self.manual_corrections.get(command.correction_id)
347 if ( 347 ↛ 358line 347 didn't jump to line 358 because the condition on line 347 was never true
348 key != command.request.command_id
349 or correction is None
350 or command.request.account_id not in correction.selected_account_ids
351 or preview is None
352 or preview.request.account_id != command.request.account_id
353 or preview.request.correction_id != command.correction_id
354 or preview.request.instruction_index != command.instruction_index
355 or command.source_id != correction.source_id
356 or (command.state == "prepared" and preview.plan is None)
357 ):
358 raise ValueError("Manual command does not match its saved correction preview")
359 if command.state == "prepared":
360 assert preview.plan is not None
361 if ( 361 ↛ 373line 361 didn't jump to line 373 because the condition on line 361 was never true
362 command.client_id is None
363 or command.client_id not in self.orders
364 or self.orders[command.client_id].message_id != correction.source_id
365 or self.orders[command.client_id].instruction_index != command.instruction_index
366 or self.orders[command.client_id].source_key
367 != self.messages[correction.source_id].source_key
368 or self.orders[command.client_id].model_dump(
369 include=set(OrderPlan.model_fields)
370 )
371 != preview.plan.model_dump()
372 ):
373 raise ValueError("Manual command intent differs from its saved preview")
374 if command.client_id is not None:
375 if command.client_id in manual_order_ids: 375 ↛ 376line 375 didn't jump to line 376 because the condition on line 375 was never true
376 raise ValueError("Manual commands share an order intent")
377 manual_order_ids.add(command.client_id)
378 for key, preview in self.lot_sale_previews.items():
379 if ( 379 ↛ 384line 379 didn't jump to line 384 because the condition on line 379 was never true
380 key != preview.request.preview_id
381 or preview.broker_account_id != self.account_id
382 or preview.environment != self.environment
383 ):
384 raise ValueError("Lot sale preview does not match its account")
385 for key, sale in self.lot_sales.items():
386 preview = self.lot_sale_previews.get(sale.request.preview_id)
387 if ( 387 ↛ 394line 387 didn't jump to line 394 because the condition on line 387 was never true
388 key != sale.request.command_id
389 or preview is None
390 or preview.request.account_id != sale.request.account_id
391 or preview.request.lot_id != sale.lot_id
392 or (sale.state == "prepared" and preview.plan is None)
393 ):
394 raise ValueError("Lot sale does not match its saved preview")
395 if sale.state == "prepared":
396 assert preview.plan is not None
397 order = self.orders.get(sale.client_id or "")
398 if ( 398 ↛ 404line 398 didn't jump to line 404 because the condition on line 398 was never true
399 order is None
400 or order.lot_id != sale.lot_id
401 or order.model_dump(include=set(OrderPlan.model_fields))
402 != preview.plan.model_dump()
403 ):
404 raise ValueError("Lot sale intent differs from its saved preview")
405 if sale.client_id is not None:
406 if sale.client_id in manual_order_ids: 406 ↛ 407line 406 didn't jump to line 407 because the condition on line 406 was never true
407 raise ValueError("Owner commands share an order intent")
408 manual_order_ids.add(sale.client_id)
409 broker_ids = {order.broker_id for order in self.orders.values() if order.broker_id}
410 if len(broker_ids) != sum(order.broker_id is not None for order in self.orders.values()): 410 ↛ 411line 410 didn't jump to line 411 because the condition on line 410 was never true
411 raise ValueError("Snapshot contains duplicate broker order identities")
412 client_ids = set(self.orders)
413 for key, evidence in self.release_evidence.items():
414 order = self.orders.get(key)
415 if ( 415 ↛ 419line 415 didn't jump to line 419 because the condition on line 415 was never true
416 key != (order.client_id if order else None)
417 or evidence.account_id != self.account_id
418 ):
419 raise ValueError("Release evidence does not match its order and account")
420 if order is None: 420 ↛ 421line 420 didn't jump to line 421 because the condition on line 420 was never true
421 raise ValueError("Release evidence does not match a submitted or released intent")
422 if evidence.submission_state == "started":
423 submission_matches = (
424 order.submit_started_at is not None
425 and evidence.checked_at >= order.submit_started_at
426 )
427 else:
428 submission_matches = (
429 order.submit_started_at is None and evidence.checked_at >= order.created_at
430 )
431 if not submission_matches or ( 431 ↛ 438line 431 didn't jump to line 438 because the condition on line 431 was never true
432 order.status != OrderStatus.RELEASED_UNSUBMITTED
433 and (
434 order.raw_broker_status is None
435 or map_broker_status(order.raw_broker_status) != order.status
436 )
437 ):
438 raise ValueError("Release evidence does not match a submitted or released intent")
439 if (
440 order.status != OrderStatus.RELEASED_UNSUBMITTED
441 and key not in self.late_order_incidents
442 ):
443 raise ValueError("Observed released order is missing its late-order incident")
444 for key, order in self.orders.items():
445 if order.status == OrderStatus.RELEASED_UNSUBMITTED:
446 if ( 446 ↛ 451line 446 didn't jump to line 451 because the condition on line 446 was never true
447 key not in self.release_evidence
448 or order.broker_id is not None
449 or order.filled_qty
450 ):
451 raise ValueError(
452 "Released order intent must have evidence and no broker activity"
453 )
454 for key, incident in self.late_order_incidents.items():
455 order = self.orders.get(key)
456 if ( 456 ↛ 491line 456 didn't jump to line 491 because the condition on line 456 was never true
457 key != incident.client_id
458 or key not in self.release_evidence
459 or order is None
460 or (order.broker_id, order.symbol, order.side, order.status, order.filled_qty)
461 != (
462 incident.broker_id,
463 incident.symbol,
464 incident.side,
465 incident.latest_status,
466 incident.latest_filled_qty,
467 )
468 or order.raw_broker_status != incident.raw_broker_status
469 or incident.first_observed_at < self.release_evidence[key].checked_at
470 or any(item.account_id != self.account_id for item in incident.clearance_history)
471 or any(
472 conflicting_id not in self.orders
473 or self.orders[conflicting_id].side != "sell"
474 or self.orders[conflicting_id].lot_id != order.lot_id
475 or self.orders[conflicting_id].symbol != order.symbol
476 or self.orders[conflicting_id].created_at > incident.first_observed_at
477 for conflicting_id in incident.conflicting_order_ids
478 )
479 or (
480 incident.cleared
481 and (
482 is_pending(order.status)
483 or any(
484 is_pending(self.orders[conflicting_id].status)
485 for conflicting_id in incident.conflicting_order_ids
486 )
487 or incident.clearance_history[-1].checked_at < incident.last_observed_at
488 )
489 )
490 ):
491 raise ValueError("Late-order incident does not match its order or account")
492 for key, fill in self.quarantined_fills.items():
493 order = self.orders.get(key)
494 if ( 494 ↛ 501line 494 didn't jump to line 501 because the condition on line 494 was never true
495 key != fill.client_id
496 or order is None
497 or order.side != "sell"
498 or (fill.broker_id, fill.lot_id, fill.symbol, fill.observed_filled_qty)
499 != (order.broker_id, order.lot_id, order.symbol, order.filled_qty)
500 ):
501 raise ValueError("Quarantined fill does not match its broker order")
502 for incident_id in fill.incident_client_ids:
503 incident = self.late_order_incidents.get(incident_id)
504 incident_order = self.orders.get(incident_id)
505 if ( 505 ↛ 524line 505 didn't jump to line 524 because the condition on line 505 was never true
506 incident is None
507 or incident_order is None
508 or incident_id not in self.release_evidence
509 or incident.side != "sell"
510 or incident_order.lot_id != fill.lot_id
511 or incident.symbol != fill.symbol
512 or (
513 incident_id != key
514 and (
515 key not in incident.conflicting_order_ids
516 or order.created_at > incident.first_observed_at
517 )
518 )
519 or (
520 incident_id == key
521 and fill.observed_filled_qty != incident.latest_filled_qty
522 )
523 ):
524 raise ValueError("Quarantined fill has an invalid incident association")
525 for incident in self.late_order_incidents.values():
526 if ( 526 ↛ 530line 526 didn't jump to line 530 because the condition on line 526 was never true
527 key in incident.conflicting_order_ids
528 and incident.client_id not in fill.incident_client_ids
529 ):
530 raise ValueError("Quarantined fill is missing its associated incident")
531 for incident_id, incident in self.late_order_incidents.items():
532 for conflicting_id in incident.conflicting_order_ids:
533 fill = self.quarantined_fills.get(conflicting_id)
534 if fill is not None and incident_id not in fill.incident_client_ids: 534 ↛ 535line 534 didn't jump to line 535 because the condition on line 534 was never true
535 raise ValueError("Incident is missing its conflicting quarantined fill link")
536 for key, sale in self.manual_sales.items():
537 lot = self.lots.get(sale.lot_id or "")
538 if key != sale.order.id or ( 538 ↛ 541line 538 didn't jump to line 541 because the condition on line 538 was never true
539 sale.lot_id is not None and (lot is None or lot.symbol != sale.order.symbol)
540 ):
541 raise ValueError("Manual sale identity or lot mismatch")
542 if sale.lot_id is None and key not in self.ownership_incidents: 542 ↛ 543line 542 didn't jump to line 543 because the condition on line 542 was never true
543 raise ValueError("Unallocated manual sale requires an ownership incident")
544 if sale.lot_id is None:
545 incident = self.ownership_incidents[key]
546 if ( 546 ↛ 551line 546 didn't jump to line 551 because the condition on line 546 was never true
547 incident.cause != "manual_sale"
548 or incident.symbol != sale.order.symbol
549 or incident.expected_qty - sale.order.filled_qty != incident.actual_qty
550 ):
551 raise ValueError("Manual sale ownership incident does not match its fill")
552 if sale.order.id in broker_ids or sale.order.client_order_id in client_ids:
553 raise ValueError("Manual sale duplicates an already recorded order")
554 broker_ids.add(sale.order.id)
555 client_ids.add(sale.order.client_order_id)
556 entry_lots: dict[str, str] = {}
557 for lot_key, lot in self.lots.items():
558 for entry in lot.entries(lot_key):
559 if entry in entry_lots: 559 ↛ 560line 559 didn't jump to line 560 because the condition on line 559 was never true
560 raise ValueError("A buy order belongs to more than one lot")
561 entry_lots[entry] = lot_key
562 for key, order in self.orders.items():
563 message = self.messages.get(order.message_id)
564 if key != order.client_id or message is None or order.source_key != message.source_key:
565 raise ValueError("Snapshot order identity mismatch")
566 manual = key in manual_order_ids
567 # A copied sell stopped before it was sent gives its call back to wait again; a later
568 # attempt of the same call, or the waiting call itself, holds the reservation.
569 sent_again = (
570 order.side == "sell"
571 and order.status == OrderStatus.ABORTED_BEFORE_SUBMIT
572 and key.startswith(copy_client_id(order.message_id, order.instruction_index))
573 )
574 # A stop is placed again each session, so only its first order is its post's link
575 # (checked with the post's stop parts above).
576 if ( 576 ↛ 585line 576 didn't jump to line 585 because the condition on line 576 was never true
577 not manual
578 and not sent_again
579 and order.stop_rule is None
580 and (
581 order.instruction_index >= len(message.parts)
582 or message.parts[order.instruction_index] != OrderLinked(client_id=key)
583 )
584 ):
585 raise ValueError("Recorded order has no matching instruction reservation")
586 if (
587 order.side == "buy"
588 and not manual
589 and (
590 message.cash_anchor is None
591 or order.created_at < message.cash_anchor.observed_at
592 )
593 ):
594 raise ValueError("Buy order requires a preceding cash anchor")
595 if order.side == "buy" and order.filled_qty > 0 and key not in entry_lots:
596 raise ValueError("Entry fills require an owned lot")
597 if order.side == "sell":
598 lot = self.lots.get(order.lot_id or "")
599 # A sell of named buys carries their price, and every one is in its lot; any
600 # other sell carries the lot's own (ADR-0010).
601 named = order.from_entries
602 # A stop protects buys at their own prices, so it carries the lot's.
603 stop = order.stop_rule is not None
604 if ( 604 ↛ 615line 604 didn't jump to line 615 because the condition on line 604 was never true
605 lot is None
606 or (lot.symbol, lot.source_key) != (order.symbol, order.source_key)
607 or (not named and lot.entry_price != order.entry_price)
608 or any(entry not in lot.entry_prices for entry in named)
609 or (
610 not stop
611 and any(lot.entry_prices.get(entry) != order.entry_price for entry in named)
612 )
613 or (stop and lot.entry_price != order.entry_price)
614 ):
615 raise ValueError("Sell order references an unknown or different lot")
616 for key, lot in self.lots.items():
617 entries = [self.orders.get(entry) for entry in lot.entries(key)]
618 # Every buy of the stock from the guru joins one lot, at whatever price (ADR-0010).
619 if any( 619 ↛ 630line 619 didn't jump to line 630 because the condition on line 619 was never true
620 entry is None
621 or entry.side != "buy"
622 or (lot.symbol, lot.source_key) != (entry.symbol, entry.source_key)
623 or lot.entry_prices.get(entry.client_id) != entry.entry_price
624 for entry in entries
625 ) or lot.original_qty != sum(
626 # What each buy brought in: a coin's fill less the fee Alpaca kept of it.
627 (entry.received_qty for entry in entries if entry is not None),
628 Decimal(0),
629 ):
630 raise ValueError("Snapshot lot does not match its entry fills")
631 sold = sum(
632 (
633 order.filled_qty
634 - (
635 self.quarantined_fills[order.client_id].unapplied_qty
636 if order.client_id in self.quarantined_fills
637 else Decimal(0)
638 )
639 for order in self.orders.values()
640 if order.side == "sell" and order.lot_id == key
641 ),
642 Decimal(0),
643 )
644 manually_sold = sum(
645 (
646 sale.order.filled_qty
647 for sale in self.manual_sales.values()
648 if sale.lot_id == key
649 ),
650 Decimal(0),
651 )
652 ownership_reductions = sum(
653 (
654 resolution.lot_reductions.get(key, Decimal(0))
655 for resolution in self.ownership_resolutions.values()
656 ),
657 Decimal(0),
658 )
659 if lot.remaining_qty != lot.original_qty - sold - manually_sold - ownership_reductions:
660 raise ValueError("Lot quantity does not match recorded sell fills")
661 return self
664def is_earlier_version(version: object) -> bool:
665 """Whether a saved snapshot's version is one an earlier CopyTrading wrote."""
666 current = LedgerSnapshot.model_fields["schema_version"].default
667 return type(version) is int and 0 < version < current