Coverage for src/copytrading_engine/execution/domain/manual_commands.py: 96%

121 statements  

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

1"""Immutable evidence and wire contracts for reviewed manual commands.""" 

2 

3from decimal import Decimal 

4from typing import Literal, Self, get_args 

5 

6from pydantic import AwareDatetime, Field, model_validator 

7 

8from copytrading_engine.execution.domain.market import Quote 

9from copytrading_engine.execution.domain.order_lifecycle import OrderStatus 

10from copytrading_engine.execution.domain.orders import OrderPlan 

11from copytrading_engine.execution.domain.sessions import Session 

12from copytrading_engine.execution.domain.values import Identifier, Positive, Quantity, Value 

13from copytrading_engine.shared.signals import Instruction, StockSignal 

14 

15type ManualRefusalReason = Literal[ 

16 # Saving the call in an account. 

17 "copying_not_started", 

18 "account_not_running", 

19 "account_unavailable", 

20 "call_not_received", 

21 "call_not_waiting", 

22 "call_changed", 

23 "correction_conflict", 

24 "identity_conflict", 

25 "record_failed", 

26 "post_unavailable", 

27 "post_ignored", 

28 "records_unreadable", 

29 # Checking and confirming the order. 

30 "correction_incomplete", 

31 "account_identity_changed", 

32 "preview_missing", 

33 "wait_pending_order", 

34 "unresolved_order_incident", 

35 # An operation that failed for a reason the engine did not expect. 

36 "correction_failed", 

37 "preview_failed", 

38 "confirm_failed", 

39 "status_failed", 

40 "history_failed", 

41 "command_not_found", 

42] 

43MANUAL_REFUSAL_REASONS: frozenset[str] = frozenset(get_args(ManualRefusalReason.__value__)) 

44 

45 

46class ManualRefusal(ValueError): 

47 """An expected refusal in the by-hand flow, carrying the code the app words for the owner. 

48 

49 The text is only the code: it is logged and sent as the reply's `reason`, never input. 

50 """ 

51 

52 def __init__(self, reason: ManualRefusalReason) -> None: 

53 super().__init__(reason) 

54 self.reason: ManualRefusalReason = reason 

55 

56 

57class ManualCorrectionRequest(Value): 

58 """One immutable reviewed interpretation shared by selected local accounts.""" 

59 

60 correction_id: Identifier 

61 source_id: Identifier 

62 selected_account_ids: tuple[Identifier, ...] = Field(min_length=1, max_length=20) 

63 actor: Identifier 

64 reason: Identifier 

65 instructions: tuple[Instruction, ...] = Field(min_length=1, max_length=20) 

66 

67 @model_validator(mode="after") 

68 def valid_identity(self) -> Self: 

69 if not self.actor.strip() or not self.reason.strip(): 

70 raise ValueError("Manual correction requires an actor and reason") 

71 if self.selected_account_ids != tuple(sorted(set(self.selected_account_ids))): 

72 raise ValueError("Selected account IDs must be unique and sorted") 

73 return self 

74 

75 

76class ManualSourceEvidence(Value): 

77 """Trusted source-store evidence copied before a correction can be admitted.""" 

78 

79 source_id: Identifier 

80 source_revision: int = Field(ge=1) 

81 source_at: AwareDatetime 

82 text: str = Field(min_length=1, max_length=50_000) 

83 accepted_interpretation: StockSignal 

84 

85 @model_validator(mode="after") 

86 def matches_interpretation(self) -> Self: 

87 signal = self.accepted_interpretation 

88 if ( 

89 self.source_id != f"{signal.source}:{signal.channel_id}:{signal.id}" 

90 or self.source_at != signal.timestamp 

91 or self.text != signal.text 

92 ): 

93 raise ValueError("Source evidence differs from its accepted interpretation") 

94 if signal.decision == "ignore": 

95 raise ValueError("An ignored post has nothing to copy") 

96 return self 

97 

98 

99class ManualCorrectionRecord(Value): 

100 """Account-owner copy of the exact correction and its original evidence.""" 

101 

102 correction_id: Identifier 

103 source_id: Identifier 

104 selected_account_ids: tuple[Identifier, ...] = Field(min_length=1, max_length=20) 

105 revision: int = Field(ge=1) 

106 actor: Identifier 

107 reason: Identifier 

108 instructions: tuple[Instruction, ...] = Field(min_length=1, max_length=20) 

109 source_revision: int = Field(ge=1) 

110 source_at: AwareDatetime 

111 source_text: str = Field(min_length=1, max_length=50_000) 

112 accepted_interpretation: StockSignal 

113 recorded_at: AwareDatetime 

114 

115 @model_validator(mode="after") 

116 def valid_identity(self) -> Self: 

117 signal = self.accepted_interpretation 

118 if self.selected_account_ids != tuple(sorted(set(self.selected_account_ids))): 118 ↛ 119line 118 didn't jump to line 119 because the condition on line 118 was never true

119 raise ValueError("Selected account IDs must be unique and sorted") 

120 if not self.actor.strip() or not self.reason.strip(): 120 ↛ 121line 120 didn't jump to line 121 because the condition on line 120 was never true

121 raise ValueError("Manual correction requires an actor and reason") 

122 if ( 122 ↛ 128line 122 didn't jump to line 128 because the condition on line 122 was never true

123 self.source_id != f"{signal.source}:{signal.channel_id}:{signal.id}" 

124 or self.source_at != signal.timestamp 

125 or self.source_text != signal.text 

126 or signal.decision == "ignore" 

127 ): 

128 raise ValueError("Correction does not retain matching reviewed source evidence") 

129 return self 

130 

131 def matches_request(self, request: ManualCorrectionRequest) -> bool: 

