Coverage for src/copytrading_engine/control/cli.py: 83%

371 statements  

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

1"""`copytrading`: check and steer a running CopyTrading from a terminal or an agent.""" 

2 

3import argparse 

4import asyncio 

5import datetime as dt 

6import json 

7import sys 

8from collections.abc import Callable, Sequence 

9from decimal import Decimal 

10from fractions import Fraction 

11from typing import Final, TextIO, assert_never 

12 

13from copytrading_engine.control import cli_setup, wire 

14from copytrading_engine.control.client import ( 

15 OLDER_CLIENT, 

16 AppUnavailable, 

17 ControlClient, 

18 NoAnswer, 

19 ProtocolMismatch, 

20 RequestTooLarge, 

21 UnsafeSocket, 

22 is_server_socket, 

23 new_request_id, 

24 socket_path, 

25) 

26 

27WAIT_INTERVAL_SECONDS: Final = 1.0 

28 

29EXIT_OK: Final = 0 

30EXIT_FAILURE: Final = 1 

31EXIT_USAGE: Final = 2 

32EXIT_APP_UNAVAILABLE: Final = 3 

33EXIT_LOCKED: Final = 4 

34EXIT_REFUSED: Final = 5 

35EXIT_NOT_COMPLETED: Final = 6 

36EXIT_PROPOSAL_CLOSED: Final = 7 

37EXIT_APPROVAL_PENDING: Final = 10 

38 

39 

40def error_exit_code(code: wire.ErrorCode) -> int: 

41 match code: 

42 case "access_off": 

43 return EXIT_APP_UNAVAILABLE 

44 case "locked": 

45 return EXIT_LOCKED 

46 case "invalid_request": 

47 return EXIT_USAGE 

48 case "forbidden" | "busy" | "cooling_down" | "proposal_limit" | "conflict": 

49 return EXIT_REFUSED 

50 case "not_found" | "unavailable": 

51 return EXIT_NOT_COMPLETED 

52 case "expired" | "rejected": 52 ↛ 54line 52 didn't jump to line 54 because the pattern on line 52 always matched

53 return EXIT_PROPOSAL_CLOSED 

54 case _: 

55 assert_never(code) 

56 

57 

58def proposal_exit_code(proposal: wire.ProposalView) -> int: 

59 match proposal.state: 

60 case "pending" | "running": 

61 return EXIT_APPROVAL_PENDING 

62 case "succeeded": 

63 return EXIT_OK 

64 case "failed" | "outcome_unknown": 

65 return EXIT_NOT_COMPLETED 

66 case "rejected" | "expired" | "discarded": 66 ↛ 68line 66 didn't jump to line 68 because the pattern on line 66 always matched

67 return EXIT_PROPOSAL_CLOSED 

68 case _: 

69 assert_never(proposal.state) 

70 

71 

72def _parser() -> argparse.ArgumentParser: 

73 output = argparse.ArgumentParser(add_help=False) 

74 output.add_argument("--json", action="store_true", help="print the raw contract response") 

75 paged = argparse.ArgumentParser(add_help=False) 

76 paged.add_argument("--limit", type=int, default=50, help="items per page (1-100)") 

77 

78 parser = argparse.ArgumentParser( 

79 prog="copytrading", 

80 description="Check, steer and set up a running CopyTrading. Actions that can trade, " 

81 "and setup that touches a live account, only create proposals; the owner approves " 

82 "them in the app.", 

83 ) 

84 commands = parser.add_subparsers(dest="command", required=True) 

85 commands.add_parser("status", parents=[output], help="engine, processing and accounts") 

86 

87 accounts = commands.add_parser("accounts", parents=[output, paged], help="accounts") 

88 accounts.add_argument("--before", dest="before_account_id") 

89 account_actions = accounts.add_subparsers(dest="action") 

90 account_actions.add_parser( 

91 "pause", parents=[output], help="stop copying into an account" 

92 ).add_argument("account_id") 

93 account_actions.add_parser( 

94 "resume", parents=[output], help="propose copying into an account again" 

95 ).add_argument("account_id") 

96 recovery = account_actions.add_parser( 

97 "recovery", parents=[output], help="propose a recovery preference" 

98 ) 

99 recovery.add_argument("account_id") 

