Coverage for src/copytrading_engine/trading/domain/config.py: 92%

158 statements  

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

1"""Validated nonsecret routing policy and transient runtime credentials.""" 

2 

3import hashlib 

4import json 

5from typing import Literal, Self 

6 

7from pydantic import BaseModel, ConfigDict, Field, SecretStr, model_validator 

8 

9from copytrading_engine.execution.domain.pricing import ( 

10 DEFAULT_ABOVE_SIGNAL_PCT, 

11 DEFAULT_BELOW_SIGNAL_PCT, 

12 AboveSignalPct, 

13 BelowSignalPct, 

14) 

15from copytrading_engine.execution.domain.signals import AccountLimits 

16from copytrading_engine.execution.domain.sizing import ( 

17 MAX_REPEAT_WINDOW_MINUTES, 

18 REPEAT_WINDOW_MINUTES, 

19 RouteConnection, 

20) 

21from copytrading_engine.shared.configuration_version import CONFIGURATION_VERSION 

22from copytrading_engine.shared.model_providers import ( 

23 LOCAL_PROVIDERS, 

24 ModelProvider, 

25 ProviderConfig, 

26 endpoint_problem, 

27) 

28from copytrading_engine.trading.domain.profiles import ProfileRevision 

29 

30 

31class SourceConfiguration(BaseModel): 

32 model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True) 

33 

34 channel_ids: tuple[str, ...] = Field(min_length=1) 

35 author_ids: tuple[str, ...] = () 

36 

37 @model_validator(mode="after") 

38 def validate_ids(self) -> Self: 

39 for value in (*self.channel_ids, *self.author_ids): 

40 if not value.isascii() or not value.isdigit() or len(value) > 32: 40 ↛ 41line 40 didn't jump to line 41 because the condition on line 40 was never true

41 raise ValueError("Discord identifiers must be decimal strings") 

42 if len(set(self.channel_ids)) != len(self.channel_ids): 42 ↛ 43line 42 didn't jump to line 43 because the condition on line 42 was never true

43 raise ValueError("source channel identifiers must be unique") 

44 return self 

45 

46 

47class ProviderConfiguration(BaseModel): 

48 """The model service that reads posts. Only a local or custom OpenAI-compatible service 

49 takes an address; every named service has its own.""" 

50 

51 model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True) 

52 

53 name: ModelProvider 

54 model: str = Field(min_length=1, max_length=128) 

55 base_url: str | None = Field(default=None, max_length=512) 

56 

57 @model_validator(mode="after") 

58 def validate_endpoint(self) -> Self: 

59 if self.name == "openrouter" and "/" not in self.model: 

60 raise ValueError( 

61 "OpenRouter model names start with their provider, like openai/gpt-5.5" 

62 ) 

63 if self.name == "openai_compatible" and self.base_url is None: 

64 raise ValueError("A custom OpenAI-compatible model needs its address") 

65 if self.base_url is not None: 

66 if self.name not in LOCAL_PROVIDERS: 

67 raise ValueError("Only a local or custom model takes an address") 

68 if (problem := endpoint_problem(self.base_url)) is not None: 

69 raise ValueError(problem) 

70 return self 

71 

72 def reader(self, api_key: SecretStr, *, timeout: float) -> ProviderConfig: 

73 """The reader's configuration; a named cloud service always needs its key.""" 

74 if not api_key.get_secret_value() and self.name not in LOCAL_PROVIDERS: 

75 raise ValueError("The model API key is required") 

76 return ProviderConfig( 

77 api_key=api_key, 

78 model=self.model, 

79 timeout=timeout, 

80 base_url=self.base_url, 

81 ) 

82 

83 

84class AccountPolicy(AccountLimits): 

85 """Existing execution policy values, kept explicit for a saved native profile: the account's 

86 limits, with entry pricing flat beside them.""" 

87 

88 max_above_signal_pct: AboveSignalPct = DEFAULT_ABOVE_SIGNAL_PCT 

89 max_below_signal_pct: BelowSignalPct = DEFAULT_BELOW_SIGNAL_PCT 

90 

91 

92class AccountConfiguration(BaseModel): 

93 model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True) 

94 

95 id: str = Field(pattern=r"^[a-zA-Z0-9_-]{1,64}$") 

96 environment: Literal["paper", "live"] 

