Coverage for src/copytrading_engine/execution/adapters/alpaca/order_stream.py: 86%

89 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-16 16:55 +0000

1"""Alpaca's live order updates: wake an account the moment one of its orders changes. 

2 

3The stream only says *that* something changed. The account's own reconciliation reads the 

4broker and decides what it means, so a dropped or duplicated update can never corrupt state. 

5The stream also says whether it is live: while it is, the periodic check only needs to be a 

6slow safety net; while it is not, the account checks often again. 

7""" 

8 

9import asyncio 

10import json 

11import logging 

12from collections.abc import Awaitable, Callable 

13 

14import aiohttp 

15 

16from copytrading_engine.execution.adapters.alpaca.broker import AlpacaCredentials 

17 

18log = logging.getLogger(__name__) 

19 

20STREAM_URLS = { 

21 "paper": "wss://paper-api.alpaca.markets/stream", 

22 "live": "wss://api.alpaca.markets/stream", 

23} 

24RETRY_SECONDS = (1.0, 2.0, 5.0, 10.0, 30.0) 

25 

26type OrderStream = Callable[ 

27 [Callable[[], None], Callable[[bool], None], asyncio.Event], Awaitable[None] 

28] 

29type Connect = Callable[[str], Awaitable[aiohttp.ClientWebSocketResponse]] 

30 

31 

32class StreamRefused(Exception): 

33 """Alpaca did not authorize the stream.""" 

34 

35 

36def alpaca_order_stream( 

37 credentials: AlpacaCredentials, 

38 environment: str, 

39 *, 

40 connect: Connect | None = None, 

41 retry_seconds: tuple[float, ...] = RETRY_SECONDS, 

42) -> OrderStream: 

43 """Watch one account's `trade_updates` until `stop`, reconnecting with backoff. `on_live` 

44 hears True once Alpaca confirms it is listening, and False whenever the connection ends.""" 

45 url = STREAM_URLS[environment] 

46 

47 async def watch( 

48 on_update: Callable[[], None], on_live: Callable[[bool], None], stop: asyncio.Event 

49 ) -> None: 

50 failures = 0 

51 while not stop.is_set(): 

52 try: 

53 async with _Socket(url, connect) as socket: 

54 await _authorize(socket, credentials) 

55 await socket.send_json( 

56 {"action": "listen", "data": {"streams": ["trade_updates"]}} 

57 ) 

58 failures = 0 

59 # Anything that changed while disconnected is caught up right away. 

60 on_update() 

61 # Stop closes the socket, ending a wait for a frame that may never come. 

62 closer = asyncio.create_task(_close_on(stop, socket)) 

63 try: 

64 async for frame in socket: 

65 message = _message(frame) 

66 if message is None: 66 ↛ 67line 66 didn't jump to line 67 because the condition on line 66 was never true

67 break 

68 if message.get("stream") == "trade_updates": 

69 on_update() 

70 elif message.get("stream") == "listening": 70 ↛ 64line 70 didn't jump to line 64 because the condition on line 70 was always true

71 on_live(_listens_to_trades(message)) 

72 finally: 

73 closer.cancel() 

74 on_live(False) 

75 if stop.is_set(): 

76 return 

77 except asyncio.CancelledError: 

78 raise 

79 except Exception as exc: # noqa: BLE001 - the periodic check covers any outage 

80 log.warning("order_stream_interrupted type=%s", type(exc).__name__) 

81 delay = retry_seconds[min(failures, len(retry_seconds) - 1)] 

82 failures += 1 

83 try: 

84 await asyncio.wait_for(stop.wait(), timeout=delay) 

85 except TimeoutError: 

86 pass 

87 

88 return watch 

89 

90 

91async def _close_on(stop: asyncio.Event, socket: aiohttp.ClientWebSocketResponse) -> None: 

92 await stop.wait() 

93 await socket.close() 

94 

95 

96class _Socket: 

97 """One websocket connection, closed with its HTTP session on exit.""" 

98 

99 def __init__(self, url: str, connect: Connect | None) -> None: 

100 self._url = url 

101 self._connect = connect 

102 self._session: aiohttp.ClientSession | None = None 

103 self._socket: aiohttp.ClientWebSocketResponse | None = None 

104 

105 async def __aenter__(self) -> aiohttp.ClientWebSocketResponse: 

106 if self._connect is not None: 106 ↛ 109line 106 didn't jump to line 109 because the condition on line 106 was always true

107 self._socket = await self._connect(self._url) 

108 else: 

109 self._session = aiohttp.ClientSession() 

110 self._socket = await self._session.ws_connect(self._url, heartbeat=20) 

111 return self._socket 

112 

113 async def __aexit__(self, *_exc: object) -> None: 

114 if self._socket is not None: 114 ↛ 116line 114 didn't jump to line 116 because the condition on line 114 was always true

115 await self._socket.close() 

116 if self._session is not None: 116 ↛ 117line 116 didn't jump to line 117 because the condition on line 116 was never true

117 await self._session.close() 

118 

119 

120async def _authorize( 

121 socket: aiohttp.ClientWebSocketResponse, credentials: AlpacaCredentials 

122) -> None: 

123 await socket.send_json( 

124 { 

125 "action": "auth", 

126 "key": credentials.key.get_secret_value(), 

127 "secret": credentials.secret.get_secret_value(), 

128 } 

129 ) 

130 reply = _message(await socket.receive(timeout=10)) 

131 data = reply.get("data") if reply is not None else None 

132 if not isinstance(data, dict) or data.get("status") != "authorized": 

133 raise StreamRefused 

134 

135 

136def _listens_to_trades(message: dict[str, object]) -> bool: 

137 data = message.get("data") 

138 streams = data.get("streams") if isinstance(data, dict) else None 

139 return isinstance(streams, list) and "trade_updates" in streams 

140 

141 

142def _message(frame: aiohttp.WSMessage) -> dict[str, object] | None: 

143 """A decoded JSON object, or None when the connection is closing or failed.""" 

144 if frame.type == aiohttp.WSMsgType.TEXT: 144 ↛ 145line 144 didn't jump to line 145 because the condition on line 144 was never true

145 raw = frame.data 

146 elif frame.type == aiohttp.WSMsgType.BINARY: 146 ↛ 149line 146 didn't jump to line 149 because the condition on line 146 was always true

147 raw = frame.data.decode("utf-8", errors="replace") 

148 else: 

149 return None 

150 try: 

151 message = json.loads(raw) 

152 except ValueError: 

153 return {} 

154 return message if isinstance(message, dict) else {}