100 recovery.add_argument("preference", choices=("manual", "automatic")) 

101 

102 limits = account_actions.add_parser( 

103 "limits", 

104 parents=[output], 

105 help="propose new limits and settings for an account (the owner approves in the app)", 

106 ) 

107 limits.add_argument("account_id") 

108 for field in wire.LIMIT_FIELDS: 

109 limits.add_argument( 

110 f"--{field.replace('_', '-')}", 

111 dest=field, 

112 metavar="VALUE", 

113 help="true or false" if field in _SWITCHES else "a number", 

114 ) 

115 

116 activity = commands.add_parser("activity", parents=[output, paged], help="source activity") 

117 activity.add_argument("--before", dest="before_seq", type=int) 

118 events = commands.add_parser("events", parents=[output, paged], help="account events") 

119 events.add_argument("account_id") 

120 events.add_argument("--before", dest="before_seq", type=int) 

121 

122 manual = commands.add_parser("manual", help="reviewed manual orders") 

123 manual_actions = manual.add_subparsers(dest="action", required=True) 

124 manual_list = manual_actions.add_parser("list", parents=[output, paged]) 

125 manual_list.add_argument("account_id") 

126 manual_list.add_argument("source_id") 

127 manual_list.add_argument("--before", dest="before_command_id") 

128 manual_show = manual_actions.add_parser("show", parents=[output]) 

129 manual_show.add_argument("account_id") 

130 manual_show.add_argument("command_id") 

131 manual_preview = manual_actions.add_parser("preview", parents=[output]) 

132 manual_preview.add_argument("account_id") 

133 manual_preview.add_argument("--correction", dest="correction_id", required=True) 

134 manual_preview.add_argument("--instruction", dest="instruction_index", type=int, required=True) 

135 manual_confirm = manual_actions.add_parser( 

136 "confirm", parents=[output], help="propose confirming a previewed order" 

137 ) 

138 manual_confirm.add_argument("account_id") 

139 manual_confirm.add_argument("--preview", dest="preview_id", required=True) 

140 

141 commands.add_parser( 

142 "start", 

143 parents=[output], 

144 help="propose starting copying with Start Copying's checks (approved in the app)", 

145 ) 

146 commands.add_parser("pause", parents=[output], help="pause all processing") 

147 

148 proposals = commands.add_parser("proposals", parents=[output], help="owner approvals") 

149 proposal_actions = proposals.add_subparsers(dest="action") 

150 proposal_actions.add_parser("show", parents=[output]).add_argument("proposal_id") 

151 wait = proposal_actions.add_parser("wait", parents=[output]) 

152 wait.add_argument("proposal_id") 

153 wait.add_argument("--timeout", type=float, default=300.0) 

154 

155 cli_setup.add_setup_parser(commands, output) 

156 

157 commands.add_parser("schema", help="print the contract's JSON Schema") 

158 commands.add_parser("mcp", help="serve the same operations as an MCP stdio server") 

159 return parser 

160 

161 

162def request_for(args: argparse.Namespace, stdin: TextIO | None = None) -> wire.Request: 

163 """Translate parsed arguments into exactly one contract request.""" 

164 request_id = new_request_id() 

165 if args.command == "setup": 

166 return cli_setup.setup_request(args, request_id, stdin or sys.stdin) 

167 match args.command, getattr(args, "action", None): 

168 case "status", _: 

169 return wire.GetStatus(request_id=request_id) 

170 case "accounts", None: 

171 return wire.ListAccounts( 

172 request_id=request_id, before_account_id=args.before_account_id, limit=args.limit 

173 ) 

174 case "accounts", "pause": 

175 return wire.PauseAccount(request_id=request_id, account_id=args.account_id) 

176 case "accounts", "resume": 

177 return wire.ProposeResumeAccount(request_id=request_id, account_id=args.account_id) 

178 case "accounts", "recovery": 

179 return wire.ProposeRecoveryPreference( 

180 request_id=request_id, account_id=args.account_id, preference=args.preference 

181 ) 

182 case "accounts", "limits": 

183 changes = tuple( 

184 wire.LimitChange(field=field, value=str(getattr(args, field))) 

185 for field in wire.LIMIT_FIELDS 

186 if getattr(args, field) is not None 

187 ) 

188 if not changes: 

