Coverage for src/copytrading_engine/control/cli_setup.py: 85%

274 statements  

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

1"""`copytrading setup …`: read and change the app's setup, the draft Connections edits. 

2 

3Keys, tokens and secrets are read only from standard input (`--secret-stdin`) or a file 

4(`--from-file PATH`), never from an argument or the environment, and nothing here prints one. 

5""" 

6 

7import argparse 

8import getpass 

9import os 

10import stat 

11from collections.abc import Callable 

12from typing import Final, TextIO, assert_never, get_args 

13 

14from pydantic import SecretStr, ValidationError 

15 

16from copytrading_engine.control import wire 

17 

18# How long `setup apply` waits for the app: every connection check, a pause when copying runs, 

19# and the start. 

20APPLY_TIMEOUT_SECONDS: Final = 300.0 

21MAX_SECRET_FILE_BYTES: Final = 64 * 1024 

22SWITCHES: Final = ("extended_hours", "overnight", "copy_exits", "approve_orders", "follow_stops") 

23# What an account does after a restart, in the account sheet's words, and the setup's value. 

24AFTER_RESTART: Final[dict[str, wire.RecoveryPreference]] = { 

25 "wait-for-me": "manual", 

26 "carry-on": "automatic", 

27} 

28AFTER_RESTART_WORDS: Final[dict[wire.RecoveryPreference, str]] = { 

29 "manual": "Wait for me", 

30 "automatic": "Carry on by itself", 

31} 

32 

33type Prompt = Callable[[str], str] 

34 

35SERVER_REFUSAL: Final = ( 

36 "`copytrading setup` changes the CopyTrading app's setup, and only the app may receive " 

37 "keys. The CopyTrading answering here is a server, which is set up in copytrading.toml." 

38) 

39 

40 

41def reads_secret(args: argparse.Namespace) -> bool: 

42 """The command reads a key or a setup file, so it first checks the app is answering.""" 

43 return args.command == "setup" and ( 

44 bool(getattr(args, "secret_stdin", False)) 

45 or getattr(args, "from_file", None) is not None 

46 or args.action == "import" 

47 ) 

48 

49 

50def add_setup_parser(commands: argparse._SubParsersAction, output: argparse.ArgumentParser) -> None: 

51 secret = argparse.ArgumentParser(add_help=False) 

52 source = secret.add_mutually_exclusive_group() 

53 source.add_argument( 

54 "--secret-stdin", 

55 action="store_true", 

56 help="read the key from standard input (asked for without echo at a terminal)", 

57 ) 

58 source.add_argument("--from-file", metavar="PATH", help="read the key from a file") 

59 limits = argparse.ArgumentParser(add_help=False) 

60 for field in wire.LIMIT_FIELDS: 

61 limits.add_argument( 

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

63 dest=field, 

64 metavar="VALUE", 

65 help="true or false" if field in SWITCHES else "a number", 

66 ) 

67 

68 setup = commands.add_parser( 

69 "setup", 

70 help="read and change the setup: Discord, model, accounts, gurus, alerts", 

71 description="Change the setup Connections shows. Edits wait in the app's unsaved setup " 

72 "until `setup apply` checks every connection, saves, and starts copying with it. " 

73 "Keys are read from standard input or a file, never from an argument.", 

74 ) 

75 actions = setup.add_subparsers(dest="action", required=True) 

76 actions.add_parser("show", parents=[output], help="the setup; keys only as saved or missing") 

77 

78 discord = actions.add_parser( 

79 "discord", 

80 parents=[output, secret], 

81 help="Discord channels, authors, and token (--secret-stdin or --from-file)", 

82 ) 

83 discord.add_argument("--channels", metavar="IDS", help="channel IDs, comma-separated") 

84 discord.add_argument( 

85 "--authors", metavar="IDS", help='author IDs, comma-separated; "" copies every author' 

86 ) 

87 

88 model = actions.add_parser( 

89 "model", 

90 parents=[output, secret], 

91 help="the model service, model, and API key (--secret-stdin or --from-file)", 

92 ) 

