Coverage for src/copytrading_engine/trading/application/paused_reader.py: 97%
126 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"""Read-only broker reads for accounts while copying is paused, so the app shows them live.
3Copying decides whether orders go out; it should not decide whether the owner can see their
4money. The app hands over read keys when the owner unlocks and takes them back when they lock.
5The keys stay in memory, and the reader can only ask for an account, its positions, its equity
6curve, a stock's latest quote, and its bars of the day: it has no path to an order.
7"""
9import asyncio
10import datetime as dt
11import logging
12from collections.abc import Callable, Iterable
13from dataclasses import dataclass
14from typing import Literal, Protocol
16from pydantic import SecretStr
18from copytrading_engine.execution.application.ports import BrokerError
19from copytrading_engine.execution.domain.market import (
20 Account,
21 Bar,
22 DailyBar,
23 DailyRange,
24 EquityHistory,
25 HistoryWindow,
26 Position,
27 Quote,
28)
30log = logging.getLogger(__name__)
32# The app reads accounts about this often; a read inside it is answered from the last one.
33FACTS_REUSE = dt.timedelta(seconds=10)
34HISTORY_REUSE = dt.timedelta(seconds=60)
35# A stock typed into the trade sheet is quoted as the owner types; a repeat inside this is reused.
36QUOTE_REUSE = dt.timedelta(seconds=2)
37# A held stock's day of bars barely changes between the app's reads.
38BARS_REUSE = dt.timedelta(seconds=60)
39# A stock's daily bars change once a day (and its last one as the session trades).
40DAILY_BARS_REUSE = dt.timedelta(minutes=5)
43class ReadOnlyBroker(Protocol):
44 """The reads the paused reader may make, and nothing that places or cancels."""
46 def account(self) -> Account: ...
47 def positions(self) -> tuple[Position, ...]: ...
48 def equity_history(self, window: HistoryWindow) -> EquityHistory: ...
49 def quote(self, symbol: str) -> Quote: ...
50 def bars(self, symbol: str) -> tuple[Bar, ...]: ...
51 def daily_bars(self, symbol: str, period: DailyRange) -> tuple[DailyBar, ...]: ...
52 def close(self) -> None: ...
55@dataclass(frozen=True, slots=True)
56class ReadKeys:
57 account_id: str
58 environment: Literal["paper", "live"]
59 key: SecretStr
60 secret: SecretStr
63@dataclass(frozen=True, slots=True)
64class LiveFacts:
65 account: Account
66 positions: tuple[Position, ...]
67 observed_at: dt.datetime
70class PausedAccountReader:
71 """Answers account reads for paused accounts from the broker, briefly cached."""
73 def __init__(
74 self,
75 broker_factory: Callable[[ReadKeys], ReadOnlyBroker],
76 clock: Callable[[], dt.datetime] = lambda: dt.datetime.now(dt.UTC),
77 ) -> None:
78 self._factory = broker_factory
79 self._clock = clock
80 self._brokers: dict[str, ReadOnlyBroker] = {}
81 self._facts: dict[str, LiveFacts] = {}
82 self._histories: dict[tuple[str, HistoryWindow], tuple[dt.datetime, EquityHistory]] = {}
83 self._quotes: dict[tuple[str, str], tuple[dt.datetime, Quote | None]] = {}
84 self._bars: dict[tuple[str, str], tuple[dt.datetime, tuple[Bar, ...]]] = {}
85 self._daily_bars: dict[
86 tuple[str, str, DailyRange], tuple[dt.datetime, tuple[DailyBar, ...]]
87 ] = {}
89 def attach(self, keys: Iterable[ReadKeys]) -> None:
90 """Hold these accounts' read keys until `detach`, replacing any held before."""
91 self.detach()
92 for item in keys:
93 self._brokers[item.account_id] = self._factory(item)
95 def holds(self, account_id: str) -> bool:
96 return account_id in self._brokers
98 def detach(self) -> None:
99 """Forget every key and every cached read, as when the owner locks the app."""
100 for broker in self._brokers.values():
101 broker.close()
102 self._brokers.clear()
103 self._facts.clear()
104 self._histories.clear()
105 self._quotes.clear()
106 self._bars.clear()
107 self._daily_bars.clear()
109 async def facts(self, account_id: str) -> LiveFacts | None:
110 """The account and its positions as the broker reports them now, or None."""
111 broker = self._brokers.get(account_id)
112 if broker is None:
113 return None
114 now = self._clock()
115 cached = self._facts.get(account_id)
116 if cached is not None and now - cached.observed_at < FACTS_REUSE:
117 return cached
118 try:
119 account, positions = await asyncio.gather(
120 asyncio.to_thread(broker.account), asyncio.to_thread(broker.positions)
121 )
122 except BrokerError as exc:
123 log.warning("paused_read_failed id=%s status=%s", account_id, exc.status)
124 return cached
125 facts = LiveFacts(account=account, positions=positions, observed_at=now)
126 self._facts[account_id] = facts
127 return facts
129 async def equity_history(self, account_id: str, window: HistoryWindow) -> EquityHistory | None:
130 """The broker's curve for a paused account, fetched at most once a minute."""
131 broker = self._brokers.get(account_id)
132 if broker is None:
133 return None
134 now = self._clock()
135 cached = self._histories.get((account_id, window))
136 if cached is not None and now - cached[0] < HISTORY_REUSE: 136 ↛ 137line 136 didn't jump to line 137 because the condition on line 136 was never true
137 return cached[1]
138 try:
139 history = await asyncio.to_thread(broker.equity_history, window)
140 except BrokerError as exc:
141 log.warning("paused_history_failed id=%s status=%s", account_id, exc.status)
142 return cached[1] if cached is not None else None
143 self._histories[(account_id, window)] = (now, history)
144 return history
146 async def quote(self, account_id: str, symbol: str) -> Quote | None:
147 """The stock's latest quote from this account's market data, or None when the account
148 has no keys here or the broker has no quote for the symbol."""
149 broker = self._brokers.get(account_id)
150 if broker is None:
151 return None
152 now = self._clock()
153 cached = self._quotes.get((account_id, symbol))
154 if cached is not None and now - cached[0] < QUOTE_REUSE:
155 return cached[1]
156 try:
157 quote: Quote | None = await asyncio.to_thread(broker.quote, symbol)
158 except BrokerError as exc:
159 # An unknown symbol answers 4xx: it has no quote, which the sheet says plainly.
160 log.warning("paused_quote_failed id=%s status=%s", account_id, exc.status)
161 quote = None
162 if quote is not None and quote.bid is None and quote.ask is None:
163 quote = None
164 self._quotes[(account_id, symbol)] = (now, quote)
165 return quote
167 async def bars(self, account_id: str, symbols: tuple[str, ...]) -> dict[str, tuple[Bar, ...]]:
168 """Each symbol's five-minute bars of its latest session through this account's keys,
169 each read at most once a minute. A symbol the broker cannot give bars for has none."""
170 broker = self._brokers.get(account_id)
171 if broker is None:
172 return {}
174 async def one(symbol: str) -> tuple[Bar, ...]:
175 now = self._clock()
176 cached = self._bars.get((account_id, symbol))
177 if cached is not None and now - cached[0] < BARS_REUSE:
178 return cached[1]
179 try:
180 bars = await asyncio.to_thread(broker.bars, symbol)
181 except BrokerError as exc:
182 log.warning("paused_bars_failed id=%s status=%s", account_id, exc.status)
183 return cached[1] if cached is not None else ()
184 self._bars[(account_id, symbol)] = (now, bars)
185 return bars
187 return dict(
188 zip(symbols, await asyncio.gather(*(one(symbol) for symbol in symbols)), strict=True)
189 )
191 async def daily_bars(
192 self, account_id: str, symbol: str, period: DailyRange
193 ) -> tuple[DailyBar, ...]:
194 """A symbol's daily bars over the period through this account's keys, each read at most
195 once in five minutes. A symbol the broker cannot give bars for has none."""
196 broker = self._brokers.get(account_id)
197 if broker is None:
198 return ()
199 key = (account_id, symbol, period)
200 now = self._clock()
201 cached = self._daily_bars.get(key)
202 if cached is not None and now - cached[0] < DAILY_BARS_REUSE:
203 return cached[1]
204 try:
205 bars = await asyncio.to_thread(broker.daily_bars, symbol, period)
206 except BrokerError as exc:
207 log.warning("paused_daily_bars_failed id=%s status=%s", account_id, exc.status)
208 return cached[1] if cached is not None else ()
209 self._daily_bars[key] = (now, bars)
210 return bars