189 raise ValueError("Name at least one setting, such as --max-order-usd 300") 

190 return wire.ProposeSetAccountLimits( 

191 request_id=request_id, account_id=args.account_id, changes=changes 

192 ) 

193 case "activity", _: 

194 return wire.ListActivity( 

195 request_id=request_id, before_seq=args.before_seq, limit=args.limit 

196 ) 

197 case "events", _: 197 ↛ 198line 197 didn't jump to line 198 because the pattern on line 197 never matched

198 return wire.ListAccountEvents( 

199 request_id=request_id, 

200 account_id=args.account_id, 

201 before_seq=args.before_seq, 

202 limit=args.limit, 

203 ) 

204 case "manual", "list": 204 ↛ 205line 204 didn't jump to line 205 because the pattern on line 204 never matched

205 return wire.ListManualCommands( 

206 request_id=request_id, 

207 account_id=args.account_id, 

208 source_id=args.source_id, 

209 before_command_id=args.before_command_id, 

210 limit=args.limit, 

211 ) 

212 case "manual", "show": 212 ↛ 213line 212 didn't jump to line 213 because the pattern on line 212 never matched

213 return wire.GetManualCommand( 

214 request_id=request_id, account_id=args.account_id, command_id=args.command_id 

215 ) 

216 case "manual", "preview": 216 ↛ 217line 216 didn't jump to line 217 because the pattern on line 216 never matched

217 return wire.PreviewManualOrder( 

218 request_id=request_id, 

219 account_id=args.account_id, 

220 correction_id=args.correction_id, 

221 instruction_index=args.instruction_index, 

222 ) 

223 case "manual", "confirm": 223 ↛ 224line 223 didn't jump to line 224 because the pattern on line 223 never matched

224 return wire.ProposeManualOrder( 

225 request_id=request_id, account_id=args.account_id, preview_id=args.preview_id 

226 ) 

227 case "start", _: 227 ↛ 228line 227 didn't jump to line 228 because the pattern on line 227 never matched

228 return wire.ProposeStartProcessing(request_id=request_id) 

229 case "pause", _: 229 ↛ 230line 229 didn't jump to line 230 because the pattern on line 229 never matched

230 return wire.PauseProcessing(request_id=request_id) 

231 case "proposals", None: 231 ↛ 232line 231 didn't jump to line 232 because the pattern on line 231 never matched

232 return wire.ListProposals(request_id=request_id) 

233 case "proposals", "show" | "wait": 233 ↛ 235line 233 didn't jump to line 235 because the pattern on line 233 always matched

234 return wire.GetProposal(request_id=request_id, proposal_id=args.proposal_id) 

235 case command, action: 

236 raise ValueError(f"Unsupported command: {command} {action}") 

237 

238 

239def main( 

240 argv: Sequence[str] | None = None, 

241 *, 

242 stdout: TextIO | None = None, 

243 stderr: TextIO | None = None, 

244 stdin: TextIO | None = None, 

245 client_factory: Callable[[], ControlClient] | None = None, 

246) -> int: 

247 stdout = stdout or sys.stdout 

248 stderr = stderr or sys.stderr 

249 parser = _parser() 

250 try: 

251 args = parser.parse_args(argv) 

252 except SystemExit as exit_request: 

253 return exit_request.code if isinstance(exit_request.code, int) else EXIT_USAGE 

254 if args.command == "schema": 

255 print(json.dumps(wire.json_schema(), indent=2, sort_keys=True), file=stdout) 

256 return EXIT_OK 

257 if args.command == "mcp": 257 ↛ 259line 257 didn't jump to line 259 because the condition on line 257 was never true

258 # Imported only here so ordinary commands never load the MCP SDK. 

259 from copytrading_engine.control.mcp_server import serve 

260 

261 serve() 

262 return EXIT_OK 

263 if args.command == "setup" and client_factory is None and is_server_socket(): 

264 print(cli_setup.SERVER_REFUSAL, file=stderr) 

265 return EXIT_APP_UNAVAILABLE 

266 # A command that reads a key first makes sure the app is the one answering (below). 

267 request: wire.Request | None = None 

268 if not cli_setup.reads_secret(args): 

269 try: 

270 request = request_for(args, stdin) 

271 except ValueError as error: 