93 model.add_argument("--service", choices=_choices(wire.ModelService)) 

94 model.add_argument("--model", metavar="NAME") 

95 model.add_argument( 

96 "--base-url", metavar="URL", help='for ollama and openai_compatible; "" clears it' 

97 ) 

98 

99 account = actions.add_parser("account", help="Alpaca accounts, their keys and limits") 

100 account_actions = account.add_subparsers(dest="item_action", required=True) 

101 for verb, words in (("add", "a new account"), ("edit", "an account")): 

102 command = account_actions.add_parser( 

103 verb, 

104 parents=[output, secret, limits], 

105 help=f"{words}: environment, keys (key ID then secret, one per line), limits", 

106 ) 

107 command.add_argument("account_id", metavar="NAME") 

108 command.add_argument("--environment", choices=("paper", "live")) 

109 command.add_argument( 

110 "--after-restart", 

111 choices=tuple(AFTER_RESTART), 

112 help="after CopyTrading restarts, wait for your Start Copying (wait-for-me, the " 

113 "default) or carry on by itself (carry-on)", 

114 ) 

115 if verb == "edit": 

116 command.add_argument("--rename", metavar="NAME") 

117 account_actions.add_parser("remove", parents=[output], help="remove an account").add_argument( 

118 "account_id", metavar="NAME" 

119 ) 

120 

121 guru = actions.add_parser("guru", help="gurus: who is copied, from where, into which account") 

122 guru_actions = guru.add_subparsers(dest="item_action", required=True) 

123 for verb, words in (("add", "a new guru"), ("edit", "a guru, by name or ID")): 

124 command = guru_actions.add_parser(verb, parents=[output], help=words) 

125 command.add_argument("guru", metavar="NAME" if verb == "add" else "GURU") 

126 if verb == "edit": 

127 command.add_argument("--rename", metavar="NAME") 

128 command.add_argument( 

129 "--channel", metavar="ID", help='channel ID; "" follows the first source channel' 

130 ) 

131 command.add_argument("--author", metavar="ID", help='author ID; "" copies every author') 

132 command.add_argument("--account", metavar="NAME", help="the one account they copy into") 

133 command.add_argument( 

134 "--full-position", 

135 metavar="USD", 

136 help="the guru's whole position in dollars: a 1/6 call buys a sixth of it; until set, " 

137 "the account's maximum per stock", 

138 ) 

139 command.add_argument("--playbook-file", metavar="PATH", help="how this guru writes") 

140 command.add_argument( 

141 "--repeat-window", 

142 metavar="MINUTES", 

143 type=int, 

144 help="skip the same call again within this many minutes; 0 copies every post", 

145 ) 

146 guru_actions.add_parser("remove", parents=[output], help="remove a guru").add_argument( 

147 "guru", metavar="GURU" 

148 ) 

149 

150 alerts = actions.add_parser( 

151 "alerts", 

152 parents=[output, secret], 

153 help="alerts by Telegram or Discord, and their token (--secret-stdin or --from-file)", 

154 ) 

155 switch = alerts.add_mutually_exclusive_group() 

156 switch.add_argument("--on", dest="enabled", action="store_const", const=True) 

157 switch.add_argument("--off", dest="enabled", action="store_const", const=False) 

158 alerts.add_argument("--service", choices=("telegram", "discord")) 

159 alerts.add_argument("--chat-id", metavar="ID", help="Telegram's chat ID") 

160 

161 imported = actions.add_parser( 

162 "import", 

163 parents=[output], 

164 help="fill the setup from a file in Import Setup's label format, or from a setup " 

165 "CopyTrading saved (one saved by an earlier version is upgraded first)", 

166 ) 

167 imported.add_argument("file", metavar="FILE") 

168 

169 apply = actions.add_parser( 

170 "apply", 

171 parents=[output], 

172 help="check every connection, save, and start copying with the setup", 

173 ) 

174 apply.add_argument( 

175 "--start", 

176 action="store_true", 

177 help="also start copying if it is paused or has never started (live accounts wait for " 

178 "the owner's approval and Touch ID)", 

179 ) 

