Coverage for src/copytrading_engine/shared/signals.py: 84%
108 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"""Version 2 signal contract, for stocks and coins. Prices and quantities are decimal strings."""
3from decimal import Decimal
4from typing import Literal, Self
6from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, model_validator
7from pydantic_core import PydanticCustomError
9from copytrading_engine.shared.reading import PostReading
10from copytrading_engine.shared.route_keys import guru_for_channel
11from copytrading_engine.shared.symbols import SYMBOL_PATTERN
13# The highest price a call may carry: a coin's, such as bitcoin's, runs above any stock's.
14MAX_PRICE = Decimal(10_000_000)
15# Models write 1/6 as 0.16666666666666666; Decimal division gives 28 digits. Same fraction.
16FRACTION_TOLERANCE = Decimal("1e-9")
19def same_fraction(first: Decimal | None, second: Decimal | None) -> bool:
20 """Both absent, or equal within rounding."""
21 if first is None or second is None:
22 return first is second
23 return abs(first - second) <= FRACTION_TOLERANCE
26class SourceIdentityConflict(ValueError):
27 """An existing source message identity was reused with different content."""
30class Instruction(BaseModel):
31 model_config = ConfigDict(frozen=True, extra="forbid")
33 def same_call(self, other: Instruction) -> bool:
34 """The same instruction, its fraction equal within rounding however it was written. What
35 a sell's share counts from is how the post was read, not what the guru called: the same
36 sell read once from what is left and once from the original buy is still one sell."""
37 return same_fraction(self.fraction, other.fraction) and (
38 self.model_copy(update={"fraction": other.fraction, "exit_basis": other.exit_basis})
39 == other
40 )
42 action: Literal["buy", "reduce", "close"]
43 # A stock, or a coin's US dollar pair (shared.symbols).
44 symbol: str = Field(pattern=SYMBOL_PATTERN)
45 # The guru's price. A sell the post gives no price, or says is at the market, has none: it
46 # sells at the market when it is placed, as a limit just under the live bid (ADR-0007).
47 price: Decimal | None = Field(gt=0, le=MAX_PRICE)
48 entry_price: Decimal | None = Field(default=None, gt=0, le=MAX_PRICE)
49 fraction: Decimal | None = Field(default=None, gt=0, le=1, allow_inf_nan=False)
50 # A buy the post sizes in dollars ("$200 of NFLX"): that amount, never more than the account's
51 # full position for the guru, instead of a share of the full position.
52 usd_amount: Decimal | None = Field(default=None, gt=0, le=100000, allow_inf_nan=False)
53 # An exit's share counts from what is left of the buys it sells from, unless the post or the
54 # playbook says the original buy (ADR-0010).
55 exit_basis: Literal["original_position", "remaining_position"] | None = None
57 @model_validator(mode="after")
58 def validate_reference(self) -> Self:
59 # An exit with no entry price sells from every open buy of the stock; with one, from the
60 # buys at exactly that price (ADR-0010).
61 if self.action == "buy" and self.entry_price is not None: 61 ↛ 62line 61 didn't jump to line 62 because the condition on line 61 was never true
62 raise PydanticCustomError(
63 "entry_has_lot_reference", "An entry cannot reference an existing lot"
64 )
65 if self.action == "buy" and self.price is None:
66 raise ValueError("A buy needs the guru's price")
67 if self.action != "buy" and self.fraction is None: 67 ↛ 68line 67 didn't jump to line 68 because the condition on line 67 was never true
68 raise ValueError("An exit requires an explicit fraction")
69 if self.action == "close" and self.fraction != 1: 69 ↛ 70line 69 didn't jump to line 70 because the condition on line 69 was never true
70 raise ValueError("A close uses all remaining shares")
71 if self.usd_amount is not None and (self.action != "buy" or self.fraction is not None): 71 ↛ 72line 71 didn't jump to line 72 because the condition on line 71 was never true
72 raise ValueError("Only a buy states a dollar amount, and never with a fraction")
73 if self.action == "buy" and self.exit_basis is not None: 73 ↛ 74line 73 didn't jump to line 74 because the condition on line 73 was never true
74 raise ValueError("Entry instructions cannot carry an exit basis")
75 return self
78class Evidence(Instruction):
79 action_evidence: str = Field(min_length=1, max_length=100)
80 symbol_evidence: str = Field(min_length=1, max_length=30)
81 # None for a sell at the market: there is no price to cite. "At market" words, when the post
82 # has them, are in the reading.
83 price_evidence: str | None = Field(min_length=1, max_length=30)
84 entry_evidence: str | None = Field(default=None, max_length=30)
85 fraction_evidence: str | None = Field(default=None, max_length=30)
86 usd_amount_evidence: str | None = Field(default=None, max_length=30)
88 @model_validator(mode="after")
89 def validate_price_evidence(self) -> Self:
90 if (self.price is None) != (self.price_evidence is None):
91 raise ValueError("A stated price needs its words, and only a stated price has them")
92 if (self.usd_amount is None) != (self.usd_amount_evidence is None): 92 ↛ 93line 92 didn't jump to line 93 because the condition on line 92 was never true
93 raise ValueError("A dollar amount needs its words, and only a dollar amount has them")
94 return self
97class StopCall(BaseModel):
98 """A stop order the guru posted: sell the shares it protects if the price falls to
99 `stop_price`. It protects the buys at `entry_price`, the buy this post's `buy_part`-th
100 instruction makes, or, with neither, every share CopyTrading bought of the stock for this
101 guru. Each value carries the post's own words."""
103 model_config = ConfigDict(frozen=True, extra="forbid")
105 symbol: str = Field(pattern=SYMBOL_PATTERN)
106 stop_price: Decimal = Field(gt=0, le=MAX_PRICE)
107 entry_price: Decimal | None = Field(default=None, gt=0, le=MAX_PRICE)
108 buy_part: int | None = Field(default=None, ge=0)
109 action_evidence: str = Field(min_length=1, max_length=100)
110 symbol_evidence: str = Field(min_length=1, max_length=30)
111 price_evidence: str = Field(min_length=1, max_length=30)
112 entry_evidence: str | None = Field(default=None, max_length=30)
114 @model_validator(mode="after")
115 def validate_protects(self) -> Self:
116 if self.entry_price is not None and self.buy_part is not None: 116 ↛ 117line 116 didn't jump to line 117 because the condition on line 116 was never true
117 raise ValueError("A stop names a buy by its price or its place in the post, not both")
118 if (self.entry_price is None) != (self.entry_evidence is None): 118 ↛ 119line 118 didn't jump to line 119 because the condition on line 118 was never true
119 raise ValueError("A named buy price needs its words, and only a named price has them")
120 return self
123class StockSignal(BaseModel):
124 # Posts stored by a release that had the chat filter carry its `sorted_by` and
125 # `sorted_confidence`; reading ignores them. A before-validator would drop them too, but it
126 # makes pydantic validate the nested models of a JSON document in Python mode, which their
127 # strict tuples refuse.
128 model_config = ConfigDict(extra="ignore", frozen=True, hide_input_in_errors=True)
129 schema_version: Literal[2] = 2
130 event_type: Literal["stock_signal"] = "stock_signal"
131 source: str = Field(pattern=r"^[a-z][a-z0-9_-]*$")
132 channel_id: str = Field(pattern=r"^[a-zA-Z0-9_-]+$")
133 author_id: str | None = Field(default=None, pattern=r"^[0-9]{1,32}$")
134 id: str = Field(pattern=r"^[a-zA-Z0-9_-]+$")
135 timestamp: AwareDatetime
136 text: str = Field(max_length=50000)
137 parser_profile: str
138 model: str
139 guru_id: str | None = Field(default=None, pattern=r"^[a-zA-Z0-9_-]{1,64}$")
140 profile_revision: str | None = Field(default=None, pattern=r"^[0-9a-f]{64}$")
141 decision: Literal["trade", "ignore", "review"]
142 reason: str = Field(min_length=1, max_length=300)
143 # How the reader read the post (ADR-0007); absent on signals read before it, or never sent
144 # to the reader.
145 reading: PostReading | None = None
146 # For a post that waits for the owner: what Copy places, as the reader read it (ADR-0007).
147 suggested: tuple[Instruction, ...] = Field(default=(), max_length=20)
148 evidence: tuple[Evidence, ...] = Field(max_length=20)
149 instructions: tuple[Instruction, ...] = Field(max_length=20)
150 # Stops the guru posted, placed only when the account follows the guru's stops.
151 stops: tuple[StopCall, ...] = Field(default=(), max_length=20)
153 @property
154 def guru(self) -> str | None:
155 """Whose post this is: its channel's guru. `guru_id` is the ID the setup gave the guru
156 when the post was read, which a setup made before IDs came from the channel may differ
157 from; a post nobody was copied from has none."""
158 return None if self.guru_id is None else guru_for_channel(self.source, self.channel_id)
160 @model_validator(mode="after")
161 def validate_decision(self) -> Self:
162 if (self.guru_id is None) != (self.profile_revision is None): 162 ↛ 163line 162 didn't jump to line 163 because the condition on line 162 was never true
163 raise ValueError("Guru identity and profile revision must be recorded together")
164 if (self.decision == "trade") != bool(self.instructions or self.stops):
165 raise ValueError("Only validated trade decisions contain instructions")
166 for stop in self.stops:
167 if stop.buy_part is not None and not (
168 stop.buy_part < len(self.instructions)
169 and self.instructions[stop.buy_part].action == "buy"
170 and self.instructions[stop.buy_part].symbol == stop.symbol
171 ):
172 raise ValueError("A stop protects a buy of its own stock in the same post")
173 if self.suggested and self.decision != "review": 173 ↛ 174line 173 didn't jump to line 174 because the condition on line 173 was never true
174 raise ValueError("Only a post that waits for the owner suggests calls to copy")
175 if len(self.evidence) != len(self.instructions): 175 ↛ 176line 175 didn't jump to line 176 because the condition on line 175 was never true
176 raise ValueError("Every instruction requires evidence")
177 for instruction, evidence in zip(self.instructions, self.evidence, strict=True):
178 for field in Instruction.model_fields:
179 if getattr(instruction, field) != getattr(evidence, field): 179 ↛ 180line 179 didn't jump to line 180 because the condition on line 179 was never true
180 raise ValueError("Instruction differs from its validated evidence")
181 return self