Coverage for src/copytrading_engine/assistant/results.py: 79%

105 statements  

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

1"""What each tool hands the model: short, named, in the owner's words, without internal fields. 

2 

3The engine's contract is for programs; the model reads these instead, so it repeats what the app 

4says (not codes), names gurus, writes money in dollars, and has fewer tokens to wade through. 

5Discord text stays under `untrusted_source_text`, which the instructions treat as data. 

6""" 

7 

8from collections.abc import Mapping 

9from decimal import Decimal 

10from fractions import Fraction 

11 

12from copytrading_engine.assistant import insights 

13from copytrading_engine.assistant.wording import ( 

14 AFTER_RESTART, 

15 COPYING_DETAILS, 

16 money, 

17 plain, 

18 shares, 

19 when, 

20) 

21from copytrading_engine.control import wire 

22 

23# How a model call is read, as Activity's "Read as" puts it. 

24ACTIONS = {"buy": "Buy", "reduce": "Sell part of", "close": "Sell all of"} 

25 

26 

27def _fraction(value: Decimal | None) -> str | None: 

28 """ "1/6 of a full position", the way the guru and the app say it.""" 

29 if value is None: 

30 return None 

31 if value == 1: 31 ↛ 32line 31 didn't jump to line 32 because the condition on line 31 was never true

32 return "a full position" 

33 near = Fraction(value).limit_denominator(100) 

34 share = ( 

35 f"{near}" 

36 if abs(Decimal(near.numerator) / near.denominator - value) < Decimal("1e-6") 

37 else f"{value:.4f}" 

38 ) 

39 return f"{share} of a full position" 

40 

41 

42def _instruction(item: wire.InstructionItem) -> str: 

43 price = money(item.price) if item.price is not None else "the market" 

44 text = f"{ACTIONS[item.action]} {item.symbol} at {price}" 

45 size = _fraction(item.fraction) 

46 return f"{text}, {size}" if size else text 

47 

48 

49def _order(order: wire.OrderView) -> str: 

50 side = "Bought" if order.side == "buy" else "Sold" 

51 if order.filled_quantity > 0 and order.average_fill_price is not None: 

52 return ( 

53 f"{side} {shares(order.filled_quantity)} {order.symbol} " 

54 f"at {money(order.average_fill_price)} ({plain(order.status)})" 

55 ) 

56 return f"{order.side} order for {shares(order.quantity)} {order.symbol}: {plain(order.status)}" 

57 

58 

59def _copying(word: wire.CopyingWord, detail: str | None) -> dict: 

60 """The word the app shows, and the line under it, never the engine's states.""" 

61 return {"copying": wire.COPYING_WORDS[word], "why": plain(detail, COPYING_DETAILS)} 

62 

63 

64def status(view: wire.StatusView) -> dict: 

65 processing = view.processing 

66 return { 

67 **_copying(processing.copying, processing.copying_detail), 

68 "discord_connected": processing.source_connected, 

69 "model_ready": processing.model_ready, 

70 "posts_waiting_to_be_read": processing.pending_source, 

71 "accounts": [ 

72 { 

73 "account": account.account_id, 

74 **_copying(account.copying, account.copying_detail), 

75 "after_a_restart": plain(account.recovery_preference, AFTER_RESTART), 

76 } 

77 for account in view.accounts 

78 ], 

79 } 

80 

81 

82def accounts(page: wire.AccountsPage) -> dict: 

83 return { 

84 "accounts": [_account(account) for account in page.items], 

85 "could_not_read": [ 

86 {"account": item.account_id, "why": plain(item.reason)} for item in page.unavailable 

87 ], 

88 } 

89 

90 

91def _account(account: wire.AccountView) -> dict: 

92 shaped: dict = { 

93 "account": account.account_id, 

94 "kind": account.environment, 

95 **_copying(account.copying, account.copying_detail), 

96 "after_a_restart": plain(account.recovery_preference, AFTER_RESTART), 

97 "in_stocks": money(account.total_exposure_usd), 

98 "positions": [ 

99 { 

100 "stock": position.symbol, 

101 "copied_shares": shares(position.owned_qty), 

102 "owners_own_shares": shares(position.external_qty), 

103 "copied_buys": [ 

104 { 

105 "shares": shares(lot.remaining_qty), 

106 "bought_at": money(lot.average_price), 

107 "bought": when(lot.bought_at), 

108 } 

109 for lot in position.lots 

110 ], 

111 } 

112 for position in account.positions 

113 ], 

114 } 

