Coverage for src/copytrading_engine/execution/domain/signals.py: 100%
30 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"""Validated per-account execution policy."""
3from decimal import Decimal
4from typing import Annotated, Self
6from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, model_validator
8from copytrading_engine.execution.domain.lifecycle import RecoveryPreference
9from copytrading_engine.execution.domain.pricing import PricePolicy
12class SignalSourceNotAllowed(ValueError):
13 """A valid signal belongs to a source outside this account's allowlist."""
16class AccountLimits(BaseModel):
17 """The limits an account copies under, defined once: the saved setup (AccountPolicy) and the
18 engine (CopyConfig) both take them from here."""
20 model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True)
21 max_order_usd: Decimal = Field(default=Decimal("100"), gt=0, allow_inf_nan=False)
22 max_symbol_usd: Decimal = Field(default=Decimal("600"), gt=0)
23 max_total_usd: Decimal = Field(default=Decimal("2500"), gt=0)
24 daily_loss_cap_usd: Decimal = Field(default=Decimal("250"), gt=0)
25 max_entries_per_day: StrictInt = Field(default=30, gt=0)
26 # How old a buy may be and still be copied; a sell never is too old (ADR-0010).
27 max_signal_age_seconds: StrictInt = Field(default=600, gt=0, le=600)
28 order_timeout_seconds: StrictInt = Field(default=60, gt=0, le=600)
29 poll_seconds: float = Field(default=2, ge=1, le=30)
30 extended_hours: StrictBool = True
31 overnight: StrictBool = False
32 copy_exits: StrictBool = True
33 # Off by default. On, no order is sent by itself: a call that would have traded waits for
34 # the owner, who approves it in the app (ADR-0008).
35 approve_orders: StrictBool = False
36 # Off by default. On, a stop the guru posts is placed as a stop order at Alpaca for the shares
37 # CopyTrading bought; off, a stop post is skipped and nothing is invented (ADR-0015).
38 follow_stops: StrictBool = False
39 # What the account does after CopyTrading restarts: "automatic" copies again once its checks
40 # pass; "manual" waits for the owner's Start Copying. The setup holds it, never the account's
41 # record, so the account sheet shows every choice that changes how it trades.
42 recovery_preference: RecoveryPreference = "manual"
44 @model_validator(mode="after")
45 def validate_sessions(self) -> Self:
46 if self.overnight and not self.extended_hours:
47 raise ValueError("Overnight trading requires extended_hours")
48 return self
51class CopyConfig(AccountLimits):
52 """Validated startup policy; collections cannot change after validation."""
54 sources: tuple[Annotated[str, Field(pattern=r"^[a-z][a-z0-9_-]*:[a-zA-Z0-9_-]+$")], ...] = (
55 Field(min_length=1)
56 )
57 pricing: PricePolicy = Field(default_factory=PricePolicy)