Coverage for src/copytrading_engine/execution/presentation/notifications.py: 92%
117 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"""Translate committed execution facts into notifications; never infer a fill from an intent."""
3import hashlib
4from decimal import Decimal
6from copytrading_engine.execution.domain.events import (
7 CancelRequested,
8 JournalEvent,
9 LateOrderIncidentCleared,
10 LateOrderIncidentOpened,
11 LateOrderIncidentReopened,
12 Message,
13 MessageDone,
14 OrderIntentReleased,
15 OrderUpdate,
16 ReadBackSummary,
17 SubmissionAborted,
18 SubmissionUncertain,
19 SubmitError,
20)
21from copytrading_engine.execution.domain.events import Skipped as SkippedEvent
22from copytrading_engine.execution.domain.ledger_state import HELD_FOR_OWNER, LedgerSnapshot
23from copytrading_engine.execution.domain.order_lifecycle import OrderStatus
24from copytrading_engine.execution.domain.progress import Skipped as SkippedInstruction
25from copytrading_engine.shared.notification_models import NotificationIntent, NotificationPayload
27REASONS = {
28 "insufficient_cash": "Insufficient cash for this entry",
29 "daily_loss_cap": "Daily loss limit reached; new entries are blocked",
30 "daily_entry_cap": "Daily entry limit reached",
31 "symbol_exposure_cap": "Symbol exposure limit reached",
32 "total_exposure_cap": "Total exposure limit reached",
33 "symbol_and_total_exposure_cap": "Symbol and total exposure limits reached",
34 "account_blocked": "The broker account is blocked from trading",
35 "halted": "New entries are paused by the operator",
36 "stopping": "Execution is stopping before order submission",
37 "session_changed": "The eligible market session changed before order submission",
38 "stale": "The signal exceeded the permitted age",
39 "out_of_order": "A newer trade signal was already processed",
40 "missing_or_ambiguous_lot": "No unique copier-owned lot matches the quoted entry price",
41 "named_buy_not_held": "None of your buys is at the buy price the guru named",
42 "sell_share_not_given": "The sell doesn't say how much",
43 "batch_size_not_given": "The playbook doesn't say how big a batch is",
44 "unsupported_asset": "The broker does not support trading this asset",
45 "crypto_paper_only": "Crypto is copied on paper accounts only",
46 "outside_session": "The broker session is not eligible for this order",
47 "below_minimum_quantity": "The allowed size is below the asset's minimum quantity",
48 "below_minimum_order_size": "Less of the coin is left than its smallest order; it cannot sell",
49 "position_mismatch": "Broker holdings do not match the copier ledger",
50 "portfolio_mismatch": "New entry blocked: account holdings do not match the copier ledger",
51 "external_open_order": "An external order already exists for this asset",
52 "insufficient_owned_shares": "The copier does not own enough shares for this exit",
53 "duplicate": "This instruction duplicates a recent signal",
54 "follow_stops_off": "Following the guru's stops is off",
55 "stop_buy_not_filled": "The buy this stop protects did not fill",
56 "stop_buy_not_held": "CopyTrading holds none of the buy this stop protects",
57 "stop_buy_not_made": "The buy this stop protects was not made",
58 "stop_not_for_coins": "Stops are not placed for coins",
59 "stop_nothing_left": "Nothing was left to protect",
60 "approval_required": "This account asks you to approve every order, so it didn't send "
61 "this one. Open Activity to approve or skip it; it expires when its trading day ends",
62}
65def execution_notification(
66 snapshot: LedgerSnapshot, event: JournalEvent
67) -> NotificationIntent | None:
68 payload = event.payload
69 if isinstance(payload, ReadBackSummary):
70 return _read_back_notification(payload, event)
71 signal_id = getattr(payload, "message_id", None)
72 if signal_id is None or signal_id not in snapshot.messages:
73 return None
74 message = snapshot.messages[signal_id]
75 client_id = getattr(payload, "client_id", None)
76 order = snapshot.orders.get(client_id) if client_id is not None else None
77 category = "info"
78 key = f"{signal_id}:{payload.kind}"
79 detail = ""
80 if isinstance(payload, Message) and payload.status in {"stale", "out_of_order"}:
81 # Read back after CopyTrading was off: told once, in the read-back summary.
82 return None
83 elif isinstance(payload, Message) and payload.status == "review_required":
84 title = "Waiting for you"
85 detail = (
86 "The post names no size and this account waits for you on such calls. "
87 "Open Activity to copy or skip it; it expires when its trading day ends"
88 )
89 category = "warning"
90 elif isinstance(payload, SkippedEvent) and payload.reason in {"stale", "out_of_order"}:
91 return None
92 elif isinstance(payload, SkippedEvent):
93 part = payload.part
94 reason = payload.reason
95 waits = reason in HELD_FOR_OWNER
96 if payload.stop:
97 title = f"{message.stops[part].symbol} — stop skipped"
98 key += ":stop"
99 else:
100 title = (
101 f"{message.instructions[part].symbol} — "
102 f"{'waiting for you' if waits else 'trade skipped'}"
103 )
104 detail = REASONS.get(reason, reason.replace("_", " "))
105 if reason == "crypto_paper_only":
106 account = message.destination.connection.account_id
107 detail = f"{account} is a live account, and crypto is copied on paper accounts only"
108 for breach in payload.exposure or ():
109 detail += (
110 f". {breach.scope.capitalize()} cost exposure "
111 f"${format(breach.current.normalize(), 'f')} + proposed budget "
112 f"${format(breach.proposed.normalize(), 'f')} "
113 f"> ${format(breach.limit.normalize(), 'f')} limit"
114 )
115 key += f":{part}"
116 elif isinstance(payload, MessageDone) and any(
117 isinstance(part, SkippedInstruction) and part.reason == "duplicate"
118 for part in message.parts
119 ):
120 title = "Duplicate instruction skipped"
121 detail = REASONS["duplicate"]
122 elif order is not None:
123 side = order.side.upper()
124 key = f"{order.client_id}:{payload.kind}"
125 if isinstance(payload, OrderUpdate):
126 state = order.status.value
127 if order.status is OrderStatus.UNRECOGNIZED:
128 raw_status = order.raw_broker_status or payload.raw_broker_status
129 key += f":{state}:{raw_status}:{order.filled_qty.normalize()}"
130 title = f"{side} {order.symbol} — broker status quarantined"
131 detail = (
132 f"Alpaca reported unrecognized status '{raw_status}'. "
133 "This order remains reserved and will be reconciled. No cancellation "
134 "or resubmission was requested."
135 )
136 category = "warning"
137 else:
138 key += f":{state}:{order.filled_qty.normalize()}"
139 titles = {
140 "pending_new": "submission received — acceptance pending",
141 "new": "order accepted",
142 "accepted": "order accepted",
143 "partially_filled": "partially filled",
144 "filled": "filled",
145 "canceled": "canceled",
146 "expired": "expired",
147 "rejected": "rejected",
148 "pending_cancel": "cancellation pending",
149 "done_for_day": "done for day",
150 "replaced": "replaced",
151 "stopped": "stopped",
152 "suspended": "suspended",
153 "calculated": "calculated",
154 "accepted_for_bidding": "accepted for bidding",
155 }
156 if order.status is not OrderStatus.UNRECOGNIZED:
157 title = f"{side} {order.symbol} — {titles.get(state, state.replace('_', ' '))}"
158 if state in {"rejected", "canceled", "expired", "suspended", "stopped"}:
159 category = "warning"
160 pricing = {
161 "market": "Market order.",
162 "stop": f"Stop: ${order.stop_price}.",
163 "limit": f"Limit: ${order.limit_price}.",
164 }[order.type]
165 detail = f"Filled: {order.filled_qty} of {order.qty} shares. {pricing}"
166 average = payload.filled_avg_price
167 if average is not None and order.filled_qty:
168 total = (Decimal(str(average)) * order.filled_qty).quantize(Decimal("0.01"))
169 detail += f" Average fill: ${average}. Filled value: ${total}."
170 elif isinstance(payload, OrderIntentReleased):
171 key += f":{event.at.isoformat()}"
172 title = f"{side} {order.symbol} — uncertain intent released"
173 detail = (
174 f"Client order ID {order.client_id} was released by "
175 f"{payload.evidence.actor} "
176 f"after broker-history review: {payload.evidence.reason}. "
177 "The original signal will not be resubmitted; broker lookup continues."
178 )
179 category = "warning"
180 elif isinstance(payload, (LateOrderIncidentOpened, LateOrderIncidentReopened)):
181 key += f":{event.at.isoformat()}"
182 action = "reopened" if isinstance(payload, LateOrderIncidentReopened) else "opened"
183 raw_status = order.raw_broker_status or payload.raw_broker_status
184 title = f"{side} {order.symbol} — late broker order incident {action}"
185 detail = (
186 f"Released client ID {order.client_id} appeared at Alpaca as broker order "
187 f"{order.broker_id} with status '{raw_status}' and "
188 f"{order.filled_qty} filled shares. "
189 "All new buys are halted until offline operator clearance follows a fresh matched "
190 "position audit. Reconciliation and safe matched-lot exits continue."
191 )
192 category = "critical"
193 elif isinstance(payload, LateOrderIncidentCleared):
194 key += f":{event.at.isoformat()}"
195 title = f"{side} {order.symbol} — late broker order incident cleared"
196 audit_ref = payload.evidence.matched_audit_ref or "recorded evidence"
197 detail = (
198 f"{payload.evidence.actor} cleared client ID {order.client_id} after a "
199 f"matched position audit ({audit_ref}). "
200 f"Reason: {payload.evidence.reason}."
201 )
202 elif isinstance(payload, (SubmissionUncertain, SubmitError)):
203 title = f"{side} {order.symbol} — submission {order.status}"
204 detail = "Broker reconciliation will determine the outcome. Do not submit a duplicate."
205 if order.status == "rejected": 205 ↛ 206line 205 didn't jump to line 206 because the condition on line 205 was never true
206 http_status = payload.http_status if isinstance(payload, SubmitError) else None
207 reason = payload.reason if isinstance(payload, SubmitError) else None
208 detail = f"Alpaca rejected submission (HTTP {http_status})."
209 if reason:
210 detail = f"Alpaca rejected it: {reason} (HTTP {http_status})."
211 key += f":{order.status}"
212 category = "warning"
213 elif isinstance(payload, SubmissionAborted): 213 ↛ 214line 213 didn't jump to line 214 because the condition on line 213 was never true
214 title = f"{side} {order.symbol} — trade skipped before submission"
215 detail = REASONS.get(payload.reason, payload.reason)
216 detail += ". No broker request was sent."
217 category = "warning"
218 elif isinstance(payload, CancelRequested):
219 title = f"{side} {order.symbol} — cancellation requested"
220 detail = "Cancellation is not yet confirmed. An order update will report the result."
221 else:
222 return None
223 else:
224 return None
225 return NotificationIntent(
226 key=key,
227 stream_id=signal_id,
228 payload=NotificationPayload(
229 labels={
230 "alertname": "TradeActivity",
231 "system": "copytrade",
232 "job": "execution",
233 "severity": category,
234 "signal_id": signal_id,
235 "notification_id": key,
236 },
237 annotations={
238 "summary": title,
239 "evidence": detail,
240 "source_excerpt": " ".join(message.text.split())[:240],
241 "signal_id": signal_id,
242 "source_time": message.timestamp.isoformat(),
243 "trace_id": hashlib.sha256(signal_id.encode()).hexdigest()[:32],
244 },
245 starts_at=event.at,
246 ),
247 )
250def _plural(count: int, word: str) -> str:
251 return f"{count} {word}" if count == 1 else f"{count} {word}s"
254def _read_back_notification(payload: ReadBackSummary, event: JournalEvent) -> NotificationIntent:
255 """One message for every post read back after CopyTrading was off, not one per post."""
256 key = f"read-back:{event.at.isoformat()}"
257 title = f"Read {_plural(payload.posts, 'post')} posted while CopyTrading was off"
258 detail = (
259 f"{_plural(payload.sells_copied, 'sell')} copied, "
260 f"{_plural(payload.buys_too_old, 'buy')} too old to copy"
261 )
262 return NotificationIntent(
263 key=key,
264 stream_id="read-back",
265 payload=NotificationPayload(
266 labels={
267 "alertname": "TradeActivity",
268 "system": "copytrade",
269 "job": "execution",
270 "severity": "info",
271 "signal_id": "read-back",
272 "notification_id": key,
273 },
274 annotations={
275 "summary": title,
276 "evidence": detail,
277 "source_excerpt": "",
278 "signal_id": "read-back",
279 "source_time": event.at.isoformat(),
280 "trace_id": hashlib.sha256(key.encode()).hexdigest()[:32],
281 },
282 starts_at=event.at,
283 ),
284 )