Coverage for src/copytrading_engine/execution/domain/ownership.py: 94%
76 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"""Durable attribution of broker holdings outside copier-owned lots."""
3from collections.abc import Sequence
4from dataclasses import dataclass
5from decimal import Decimal
6from typing import Literal, Self
8from pydantic import AwareDatetime, Field, model_validator
10from copytrading_engine.execution.domain.market import BrokerOrder, Position
11from copytrading_engine.execution.domain.order_lifecycle import OrderStatus
12from copytrading_engine.execution.domain.orders import OrderRecord
13from copytrading_engine.execution.domain.values import Identifier, Money, Quantity, Value
15# Why the app settled a holdings count from the broker's filled count by itself (ADR-0011).
16SyncReason = Literal[
17 "broker_matches_again",
18 "owner_bought_outside",
19 "owner_sold_own_shares",
20 "owner_sold_copied_shares",
21]
24@dataclass(frozen=True, slots=True)
25class Allocation:
26 """How a broker count splits: what each copied lot keeps, and what is the owner's own."""
28 lot_remaining: dict[str, Decimal]
29 external_qty: Decimal
32def allocate(broker_qty: Decimal, lots_oldest_first: Sequence[tuple[str, Decimal]]) -> Allocation:
33 """Copied shares the broker still holds stay copied and the rest are the owner's own. A count
34 below the copied shares means copied shares were sold outside the app, and they come off the
35 oldest buys first, the way the app's own sells take them."""
36 copied = sum((held for _, held in lots_oldest_first), Decimal(0))
37 if broker_qty >= copied:
38 return Allocation(dict(lots_oldest_first), broker_qty - copied)
39 missing = copied - broker_qty
40 remaining: dict[str, Decimal] = {}
41 for key, held in lots_oldest_first:
42 taken = min(held, missing)
43 remaining[key] = held - taken
44 missing -= taken
45 return Allocation(remaining, Decimal(0))
48def sync_reason(broker_qty: Decimal, expected: Decimal, copied: Decimal) -> SyncReason:
49 """What a settled count says the owner did."""
50 if broker_qty == expected:
51 return "broker_matches_again"
52 if broker_qty > expected:
53 return "owner_bought_outside"
54 return "owner_sold_own_shares" if broker_qty >= copied else "owner_sold_copied_shares"
57class ExternalPosition(Value):
58 symbol: Identifier
59 qty: Quantity
60 allocation_revision: int = Field(default=0, ge=0)
63class OwnershipIncident(Value):
64 incident_id: Identifier
65 symbol: Identifier
66 expected_qty: Quantity
67 actual_qty: Money
68 observed_at: AwareDatetime
69 cause: Literal["position_mismatch", "manual_sale"]
70 resolved_by: Identifier | None = None
72 @property
73 def resolved(self) -> bool:
74 return self.resolved_by is not None
77class OwnershipResolutionRequest(Value):
78 resolution_id: Identifier
79 incident_id: Identifier
80 account_id: Identifier
81 symbol: Identifier
82 actor: Identifier
83 reason: Identifier
84 broker_qty: Quantity
85 external_qty: Quantity
86 lot_remaining: dict[Identifier, Quantity] = Field(default_factory=dict)
88 @model_validator(mode="after")
89 def conserved(self) -> Self:
90 if not self.actor.strip() or not self.reason.strip(): 90 ↛ 91line 90 didn't jump to line 91 because the condition on line 90 was never true
91 raise ValueError("Ownership resolution requires actor and reason")
92 if self.external_qty + sum(self.lot_remaining.values()) != self.broker_qty:
93 raise ValueError("Ownership resolution quantity conservation failed")
94 return self
97class OwnershipResolution(Value):
98 request: OwnershipResolutionRequest
99 checked_at: AwareDatetime
100 lot_reductions: dict[Identifier, Quantity]
101 allocation_revision: int = Field(ge=1)
103 @property
104 def external_qty(self) -> Quantity:
105 return self.request.external_qty
108class OwnershipInspection(Value):
109 account_id: Identifier
110 environment: Literal["paper", "live"]
111 external_positions: tuple[ExternalPosition, ...]
112 incidents: tuple[OwnershipIncident, ...]
113 broker_positions: tuple[Position, ...]
114 expected_quantities: dict[Identifier, Quantity]
115 account_risk_status: Literal["ready", "unavailable"]
116 account_risk_reason: str | None
117 total_exposure_usd: Quantity | None
118 account_activity_status: Literal["ready", "unavailable"]
119 account_activity_reason: str | None
121 @model_validator(mode="after")
122 def risk_fact_consistency(self) -> Self:
123 if (self.account_risk_status == "ready") != (self.total_exposure_usd is not None): 123 ↛ 124line 123 didn't jump to line 124 because the condition on line 123 was never true
124 raise ValueError("Ready account risk requires valued exposure")
125 if (self.account_activity_status == "ready") != (self.account_activity_reason is None): 125 ↛ 126line 125 didn't jump to line 126 because the condition on line 125 was never true
126 raise ValueError("Ready account activity requires no unresolved reason")
127 return self
130def account_activity_reason(
131 open_orders: tuple[BrokerOrder, ...],
132 known_open_orders: tuple[OrderRecord, ...],
133 *,
134 unresolved_order_incidents: bool,
135 symbol: str | None = None,
136) -> str | None:
137 """Check an observed open-order page against persisted account activity. The page is checked
138 whole, since a full or repeating page can't be trusted for any stock; with `symbol` (a sell),
139 only an order on that stock that CopyTrading didn't place holds it (ADR-0010)."""
140 if unresolved_order_incidents:
141 return "unresolved_order_incident"
142 if len(open_orders) >= 500:
143 return "incomplete_account_orders"
144 observed_ids = [order.client_order_id for order in open_orders]
145 if len(set(observed_ids)) != len(observed_ids):
146 return "incomplete_account_orders"
147 known_by_id = {order.client_id: order for order in known_open_orders}
148 if any(
149 (saved := known_by_id.get(observed.client_order_id)) is None
150 or not _same_order(observed, saved)
151 for observed in open_orders
152 if symbol is None or observed.symbol == symbol
153 ):
154 return "unresolved_account_order"
155 return None
158# What only the broker reports: an order the app aborted or never sent is not settled.
159_BROKER_SETTLED = frozenset(
160 {
161 OrderStatus.FILLED,
162 OrderStatus.CANCELED,
163 OrderStatus.EXPIRED,
164 OrderStatus.REPLACED,
165 OrderStatus.REJECTED,
166 }
167)
170def still_open(
171 open_orders: tuple[BrokerOrder, ...], orders: tuple[OrderRecord, ...]
172) -> tuple[BrokerOrder, ...]:
173 """The broker's open orders, less the app's own that the broker already reported settled.
175 The open-order list can trail a fill or cancel the broker has reported: in a burst, a buy
176 planned just after another fills still sees that one listed as open."""
177 settled = {order.client_id: order for order in orders if order.status in _BROKER_SETTLED}
178 return tuple(
179 observed
180 for observed in open_orders
181 if (saved := settled.get(observed.client_order_id)) is None
182 or not _same_order(observed, saved)
183 )
186def _same_order(observed: BrokerOrder, saved: OrderRecord) -> bool:
187 return (
188 observed.symbol == saved.symbol
189 and observed.side == saved.side
190 and observed.qty == saved.qty
191 and (saved.broker_id is None or observed.id == saved.broker_id)
192 and (observed.position_intent is None or observed.position_intent == saved.position_intent)
193 )