Coverage for src/copytrading_engine/execution/domain/risk.py: 93%
100 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"""Pure entry-budget policy: input facts in, approved budget or reason out."""
3from dataclasses import dataclass
4from decimal import ROUND_DOWN, ROUND_HALF_UP, Decimal
5from typing import Literal, Protocol
7from copytrading_engine.execution.domain.market import Position
8from copytrading_engine.execution.domain.orders import BuyLimit, OrderRecord, OwnedLot
9from copytrading_engine.execution.domain.sizing import RouteConnection
12class EntryLimits(Protocol):
13 """Read-only limits needed by this policy; no signal or startup configuration."""
15 @property
16 def max_order_usd(self) -> Decimal: ...
17 @property
18 def max_symbol_usd(self) -> Decimal: ...
19 @property
20 def max_total_usd(self) -> Decimal: ...
21 @property
22 def daily_loss_cap_usd(self) -> Decimal: ...
23 @property
24 def max_entries_per_day(self) -> int: ...
27PRODUCT_PLACES = Decimal("1e-10")
28# Alpaca's smallest order in dollars: a limit with less room than this leaves nothing to buy.
29MINIMUM_ORDER_USD = Decimal("1")
30# Alpaca refuses a coin's buy that costs less than $10 at its limit ("cost basis must be >= minimal
31# amount of order 10", seen on paper on 23 October 2026), well above the asset's own minimum size.
32# A coin's sale has no such floor (ADR-0014).
33MINIMUM_CRYPTO_BUY_USD = Decimal("10")
34# What a broker position may be: a stock, or a coin held against the dollar.
35_HELD_CLASSES = frozenset({"us_equity", "crypto"})
38@dataclass(frozen=True, slots=True)
39class EntryFacts:
40 symbol_exposure: Decimal
41 total_exposure: Decimal
42 cash: Decimal
43 buying_power: Decimal
44 equity: Decimal
45 last_equity: Decimal
46 entries_today: int
47 account_active: bool
50@dataclass(frozen=True, slots=True)
51class ExposureBreach:
52 scope: Literal["symbol", "total"]
53 current: Decimal
54 proposed: Decimal
55 limit: Decimal
58@dataclass(frozen=True, slots=True)
59class BudgetDecision:
60 budget: Decimal | None
61 reason: str
62 breaches: tuple[ExposureBreach, ...] = ()
63 # What the call asked for before a limit cut it.
64 requested: Decimal | None = None
65 # The limit that cut it, when one did.
66 limited_by: BuyLimit | None = None
68 @property
69 def trimmed(self) -> bool:
70 return (
71 self.budget is not None and self.requested is not None and self.budget < self.requested
72 )
75def requested_entry_budget(
76 connection: RouteConnection,
77 source_fraction: Decimal | None,
78 source_usd: Decimal | None,
79 *,
80 unsized_usd: Decimal | None,
81) -> BudgetDecision:
82 """What the call asks for, before account facts and limits: the dollars the post names, never
83 more than the full position; else its share of the full position. A call that states no size
84 buys the account's largest single buy (`unsized_usd`), never more than the full position;
85 without one, it is `unsized_buy` (ADR-0010)."""
86 if source_usd is not None:
87 if not source_usd.is_finite() or source_usd <= 0: 87 ↛ 88line 87 didn't jump to line 88 because the condition on line 87 was never true
88 raise ValueError("A dollar size must be positive")
89 return _asked(min(source_usd, connection.full_position_usd))
90 if source_fraction is None:
91 if unsized_usd is None:
92 return BudgetDecision(None, "unsized_buy")
93 return _asked(min(unsized_usd, connection.full_position_usd))
94 if not source_fraction.is_finite() or not 0 < source_fraction <= 1: 94 ↛ 95line 94 didn't jump to line 95 because the condition on line 94 was never true
95 raise ValueError("Source fraction must be between zero and one")
96 # A third is 0.333…3 in Decimal, so first settle the product's last digits (a third of $3000
97 # is $1000, not $999.99), then round down to the cent so six sixths never pass the position.
98 exact = (connection.full_position_usd * source_fraction).quantize(PRODUCT_PLACES, ROUND_HALF_UP)
99 return _asked(exact)
102def _asked(amount: Decimal) -> BudgetDecision:
103 requested = amount.quantize(Decimal("0.01"), rounding=ROUND_DOWN)
104 if requested <= 0:
105 return BudgetDecision(None, "below_minimum_budget")
106 return BudgetDecision(requested, "ready", requested=requested)
109@dataclass(frozen=True, slots=True)
110class AccountExposure:
111 by_symbol: dict[str, Decimal]
112 total: Decimal
114 def symbol(self, name: str) -> Decimal:
115 return self.by_symbol.get(name, Decimal(0))
118def account_exposure(
119 positions: tuple[Position, ...],
120 lots: tuple[OwnedLot, ...],
121 pending: tuple[OrderRecord, ...],
122 *,
123 account_currency: str,
124) -> AccountExposure:
125 """What CopyTrading has in each stock, in USD: the shares it bought, at the higher of what they
126 cost and what they are worth now, plus unfilled buy reserves. The owner's own shares are not
127 counted; the limits bound what CopyTrading does."""
128 if account_currency != "USD":
129 raise ValueError("Unsupported account valuation currency")
130 if len({position.symbol for position in positions}) != len(positions): 130 ↛ 131line 130 didn't jump to line 131 because the condition on line 130 was never true
131 raise ValueError("Duplicate broker positions prevent account risk evaluation")
132 shares: dict[str, Decimal] = {}
133 cost: dict[str, Decimal] = {}
134 for lot in lots:
135 if lot.remaining_qty:
136 shares[lot.symbol] = shares.get(lot.symbol, Decimal(0)) + lot.remaining_qty
137 cost[lot.symbol] = (
138 cost.get(lot.symbol, Decimal(0)) + lot.remaining_qty * lot.average_price
139 )
140 held = {position.symbol: position for position in positions}
141 by_symbol: dict[str, Decimal] = {}
142 for symbol, basis in cost.items():
143 worth = Decimal(0)
144 position = held.get(symbol)
145 if position is not None and position.qty:
146 if position.qty < 0 or position.asset_class not in _HELD_CLASSES:
147 raise ValueError("Unsupported short, option, or other broker position")
148 value = position.market_value
149 # A holding worth under a cent, such as a coin's last billionths, is listed at $0.
150 if position.currency != "USD" or value is None or not value.is_finite() or value < 0:
151 raise ValueError("Broker position valuation is unavailable or non-USD")
152 worth = shares[symbol] * value / position.qty
153 by_symbol[symbol] = max(worth, basis)
154 for order in pending:
155 if order.pending and order.side == "buy":
156 if order.limit_price is None: 156 ↛ 157line 156 didn't jump to line 157 because the condition on line 156 was never true
157 raise ValueError("Pending purchase has no valuation")
158 by_symbol[order.symbol] = (
159 by_symbol.get(order.symbol, Decimal(0))
160 + (order.qty - order.filled_qty) * order.limit_price
161 )
162 return AccountExposure(by_symbol, sum(by_symbol.values(), Decimal(0)))
165def entry_budget(
166 config: EntryLimits,
167 facts: EntryFacts,
168 connection: RouteConnection,
169 source_fraction: Decimal | None,
170 source_usd: Decimal | None = None,
171 *,
172 minimum_usd: Decimal = MINIMUM_ORDER_USD,
173) -> BudgetDecision:
174 """Each buy gets its destination's budget once. The largest single buy and the room left
175 under the per-stock and total limits cut it; it is refused only when that room is under
176 Alpaca's minimum: $1 for a stock, `MINIMUM_CRYPTO_BUY_USD` for a coin. The daily loss cap
177 refuses outright: it is a stop, not a size."""
178 if not facts.account_active:
179 return BudgetDecision(None, "account_blocked")
180 if facts.equity - facts.last_equity <= -config.daily_loss_cap_usd:
181 return BudgetDecision(None, "daily_loss_cap")
182 if facts.entries_today >= config.max_entries_per_day:
183 return BudgetDecision(None, "daily_entry_cap")
184 asked = requested_entry_budget(
185 connection, source_fraction, source_usd, unsized_usd=config.max_order_usd
186 )
187 if asked.budget is None: 187 ↛ 188line 187 didn't jump to line 188 because the condition on line 187 was never true
188 return asked
189 requested = asked.budget
190 budget, limited_by = requested, None
191 room: tuple[tuple[BuyLimit, Decimal], ...] = (
192 ("largest_single_buy", config.max_order_usd),
193 ("symbol_exposure_cap", config.max_symbol_usd - facts.symbol_exposure),
194 ("total_exposure_cap", config.max_total_usd - facts.total_exposure),
195 )
196 for limit, left in room:
197 if left < budget:
198 budget, limited_by = left, limit
199 budget = max(budget, Decimal(0)).quantize(Decimal("0.01"), rounding=ROUND_DOWN)
200 if budget < minimum_usd:
201 breaches = tuple(
202 breach
203 for breach in (
204 ExposureBreach("symbol", facts.symbol_exposure, requested, config.max_symbol_usd),
205 ExposureBreach("total", facts.total_exposure, requested, config.max_total_usd),
206 )
207 if breach.limit - breach.current < minimum_usd
208 )
209 scopes = {breach.scope for breach in breaches}
210 reason = (
211 "symbol_and_total_exposure_cap"
212 if len(scopes) == 2
213 else f"{next(iter(scopes))}_exposure_cap"
214 if scopes
215 else "below_minimum_budget"
216 )
217 return BudgetDecision(None, reason, breaches, requested)
218 if budget > min(facts.cash, facts.buying_power):
219 return BudgetDecision(None, "insufficient_cash", requested=requested)
220 return BudgetDecision(budget, "ready", requested=requested, limited_by=limited_by)