Coverage for src/copytrading_engine/headless/cli.py: 60%
181 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-16 16:55 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-16 16:55 +0000
1"""copytrading-server: run the CopyTrading engine without the Mac app.
3This module is the command line only: it parses arguments, asks the server or the engine,
4and prints the typed answers. Formatting lives here and nowhere else.
5"""
7import argparse
8import asyncio
9import datetime as dt
10import sys
11from importlib import resources
12from pathlib import Path
13from typing import TextIO
15from pydantic import ValidationError
17from copytrading_engine.control.client import server_state_root
18from copytrading_engine.control.wire import (
19 ApplySetupSubject,
20 LimitsSubject,
21 ManualOrderSubject,
22 ProposalSubject,
23 ProposalView,
24 RecoverySubject,
25 ResumeAccountSubject,
26 StartProcessingSubject,
27)
28from copytrading_engine.headless.config import ConfigError, load_secrets, load_setup
29from copytrading_engine.headless.engine import EngineRefused, SetupNotReady, SetupReport
30from copytrading_engine.headless.owner import (
31 Approve,
32 AskStatus,
33 CopyingStatus,
34 EntriesChanged,
35 ListProposals,
36 OwnerAnswer,
37 OwnerRequest,
38 Pause,
39 ProposalChanged,
40 Proposals,
41 Reject,
42 Resume,
43 SetEntries,
44)
45from copytrading_engine.headless.server import ServerPaths, check_setup, run_server
46from copytrading_engine.headless.sockets import (
47 OwnerRequestFailed,
48 ServerNotRunning,
49 UnsafeStateDirectory,
50 ask_owner_socket,
51)
53DEFAULT_CONFIG = Path("copytrading.toml")
55EXIT_OK = 0
56EXIT_FAILED = 1
57EXIT_USAGE = 2
58EXIT_NOT_RUNNING = 3
61class UnexpectedAnswer(Exception):
62 """The server answered with something other than what this command asked for."""
65def main(
66 argv: list[str] | None = None, *, out: TextIO = sys.stdout, err: TextIO = sys.stderr
67) -> int:
68 parser = _parser()
69 args = parser.parse_args(argv)
70 if args.command is None: 70 ↛ 71line 70 didn't jump to line 71 because the condition on line 70 was never true
71 parser.print_help(out)
72 return EXIT_USAGE
73 state = Path(args.state_dir).expanduser().resolve() if args.state_dir else server_state_root()
74 paths = ServerPaths(state)
75 try:
76 return _COMMANDS[args.command](args, paths, out, err)
77 except ConfigError as problem:
78 for line in problem.problems:
79 print(f"✗ {line}", file=err)
80 return EXIT_USAGE
81 except ValidationError as problem:
82 # An argument outside the owner contract, such as "my account" for an account id.
83 for item in problem.errors(include_url=False):
84 print(f"✗ {'.'.join(map(str, item['loc']))}: {item['msg']}", file=err)
85 return EXIT_USAGE
86 except ServerNotRunning:
87 print(
88 f"No CopyTrading server is running with state in {paths.root}. "
89 "Start one with `copytrading-server run`.",
90 file=err,
91 )
92 return EXIT_NOT_RUNNING
93 except (OwnerRequestFailed, EngineRefused, UnsafeStateDirectory, UnexpectedAnswer) as problem:
94 print(f"✗ {problem}", file=err)
95 return EXIT_FAILED
96 except KeyboardInterrupt:
97 return EXIT_FAILED
100def _parser() -> argparse.ArgumentParser:
101 parser = argparse.ArgumentParser(
102 prog="copytrading-server",
103 description="Run the CopyTrading engine without the Mac app: on a Mac, a Linux server, "
104 "or in Docker. Setup comes from copytrading.toml; keys come from the environment.",
105 )
106 parser.add_argument(
107 "--state-dir",
108 help=f"where the server keeps its data (default: {server_state_root()})",
109 )
110 commands = parser.add_subparsers(dest="command", metavar="COMMAND")
112 init = commands.add_parser("init", help="write a commented copytrading.toml to start from")
113 init.add_argument("path", nargs="?", default=str(DEFAULT_CONFIG))
115 for name, text in (
116 ("check", "check the file, the keys, and every connection; nothing is saved or traded"),
117 ("run", "start copying and keep running until Ctrl-C or SIGTERM"),
118 ):
119 command = commands.add_parser(name, help=text)
120 command.add_argument("--config", "-c", default=str(DEFAULT_CONFIG))
122 commands.add_parser("status", help="show whether copying runs and each account's state")
123 entries = commands.add_parser("entries", help="turn new buys on or off for an account")
124 entries.add_argument("switch", choices=("enable", "disable"))
125 entries.add_argument("account")
126 commands.add_parser("pause", help="pause copying")
127 commands.add_parser("resume", help="check the setup again and resume copying")
128 commands.add_parser("proposals", help="list what agents asked you to approve")
129 approve = commands.add_parser("approve", help="approve a proposal after showing what it does")
130 approve.add_argument("proposal_id")
131 approve.add_argument("--yes", "-y", action="store_true", help="do not ask to confirm")
132 reject = commands.add_parser("reject", help="reject a proposal")
133 reject.add_argument("proposal_id")
134 return parser
137def _init(args: argparse.Namespace, paths: ServerPaths, out: TextIO, err: TextIO) -> int:
138 target = Path(args.path)
139 if target.exists():
140 print(f"✗ {target} already exists; nothing was changed.", file=err)
141 return EXIT_FAILED
142 template = resources.files("copytrading_engine.headless").joinpath("template.toml")
143 target.write_text(template.read_text(encoding="utf-8"), encoding="utf-8")
144 print(f"Wrote {target}. Edit it, set the keys it lists, then run:", file=out)
145 print(f" copytrading-server check --config {target}", file=out)
146 return EXIT_OK
149def _check(args: argparse.Namespace, paths: ServerPaths, out: TextIO, err: TextIO) -> int:
150 setup = load_setup(Path(args.config))
151 secrets = load_secrets(setup.configuration)
152 print("Checking Discord, the model, and each account…", file=out)
153 report = asyncio.run(check_setup(setup, secrets))
154 _print_report(report, out)
155 print(
156 "✓ Ready. Start with `copytrading-server run`."
157 if report.activatable
158 else "✗ Not ready. Fix the lines marked ✗ and check again.",
159 file=out,
160 )
161 return EXIT_OK if report.activatable else EXIT_FAILED
164def _run(args: argparse.Namespace, paths: ServerPaths, out: TextIO, err: TextIO) -> int:
165 setup = load_setup(Path(args.config))
166 secrets = load_secrets(setup.configuration)
168 def say(line: str) -> None:
169 stamp = dt.datetime.now().astimezone().strftime("%Y-%m-%d %H:%M:%S")
170 print(f"{stamp} {line}", file=out, flush=True)
172 try:
173 asyncio.run(run_server(setup, secrets, paths, say=say))
174 except SetupNotReady as not_ready:
175 _print_report(not_ready.report, out)
176 print("✗ The setup check did not pass, so copying did not start.", file=err)
177 return EXIT_FAILED
178 return EXIT_OK
181def _status(args: argparse.Namespace, paths: ServerPaths, out: TextIO, err: TextIO) -> int:
182 status = _ask(paths, AskStatus(), CopyingStatus)
183 print(f"Copying {status.state}", file=out)
184 print(f"Discord {'connected' if status.source_connected else 'not connected'}", file=out)
185 print(f"Model {'ready' if status.model_ready else 'not ready'}", file=out)
186 print(f"Handled {status.processed_signals} post(s)", file=out)
187 if status.error_code: 187 ↛ 188line 187 didn't jump to line 188 because the condition on line 187 was never true
188 print(f"Problem {_plain(status.error_code)}", file=out)
189 for account in status.accounts: 189 ↛ 190line 189 didn't jump to line 190 because the loop on line 189 never started
190 entries = "entries on" if account.entry_permission == "enabled" else "entries off"
191 print(f"Account {account.id} {account.state}, {entries}", file=out)
192 return EXIT_OK
195def _entries(args: argparse.Namespace, paths: ServerPaths, out: TextIO, err: TextIO) -> int:
196 request = SetEntries(account=args.account, enabled=args.switch == "enable")
197 changed = _ask(paths, request, EntriesChanged)
198 print(f"{changed.account_id}: entries {changed.entry_permission}.", file=out)
199 return EXIT_OK
202def _pause(args: argparse.Namespace, paths: ServerPaths, out: TextIO, err: TextIO) -> int:
203 print(f"Copying {_ask(paths, Pause(), CopyingStatus).state}.", file=out)
204 return EXIT_OK
207def _resume(args: argparse.Namespace, paths: ServerPaths, out: TextIO, err: TextIO) -> int:
208 print(f"Copying {_ask(paths, Resume(), CopyingStatus).state}.", file=out)
209 return EXIT_OK
212def _proposals(args: argparse.Namespace, paths: ServerPaths, out: TextIO, err: TextIO) -> int:
213 pending = _pending(paths)
214 if not pending: 214 ↛ 216line 214 didn't jump to line 216 because the condition on line 214 was always true
215 print("Nothing is waiting for your approval.", file=out)
216 for proposal in pending.values(): 216 ↛ 217line 216 didn't jump to line 217 because the loop on line 216 never started
217 print(
218 f"{proposal.proposal_id} {_describe(proposal.subject)} "
219 f"(expires {proposal.expires_at:%H:%M})",
220 file=out,
221 )
222 return EXIT_OK
225def _approve(args: argparse.Namespace, paths: ServerPaths, out: TextIO, err: TextIO) -> int:
226 proposal = _pending(paths).get(args.proposal_id)
227 if proposal is None: 227 ↛ 230line 227 didn't jump to line 230 because the condition on line 227 was always true
228 print(f"✗ {args.proposal_id} is not waiting for approval.", file=err)
229 return EXIT_FAILED
230 print(f"Approve: {_describe(proposal.subject)}?", file=out)
231 if not args.yes:
232 out.flush()
233 if input("Type yes to approve: ").strip().lower() != "yes":
234 print("Not approved.", file=out)
235 return EXIT_FAILED
236 # The digest pins the approval to exactly what was shown above.
237 request = Approve(proposal_id=proposal.proposal_id, digest=proposal.digest)
238 changed = _ask(paths, request, ProposalChanged).proposal
239 print(f"{changed.proposal_id}: {changed.state}.", file=out)
240 return EXIT_OK if changed.state in {"running", "succeeded"} else EXIT_FAILED
243def _reject(args: argparse.Namespace, paths: ServerPaths, out: TextIO, err: TextIO) -> int:
244 changed = _ask(paths, Reject(proposal_id=args.proposal_id), ProposalChanged).proposal
245 print(f"{changed.proposal_id}: {changed.state}.", file=out)
246 return EXIT_OK
249_COMMANDS = {
250 "init": _init,
251 "check": _check,
252 "run": _run,
253 "status": _status,
254 "entries": _entries,
255 "pause": _pause,
256 "resume": _resume,
257 "proposals": _proposals,
258 "approve": _approve,
259 "reject": _reject,
260}
263def _ask[T: OwnerAnswer](paths: ServerPaths, request: OwnerRequest, expected: type[T]) -> T:
264 answer = asyncio.run(ask_owner_socket(paths.owner_socket, request))
265 if not isinstance(answer, expected): 265 ↛ 266line 265 didn't jump to line 266 because the condition on line 265 was never true
266 raise UnexpectedAnswer(f"the server answered {type(answer).__name__}")
267 return answer
270def _pending(paths: ServerPaths) -> dict[str, ProposalView]:
271 proposals = _ask(paths, ListProposals(), Proposals).items
272 return {item.proposal_id: item for item in proposals if item.state == "pending"}
275def _print_report(report: SetupReport, out: TextIO) -> None:
276 for check in report.checks:
277 subject = f" {check.subject}" if check.subject else ""
278 environment = f" ({check.environment})" if check.environment else ""
279 reason = f": {_plain(check.reason_code)}" if check.reason_code else ""
280 print(
281 f"{'✓' if check.passed else '✗'} {_plain(check.name)}{subject}{environment} — "
282 f"{_plain(check.state)}{reason}",
283 file=out,
284 )
287def _describe(subject: ProposalSubject) -> str:
288 match subject:
289 case ResumeAccountSubject(account_id=account_id):
290 return f"turn entries back on in {account_id}"
291 case RecoverySubject(account_id=account_id, preference=preference):
292 return f"set recovery in {account_id} to {_plain(preference)}"
293 case StartProcessingSubject():
294 return "start copying"
295 case ApplySetupSubject():
296 return "apply the app's setup"
297 case LimitsSubject():
298 return f"change {subject.account_id}: " + ", ".join(
299 f"{_plain(change.field)} = {change.value}" for change in subject.changes
300 )
301 case ManualOrderSubject():
302 price = f" at ${subject.limit_price}" if subject.limit_price else " at market"
303 return (
304 f"{subject.side} {subject.quantity} {subject.symbol}{price} "
305 f"in {subject.account_id} ({subject.environment})"
306 )
309def _plain(code: str) -> str:
310 return code.replace("_", " ")