180 apply.add_argument("--timeout", type=float, default=APPLY_TIMEOUT_SECONDS) 

181 actions.add_parser("discard", parents=[output], help="drop the unsaved changes") 

182 

183 

184def _choices(alias: object) -> tuple[str, ...]: 

185 return get_args(getattr(alias, "__value__", alias)) 

186 

187 

188def no_answer(args: argparse.Namespace, seconds: object) -> str: 

189 """What to do when a request was sent and no answer came: its outcome is unknown.""" 

190 waited = f" within {seconds:g} seconds" if isinstance(seconds, int | float) else "" 

191 if args.command == "setup" and args.action == "apply": 191 ↛ 198line 191 didn't jump to line 198 because the condition on line 191 was always true

192 return ( 

193 f"CopyTrading didn't answer{waited}, so whether the setup was applied is not known; " 

194 "it may still be checking. Run `copytrading setup show`: no unsaved changes means it " 

195 "was saved, and it shows whether copying runs. Running `copytrading setup apply` " 

196 "again is safe: the same setup is never saved or started twice." 

197 ) 

198 return ( 

199 f"CopyTrading didn't answer{waited}, so whether the request took effect is not known. " 

200 "Check with `copytrading status` before trying again." 

201 ) 

202 

203 

204def timeout_for(args: argparse.Namespace) -> float | None: 

205 """`setup apply` waits for the app's checks and start; everything else uses the default.""" 

206 if args.command == "setup" and args.action == "apply": 

207 return args.timeout 

208 return None 

209 

210 

211def setup_request( 

212 args: argparse.Namespace, 

213 request_id: str, 

214 stdin: TextIO, 

215 prompt: Prompt = getpass.getpass, 

216) -> wire.Request: 

217 """Translate `setup …` arguments into one contract request, reading any key they name.""" 

218 try: 

219 return _request(args, request_id, stdin, prompt) 

220 except ValidationError as error: 

221 # Errors hide their input, so no key can appear here; name the fields only. 

222 problems = "; ".join( 

223 f"{'.'.join(str(part) for part in item['loc']) or 'request'}: {item['msg']}" 

224 for item in error.errors(include_input=False, include_url=False) 

225 ) 

226 raise ValueError(problems) from None 

227 

228 

229def _request( 

230 args: argparse.Namespace, request_id: str, stdin: TextIO, prompt: Prompt 

231) -> wire.Request: 

232 match args.action, getattr(args, "item_action", None): 

233 case "show", _: 

234 return wire.GetSetup(request_id=request_id) 

235 case "discord", _: 

236 token = _one_secret(args, stdin, prompt, "Discord token") 

237 return wire.EditSetupDiscord( 

238 request_id=request_id, 

239 channel_ids=_ids(args.channels), 

240 author_ids=_ids(args.authors), 

241 token=token, 

242 ) 

243 case "model", _: 

244 key = _one_secret(args, stdin, prompt, "Model API key") 

245 return wire.EditSetupModel( 

246 request_id=request_id, 

247 service=args.service, 

248 model=args.model, 

249 base_url=args.base_url, 

250 key=key, 

251 ) 

252 case "account", "add" | "edit" as verb: 

253 keys = _secrets(args, stdin, prompt, ("Alpaca API key ID", "Alpaca secret key")) 

254 key, secret = (keys[0], keys[1]) if keys else (None, None) 

255 return wire.EditSetupAccount( 

256 request_id=request_id, 

257 action=verb, 

258 account_id=args.account_id, 

259 rename=getattr(args, "rename", None), 

260 environment=args.environment, 

261 key=key, 

262 secret=secret, 

263 limits=tuple( 

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

265 for field in wire.LIMIT_FIELDS 

266 if getattr(args, field) is not None 

267 ), 

268 recovery_preference=( 

269 None if args.after_restart is None else AFTER_RESTART[args.after_restart] 

270 ), 

271 ) 

272 case "account", "remove": 272 ↛ 273line 272 didn't jump to line 273 because the pattern on line 272 never matched

