Coverage for src/copytrading_engine/execution/application/ports.py: 92%
111 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"""Execution dependencies; broker adapters implement this interface."""
3from __future__ import annotations
5import datetime as dt
6from collections.abc import Mapping
7from contextlib import AbstractContextManager, nullcontext
8from dataclasses import dataclass
9from decimal import Decimal
10from typing import Literal, Protocol, get_args, runtime_checkable
12from copytrading_engine.execution.domain.events import JournalEvent
13from copytrading_engine.execution.domain.ledger_state import LedgerSnapshot
14from copytrading_engine.execution.domain.market import (
15 Account,
16 Asset,
17 BrokerOrder,
18 CalendarDay,
19 EquityHistory,
20 HistoryWindow,
21 Position,
22 Quote,
23)
24from copytrading_engine.execution.domain.orders import OrderRequest
25from copytrading_engine.execution.domain.positions import PositionAudit
28class Broker(Protocol):
29 def account(self) -> Account: ...
30 def asset(self, symbol: str) -> Asset: ...
31 def calendar(self, date: str) -> tuple[CalendarDay, ...]: ...
32 def positions(self) -> tuple[Position, ...]: ...
33 def open_orders(self) -> tuple[BrokerOrder, ...]: ...
34 def lookup(self, client_id: str) -> BrokerOrder | None: ...
35 def submit(self, order: OrderRequest) -> BrokerOrder: ...
36 def cancel(self, order_id: str) -> None: ...
39@runtime_checkable
40class RestoreEvidenceBroker(Protocol):
41 """Narrow read-only broker capability used by restore reconciliation."""
43 def restore_evidence(
44 self,
45 snapshot: LedgerSnapshot,
46 created_at: dt.datetime,
47 ) -> BrokerRestoreEvidence: ...
49 def close(self) -> None: ...
52@runtime_checkable
53class EquityHistoryBroker(Protocol):
54 """Narrow read-only broker capability behind the equity chart."""
56 def equity_history(self, window: HistoryWindow) -> EquityHistory: ...
59class BrokerError(Exception):
60 """Sanitized broker failure: the HTTP status and Alpaca's own one-line reason, never the
61 rest of the response body or any credential."""
63 def __init__(self, status: int | None = None, reason: str | None = None) -> None:
64 self.status = status
65 self.reason = reason
66 text = f"Alpaca HTTP {status}" if status else "Alpaca network error"
67 super().__init__(f"{text}: {reason}" if reason else text)
69 @property
70 def transient(self) -> bool:
71 """A failure that passes on its own: no connection, a timeout, a rate limit, or an
72 outage on Alpaca's side. Anything else (rejected keys, a refused request) needs a person.
73 """
74 return self.status is None or self.status in {408, 429} or self.status >= 500
77# Why a broker account cannot connect until its owner acts.
78type AccountOpenRefusal = Literal[
79 "outside_open_orders",
80 "broker_account_inactive",
81 "account_in_use",
82 "alpaca_account_shared",
83 "record_unreadable",
84]
85ACCOUNT_OPEN_REFUSALS: frozenset[str] = frozenset(get_args(AccountOpenRefusal.__value__))
86# Why an account could not open or stopped. `accounts_unavailable` is several accounts failing for
87# different reasons; `account_unavailable` is a cause CopyTrading could not tell.
88type AccountFailure = (
89 AccountOpenRefusal
90 | Literal[
91 "broker_keys_rejected", "broker_unreachable", "accounts_unavailable", "account_unavailable"
92 ]
93)
94ACCOUNT_FAILURES: frozenset[str] = ACCOUNT_OPEN_REFUSALS | {
95 "broker_keys_rejected",
96 "broker_unreachable",
97 "accounts_unavailable",
98 "account_unavailable",
99}
102class AccountOpenRefused(RuntimeError):
103 """The broker account cannot be connected until its owner acts; `reason` says why."""
105 def __init__(self, reason: AccountOpenRefusal) -> None:
106 self.reason = reason
107 super().__init__(reason)
110class BrokerResponseError(BrokerError):
111 """The broker response failed validation; its delivery outcome remains uncertain."""
113 def __init__(self) -> None:
114 super().__init__()
115 self.args = ("Alpaca response failed validation",)
117 @property
118 def transient(self) -> bool:
119 return False
122@dataclass(frozen=True, slots=True)
123class BrokerTimelineEvent:
124 """Broker event timestamp and exact wire precision, including sub-microseconds."""
126 identifier: str
127 occurred_at: dt.datetime
128 resolution_nanoseconds: int
129 submicrosecond_nanoseconds: int = 0
131 def __post_init__(self) -> None:
132 if not self.identifier: 132 ↛ 133line 132 didn't jump to line 133 because the condition on line 132 was never true
133 raise ValueError("Broker timeline event identifier is required")
134 if self.occurred_at.tzinfo is None or self.occurred_at.utcoffset() is None: 134 ↛ 135line 134 didn't jump to line 135 because the condition on line 134 was never true
135 raise ValueError("Broker timeline event timestamp must be timezone-aware")
136 if self.resolution_nanoseconds <= 0: 136 ↛ 137line 136 didn't jump to line 137 because the condition on line 136 was never true
137 raise ValueError("Broker timeline event resolution must be positive")
138 if not 0 <= self.submicrosecond_nanoseconds < 1_000: 138 ↛ 139line 138 didn't jump to line 139 because the condition on line 138 was never true
139 raise ValueError("Broker timeline event sub-microsecond offset is invalid")
141 def overlaps_or_follows(self, cutoff: dt.datetime) -> bool:
142 """Return true unless the entire timestamp-resolution interval predates cutoff."""
143 if cutoff.tzinfo is None or cutoff.utcoffset() is None: 143 ↛ 144line 143 didn't jump to line 144 because the condition on line 143 was never true
144 raise ValueError("Broker timeline cutoff must be timezone-aware")
145 cutoff_utc = cutoff.astimezone(dt.UTC)
146 event_start = _datetime_nanoseconds(self.occurred_at) + self.submicrosecond_nanoseconds
147 event_end = event_start + self.resolution_nanoseconds
148 return event_end > _datetime_nanoseconds(cutoff_utc)
151def _datetime_nanoseconds(value: dt.datetime) -> int:
152 utc_value = value.astimezone(dt.UTC)
153 epoch = dt.datetime(1970, 1, 1, tzinfo=dt.UTC)
154 elapsed = utc_value - epoch
155 elapsed_seconds = elapsed.days * 86_400 + elapsed.seconds
156 return elapsed_seconds * 1_000_000_000 + elapsed.microseconds * 1_000
159@dataclass(frozen=True, slots=True)
160class BrokerRestoreEvidence:
161 """Read-only facts; complete means bounded queries paginated to completion.
163 The order endpoint has a submitted-time cursor, not a complete updated-time
164 history. This evidence is an activation check, not a full broker audit export.
165 """
167 account: Account
168 environment: str
169 positions: Mapping[str, Decimal]
170 open_order_client_ids: tuple[str, ...]
171 known_orders: Mapping[str, BrokerOrder]
172 snapshot_started_at: dt.datetime
173 order_events_near_snapshot: tuple[BrokerTimelineEvent, ...]
174 activity_events_near_snapshot: tuple[BrokerTimelineEvent, ...]
175 complete: bool
177 @property
178 def orders_after_snapshot(self) -> tuple[str, ...]:
179 return tuple(
180 dict.fromkeys(
181 event.identifier
182 for event in self.order_events_near_snapshot
183 if event.overlaps_or_follows(self.snapshot_started_at)
184 )
185 )
187 @property
188 def activity_ids_after_snapshot(self) -> tuple[str, ...]:
189 return tuple(
190 dict.fromkeys(
191 event.identifier
192 for event in self.activity_events_near_snapshot
193 if event.overlaps_or_follows(self.snapshot_started_at)
194 )
195 )
198class LedgerRepository(Protocol):
199 def load(self) -> LedgerSnapshot: ...
200 def save(self, snapshot: LedgerSnapshot, event: JournalEvent) -> None:
201 """Commit the snapshot and journal event atomically, or leave both unchanged."""
202 ...
205@runtime_checkable
206class QuoteBroker(Protocol):
207 def quote(self, symbol: str) -> Quote: ...
210class ExecutionObserver(Protocol):
211 def span(self, name: str, message_id: str) -> AbstractContextManager: ...
212 def event(self, name: str, facts: Mapping[str, object] | None = None) -> None: ...
215class NoOpObserver:
216 def span(self, name: str, message_id: str) -> AbstractContextManager:
217 return nullcontext()
219 def event(self, name: str, facts: Mapping[str, object] | None = None) -> None:
220 pass
223@dataclass(frozen=True)
224class ExecutionObservation:
225 account: Account
226 ledger: LedgerSnapshot
227 total_cost_exposure_usd: Decimal
228 position_audit: PositionAudit | None
231@dataclass(frozen=True)
232class AccountRuntimeView:
233 entry_permission: str
234 recovery_preference: str
235 readiness: str
236 account_risk_status: str
237 account_risk_reason: str | None
238 account_activity_status: str
239 account_activity_reason: str | None