272 print(f"Invalid arguments: {error}", file=stderr) 

273 return EXIT_USAGE 

274 timeout = cli_setup.timeout_for(args) 

275 client = ( 

276 client_factory() 

277 if client_factory 

278 else ControlClient(socket_path()) 

279 if timeout is None 

280 else ControlClient(socket_path(), timeout=timeout) 

281 ) 

282 try: 

283 return asyncio.run(_execute(client, args, request, stdin, stdout, stderr)) 

284 except RequestTooLarge as large: 

285 print( 

286 f"The request is too large ({large.args[0]:,} bytes): CopyTrading takes at most " 

287 f"{wire.MAX_LINE_BYTES // 1024} KB. For `setup import`, keep only the setup's lines " 

288 "in the file.", 

289 file=stderr, 

290 ) 

291 return EXIT_USAGE 

292 except NoAnswer as silent: 

293 print(cli_setup.no_answer(args, silent.args[0] if silent.args else None), file=stderr) 

294 return EXIT_NOT_COMPLETED 

295 except AppUnavailable: 

296 print("CopyTrading is not running, or agent access is turned off.", file=stderr) 

297 return EXIT_APP_UNAVAILABLE 

298 except UnsafeSocket as unsafe: 

299 print(f"Refusing to use {unsafe}: it is not the app's private socket.", file=stderr) 

300 return EXIT_FAILURE 

301 except ProtocolMismatch as mismatch: 

302 if str(mismatch) == OLDER_CLIENT: 

303 print(f"CopyTrading answered with something new: {OLDER_CLIENT}.", file=stderr) 

304 return EXIT_FAILURE 

305 print(f"Unexpected answer from CopyTrading: {mismatch}", file=stderr) 

306 return EXIT_FAILURE 

307 

308 

309async def _execute( 

310 client: ControlClient, 

311 args: argparse.Namespace, 

312 request: wire.Request | None, 

313 stdin: TextIO | None, 

314 stdout: TextIO, 

315 stderr: TextIO, 

316) -> int: 

317 if request is None: 

318 # Keys go only to the Mac app: it must answer `get_setup` before any key is read. 

319 checked = await client.send(wire.GetSetup(request_id=new_request_id())) 

320 if checked.error is not None: 

321 print(checked.error.message, file=stderr) 

322 return error_exit_code(checked.error.code) 

323 if not isinstance(checked.ok, wire.SetupView): 323 ↛ 324line 323 didn't jump to line 324 because the condition on line 323 was never true

324 raise ProtocolMismatch("the socket did not answer as the CopyTrading app") 

325 try: 

326 request = request_for(args, stdin) 

327 except ValueError as error: 

328 print(f"Invalid arguments: {error}", file=stderr) 

329 return EXIT_USAGE 

330 response = await client.send(request) 

331 if args.command == "proposals" and args.action == "wait": 

332 response = await _wait(client, response, args.timeout) 

333 if args.json: 

334 print(response.model_dump_json(), file=stdout) 

335 if response.error is not None: 

336 if not args.json: 336 ↛ 338line 336 didn't jump to line 338 because the condition on line 336 was always true

337 print(response.error.message, file=stderr) 

338 return error_exit_code(response.error.code) 

339 result = response.ok 

340 if result is None: 340 ↛ 341line 340 didn't jump to line 341 because the condition on line 340 was never true

341 raise ProtocolMismatch("response has no result") 

342 if not args.json: 

343 print(render(result), file=stdout) 

344 if isinstance(result, wire.ProposalView): 

345 return proposal_exit_code(result) 

346 if isinstance(result, wire.SetupApplied): 

347 return cli_setup.setup_exit_code(result) 

348 return EXIT_OK 

349 

350 

351async def _wait(client: ControlClient, response: wire.Response, timeout: float) -> wire.Response: 

352 """Poll a proposal until the owner decides, it expires, or the wait times out.""" 

353 loop = asyncio.get_running_loop() 

354 deadline = loop.time() + timeout 

355 while ( 

356 isinstance(response.ok, wire.ProposalView) 

357 and response.ok.state in ("pending", "running") 

358 and loop.time() < deadline 

359 ): 

360 await asyncio.sleep(WAIT_INTERVAL_SECONDS) 