115 if account.balance is not None: 115 ↛ 123line 115 didn't jump to line 123 because the condition on line 115 was always true

116 shaped["balance"] = { 

117 "equity": money(account.balance.equity), 

118 "today": money(account.balance.day_change_usd), 

119 "cash": money(account.balance.cash), 

120 "buying_power": money(account.balance.buying_power), 

121 "as_of": when(account.balance.observed_at), 

122 } 

123 if account.ownership_incidents: 123 ↛ 124line 123 didn't jump to line 124 because the condition on line 123 was never true

124 shaped["holdings_need_review"] = account.ownership_incidents 

125 if account.pending_orders: 125 ↛ 127line 125 didn't jump to line 127 because the condition on line 125 was always true

126 shaped["open_orders"] = account.pending_orders 

127 for name, status_, reason in ( 

128 ("risk_check", account.risk_status, account.risk_reason), 

129 ("broker_activity_check", account.activity_status, account.activity_reason), 

130 ): 

131 if status_ != "ready": 131 ↛ 132line 131 didn't jump to line 132 because the condition on line 131 was never true

132 shaped[name] = plain(reason) or plain(status_) 

133 return shaped 

134 

135 

136def activity(page: wire.ActivityPage, guru_names: Mapping[str, str]) -> dict: 

137 return { 

138 "posts": [_post(item, guru_names) for item in page.items], 

139 "posts_not_read": [ 

140 {"post": item.source_id, "when": when(item.rejected_at), "why": plain(item.reason)} 

141 for item in page.rejected 

142 ], 

143 "could_not_read": [ 

144 {"account": item.account_id, "why": plain(item.reason)} for item in page.unavailable 

145 ], 

146 } 

147 

148 

149def _post(item: wire.ActivityItem, guru_names: Mapping[str, str]) -> dict: 

150 shaped: dict = { 

151 "post": item.source_id, 

152 "when": when(item.source_at), 

153 "guru": guru_names.get(item.guru_id or "", item.guru_id), 

154 "untrusted_source_text": item.untrusted_source_text, 

155 "read_as": [_instruction(instruction) for instruction in item.understood_as], 

156 } 

157 if item.parser_reason: 157 ↛ 159line 157 didn't jump to line 159 because the condition on line 157 was always true

158 shaped["why_not_a_trade"] = plain(item.parser_reason) 

159 shaped["accounts"] = [ 

160 { 

161 "account": destination.account_id, 

162 "outcome": [plain(code) for code in destination.instruction_outcomes] 

163 or [plain(destination.status)], 

164 "orders": [_order(order) for order in destination.orders], 

165 } 

166 for destination in item.destinations 

167 ] 

168 return shaped 

169 

170 

171def account_events(page: wire.AccountEventsPage) -> dict: 

172 return { 

173 "account": page.account_id, 

174 "events": [ 

175 { 

176 key: value 

177 for key, value in ( 

178 ("when", when(event.at)), 

179 ("what", plain(event.kind)), 

180 ("why", plain(event.reason)), 

181 ("status", plain(event.status)), 

182 ) 

183 if value 

184 } 

185 for event in page.items 

186 ], 

187 } 

188 

189 

190def _asks_to(subject: wire.ProposalSubject) -> str: 

191 match subject: 

192 case wire.ResumeAccountSubject(): 

193 return f"start copying into {subject.account_id}" 

194 case wire.RecoverySubject(): 194 ↛ 195line 194 didn't jump to line 195 because the pattern on line 194 never matched

195 return ( 

196 f"set {subject.account_id} so that after a restart it " 

197 + (AFTER_RESTART[subject.preference]) 

198 ) 

199 case wire.ManualOrderSubject(): 199 ↛ 200line 199 didn't jump to line 200 because the pattern on line 199 never matched

200 return ( 

201 f"{subject.side} {shares(subject.quantity)} {subject.symbol} " 

202 f"in {subject.account_id}" 

203 ) 