132 return ( 

133 self.correction_id == request.correction_id 

134 and self.source_id == request.source_id 

135 and self.selected_account_ids == request.selected_account_ids 

136 and self.actor == request.actor 

137 and self.reason == request.reason 

138 and self.instructions == request.instructions 

139 ) 

140 

141 

142class ManualPreviewRequest(Value): 

143 preview_id: Identifier 

144 account_id: Identifier 

145 correction_id: Identifier 

146 instruction_index: int = Field(ge=0) 

147 

148 

149class ManualCheck(Value): 

150 name: Literal[ 

151 "source", 

152 "account", 

153 "permission", 

154 "session", 

155 "quote", 

156 "risk", 

157 "ownership", 

158 "activity", 

159 "prior_action", 

160 ] 

161 status: Literal["passed", "warning", "blocked"] 

162 reason: str | None = None 

163 

164 

165class ManualOrderPreview(Value): 

166 request: ManualPreviewRequest 

167 broker_account_id: Identifier 

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

169 correction_revision: int = Field(ge=1) 

170 source_at: AwareDatetime 

171 source_age_seconds: int 

172 instruction: Instruction 

173 created_at: AwareDatetime 

174 expires_at: AwareDatetime 

175 session: Session | None 

176 quote: Quote | None 

177 fresh_price: Positive | None 

178 plan: OrderPlan | None 

179 # The limit the order would carry, kept when a check blocks it, so the owner sees the number 

180 # the fresh price was held against. 

181 limit_price: Positive | None = None 

182 checks: tuple[ManualCheck, ...] 

183 reasons: tuple[Identifier, ...] 

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

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

186 

187 @model_validator(mode="after") 

188 def valid_decision(self) -> Self: 

189 if (self.plan is not None) != (not self.reasons): 

190 raise ValueError("A manual preview plan must agree with its blocking reasons") 

191 if self.expires_at <= self.created_at: 

192 raise ValueError("Manual preview expiration must follow its creation") 

193 if (self.quote is None) != (self.fresh_price is None): 

194 raise ValueError("A fresh preview price requires its quote evidence") 

195 if self.plan is not None and self.session is None: 

196 raise ValueError("A ready manual preview requires a market session") 

197 return self 

198 

199 

200class ManualConfirmationRequest(Value): 

201 command_id: Identifier 

202 preview_id: Identifier 

203 account_id: Identifier 

204 actor: Identifier 

205 

206 @model_validator(mode="after") 

207 def valid_actor(self) -> Self: 

208 if not self.actor.strip(): 

209 raise ValueError("Manual confirmation requires an actor") 

210 return self 

211 

212 

213class ManualCommandRecord(Value): 

214 request: ManualConfirmationRequest 

215 correction_id: Identifier 

216 source_id: Identifier 

217 instruction_index: int = Field(ge=0) 

218 confirmed_at: AwareDatetime 

219 state: Literal["rejected", "prepared"] 

220 reason: Identifier | None = None 

221 client_id: Identifier | None = None 

222 

223 @model_validator(mode="after") 

224 def valid_state(self) -> Self: 

225 if self.state == "rejected" and (self.reason is None or self.client_id is not None): 

226 raise ValueError("Rejected manual command requires a reason and no order intent") 

227 if self.state == "prepared" and (self.reason is not None or self.client_id is None): 

228 raise ValueError("Prepared manual command requires its order intent") 

229 return self 

230 

231 

232class ManualCommandResult(Value): 

233 command: ManualCommandRecord 

234 status: Literal[ 

235 "rejected", 

236 "prepared", 

237 "uncertain", 

238 "accepted", 

239 "partially_filled", 

240 "filled", 

241 "cancelled", 

242 "broker_rejected", 

243 "expired", 

244 ] 

245 reason: Identifier | None = None 

246 client_id: Identifier | None = None 

247 broker_order_id: Identifier | None = None 

248 order_status: OrderStatus | None = None 

249 filled_qty: Quantity = Decimal(0) 

250 

251 

252class ManualCorrectionAccountResult(Value): 

253 account_id: Identifier 

254 status: Literal["recorded", "unavailable", "failed"] 

255 reason: Identifier | None = None 

256 

257 

258class ManualCorrectionOutcome(Value): 

259 correction: ManualCorrectionRecord 

260 accounts: tuple[ManualCorrectionAccountResult, ...] 

261 

262 

263class ManualAccountCommandResult(Value): 

264 account_id: Identifier 

265 command_id: Identifier 

266 result: ManualCommandResult | None = None 

267 error: Identifier | None = None 

268 

269 @model_validator(mode="after") 

270 def has_one_outcome(self) -> Self: 

271 if (self.result is None) == (self.error is None): 

272 raise ValueError("Manual account command needs exactly one outcome") 

273 if self.result is not None and self.result.command.request.account_id != self.account_id: 

274 raise ValueError("Manual command result belongs to another account") 

275 return self 

276 

277 

278class ManualCommandsOutcome(Value): 

279 outcomes: tuple[ManualAccountCommandResult, ...] 

280 

281 

282class ManualCommandPage(Value): 

283 account_id: Identifier 

284 source_id: Identifier 

285 items: tuple[ManualCommandResult, ...] 

286 next_before_command_id: Identifier | None = None 

287 

288 @model_validator(mode="after") 

289 def rows_match_page_identity(self) -> Self: 

290 if any( 

291 item.command.request.account_id != self.account_id 

292 or item.command.source_id != self.source_id 

293 for item in self.items 

294 ): 

295 raise ValueError("Manual command page contains a result for another account or source") 

296 return self 

297 

298 

299class ManualCommandPageRequest(Value): 

300 account_id: Identifier 

301 source_id: Identifier 

302 before_command_id: Identifier | None = None 

303 limit: int = Field(default=50, ge=1, le=100)