361 response = await client.send( 

362 wire.GetProposal(request_id=new_request_id(), proposal_id=response.ok.proposal_id) 

363 ) 

364 return response 

365 

366 

367# Text output 

368 

369 

370_SWITCHES: Final = ("extended_hours", "overnight", "copy_exits", "approve_orders", "follow_stops") 

371 

372 

373def _words(code: str | None) -> str: 

374 return "—" if code is None else code.replace("_", " ") 

375 

376 

377def _unavailable(reason: str) -> str: 

378 """Why an account could not be shown; an earlier version's history is kept, not broken.""" 

379 if reason == "earlier_version": 379 ↛ 381line 379 didn't jump to line 381 because the condition on line 379 was always true

380 return "history kept from an earlier version of CopyTrading" 

381 return f"unavailable ({_words(reason)})" 

382 

383 

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

385 """One of the app's five words, with the reason under it when there is one.""" 

386 return wire.COPYING_WORDS[word] + (f" ({_words(detail)})" if detail else "") 

387 

388 

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

390 "enabled": "copying", 

391 "paused": "sells_only", 

392 "disabled": "not_started", 

393} 

394 

395 

396def _time(value: dt.datetime) -> str: 

397 return value.astimezone().strftime("%Y-%m-%d %H:%M:%S") 

398 

399 

400def _amount(value: Decimal | None) -> str: 

401 return "—" if value is None else f"{value.normalize():f}" 

402 

403 

404def _dollars(value: Decimal | None) -> str: 

405 """Dollars with cents, keeping any finer digits a price really has: $25.10, $121.385.""" 

406 if value is None: 406 ↛ 407line 406 didn't jump to line 407 because the condition on line 406 was never true

407 return "—" 

408 exponent = value.normalize().as_tuple().exponent 

409 places = max(2, -exponent if isinstance(exponent, int) else 2) 

410 return f"${value:,.{places}f}" 

411 

412 

413def render(result: wire.Result) -> str: 

414 match result: 

415 case wire.StatusView(): 

416 return _render_status(result) 

417 case wire.AccountsPage(): 

418 return _render_accounts(result) 

419 case wire.ActivityPage(): 

420 return _render_activity(result) 

421 case wire.AccountEventsPage(): 421 ↛ 422line 421 didn't jump to line 422 because the pattern on line 421 never matched

422 lines = [f"Events for {result.account_id}"] 

423 lines += [ 

424 f" #{item.sequence} {_time(item.at)} {_words(item.kind)}" 

425 + (f" {_words(item.status)}" if item.status else "") 

426 + (f" ({_words(item.reason)})" if item.reason else "") 

427 for item in result.items 

428 ] 

429 return "\n".join(lines + _next("--before", result.next_before_seq)) 

430 case wire.ManualCommandsPage(): 430 ↛ 431line 430 didn't jump to line 431 because the pattern on line 430 never matched

431 lines = [f"Manual commands for {result.account_id}"] 

432 lines += [_render_command(item) for item in result.items] 

433 return "\n".join(lines + _next("--before", result.next_before_command_id)) 

434 case wire.ManualCommand(): 434 ↛ 435line 434 didn't jump to line 435 because the pattern on line 434 never matched

435 return _render_command(result.command) 

436 case wire.ManualPreview(): 436 ↛ 437line 436 didn't jump to line 437 because the pattern on line 436 never matched

437 return _render_preview(result) 

438 case wire.ProposalView(): 

439 return _render_proposal(result) 

440 case wire.ProposalsPage(): 440 ↛ 441line 440 didn't jump to line 441 because the pattern on line 440 never matched

441 if not result.items: 

442 return "No proposals." 

443 return "\n".join(_render_proposal(item) for item in result.items) 

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

445 processing = result.processing 

446 return f"{_copying(processing.copying, processing.copying_detail)}." 

447 case wire.AccountControlView(): 

448 word = _BUYS.get(result.entry_permission, "not_started") 

449 return f"{result.account_id}: {wire.COPYING_WORDS[word]}." 

450 case wire.SetupView(): 

451 return cli_setup.render_setup(result) 

452 case wire.SetupImported(): 

453 return cli_setup.render_imported(result) 

454 case wire.SetupApplied(): 454 ↛ 456line 454 didn't jump to line 456 because the pattern on line 454 always matched