273 return wire.EditSetupAccount( 

274 request_id=request_id, action="remove", account_id=args.account_id 

275 ) 

276 case "guru", "add" | "edit" as verb: 

277 return wire.EditSetupGuru( 

278 request_id=request_id, 

279 action=verb, 

280 guru=args.guru, 

281 rename=getattr(args, "rename", None), 

282 channel_id=args.channel, 

283 author_id=args.author, 

284 account_id=args.account, 

285 full_position_usd=args.full_position, 

286 playbook=None if args.playbook_file is None else _text(args.playbook_file), 

287 repeat_window_minutes=args.repeat_window, 

288 ) 

289 case "guru", "remove": 

290 return wire.EditSetupGuru(request_id=request_id, action="remove", guru=args.guru) 

291 case "alerts", _: 

292 token = _one_secret(args, stdin, prompt, "Alert token or webhook URL") 

293 return wire.EditSetupAlerts( 

294 request_id=request_id, 

295 enabled=args.enabled, 

296 service=args.service, 

297 chat_id=args.chat_id, 

298 token=token, 

299 ) 

300 case "import", _: 

301 return wire.ImportSetup(request_id=request_id, text=SecretStr(_text(args.file))) 

302 case "apply", _: 

303 return wire.ApplySetup(request_id=request_id, start=args.start) 

304 case "discard", _: 304 ↛ 306line 304 didn't jump to line 306 because the pattern on line 304 always matched

305 return wire.DiscardSetup(request_id=request_id) 

306 case action, item: 

307 raise ValueError(f"Unsupported command: setup {action} {item or ''}".strip()) 

308 

309 

310def _ids(value: str | None) -> tuple[str, ...] | None: 

311 """Comma-separated IDs, as Connections takes them; full-width commas too.""" 

312 if value is None: 

313 return None 

314 return tuple(part.strip() for part in value.replace("\uff0c", ",").split(",") if part.strip()) 

315 

316 

317def _text(path: str) -> str: 

318 """A small regular file's text. It is opened once and read at most one byte past the limit, 

319 so a pipe, a device, or a file still growing is refused rather than read forever.""" 

320 try: 

321 descriptor = os.open(path, os.O_RDONLY | os.O_NONBLOCK) 

322 except FileNotFoundError: 

323 raise ValueError(f"{path} does not exist") from None 

324 except OSError as error: 

325 raise ValueError(f"{path} cannot be read ({error.strerror})") from None 

326 try: 

327 if not stat.S_ISREG(os.fstat(descriptor).st_mode): 

328 raise ValueError(f"{path} is not a regular file") 

329 data = b"" 

330 while len(data) <= MAX_SECRET_FILE_BYTES: 

331 chunk = os.read(descriptor, MAX_SECRET_FILE_BYTES + 1 - len(data)) 

332 if not chunk: 

333 break 

334 data += chunk 

335 except OSError as error: 

336 raise ValueError(f"{path} cannot be read ({error.strerror})") from None 

337 finally: 

338 os.close(descriptor) 

339 if len(data) > MAX_SECRET_FILE_BYTES: 

340 raise ValueError(f"{path} is larger than a setup file can be (64 KB)") 

341 try: 

342 return data.decode("utf-8") 

343 except UnicodeDecodeError: 

344 raise ValueError(f"{path} is not a text file") from None 

345 

346 

347def _one_secret( 

348 args: argparse.Namespace, stdin: TextIO, prompt: Prompt, name: str 

349) -> SecretStr | None: 

350 values = _secrets(args, stdin, prompt, (name,)) 

351 return values[0] if values else None 

352 

353 

354def _secrets( 

355 args: argparse.Namespace, stdin: TextIO, prompt: Prompt, names: tuple[str, ...] 

356) -> tuple[SecretStr, ...] | None: 

357 """The keys a command takes, one per line, from stdin or a file; None when it takes none.""" 

358 if args.from_file is not None: 

359 lines = _text(args.from_file).splitlines() 

360 where = args.from_file 

361 elif args.secret_stdin: 

362 if stdin.isatty(): 

