Coverage for src/copytrading_engine/execution/domain/pricing.py: 91%
36 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"""Deterministic signal pricing policy, independent of quotes and broker clients."""
3import datetime as dt
4from decimal import ROUND_DOWN, ROUND_UP, Decimal
5from typing import Annotated
7from pydantic import BaseModel, ConfigDict, Field
9from copytrading_engine.execution.domain.market import Quote
11# A quote older than this is not the market now.
12QUOTE_MAX_AGE_SECONDS = 30
13# A sell at the market only takes its floor from the bid: an older bid can leave the order resting
14# but never fill it worse, since a limit sell fills at the market's better price. Outside regular
15# hours the free feed stops updating at the close, so the day's last bid is the bid there is; at
16# worst the sell rests at that floor until the market reaches it.
17SELL_FLOOR_QUOTE_MAX_AGE_SECONDS = 6 * 3600
20def quote_problem(
21 quote: Quote, price: Decimal | None, now: dt.datetime, max_age: float = QUOTE_MAX_AGE_SECONDS
22) -> str | None:
23 """Why a quote's price cannot stand for the market now, if it cannot."""
24 if quote.timestamp is None or price is None or price <= 0: 24 ↛ 25line 24 didn't jump to line 25 because the condition on line 24 was never true
25 return "quote_unavailable"
26 age = (now - quote.timestamp).total_seconds()
27 if age < -5 or age > max_age:
28 return "quote_stale"
29 return None
32# How far above the guru's price a buy may fill.
33AboveSignalPct = Annotated[Decimal, Field(ge=0, le=100)]
34# How far below the guru's sell price an exit may fill: a sell is always a limit order, and under
35# 100% so its floor is a price.
36BelowSignalPct = Annotated[Decimal, Field(ge=0, lt=100)]
37DEFAULT_ABOVE_SIGNAL_PCT = Decimal("0")
38DEFAULT_BELOW_SIGNAL_PCT = Decimal("1")
41class PricePolicy(BaseModel):
42 """How far a copy may stray from the guru's price, one rule per side: a buy pays at most
43 its ceiling above it, a sell takes at least its floor below it. Both land on a valid tick:
44 a stock's, or the coin's own `increment`."""
46 model_config = ConfigDict(extra="forbid", frozen=True)
47 max_above_signal_pct: AboveSignalPct = DEFAULT_ABOVE_SIGNAL_PCT
48 max_below_signal_pct: BelowSignalPct = DEFAULT_BELOW_SIGNAL_PCT
50 def buy_ceiling(self, guru_price: Decimal, increment: Decimal | None = None) -> Decimal:
51 """The highest a copied buy pays, rounded down so it never passes the allowance."""
52 ceiling = _checked(guru_price) * (Decimal(1) + self.max_above_signal_pct / Decimal(100))
53 return ceiling.quantize(price_tick(ceiling, increment), rounding=ROUND_DOWN)
55 def sell_floor(self, guru_price: Decimal, increment: Decimal | None = None) -> Decimal:
56 """The lowest a copied sell takes, rounded up so it never passes the allowance. Every
57 sell is a limit order, so a copy never fills far below what the guru got."""
58 floor = _checked(guru_price) * (Decimal(1) - self.max_below_signal_pct / Decimal(100))
59 return floor.quantize(price_tick(floor, increment), rounding=ROUND_UP)
62def _checked(guru_price: Decimal) -> Decimal:
63 if not guru_price.is_finite() or guru_price <= 0: 63 ↛ 64line 63 didn't jump to line 64 because the condition on line 63 was never true
64 raise ValueError("Signal price must be finite and positive")
65 return guru_price
68def price_tick(price: Decimal, increment: Decimal | None = None) -> Decimal:
69 """The step a price moves in: a coin's own increment from Alpaca, else a stock's cent, or a
70 hundredth of a cent under $1."""
71 if increment is not None:
72 return increment
73 return Decimal("0.01") if price >= 1 else Decimal("0.0001")