455 return cli_setup.render_applied(result) 

456 case _: 

457 assert_never(result) 

458 

459 

460def _next(flag: str, value: object) -> list[str]: 

461 return [] if value is None else [f"More: {flag} {value}"] 

462 

463 

464def _render_status(status: wire.StatusView) -> str: 

465 processing = status.processing 

466 lines = [ 

467 f"Engine {_words(status.engine_state)}", 

468 f"Copying {_copying(processing.copying, processing.copying_detail)}", 

469 f"Source {'connected' if processing.source_connected else 'not connected'}", 

470 f"Model {'ready' if processing.model_ready else 'not ready'}", 

471 f"Queued {processing.pending_source} messages, {processing.pending_signals} signals", 

472 ] 

473 for account in status.accounts: 

474 lines.append( 

475 f"Account {account.account_id} " 

476 f"{_copying(account.copying, account.copying_detail)}, " 

477 f"after a restart {_words(account.recovery_preference)}" 

478 ) 

479 return "\n".join(lines) 

480 

481 

482def _render_accounts(page: wire.AccountsPage) -> str: 

483 lines: list[str] = [] 

484 for account in page.items: 

485 lines.append( 

486 f"{account.account_id} ({account.environment}) " 

487 f"{_copying(account.copying, account.copying_detail)}, " 

488 f"after a restart {_words(account.recovery_preference)}, " 

489 f"risk {_words(account.risk_status)}, exposure {_dollars(account.total_exposure_usd)}" 

490 ) 

491 for position in account.positions: 

492 if not (position.owned_qty or position.external_qty or position.lots): 492 ↛ 493line 492 didn't jump to line 493 because the condition on line 492 was never true

493 continue # a stock traded before and now at zero is history, not a position 

494 lines.append( 

495 f" {position.symbol} app {_amount(position.owned_qty)}, " 

496 f"external {_amount(position.external_qty)}" 

497 ) 

498 lines += [ 

499 f" lot {lot.lot_id} {_amount(lot.remaining_qty)} of " 

500 f"{_amount(lot.original_qty)} at {_dollars(lot.average_price)}" 

501 f"{f' from {lot.guru_id}' if lot.guru_id else ''}" 

502 f"{f' ({lot.source_id})' if lot.source_id else ''}" 

503 for lot in position.lots 

504 ] 

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

506 lines.append(f" {account.ownership_incidents} ownership incident(s) need review") 

507 lines += [f"{item.account_id}: {_unavailable(item.reason)}" for item in page.unavailable] 

508 return "\n".join(lines or ["No accounts."]) + "".join( 

509 "\n" + line for line in _next("--before", page.next_before_account_id) 

510 ) 

511 

512 

513def _share(fraction: Decimal) -> str: 

514 """A share as the guru writes it: 1/6, not 16.666…%.""" 

515 near = Fraction(fraction).limit_denominator(12) 

516 if abs(Decimal(near.numerator) / Decimal(near.denominator) - fraction) < Decimal("0.0001"): 516 ↛ 518line 516 didn't jump to line 518 because the condition on line 516 was always true

517 return f"{near.numerator}/{near.denominator}" 

518 return f"{(fraction * 100).quantize(Decimal('0.01')).normalize():f}%" 

519 

520 

521def _instruction(step: wire.InstructionItem) -> str: 

522 if step.action == "close": 

523 verb, size = "sell all", "" 

524 elif step.usd_amount is not None: 

525 verb, size = step.action, f"{_dollars(step.usd_amount)} of " 

526 else: 

527 verb = "buy" if step.action == "buy" else "sell" 

528 size = f"{_share(step.fraction)} of " if step.fraction is not None else "" 

529 price = _dollars(step.price) if step.price is not None else "the market" 

530 return f"{verb} {size}{step.symbol} at {price}" 

531 

532 

533def _destination(target: wire.DestinationView) -> str: 

534 """An account's outcome, and why any call in the post placed no order.""" 

535 line = f" → {target.account_id}: {_words(target.status)}" 

536 reasons = [ 

537 f"call {index}: {_words(outcome)}" 

538 for index, outcome in enumerate(target.instruction_outcomes, 1) 

539 if outcome != "order_linked" 

540 ] 

