Coverage for src/copytrading_engine/parsing/application.py: 92%
153 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"""Extraction use case, independent of model provider and message transport."""
3import datetime as dt
4from collections.abc import Sequence
5from decimal import Decimal
6from typing import Literal
8from copytrading_engine.parsing.contracts import RawMessage as _RawMessage
9from copytrading_engine.parsing.extraction import (
10 PROMPT_VERSION,
11 DecodeError,
12 Decoder,
13 GroundingError,
14 check_reading,
15 exit_basis,
16 normalize,
17 same_side,
18)
19from copytrading_engine.parsing.history import RecentCall
20from copytrading_engine.parsing.routes import Route
21from copytrading_engine.shared import reading as r
22from copytrading_engine.shared.signals import (
23 Evidence,
24 Instruction,
25 StockSignal,
26 StopCall,
27 same_fraction,
28)
31def outcome(
32 event: _RawMessage,
33 decision: Literal["trade", "ignore", "review"],
34 reason: str,
35 *,
36 model: str,
37 instructions: Sequence[Instruction] = (),
38 evidence: Sequence[Evidence] = (),
39 stops: Sequence[StopCall] = (),
40 guru_id: str | None = None,
41 profile_revision: str | None = None,
42 reading: r.PostReading | None = None,
43 suggested: Sequence[Instruction] = (),
44) -> StockSignal:
45 return StockSignal(
46 reading=reading,
47 suggested=tuple(suggested),
48 source=event.source,
49 channel_id=event.channel_id,
50 author_id=event.author_id,
51 id=event.id,
52 timestamp=event.timestamp,
53 text=event.text,
54 parser_profile=PROMPT_VERSION,
55 model=model,
56 guru_id=guru_id,
57 profile_revision=profile_revision,
58 decision=decision,
59 reason=reason,
60 instructions=tuple(instructions),
61 evidence=tuple(evidence),
62 stops=tuple(stops),
63 )
66def without_model(event: _RawMessage, route: Route, model: str) -> StockSignal | None:
67 """Settle an empty post before reserving a paid provider attempt."""
68 text = normalize(event.text).strip()
69 if not text:
70 return outcome(
71 event,
72 "review",
73 "no_text_to_decode",
74 model=model,
75 guru_id=route.guru_id,
76 profile_revision=route.profile_revision,
77 )
78 return None
81async def transform(
82 event: _RawMessage,
83 route: Route,
84 decoder: Decoder,
85 model: str,
86 recent: tuple[RecentCall, ...] = (),
87) -> StockSignal:
88 local = without_model(event, route, model)
89 if local is not None: 89 ↛ 90line 89 didn't jump to line 90 because the condition on line 89 was never true
90 return local
91 text = normalize(event.text).strip()
92 answer = await decoder.answer(text, route, recent)
93 reading = answer.reading
94 try:
95 check_reading(reading, text, route)
96 except GroundingError as exc:
97 raise DecodeError(
98 "evidence_validation_failed", retryable=False, issues=(exc.issue,)
99 ) from None
100 acted, repeat = _without_repeats(reading, route, recent, event.timestamp)
101 stops: tuple[StopCall, ...] = ()
102 if repeat is not None:
103 decision, reason, calls = (
104 repeat,
105 ("repeats_a_recent_call" if repeat == "ignore" else "repeats_an_earlier_call"),
106 (),
107 )
108 else:
109 decision, reason, calls, stops = _act_on(acted, route.playbook)
110 return outcome(
111 event,
112 decision,
113 reason,
114 model=answer.model or model,
115 instructions=tuple(call for call, _ in calls),
116 evidence=tuple(evidence for _, evidence in calls),
117 stops=stops,
118 guru_id=route.guru_id,
119 profile_revision=route.profile_revision,
120 reading=reading,
121 suggested=suggested(reading, route.playbook) if decision == "review" else (),
122 )
125def _without_repeats(
126 reading: r.PostReading,
127 route: Route,
128 recent: tuple[RecentCall, ...],
129 at: dt.datetime,
130) -> tuple[r.PostReading, Literal["ignore", "review"] | None]:
131 """A call the reader says restates one of the guru's recent calls is not a new call while
132 the guru's repeat window is on (ADR-0010): within the window it is dropped, and a post that
133 only restates is ignored; a restatement after the window waits for the owner, who can tell a
134 reminder from a second buy. With the window off, every call is a new call."""
135 window = route.repeat_window_minutes
136 if window is None or not isinstance(reading, r.TradeMade | r.Instruction):
137 return reading, None
138 by_ref = {call.ref: call for call in recent}
139 kept: list[tuple[int, r.Call]] = []
140 for index, call in enumerate(reading.calls):
141 earlier = (
142 None if isinstance(call, r.Stop) or call.repeats is None else by_ref.get(call.repeats)
143 )
144 # A sell is never a re-post of the buy it sells, whatever the reader says, and a call
145 # after the guru traded the other side of that stock is a new call however it reads.
146 if (
147 earlier is None
148 or isinstance(call, r.Stop)
149 or not same_side(earlier, call)
150 or not _same_terms(earlier, call)
151 or _traded_since(earlier, call, recent)
152 ):
153 kept.append((index, call))
154 elif (at - earlier.at).total_seconds() > window * 60:
155 return reading, "review"
156 # A stop beside a buy that was a re-post goes with it; the others keep their buy's new place.
157 survivors = [
158 (old, call)
159 for old, call in kept
160 if not (
161 isinstance(call, r.Stop)
162 and isinstance(call.protects, r.Alongside)
163 and call.protects.call not in {index for index, _ in kept}
164 )
165 ]
166 place = {old: new for new, (old, _) in enumerate(survivors)}
167 calls = tuple(
168 call.model_copy(update={"protects": r.Alongside(call=place[call.protects.call])})
169 if isinstance(call, r.Stop) and isinstance(call.protects, r.Alongside)
170 else call
171 for _, call in survivors
172 )
173 if not calls:
174 return reading, "ignore"
175 return reading.model_copy(update={"calls": calls}), None
178def _same_terms(earlier: RecentCall, call: r.Buy | r.Sell) -> bool:
179 """A re-post states the earlier call's price and size again; "Closed SOFI" after "Sold half
180 SOFI" at the same price is the rest of the position, a new call whatever the reader says, and
181 so is "Sold all F 12.30" after "出掉12.41的f 12.30", which sold only the buy at 12.41, and
182 "Bought $200 of F" after "Bought $100 of F" at the same price.
183 Terms the post leaves out, or the earlier call doesn't record, don't count against it."""
184 if isinstance(call.price, r.Exact) and earlier.price is not None: 184 ↛ 187line 184 didn't jump to line 187 because the condition on line 184 was always true
185 if call.price.value != earlier.price:
186 return False
187 if isinstance(call, r.Sell):
188 lot = call.sell_from.buy_price if isinstance(call.sell_from, r.Lot) else None
189 if lot != earlier.entry_price:
190 return False
191 match call.share:
192 case r.All():
193 return earlier.action == "close"
194 case r.Fraction(value=value): 194 ↛ 196line 194 didn't jump to line 196 because the pattern on line 194 always matched
195 return earlier.action == "reduce" and same_fraction(earlier.fraction, value)
196 case _:
197 return True
198 if isinstance(call.size, r.Fraction):
199 return same_fraction(earlier.fraction, call.size.value)
200 if isinstance(call.size, r.Dollars): 200 ↛ 202line 200 didn't jump to line 202 because the condition on line 200 was always true
201 return earlier.usd_amount == call.size.value
202 if isinstance(call.size, r.NotGiven):
203 return earlier.fraction is None and earlier.usd_amount is None
204 return True
207def _traded_since(
208 earlier: RecentCall, call: r.Buy | r.Sell, recent: tuple[RecentCall, ...]
209) -> bool:
210 """The guru bought or sold this stock the other way after `earlier`: a sell after a new buy,
211 or a buy after a sell, is a new call even when it reads the same as the earlier one."""
212 return any(
213 other.symbol == earlier.symbol and other.at > earlier.at and not same_side(other, call)
214 for other in recent
215 )
218class _Wait(Exception):
219 """A call the engine cannot place as written; the post waits for the owner."""
221 def __init__(self, reason: str) -> None:
222 self.reason = reason
223 super().__init__(reason)
226def _act_on(
227 reading: r.PostReading, playbook: str
228) -> tuple[
229 Literal["trade", "ignore", "review"],
230 str,
231 tuple[tuple[Instruction, Evidence], ...],
232 tuple[StopCall, ...],
233]:
234 """Act or ask (ADR-0007): a trade made or an instruction with every call placeable trades;
235 conditionals, suggestions, a range, a buy with no exact price, and a vague trim wait for the
236 owner; commentary and chatter are ignored. A stop the guru posts rides with the trade."""
237 match reading:
238 case r.Commentary():
239 return "ignore", reading.summary, (), ()
240 case r.Chatter(): 240 ↛ 241line 240 didn't jump to line 241 because the pattern on line 240 never matched
241 return "ignore", "chatter", (), ()
242 case r.Unclear():
243 return "review", "unclear", (), ()
244 case r.Conditional() | r.Suggestion():
245 return "review", reading.kind, (), ()
246 case r.TradeMade() | r.Instruction(): 246 ↛ exitline 246 didn't return from function '_act_on' because the pattern on line 246 always matched
247 try:
248 calls = tuple(
249 _placeable(call, playbook)
250 for call in reading.calls
251 if not isinstance(call, r.Stop)
252 )
253 except _Wait as wait:
254 return "review", wait.reason, (), ()
255 return "trade", reading.summary, calls, _stops(reading.calls)
258def _stops(calls: tuple[r.Call, ...]) -> tuple[StopCall, ...]:
259 """The stops among a post's calls, each beside the instruction its buy becomes: the buys and
260 sells of a post become instructions in order, and the stops are kept apart from them."""
261 instruction_at = {
262 index: place
263 for place, index in enumerate(
264 index for index, call in enumerate(calls) if not isinstance(call, r.Stop)
265 )
266 }
267 stops = []
268 for call in calls:
269 if not isinstance(call, r.Stop):
270 continue
271 protects = call.protects
272 stops.append(
273 StopCall(
274 symbol=call.stock.ticker,
275 stop_price=call.price.value,
276 entry_price=protects.buy_price if isinstance(protects, r.Lot) else None,
277 buy_part=(
278 instruction_at[protects.call] if isinstance(protects, r.Alongside) else None
279 ),
280 action_evidence=call.action_words,
281 symbol_evidence=call.stock.words,
282 price_evidence=call.price.words,
283 entry_evidence=protects.words if isinstance(protects, r.Lot) else None,
284 )
285 )
286 return tuple(stops)
289def _placeable(call: r.Buy | r.Sell, playbook: str) -> tuple[Instruction, Evidence]:
290 """The engine's call for a stated one, with the post's words behind each field. Raises
291 _Wait when it cannot be placed without the owner."""
292 instruction = _instruction(call, playbook, owner=False)
293 if isinstance(call, r.Buy):
294 fraction_words = call.size.words if isinstance(call.size, r.Fraction) else None
295 usd_words = call.size.words if isinstance(call.size, r.Dollars) else None
296 entry_words = None
297 else:
298 assert not isinstance(call.share, r.NotGiven) # _instruction waits on it
299 fraction_words = call.share.words
300 usd_words = None
301 entry_words = (
302 call.sell_from.words
303 if instruction.entry_price is not None and isinstance(call.sell_from, r.Lot)
304 else None
305 )
306 evidence = Evidence(
307 **instruction.model_dump(),
308 action_evidence=call.action_words,
309 symbol_evidence=call.stock.words,
310 # A sell at the market has no price to cite (_instruction waits on any other price).
311 price_evidence=call.price.words if isinstance(call.price, r.Exact) else None,
312 entry_evidence=entry_words,
313 fraction_evidence=fraction_words,
314 usd_amount_evidence=usd_words,
315 )
316 return instruction, evidence
319def suggested(reading: r.PostReading | None, playbook: str) -> tuple[Instruction, ...]:
320 """What Copy places for a post that waits for the owner (ADR-0007, ADR-0010): each call the
321 owner can copy as read, a range at its top and a batch at the full position, trimmed by the
322 account's limits. A buy with no price, or a sell that states no share, has nothing to copy;
323 the owner enters it or sells the lot from Accounts."""
324 if not isinstance(reading, r.TradeMade | r.Instruction | r.Conditional | r.Suggestion):
325 return ()
326 calls = []
327 for call in reading.calls:
328 if isinstance(call, r.Stop): 328 ↛ 329line 328 didn't jump to line 329 because the condition on line 328 was never true
329 continue # a stop is never copied by hand: it would sell at once (ADR-0015)
330 try:
331 calls.append(_instruction(call, playbook, owner=True))
332 except _Wait:
333 continue
334 return tuple(calls)
337def _instruction(call: r.Buy | r.Sell, playbook: str, *, owner: bool) -> Instruction:
338 """One call as the engine places it (ADR-0007, ADR-0010). On its own (`owner=False`) the
339 engine waits for the owner on a range and on a sell that states no share; when the owner
340 copies, a range buys at its top. A sell with no price, or one at the market, sells at the
341 market when placed ("sell wmt half"): the guru is getting out now, and the limit under the
342 live bid bounds it. A buy needs the guru's price, which bounds what the copy pays. A buy with
343 no size asks for the full position, and one whose size is a batch the playbook gives no share
344 waits; a sell that names a buy price sells from the buys at that price, and one that names
345 none from every buy; a share counts from what is left unless the post or the playbook says
346 the original buy, which code decides (`exit_basis`)."""
347 price: Decimal | None
348 match call.price:
349 case r.Exact(value=price):
350 pass
351 case r.Range(high=high) if owner:
352 price = high
353 case r.Range():
354 raise _Wait("price_range")
355 case r.AtMarket() | r.NotGiven() if isinstance(call, r.Sell):
356 price = None
357 case r.AtMarket():
358 raise _Wait("price_at_market")
359 case _:
360 raise _Wait("price_not_given")
361 if isinstance(call, r.Buy):
362 # A batch the playbook gives no size waits like a vague trim: "the second batch" is a
363 # share of a position, not the whole of one. The owner copying it chooses the size.
364 if isinstance(call.size, r.Batch) and not owner:
365 raise _Wait("batch_size_not_given")
366 fraction = call.size.value if isinstance(call.size, r.Fraction) else None
367 usd_amount = call.size.value if isinstance(call.size, r.Dollars) else None
368 return Instruction(
369 action="buy",
370 symbol=call.stock.ticker,
371 price=price,
372 fraction=fraction,
373 usd_amount=usd_amount,
374 )
375 if isinstance(call.share, r.NotGiven):
376 raise _Wait("sell_share_not_given")
377 share = Decimal(1) if isinstance(call.share, r.All) else call.share.value
378 return Instruction(
379 action="close" if share == 1 else "reduce",
380 symbol=call.stock.ticker,
381 price=price,
382 entry_price=call.sell_from.buy_price if isinstance(call.sell_from, r.Lot) else None,
383 fraction=share,
384 exit_basis=(
385 "original_position"
386 if exit_basis(call, playbook) == "original"
387 else "remaining_position"
388 ),
389 )