97 policy: AccountPolicy = Field(default_factory=AccountPolicy) 

98 

99 

100class RouteConfiguration(BaseModel): 

101 model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True) 

102 

103 source: Literal["discord"] = "discord" 

104 channel_id: str 

105 author_id: str | None = None 

106 guru_id: str = Field(pattern=r"^[a-zA-Z0-9_-]{1,64}$") 

107 profile_revision: str = Field(pattern=r"^[0-9a-f]{64}$") 

108 connections: tuple[RouteConnection, ...] = Field(min_length=1) 

109 # The same call again within this many minutes is the guru re-posting it, not a new trade; 

110 # None turns the check off, so every post is copied. 

111 repeat_window_minutes: int | None = Field( 

112 default=REPEAT_WINDOW_MINUTES, ge=1, le=MAX_REPEAT_WINDOW_MINUTES 

113 ) 

114 

115 @model_validator(mode="after") 

116 def validate_source_identity(self) -> Self: 

117 for value in (self.channel_id, self.author_id): 

118 if value is not None and ( 118 ↛ 121line 118 didn't jump to line 121 because the condition on line 118 was never true

119 not value.isascii() or not value.isdigit() or len(value) > 32 

120 ): 

121 raise ValueError("Discord identifiers must be decimal strings") 

122 return self 

123 

124 

125type AlertService = Literal["telegram", "discord"] 

126 

127 

128class NotificationConfiguration(BaseModel): 

129 """Where alerts go. Telegram names a chat; a Discord webhook already names its channel, and its 

130 URL is the secret, kept with the other keys.""" 

131 

132 model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True) 

133 

134 service: AlertService = "telegram" 

135 chat_id: str | None = Field(default=None, min_length=1, max_length=128) 

136 

137 @model_validator(mode="after") 

138 def validate_destination(self) -> Self: 

139 if self.service == "telegram" and self.chat_id is None: 

140 raise ValueError("Telegram alerts need a chat ID") 

141 if self.service == "discord" and self.chat_id is not None: 

142 raise ValueError("Discord alerts take no chat ID") 

143 return self 

144 

145 

146class TradingConfiguration(BaseModel): 

147 model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True) 

148 

149 version: Literal[10] = CONFIGURATION_VERSION 

150 source: SourceConfiguration 

151 provider: ProviderConfiguration 

152 accounts: tuple[AccountConfiguration, ...] = Field(min_length=1) 

153 profiles: tuple[ProfileRevision, ...] = Field(min_length=1) 

154 routes: tuple[RouteConfiguration, ...] = Field(min_length=1) 

155 notification: NotificationConfiguration | None = None 

156 

157 def revision(self) -> str: 

158 return _fingerprint(self.model_dump(mode="json")) 

159 

160 def routing_revision(self) -> str: 

161 """The revision without account limits: where posts go, not how much each order spends. 

162 Queued work stays bound to it, so changing a limit while copying strands nothing.""" 

163 return _fingerprint(self.without_limits()) 

164 

165 def without_limits(self) -> dict[str, object]: 

166 return self.model_dump(mode="json", exclude={"accounts": {"__all__": {"policy"}}}) 

167 

168 @model_validator(mode="after") 

169 def validate_references(self) -> Self: 

170 accounts = {account.id: account for account in self.accounts} 

171 if len(accounts) != len(self.accounts): 171 ↛ 172line 171 didn't jump to line 172 because the condition on line 171 was never true

172 raise ValueError("account identifiers must be unique") 

173 profile_revisions = {profile.profile_revision: profile for profile in self.profiles} 

174 if len(profile_revisions) != len(self.profiles): 174 ↛ 175line 174 didn't jump to line 175 because the condition on line 174 was never true

175 raise ValueError("profile revisions must be unique") 

176 source_rules = [(route.source, route.channel_id, route.author_id) for route in self.routes] 

177 if len(set(source_rules)) != len(source_rules): 

178 raise ValueError("source identity rules must be unique") 

179 by_channel: dict[tuple[str, str], list[RouteConfiguration]] = {} 

180 for route in self.routes: 

181 if route.source != "discord" or route.channel_id not in self.source.channel_ids: 181 ↛ 182line 181 didn't jump to line 182 because the condition on line 181 was never true

182 raise ValueError("route references an unknown source channel") 

