Coverage for src/copytrading_engine/trading/entrypoints/factories.py: 66%

57 statements  

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

1"""What the runtime builds collaborators with: the Discord session, notifier, decoder, owner, and 

2the check of which Alpaca account an account's keys open.""" 

3 

4import asyncio 

5import datetime as dt 

6from collections.abc import Awaitable, Callable 

7from dataclasses import dataclass 

8from pathlib import Path 

9from typing import Protocol 

10 

11import discord 

12 

13from copytrading_engine.execution.adapters.alpaca.broker import ( 

14 AlpacaBroker, 

15 AlpacaCredentials, 

16 Environment, 

17) 

18from copytrading_engine.execution.adapters.owner import ExecutionOwner 

19from copytrading_engine.execution.adapters.resources import default_account_lock_root 

20from copytrading_engine.execution.domain.signals import CopyConfig 

21from copytrading_engine.parsing.providers.registry import ( 

22 ManagedDecoder, 

23 NamedDecoderFactory, 

24 builtin_registry, 

25) 

26from copytrading_engine.shared.model_providers import ProviderConfig 

27from copytrading_engine.shared.notification_models import NotificationPayload 

28from copytrading_engine.shared.payload_capture import PayloadCapture 

29from copytrading_engine.sources.application import ForwardBatch 

30from copytrading_engine.sources.session import DiscordSession 

31from copytrading_engine.sources.sqlite import SQLiteSourceStore 

32from copytrading_engine.trading.adapters.notifications import alert_sender 

33from copytrading_engine.trading.adapters.telemetry import TradingTelemetry 

34from copytrading_engine.trading.application.accounts import AccountOwner 

35from copytrading_engine.trading.domain.config import NotificationConfiguration 

36 

37 

38class SourceSession(Protocol): 

39 @property 

40 def ready(self) -> bool: ... 

41 

42 def start(self, token: str) -> None: ... 

43 

44 async def ensure_running(self) -> None: ... 

45 

46 async def forward_if_ready(self, forwarder: ForwardBatch) -> None: ... 

47 

48 async def close(self) -> None: ... 

49 

50 

51class NotificationSender(Protocol): 

52 async def send(self, payload: NotificationPayload) -> None: ... 

53 

54 

55type OwnerFactory = Callable[[Path, AlpacaCredentials, CopyConfig, str], Awaitable[AccountOwner]] 

56 

57 

58# The Alpaca account ID a pair of keys opens, for an environment. 

59type IdentityFactory = Callable[[AlpacaCredentials, Environment], Awaitable[str]] 

60 

61 

62type SessionFactory = Callable[ 

63 [ 

64 SQLiteSourceStore, 

65 set[int], 

66 set[int] | None, 

67 asyncio.Event, 

68 Callable[[str, BaseException | None], None], 

69 ], 

70 SourceSession, 

71] 

72 

73 

74type NotifierFactory = Callable[[NotificationConfiguration, str], NotificationSender] 

75 

76 

77async def open_owner( 

78 path: Path, 

79 credentials: AlpacaCredentials, 

80 policy: CopyConfig, 

81 environment: str, 

82 *, 

83 telemetry: TradingTelemetry | None = None, 

84) -> AccountOwner: 

85 if environment not in {"paper", "live"}: 

86 raise ValueError("Unknown broker environment") 

87 owner = await ExecutionOwner.open( 

88 path, 

89 credentials, 

90 policy, 

91 environment=environment, 

92 account_lock_root=default_account_lock_root(), 

93 observer=telemetry, 

94 ) 

95 try: 

96 await owner.recover_account(dt.datetime.now(dt.UTC)) 

97 return owner 

98 except BaseException: 

99 await owner.close() 

100 raise 

101 

102 

103async def broker_identity(credentials: AlpacaCredentials, environment: Environment) -> str: 

104 """Which Alpaca account the keys open, so its record is found whatever the setup names it.""" 

105 

106 def read() -> str: 

107 broker = AlpacaBroker(credentials, environment) 

108 try: 

109 return broker.account().id 

110 finally: 

111 broker.close() 

112 

113 return await asyncio.to_thread(read) 

114 

115 

116async def create_decoder( 

117 name: str, 

118 config: ProviderConfig, 

119 *, 

120 diagnostics: PayloadCapture | None = None, 

121) -> ManagedDecoder: 

122 return await builtin_registry().create(name, config, diagnostics=diagnostics) 

123 

124 

125def _create_session( 

126 source: SQLiteSourceStore, 

127 channels: set[int], 

128 authors: set[int] | None, 

129 stop: asyncio.Event, 

130 report_failure: Callable[[str, BaseException | None], None], 

131) -> SourceSession: 

132 client = discord.Client() 

133 return DiscordSession( 

134 client, channels, source, stop, authors=authors, report_failure=report_failure 

135 ) 

136 

137 

138@dataclass(frozen=True) 

139class TradingFactories: 

140 owner: OwnerFactory = open_owner 

141 decoder: NamedDecoderFactory = create_decoder 

142 session: SessionFactory = _create_session 

143 notifier: NotifierFactory = alert_sender 

144 # None leaves every record where it is: for fakes whose owners have no Alpaca account. 

145 identity: IdentityFactory | None = None