204 case wire.StartProcessingSubject(): 204 ↛ 205line 204 didn't jump to line 205 because the pattern on line 204 never matched

205 return "start copying" 

206 case wire.ApplySetupSubject(): 206 ↛ 215line 206 didn't jump to line 215 because the pattern on line 206 always matched

207 touched = { 

208 *subject.made_live, 

209 *subject.new_live_keys, 

210 *subject.changed_live, 

211 *subject.starts_live, 

212 } 

213 live = ", ".join(sorted(touched)) 

214 return f"apply the setup, which touches live {live or 'accounts'}" 

215 case wire.LimitsSubject(): 

216 return f"change {subject.account_id}'s limits: " + ", ".join( 

217 f"{change.field.replace('_', ' ')} to {change.value}" for change in subject.changes 

218 ) 

219 

220 

221PROPOSAL_STATES = { 

222 "pending": "waiting for the owner's approval with Touch ID in the app", 

223 "running": "approved, being carried out", 

224 "succeeded": "approved and done", 

225 "failed": "approved but it failed", 

226 "outcome_unknown": "approved, outcome not known yet", 

227 "rejected": "the owner rejected it", 

228 "expired": "expired before the owner approved it", 

229 "discarded": "discarded", 

230} 

231 

232 

233def proposal(view: wire.ProposalView) -> dict: 

234 return { 

235 "request": view.proposal_id, 

236 "asks_to": _asks_to(view.subject), 

237 "state": PROPOSAL_STATES[view.state], 

238 "expires": when(view.expires_at), 

239 } 

240 

241 

242def proposals(page: wire.ProposalsPage) -> dict: 

243 return {"requests": [proposal(view) for view in page.items]} 

244 

245 

246def paused(view: wire.ProcessingPaused) -> dict: 

247 return _copying(view.processing.copying, view.processing.copying_detail) 

248 

249 

250# An account's new buys after the owner paused or resumed them. 

251_BUYS: dict[str, wire.CopyingWord] = { 

252 "enabled": "copying", 

253 "paused": "sells_only", 

254 "disabled": "not_started", 

255} 

256 

257 

258def account_control(view: wire.AccountControlView) -> dict: 

259 word = _BUYS.get(view.entry_permission, "not_started") 

260 return { 

261 "account": view.account_id, 

262 **_copying(word, "account_paused" if word == "sells_only" else None), 

263 "done": when(view.applied_at), 

264 } 

265 

266 

267def result(view: wire.Result, guru_names: Mapping[str, str]) -> dict: 

268 """The model's view of one control result.""" 

269 match view: 

270 case wire.StatusView(): 

271 return status(view) 

272 case wire.AccountsPage(): 

273 return accounts(view) 

274 case wire.ActivityPage(): 

275 return activity(view, guru_names) 

276 case wire.AccountEventsPage(): 

277 return account_events(view) 

278 case wire.ProposalView(): 

279 return proposal(view) 

280 case wire.ProposalsPage(): 

281 return proposals(view) 

282 case wire.ProcessingPaused(): 282 ↛ 283line 282 didn't jump to line 283 because the pattern on line 282 never matched

283 return paused(view) 

284 case wire.AccountControlView(): 284 ↛ 286line 284 didn't jump to line 286 because the pattern on line 284 always matched

285 return account_control(view) 

286 case _: 

287 return view.model_dump(mode="json") 

288 

289 

290def guru_record(record: insights.GuruRecord, name: str) -> dict: 

291 return { 

292 "guru": name, 

293 "days": record.days, 

294 "posts": record.posts, 

295 "calls": record.calls, 

296 "copied": record.copied, 

297 "skipped": {plain(code): count for code, count in record.skipped.items()}, 

298 } 

299 

300 

301def skip(explanation: insights.SkipExplanation) -> dict: 

302 return { 

303 "post": explanation.source_id, 

304 "untrusted_source_text": explanation.untrusted_source_text, 

305 "read_as": explanation.understood_as, 

306 "accounts": [ 

307 {"account": account.account_id, "outcome": account.reason} 

308 for account in explanation.accounts 

309 ], 

310 }