363 return tuple(SecretStr(_typed(prompt, name)) for name in names) 

364 lines = stdin.read(MAX_SECRET_FILE_BYTES + 1).splitlines() 

365 where = "standard input" 

366 else: 

367 return None 

368 values = [line.strip() for line in lines if line.strip()] 

369 if len(values) != len(names): 

370 expected = " and ".join(names) if len(names) > 1 else names[0] 

371 layout = ", one per line, in that order" if len(names) > 1 else " alone on one line" 

372 raise ValueError(f"{where} must hold the {expected}{layout}") 

373 return tuple(SecretStr(value) for value in values) 

374 

375 

376def _typed(prompt: Prompt, name: str) -> str: 

377 value = prompt(f"{name}: ").strip() 

378 if not value: 378 ↛ 379line 378 didn't jump to line 379 because the condition on line 378 was never true

379 raise ValueError(f"No {name} was typed") 

380 return value 

381 

382 

383# Text output 

384 

385 

386def setup_exit_code(result: wire.SetupApplied) -> int: 

387 """0 once the setup took effect or had nothing to apply, 6 when it did not.""" 

388 return 0 if result.status in ("applied", "unchanged") else 6 

389 

390 

391def _key(state: wire.KeyState) -> str: 

392 match state: 

393 case "saved": 

394 return "saved" 

395 case "missing": 

396 return "missing" 

397 case "entered": 397 ↛ 399line 397 didn't jump to line 399 because the pattern on line 397 always matched

398 return "entered, not saved yet" 

399 case "not_needed": 

400 return "not needed" 

401 case _: 

402 assert_never(state) 

403 

404 

405def _check(check: wire.SetupCheckView | None) -> str: 

406 if check is None: 406 ↛ 408line 406 didn't jump to line 408 because the condition on line 406 was always true

407 return "" 

408 match check.state: 

409 case "passed": 

410 return " [connected]" 

411 case "not_configured": 

412 return " [not set up]" 

413 case "failed": 

414 return " [needs attention]" 

415 case _: 

416 assert_never(check.state) 

417 

418 

419def _problem(check: wire.SetupCheckView | None) -> list[str]: 

420 if check is None or check.state != "failed": 420 ↛ 422line 420 didn't jump to line 422 because the condition on line 420 was always true

421 return [] 

422 return [f" ! {check.message or check.reason or 'the check failed'}"] 

423 

424 

425def _ids_text(values: tuple[str, ...], empty: str) -> str: 

426 return ", ".join(values) if values else empty 

427 

428 

429def _dollars(value: str | None) -> str: 

430 return "—" if not value else f"${value}" 

431 

432 

433def _limit(change: wire.LimitChange) -> str: 

434 return f"{change.field.replace('_', ' ')} {change.value}" 

435 

436 

437def render_setup(setup: wire.SetupView) -> str: 

438 if not setup.saved: 438 ↛ 439line 438 didn't jump to line 439 because the condition on line 438 was never true

439 state = "not saved yet" 

440 elif setup.unsaved_changes: 

441 state = "saved, with unsaved changes" 

442 else: 

443 state = "saved" 

444 lines = [f"Setup {state}; {wire.COPYING_WORDS[setup.copying]}"] 

445 discord = setup.discord 

446 lines.append( 

447 f"Discord channels {_ids_text(discord.channel_ids, 'none')}; " 

448 f"authors {_ids_text(discord.author_ids, 'any')}; token {_key(discord.token)}" 

449 + _check(discord.check) 

450 ) 

451 lines += _problem(discord.check) 

452 model = setup.model 

453 lines.append( 

454 f"Model {model.service} {model.model or '(no model)'}" 

455 + (f" at {model.base_url}" if model.base_url else "") 

456 + f"; key {_key(model.key)}" 

457 + _check(model.check) 

458 ) 

459 lines += _problem(model.check) 

460 for account in setup.accounts: 

461 lines.append( 

462 f"Account {account.account_id} ({account.environment}); keys {_key(account.keys)}; " 

463 f"after a restart {AFTER_RESTART_WORDS[account.recovery_preference]}" 

464 + _check(account.check) 

465 ) 