541 return line + (f" ({'; '.join(reasons)})" if reasons else "") 

542 

543 

544def _render_activity(page: wire.ActivityPage) -> str: 

545 lines: list[str] = [] 

546 for item in page.items: 

547 lines.append( 

548 f"#{item.sequence} {_time(item.source_at)} parse {_words(item.parse_status)}, " 

549 f"delivery {_words(item.delivery_status)}" 

550 + (f", {_words(item.decision)}" if item.decision else "") 

551 ) 

552 lines.append(" Source text (untrusted):") 

553 lines += [f" │ {text}" for text in item.untrusted_source_text.splitlines() or [""]] 

554 lines += [f" Understood as: {_instruction(step)}" for step in item.understood_as] 

555 lines += [_destination(target) for target in item.destinations] 

556 lines += [ 

557 f"Rejected {item.source_id} at {_time(item.rejected_at)}: {_words(item.reason)}" 

558 for item in page.rejected 

559 ] 

560 return "\n".join((lines or ["No activity."]) + _next("--before", page.next_before_seq)) 

561 

562 

563def _render_command(command: wire.ManualCommandView) -> str: 

564 return ( 

565 f"{command.command_id} {_words(command.status)} confirmed {_time(command.confirmed_at)}" 

566 + (f" ({_words(command.reason)})" if command.reason else "") 

567 ) 

568 

569 

570def _render_preview(preview: wire.ManualPreview) -> str: 

571 instruction = preview.instruction 

572 lines = [ 

573 f"Preview {preview.preview_id} for {preview.account_id} ({preview.environment}), " 

574 f"expires {_time(preview.expires_at)}", 

575 f" Instruction: {instruction.action} {instruction.symbol} at " 

576 + (_dollars(instruction.price) if instruction.price is not None else "the market"), 

577 ] 

578 if preview.plan is None: 

579 lines.append(" Blocked: " + ", ".join(_words(reason) for reason in preview.reasons)) 

580 else: 

581 plan = preview.plan 

582 lines.append( 

583 f" Order: {plan.side} {_amount(plan.quantity)} {plan.type}" 

584 + (f" at {_dollars(plan.limit_price)}" if plan.limit_price is not None else "") 

585 + f" ({_words(plan.session)} session)" 

586 ) 

587 lines.append( 

588 f" To ask the owner: copytrading manual confirm {preview.account_id} " 

589 f"--preview {preview.preview_id}" 

590 ) 

591 lines += [ 

592 f" Check {_words(check.name)}: {check.status}" 

593 + (f" ({_words(check.reason)})" if check.reason else "") 

594 for check in preview.checks 

595 ] 

596 return "\n".join(lines) 

597 

598 

599def _render_proposal(proposal: wire.ProposalView) -> str: 

600 subject = proposal.subject 

601 match subject: 

602 case wire.ResumeAccountSubject(): 

603 what = f"start copying into {subject.account_id}" 

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

605 what = f"set recovery for {subject.account_id} to {subject.preference}" 

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

607 what = "start copying" 

608 case wire.ApplySetupSubject(): 

609 what = cli_setup.describe_apply_proposal(subject) 

610 case wire.LimitsSubject(): 610 ↛ 614line 610 didn't jump to line 614 because the pattern on line 610 always matched

611 what = f"change {subject.account_id}: " + ", ".join( 

612 f"{_words(change.field)} = {change.value}" for change in subject.changes 

613 ) 

614 case wire.ManualOrderSubject(): 

615 what = ( 

616 f"{subject.side} {_amount(subject.quantity)} {subject.symbol} " 

617 f"({subject.order_type}" 

618 + (f" at {_dollars(subject.limit_price)}" if subject.limit_price else "") 

619 + f") in {subject.account_id} ({subject.environment})" 

620 ) 

621 if proposal.state == "pending": 

622 return ( 

623 f"Waiting for approval in CopyTrading: {what}. " 

624 f"Proposal {proposal.proposal_id}, expires {_time(proposal.expires_at)}." 

625 ) 

626 outcome = proposal.outcome 

627 detail = f" ({_words(outcome.code)})" if outcome is not None and outcome.code else "" 

628 return f"Proposal {proposal.proposal_id} {_words(proposal.state)}{detail}: {what}."