183 by_channel.setdefault((route.source, route.channel_id), []).append(route) 

184 profile = profile_revisions.get(route.profile_revision) 

185 if profile is None or profile.guru_id != route.guru_id: 185 ↛ 186line 185 didn't jump to line 186 because the condition on line 185 was never true

186 raise ValueError("route references an unknown guru profile revision") 

187 # One guru copies into one account (ADR-0007). Its full position is its own; the 

188 # account's maximum per stock only caps what is bought (ADR-0010). 

189 if len(route.connections) != 1: 

190 raise ValueError("a guru copies into exactly one account") 

191 [connection] = route.connections 

192 account = accounts.get(connection.account_id) 

193 if account is None: 

194 raise ValueError("route references an unknown account") 

195 copied_into = [route.connections[0].account_id for route in self.routes] 

196 if len(set(copied_into)) != len(copied_into): 

197 raise ValueError("an account copies one guru") 

198 gurus = [route.guru_id for route in self.routes] 

199 if len(set(gurus)) != len(gurus): 

200 raise ValueError("a guru copies into one account") 

201 # The channel names its guru (route_keys.guru_for_channel), so a channel has one. 

202 if any(len(rules) > 1 for rules in by_channel.values()): 

203 raise ValueError("a channel copies one guru") 

204 return self 

205 

206 

207class BrokerCredentials(BaseModel): 

208 model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True) 

209 

210 account_id: str 

211 key: SecretStr 

212 secret: SecretStr 

213 

214 

215class TradingSecrets(BaseModel): 

216 """IPC-only credentials. No instance is serialized to engine storage or logs.""" 

217 

218 model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True) 

219 

220 discord_token: SecretStr 

221 provider_api_key: SecretStr 

222 brokers: tuple[BrokerCredentials, ...] 

223 notification_token: SecretStr | None = None 

224 

225 @model_validator(mode="after") 

226 def validate_brokers(self) -> Self: 

227 identifiers = [broker.account_id for broker in self.brokers] 

228 if len(set(identifiers)) != len(identifiers): 228 ↛ 229line 228 didn't jump to line 229 because the condition on line 228 was never true

229 raise ValueError("broker credential identifiers must be unique") 

230 return self 

231 

232 

233class SourceCheck(BaseModel): 

234 """The Discord channels to read, with the token that reads them.""" 

235 

236 model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True) 

237 

238 kind: Literal["source"] 

239 source: SourceConfiguration 

240 token: SecretStr 

241 

242 def secret_values(self) -> tuple[str, ...]: 

243 return (self.token.get_secret_value(),) 

244 

245 

246class ModelCheck(BaseModel): 

247 """The interpreter, with its key; a model on this Mac may have none.""" 

248 

249 model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True) 

250 

251 kind: Literal["model"] 

252 provider: ProviderConfiguration 

253 api_key: SecretStr 

254 

255 def secret_values(self) -> tuple[str, ...]: 

256 return (self.api_key.get_secret_value(),) 

257 

258 

259class BrokerCheck(BaseModel): 

260 """One broker account, with its keys.""" 

261 

262 model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True) 

263 

264 kind: Literal["broker"] 

265 account: AccountConfiguration 

266 credentials: BrokerCredentials 

267 

268 @model_validator(mode="after") 

269 def validate_account(self) -> Self: 

270 if self.credentials.account_id != self.account.id: 

271 raise ValueError("broker credentials must name the account they are for") 

272 return self 

273 

274 def secret_values(self) -> tuple[str, ...]: 

275 return (self.credentials.key.get_secret_value(), self.credentials.secret.get_secret_value()) 

276 

277 

278class NotificationCheck(BaseModel): 

279 """Where alerts go, with the bot token or webhook URL that sends them.""" 

280 

281 model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True) 

282 

283 kind: Literal["notification"] 

284 notification: NotificationConfiguration 

285 token: SecretStr 

286 

287 def secret_values(self) -> tuple[str, ...]: 

288 return (self.token.get_secret_value(),) 

289 

290 

291type ConnectionCheck = SourceCheck | ModelCheck | BrokerCheck | NotificationCheck 

292 

293 

294def _fingerprint(value: object) -> str: 

295 canonical = json.dumps(value, sort_keys=True, separators=(",", ":")) 

296 return hashlib.sha256(canonical.encode()).hexdigest()