Coverage for src/copytrading_engine/parsing/notifications.py: 94%
53 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"""Human-readable parser decisions; transport and persistence are separate adapters."""
3import hashlib
4from datetime import datetime
6from pydantic import AwareDatetime, TypeAdapter
8from copytrading_engine.parsing.diagnostics import ValidationIssue
9from copytrading_engine.shared.notification_models import NotificationIntent, NotificationPayload
10from copytrading_engine.shared.reading import Chatter
11from copytrading_engine.shared.signals import Instruction, StockSignal
13_SOURCE_TIMESTAMP_SERIALIZER = TypeAdapter(AwareDatetime)
16def _serialize_source_timestamp(value: datetime) -> str:
17 serialized = _SOURCE_TIMESTAMP_SERIALIZER.dump_python(value, mode="json")
18 if not isinstance(serialized, str): 18 ↛ 19line 18 didn't jump to line 19 because the condition on line 18 was never true
19 raise TypeError("Source timestamp did not serialize to text")
20 return serialized
23# Why a post waits for the owner (ADR-0007, ADR-0010), as the alert says it.
24WAITING = {
25 "conditional": "The guru would trade only if something happens",
26 "suggestion": "The guru suggested it but didn't trade",
27 "unclear": "The post's meaning wasn't clear",
28 "price_range": "The guru gave a price range",
29 "price_at_market": "The guru said to trade at the market price",
30 "price_not_given": "The post gave no price",
31 "sell_share_not_given": "The sell doesn't say how much",
32 "batch_size_not_given": "The playbook doesn't say how big a batch is",
33 "repeats_an_earlier_call": "The post repeats an earlier call of the guru's",
34}
37def _call(instruction: Instruction) -> str:
38 action = {"buy": "Buy", "reduce": "Sell part of", "close": "Sell"}[instruction.action]
39 price = f"${instruction.price}" if instruction.price is not None else "the market"
40 return f"{action} {instruction.symbol} at {price}"
43def waiting_notification(
44 key: str, result: StockSignal, *, observed_at: datetime | None = None
45) -> NotificationIntent:
46 """A post that waits for the owner: what it says, why it waits, and what Copy places."""
47 reading = result.reading
48 summary = (
49 reading.summary
50 if reading is not None and not isinstance(reading, Chatter)
51 else result.reason
52 )
53 copy = "; ".join(_call(instruction) for instruction in result.suggested)
54 return NotificationIntent(
55 key=key,
56 stream_id=key,
57 payload=NotificationPayload(
58 labels={
59 "alertname": "SignalWaiting",
60 "system": "copytrade",
61 "job": "stock-parser",
62 "severity": "warning",
63 "signal_id": key,
64 },
65 annotations={
66 "summary": f"Waiting for you: {summary}"[:300],
67 "evidence": WAITING[result.reason] + ".",
68 "impact": (
69 f"Copy places: {copy}. Nothing is placed unless you copy it."
70 if copy
71 else "Nothing is placed unless you enter the trade yourself."
72 ),
73 "action": "Open Activity to copy or skip it. It expires when its trading day ends.",
74 "signal_id": key,
75 "trace_id": hashlib.sha256(key.encode()).hexdigest()[:32],
76 "reason": result.reason,
77 "source_time": _serialize_source_timestamp(result.timestamp),
78 "source_excerpt": " ".join(result.text.split())[:240],
79 },
80 starts_at=observed_at if observed_at is not None else result.timestamp,
81 ),
82 )
85def review_notification(
86 key: str,
87 result: StockSignal,
88 issues: tuple[ValidationIssue, ...],
89 *,
90 observed_at: datetime | None = None,
91) -> NotificationIntent:
92 # Explanations are bounded source/model data; the Telegram renderer HTML-escapes them.
93 reasons = {
94 "invalid_model_output": "Model output failed schema validation",
95 "model_output_budget_exceeded": "Model output exceeded the response budget",
96 "provider_rejected": "Model provider rejected the request",
97 "provider_key_rejected": "Model provider did not accept the API key",
98 "provider_model_not_found": "Model provider has no model with that name",
99 "decode_attempts_exhausted": "Model requests failed after bounded retries",
100 "stale_signal": "Signal exceeded the permitted processing age",
101 "future_signal": "Source timestamp is ahead of the parser clock beyond the allowed skew",
102 "daily_model_request_budget_exhausted": "Daily model request budget exhausted",
103 "evidence_validation_failed": "Extracted trade did not pass source-evidence checks",
104 "source_not_configured": "Source has no configured parsing route",
105 "no_text_to_decode": "Signal contained no text to interpret",
106 }
107 reason = result.reason if result.reason in reasons else "ambiguous_signal"
108 explanations = {
109 "entry_has_lot_reference": "A buy was incorrectly tied to an existing lot",
110 "exit_missing_lot_reference": "An exit did not identify the original entry lot",
111 "price_not_grounded": "The extracted price could not be verified in the source",
112 "price_occurrence_reused": "One quoted price was incorrectly used for two roles",
113 "action_not_grounded": "The proposed trade action was not supported by the source",
114 }
115 detail = "; ".join(
116 f"{explanations.get(issue.code, 'Validation rejected this field')} "
117 f"({issue.path}: {issue.code})"
118 for issue in issues[:3]
119 )
120 source_at = _serialize_source_timestamp(result.timestamp)
121 observed_at_text = observed_at.isoformat() if observed_at is not None else None
122 return NotificationIntent(
123 key=key,
124 stream_id=key,
125 payload=NotificationPayload(
126 labels={
127 "alertname": "SignalNeedsReview",
128 "system": "copytrade",
129 "job": "stock-parser",
130 "severity": "warning",
131 "signal_id": key,
132 },
133 annotations={
134 "summary": "Signal needs review — automatic trading skipped",
135 "evidence": reasons.get(reason, result.reason)
136 + (f". Validation: {detail}" if detail else "")
137 + ".",
138 "impact": "The parser emitted no trade instructions for this signal. "
139 "No order can be created from this parser result.",
140 "action": (
141 "Check the source timestamp and host clock before deciding what to do. "
142 "Do not rewrite timestamps or replay the alert as a fresh trade."
143 if reason == "future_signal"
144 else "Inspect this signal before deciding what to do. "
145 "Do not replay an old alert as a fresh trade."
146 ),
147 "signal_id": key,
148 "trace_id": hashlib.sha256(key.encode()).hexdigest()[:32],
149 "reason": reason,
150 "source_time": source_at,
151 **({"observed_time": observed_at_text} if observed_at_text is not None else {}),
152 "source_excerpt": " ".join(result.text.split())[:240],
153 },
154 starts_at=observed_at if observed_at is not None else result.timestamp,
155 ),
156 )
159def decision_notification(
160 key: str,
161 result: StockSignal,
162 issues: tuple[ValidationIssue, ...],
163 *,
164 observed_at: datetime | None = None,
165) -> NotificationIntent:
166 if result.decision == "review" and result.reason in WAITING:
167 return waiting_notification(key, result, observed_at=observed_at)
168 if result.decision == "review":
169 return review_notification(key, result, issues, observed_at=observed_at)
170 trade = result.decision == "trade"
171 lines = []
172 for instruction in result.instructions:
173 action = {"buy": "BUY", "reduce": "TRIM", "close": "EXIT"}[instruction.action]
174 line = (
175 f"{action} {instruction.symbol} at source price ${instruction.price}"
176 if instruction.price is not None
177 else f"{action} {instruction.symbol} at the market"
178 )
179 if instruction.action != "buy":
180 line += f"; original entry ${instruction.entry_price}"
181 if instruction.action == "reduce":
182 line += f"; fraction of original lot: {instruction.fraction}"
183 lines.append(line)
184 lines.extend(f"STOP {stop.symbol} at ${stop.stop_price}" for stop in result.stops)
185 detail = "\n".join(lines)
186 if len(detail) > 1800: 186 ↛ 187line 186 didn't jump to line 187 because the condition on line 186 was never true
187 detail = detail[:1800] + "… Full instructions are in the signal trace."
188 source_at = _serialize_source_timestamp(result.timestamp)
189 observed_at_text = observed_at.isoformat() if observed_at is not None else None
190 return NotificationIntent(
191 key=key,
192 stream_id=key,
193 payload=NotificationPayload(
194 labels={
195 "alertname": "SignalDecision",
196 "system": "copytrade",
197 "job": "stock-parser",
198 "severity": "info",
199 "signal_id": key,
200 "notification_id": key,
201 },
202 annotations={
203 "summary": "Trade signal parsed" if trade else "Signal ignored — no trade",
204 "evidence": detail if trade else result.reason,
205 "impact": "Parsing is complete. Risk checks and broker execution are separate; "
206 "this message does not confirm an order or fill."
207 if trade
208 else "No order will be created from this parser decision.",
209 "source_excerpt": " ".join(result.text.split())[:240],
210 "signal_id": key,
211 "source_time": source_at,
212 **({"observed_time": observed_at_text} if observed_at_text is not None else {}),
213 "trace_id": hashlib.sha256(key.encode()).hexdigest()[:32],
214 },
215 starts_at=observed_at if observed_at is not None else result.timestamp,
216 ),
217 )