466 lines += _problem(account.check) 

467 lines.append(" " + ", ".join(_limit(item) for item in account.limits)) 

468 if not setup.accounts: 468 ↛ 469line 468 didn't jump to line 469 because the condition on line 468 was never true

469 lines.append("Account none") 

470 for guru in setup.gurus: 

471 lines.append( 

472 f"Guru {guru.name} ({guru.guru_id or 'no ID until they have a channel'}); " 

473 f"channel {guru.channel_id or '—'}, " 

474 f"author {guru.author_id or 'any'}, account {guru.account_id or 'none'}, " 

475 f"full position {_dollars(guru.full_position_usd)}, " 

476 + ( 

477 f"skips re-posts within {guru.repeat_window_minutes} min" 

478 if guru.repeat_window_minutes 

479 else "copies every post" 

480 ) 

481 + f", playbook {guru.playbook_characters} characters" 

482 ) 

483 if not setup.gurus: 

484 lines.append("Guru none") 

485 alerts = setup.alerts 

486 if alerts.enabled: 

487 lines.append( 

488 f"Alerts {alerts.service}" 

489 + (f" chat {alerts.chat_id}" if alerts.chat_id else "") 

490 + f"; token {_key(alerts.token)}" 

491 + _check(alerts.check) 

492 ) 

493 lines += _problem(alerts.check) 

494 else: 

495 lines.append("Alerts off") 

496 if setup.unsaved_changes or not setup.saved: 

497 lines.append("Run `copytrading setup apply` to check every connection, save, and start.") 

498 return "\n".join(lines) 

499 

500 

501def render_imported(result: wire.SetupImported) -> str: 

502 lines = ["Filled from the file: " + (", ".join(result.filled) or "nothing")] 

503 if result.missing: 503 ↛ 505line 503 didn't jump to line 505 because the condition on line 503 was always true

504 lines.append("Still needed: " + ", ".join(result.missing)) 

505 lines.append(render_setup(result.setup)) 

506 return "\n".join(lines) 

507 

508 

509def render_applied(result: wire.SetupApplied) -> str: 

510 match result.status: 

511 case "applied": 

512 head = "Applied: the setup is saved, and copying uses it." 

513 case "unchanged": 513 ↛ 514line 513 didn't jump to line 514 because the pattern on line 513 never matched

514 head = "Nothing to apply: the saved setup is already the current one." 

515 case "failed_checks": 515 ↛ 517line 515 didn't jump to line 517 because the pattern on line 515 always matched

516 head = "Not applied: some connections need attention. Nothing was saved." 

517 case "failed": 

518 head = "Not applied." 

519 case _: 

520 assert_never(result.status) 

521 lines = [head] 

522 if result.message and result.message not in head: 

523 lines.append(result.message) 

524 for check in result.checks: 

525 name = check.subject or check.connection 

526 match check.state: 

527 case "passed": 

528 lines.append(f" ok {name}") 

529 case "not_configured": 529 ↛ 530line 529 didn't jump to line 530 because the pattern on line 529 never matched

530 lines.append(f" - {name}: not set up") 

531 case "failed": 531 ↛ 524line 531 didn't jump to line 524 because the pattern on line 531 always matched

532 lines.append(f" failed {check.message or f'{name}: {check.reason}'}") 

533 return "\n".join(lines) 

534 

535 

536def describe_apply_proposal(subject: wire.ApplySetupSubject) -> str: 

537 parts = [ 

538 (f"makes {', '.join(subject.made_live)} live" if subject.made_live else ""), 

539 (f"saves new keys for {', '.join(subject.new_live_keys)}" if subject.new_live_keys else ""), 

540 (f"changes {', '.join(subject.changed_live)}" if subject.changed_live else ""), 

541 (f"copies into live {', '.join(subject.starts_live)}" if subject.starts_live else ""), 

542 ] 

543 detail = "; ".join(part for part in parts if part) 

544 return "apply the setup" + (f" ({detail})" if detail else "")