Coverage for src/copytrading_engine/shared/reading.py: 94%
86 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"""What a guru's post says, in one shape for every guru (ADR-0007).
3The reader model fills this in; plain code decides what to do with it. Each choice is a tagged
4alternative, so a combination that makes no sense, such as an exact price and a range, or a batch
5and a fraction, cannot be written down. Every stated value carries the post's own words beside
6it, so a value without its evidence cannot exist. A field the post does not state is `NotGiven`
7or `NotSaid`; nothing is filled in for the guru.
8"""
10import re
11from decimal import Decimal
12from typing import Annotated, Literal, Self
14from pydantic import BaseModel, BeforeValidator, ConfigDict, Field, model_validator
16from copytrading_engine.shared.symbols import SYMBOL_PATTERN, crypto_pair
18Words = Annotated[str, Field(min_length=1, max_length=200)]
19"""The post's exact words behind a value."""
21# Up to a coin's price, such as bitcoin's (signals.MAX_PRICE).
22Money = Annotated[Decimal, Field(gt=0, le=10_000_000, allow_inf_nan=False)]
23_WRITTEN_PAIR = re.compile(r"[A-Za-z]{2,10}[/-]?(?:USDT|USDC|USD)", re.IGNORECASE)
26def _pair(value: object) -> object:
27 """A coin the reader writes as a pair in another spelling (BTCUSD, btc-usd) is its pair,
28 BTC/USD. A bare ticker is left alone: BTC is an ETF as well as a coin."""
29 if isinstance(value, str) and _WRITTEN_PAIR.fullmatch(value.strip()):
30 return crypto_pair(value) or value
31 return value
34# A stock, or a coin's US dollar pair (shared.symbols).
35Ticker = Annotated[str, BeforeValidator(_pair), Field(pattern=SYMBOL_PATTERN)]
38class _Part(BaseModel):
39 model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True)
42class NotGiven(_Part):
43 """The post does not state this."""
45 kind: Literal["not_given"] = "not_given"
48class Exact(_Part):
49 kind: Literal["exact"] = "exact"
50 value: Money
51 words: Words
54class Range(_Part):
55 """A zone such as 160-179."""
57 kind: Literal["range"] = "range"
58 low: Money
59 high: Money
60 low_words: Words
61 high_words: Words
63 @model_validator(mode="after")
64 def low_to_high(self) -> Self:
65 if self.low >= self.high:
66 raise ValueError("A price range runs from low to high")
67 return self
70class AtMarket(_Part):
71 """Buy or sell now, at whatever the market is, as the post says."""
73 kind: Literal["at_market"] = "at_market"
74 words: Words
77type Price = Annotated[Exact | Range | AtMarket | NotGiven, Field(discriminator="kind")]
80def _exact_fraction(value: object) -> object:
81 """A value written as a ratio, "1/6", is that exact fraction: a model may write it either way,
82 and a rounded decimal such as 0.1667 would no longer match the post's own 1/6."""
83 if isinstance(value, str) and (match := re.fullmatch(r"\s*(\d+)\s*/\s*(\d+)\s*", value)): 83 ↛ 84line 83 didn't jump to line 84 because the condition on line 83 was never true
84 numerator, denominator = (int(group) for group in match.groups())
85 if denominator:
86 return Decimal(numerator) / Decimal(denominator)
87 return value
90class Fraction(_Part):
91 """A share of a full position, as written: 6分之一, half, 1/3."""
93 kind: Literal["fraction"] = "fraction"
94 value: Annotated[
95 Decimal, BeforeValidator(_exact_fraction), Field(gt=0, le=1, allow_inf_nan=False)
96 ]
97 words: Words
100class Batch(_Part):
101 """The guru's Nth batch, such as 第二批."""
103 kind: Literal["batch"] = "batch"
104 number: Annotated[int, Field(ge=1, le=20)]
105 words: Words
108class Dollars(_Part):
109 """A dollar amount to put in, as written: $200 of, 200$, 200 dollars, 两百刀."""
111 kind: Literal["dollars"] = "dollars"
112 value: Money
113 words: Words
116type Size = Annotated[Fraction | Batch | Dollars | NotGiven, Field(discriminator="kind")]
119class All(_Part):
120 """Everything this sell refers to, such as 出掉 or 跑路."""
122 kind: Literal["all"] = "all"
123 words: Words
126# A vague trim ("trimmed", 减仓) states no share; it waits for the owner (ADR-0010).
127type Share = Annotated[Fraction | All | NotGiven, Field(discriminator="kind")]
130class Lot(_Part):
131 """The buy a sell names by its price, such as the 39.5 in 出一半39.5的iren."""
133 kind: Literal["lot"] = "lot"
134 buy_price: Money
135 words: Words
138class NotSaid(_Part):
139 """The sell does not say which buy it comes from."""
141 kind: Literal["not_said"] = "not_said"
144type SellFrom = Annotated[Lot | NotSaid, Field(discriminator="kind")]
147class Alongside(_Part):
148 """The stop protects the buy this same post makes, as in 43.4加了3分之一常规仓soxl 止损放38.4.
149 `call` is that buy's place among the post's calls."""
151 kind: Literal["alongside"] = "alongside"
152 call: Annotated[int, Field(ge=0, le=19)]
155# Which shares a stop protects: the buys at a price the post names, the buy the post itself makes,
156# or (not said) every share CopyTrading bought of the stock for this guru.
157type Protects = Annotated[Lot | Alongside | NotSaid, Field(discriminator="kind")]
160class Stock(_Part):
161 """The ticker, or a coin's US dollar pair (BTC/USD), and the post's words for it: the ticker
162 itself, a coin's ticker or name (BTC, bitcoin, 比特币), or a name the playbook maps."""
164 ticker: Ticker
165 words: Words
168# A recent call of the guru's, as the reader was shown it: c1, c2, … (ADR-0010).
169type CallRef = Annotated[str, Field(pattern=r"^c[0-9]{1,4}$")]
172class Buy(_Part):
173 action: Literal["buy"] = "buy"
174 action_words: Words
175 stock: Stock
176 price: Price
177 size: Size
178 # The recent call this one restates, when the post re-posts it rather than making a new one.
179 repeats: CallRef | None = None
182class Sell(_Part):
183 action: Literal["sell"] = "sell"
184 action_words: Words
185 stock: Stock
186 price: Price
187 share: Share
188 # Whether a share counts from the original buy or from what is left; None when the post does
189 # not say, which leaves it to the guru's playbook default. "original" departs from the
190 # default, so it carries the post's own words for it (counts_from_words).
191 counts_from: Literal["original", "remaining"] | None = None
192 counts_from_words: Words | None = None
193 sell_from: SellFrom
194 repeats: CallRef | None = None
197class Stop(_Part):
198 """A stop order the guru posts: sell the shares it protects when the price falls to `price`,
199 as in 跌破50.95出剩下的保护 or 止损放38.4. It is never a sell at that price now."""
201 action: Literal["stop"] = "stop"
202 action_words: Words
203 stock: Stock
204 price: Exact
205 protects: Protects
208type Call = Annotated[Buy | Sell | Stop, Field(discriminator="action")]
210Summary = Annotated[str, Field(min_length=1, max_length=300)]
211Calls = Annotated[tuple[Call, ...], Field(min_length=1, max_length=20)]
214class TradeMade(_Part):
215 """The guru did it: 加了, 出掉, 买了, 跑路了."""
217 kind: Literal["trade_made"] = "trade_made"
218 summary: Summary
219 calls: Calls
222class Instruction(_Part):
223 """Do it now: buy NVDA here."""
225 kind: Literal["instruction"] = "instruction"
226 summary: Summary
227 calls: Calls
230class Conditional(_Part):
231 """If something happens, the guru would trade: 如果明天20以下我会买第一批."""
233 kind: Literal["conditional"] = "conditional"
234 summary: Summary
235 condition: Words
236 calls: Calls
239class Suggestion(_Part):
240 """Consider it, or a zone to trade in: 建仓区域160-179, 可以考虑一点."""
242 kind: Literal["suggestion"] = "suggestion"
243 summary: Summary
244 calls: Calls
247class Commentary(_Part):
248 """Market talk with nothing to trade."""
250 kind: Literal["commentary"] = "commentary"
251 summary: Summary
254class Chatter(_Part):
255 """Small talk with nothing about stocks or the market: a greeting, a reaction, an emoji. It
256 has no words to cite."""
258 kind: Literal["chatter"] = "chatter"
261class Unclear(_Part):
262 """The reader cannot tell what the post means; a person should look."""
264 kind: Literal["unclear"] = "unclear"
265 summary: Summary
268type ReaderReading = Annotated[
269 TradeMade | Instruction | Conditional | Suggestion | Commentary | Unclear,
270 Field(discriminator="kind"),
271]
272"""What the reader writes. Chat is not a reading: the reader says it through its own output,
273which carries nothing, and the engine stores it as `Chatter` (ADR-0012)."""
275type PostReading = Annotated[
276 TradeMade | Instruction | Conditional | Suggestion | Commentary | Chatter | Unclear,
277 Field(discriminator="kind"),
278]