capitalcom-cli 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,549 @@
1
+ """capctl trade ... — positions, orders, confirmations, preview, execute."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import typer
8
+
9
+ from capital_cli.cli.live_guard import warn_if_live
10
+ from capital_cli.cli.runner import run
11
+ from capital_cli.core.http_client import get_client
12
+ from capital_cli.core.models import (
13
+ Direction,
14
+ PreviewPositionRequest,
15
+ PreviewWorkingOrderRequest,
16
+ WorkingOrderType,
17
+ )
18
+ from capital_cli.core.risk import get_risk_engine
19
+ from capital_cli.core.session import get_session_manager
20
+ from capital_cli.core.utils import poll_until
21
+
22
+ app = typer.Typer(no_args_is_help=True, help="Trading: positions, orders, preview, execute.")
23
+
24
+
25
+ async def _wait_for_confirmation(
26
+ deal_reference: str, timeout_s: float, poll_interval_ms: int = 500
27
+ ) -> dict[str, Any]:
28
+ """Poll GET /confirms/{dealReference} until the broker accepts or rejects the deal.
29
+
30
+ The Capital.com API reports the broker's decision in the ``dealStatus``
31
+ field (ACCEPTED/REJECTED); ``status`` is the resulting position/order
32
+ lifecycle state (e.g. OPEN, CLOSED) and is not a useful done-condition.
33
+ The returned dict normalizes ``status`` to the ``dealStatus`` value so
34
+ callers can uniformly check ``confirmation["status"]``.
35
+ """
36
+ client = get_client()
37
+
38
+ async def check() -> dict[str, Any]:
39
+ return (await client.get(f"/confirms/{deal_reference}")).json()
40
+
41
+ def done(data: dict[str, Any]) -> bool:
42
+ return data.get("dealStatus") in ("ACCEPTED", "REJECTED")
43
+
44
+ result = await poll_until(check, done, timeout_s=timeout_s, poll_interval_ms=poll_interval_ms)
45
+ if result is None:
46
+ return {"status": "TIMEOUT", "message": f"Confirmation timed out after {timeout_s}s"}
47
+ if "dealStatus" in result:
48
+ result = {**result, "status": result["dealStatus"]}
49
+ return result
50
+
51
+
52
+ def _parse_direction(direction: str) -> Direction:
53
+ try:
54
+ return Direction(direction.upper())
55
+ except ValueError:
56
+ raise typer.BadParameter("direction must be BUY or SELL.") from None
57
+
58
+
59
+ def _parse_order_type(order_type: str) -> WorkingOrderType:
60
+ try:
61
+ return WorkingOrderType(order_type.upper())
62
+ except ValueError:
63
+ raise typer.BadParameter("order type must be LIMIT or STOP.") from None
64
+
65
+
66
+ def _preview_payload(preview: Any) -> dict[str, Any]:
67
+ return {
68
+ "preview_id": preview.preview_id,
69
+ "normalized_request": preview.normalized_request,
70
+ "checks": [c.model_dump() for c in preview.checks],
71
+ "all_checks_passed": preview.all_checks_passed,
72
+ "estimated_entry": preview.estimated_entry,
73
+ "estimated_risk_notes": preview.estimated_risk_notes,
74
+ "expires_in_seconds": 120,
75
+ }
76
+
77
+
78
+ # ----- Read-only -----
79
+
80
+
81
+ @app.command()
82
+ def positions(ctx: typer.Context) -> None:
83
+ """List open positions."""
84
+ out = ctx.obj.out
85
+ sm = get_session_manager()
86
+ client = get_client()
87
+
88
+ async def _do() -> dict[str, Any]:
89
+ await sm.ensure_logged_in()
90
+ return (await client.get("/positions")).json()
91
+
92
+ data = run(out, _do, label="trade positions")
93
+ if out.json_mode:
94
+ out.raw(data)
95
+ else:
96
+ rows = [
97
+ {
98
+ "dealId": p.get("position", {}).get("dealId"),
99
+ "epic": p.get("market", {}).get("epic"),
100
+ "direction": p.get("position", {}).get("direction"),
101
+ "size": p.get("position", {}).get("size"),
102
+ "level": p.get("position", {}).get("level"),
103
+ "upl": p.get("position", {}).get("upl"),
104
+ }
105
+ for p in data.get("positions", [])
106
+ ]
107
+ out.rows(
108
+ rows,
109
+ ["dealId", "epic", "direction", "size", "level", "upl"],
110
+ title="Open positions",
111
+ )
112
+
113
+
114
+ @app.command()
115
+ def position(
116
+ ctx: typer.Context, deal_id: str = typer.Argument(..., help="Position deal ID.")
117
+ ) -> None:
118
+ """Get a single position by deal ID."""
119
+ out = ctx.obj.out
120
+ sm = get_session_manager()
121
+ client = get_client()
122
+
123
+ async def _do() -> dict[str, Any]:
124
+ await sm.ensure_logged_in()
125
+ return (await client.get(f"/positions/{deal_id}")).json()
126
+
127
+ out.raw(run(out, _do, label="trade position"))
128
+
129
+
130
+ @app.command()
131
+ def orders(ctx: typer.Context) -> None:
132
+ """List working orders."""
133
+ out = ctx.obj.out
134
+ sm = get_session_manager()
135
+ client = get_client()
136
+
137
+ async def _do() -> dict[str, Any]:
138
+ await sm.ensure_logged_in()
139
+ return (await client.get("/workingorders")).json()
140
+
141
+ data = run(out, _do, label="trade orders")
142
+ if out.json_mode:
143
+ out.raw(data)
144
+ else:
145
+ rows = [
146
+ {
147
+ "dealId": o.get("workingOrderData", {}).get("dealId"),
148
+ "epic": o.get("marketData", {}).get("epic"),
149
+ "direction": o.get("workingOrderData", {}).get("direction"),
150
+ "type": o.get("workingOrderData", {}).get("orderType"),
151
+ "level": o.get("workingOrderData", {}).get("orderLevel"),
152
+ "size": o.get("workingOrderData", {}).get("orderSize"),
153
+ }
154
+ for o in data.get("workingOrders", [])
155
+ ]
156
+ out.rows(
157
+ rows,
158
+ ["dealId", "epic", "direction", "type", "level", "size"],
159
+ title="Working orders",
160
+ )
161
+
162
+
163
+ @app.command()
164
+ def confirm(
165
+ ctx: typer.Context,
166
+ deal_reference: str = typer.Argument(..., help="Deal reference (e.g. o_...)."),
167
+ wait: bool = typer.Option(False, "--wait", help="Poll until ACCEPTED/REJECTED."),
168
+ timeout: float = typer.Option(15.0, "--timeout", help="Polling timeout in seconds."),
169
+ ) -> None:
170
+ """Get (or wait for) a deal confirmation."""
171
+ out = ctx.obj.out
172
+ sm = get_session_manager()
173
+ client = get_client()
174
+
175
+ async def _do() -> dict[str, Any]:
176
+ await sm.ensure_logged_in()
177
+ if wait:
178
+ return await _wait_for_confirmation(deal_reference, timeout_s=timeout)
179
+ return (await client.get(f"/confirms/{deal_reference}")).json()
180
+
181
+ out.record(run(out, _do, label="trade confirm"), title="Confirmation")
182
+
183
+
184
+ # ----- Preview (no side effects) -----
185
+
186
+
187
+ @app.command("preview-position")
188
+ def preview_position(
189
+ ctx: typer.Context,
190
+ epic: str = typer.Argument(..., help="Market EPIC."),
191
+ direction: str = typer.Argument(..., help="BUY or SELL."),
192
+ size: float = typer.Argument(..., help="Position size."),
193
+ stop_level: float | None = typer.Option(None, "--stop-level"),
194
+ stop_distance: float | None = typer.Option(None, "--stop-distance"),
195
+ profit_level: float | None = typer.Option(None, "--profit-level"),
196
+ profit_distance: float | None = typer.Option(None, "--profit-distance"),
197
+ guaranteed_stop: bool = typer.Option(False, "--guaranteed-stop"),
198
+ trailing_stop: bool = typer.Option(False, "--trailing-stop"),
199
+ auto_normalize_size: bool = typer.Option(
200
+ False, "--auto-normalize-size", help="Round size to the broker increment instead of failing."
201
+ ),
202
+ ) -> None:
203
+ """Validate a position against risk policy and return a preview_id (no trade)."""
204
+ out = ctx.obj.out
205
+ sm = get_session_manager()
206
+ risk = get_risk_engine()
207
+ direction_e = _parse_direction(direction)
208
+
209
+ async def _do() -> dict[str, Any]:
210
+ await sm.ensure_logged_in()
211
+ request = PreviewPositionRequest(
212
+ epic=epic,
213
+ direction=direction_e,
214
+ size=size,
215
+ guaranteed_stop=guaranteed_stop,
216
+ trailing_stop=trailing_stop,
217
+ stop_level=stop_level,
218
+ stop_distance=stop_distance,
219
+ profit_level=profit_level,
220
+ profit_distance=profit_distance,
221
+ auto_normalize_size=auto_normalize_size,
222
+ )
223
+ return _preview_payload(await risk.preview_position(request))
224
+
225
+ data = run(out, _do, label="trade preview-position")
226
+ if out.json_mode:
227
+ out.raw(data)
228
+ else:
229
+ out.rows(data["checks"], ["check", "passed", "message"], title="Risk checks")
230
+ out.record(
231
+ {
232
+ "preview_id": data["preview_id"],
233
+ "all_checks_passed": data["all_checks_passed"],
234
+ "estimated_entry": data["estimated_entry"],
235
+ "expires_in_seconds": data["expires_in_seconds"],
236
+ },
237
+ title="Preview",
238
+ )
239
+
240
+
241
+ @app.command("preview-order")
242
+ def preview_order(
243
+ ctx: typer.Context,
244
+ epic: str = typer.Argument(..., help="Market EPIC."),
245
+ direction: str = typer.Argument(..., help="BUY or SELL."),
246
+ order_type: str = typer.Argument(..., help="LIMIT or STOP."),
247
+ level: float = typer.Argument(..., help="Trigger level."),
248
+ size: float = typer.Argument(..., help="Order size."),
249
+ stop_level: float | None = typer.Option(None, "--stop-level"),
250
+ profit_level: float | None = typer.Option(None, "--profit-level"),
251
+ good_till_date: str | None = typer.Option(None, "--good-till", help="Expiry ISO 8601."),
252
+ auto_normalize_size: bool = typer.Option(
253
+ False, "--auto-normalize-size", help="Round size to the broker increment instead of failing."
254
+ ),
255
+ ) -> None:
256
+ """Validate a working order and return a preview_id (no order created)."""
257
+ out = ctx.obj.out
258
+ sm = get_session_manager()
259
+ risk = get_risk_engine()
260
+ direction_e = _parse_direction(direction)
261
+ order_type_e = _parse_order_type(order_type)
262
+
263
+ async def _do() -> dict[str, Any]:
264
+ await sm.ensure_logged_in()
265
+ request = PreviewWorkingOrderRequest(
266
+ epic=epic,
267
+ direction=direction_e,
268
+ type=order_type_e,
269
+ level=level,
270
+ size=size,
271
+ stop_level=stop_level,
272
+ profit_level=profit_level,
273
+ good_till_date=good_till_date,
274
+ auto_normalize_size=auto_normalize_size,
275
+ )
276
+ return _preview_payload(await risk.preview_working_order(request))
277
+
278
+ data = run(out, _do, label="trade preview-order")
279
+ if out.json_mode:
280
+ out.raw(data)
281
+ else:
282
+ out.rows(data["checks"], ["check", "passed", "message"], title="Risk checks")
283
+ out.record(
284
+ {"preview_id": data["preview_id"], "all_checks_passed": data["all_checks_passed"]},
285
+ title="Preview",
286
+ )
287
+
288
+
289
+ # ----- Execute (side effects, guarded) -----
290
+
291
+
292
+ def _build_broker_request(normalized: dict[str, Any], *, include_order_fields: bool) -> dict[str, Any]:
293
+ body: dict[str, Any] = {
294
+ "epic": normalized["epic"],
295
+ "direction": normalized["direction"],
296
+ "size": normalized["size"],
297
+ }
298
+ if include_order_fields:
299
+ body["type"] = normalized["type"]
300
+ body["level"] = normalized["level"]
301
+ if normalized.get("good_till_date"):
302
+ body["goodTillDate"] = normalized["good_till_date"]
303
+ if normalized.get("guaranteed_stop"):
304
+ body["guaranteedStop"] = True
305
+ if normalized.get("trailing_stop"):
306
+ body["trailingStop"] = True
307
+ for src, dst in [
308
+ ("stop_level", "stopLevel"),
309
+ ("stop_distance", "stopDistance"),
310
+ ("stop_amount", "stopAmount"),
311
+ ("profit_level", "profitLevel"),
312
+ ("profit_distance", "profitDistance"),
313
+ ("profit_amount", "profitAmount"),
314
+ ]:
315
+ if normalized.get(src):
316
+ body[dst] = normalized[src]
317
+ return body
318
+
319
+
320
+ @app.command("execute-position")
321
+ def execute_position(
322
+ ctx: typer.Context,
323
+ preview_id: str = typer.Argument(..., help="Preview ID from preview-position."),
324
+ yes: bool = typer.Option(
325
+ False, "--yes", "-y", help="Confirm execution (creates a real trade)."
326
+ ),
327
+ wait: bool = typer.Option(True, "--wait/--no-wait", help="Wait for broker confirmation."),
328
+ timeout: float = typer.Option(15.0, "--timeout"),
329
+ ) -> None:
330
+ """Execute a previewed position (SIDE EFFECT)."""
331
+ out = ctx.obj.out
332
+ sm = get_session_manager()
333
+ client = get_client()
334
+ risk = get_risk_engine()
335
+
336
+ async def _do() -> dict[str, Any]:
337
+ warn_if_live(out)
338
+ await sm.ensure_logged_in()
339
+ risk.validate_execution_guards(confirm=yes, preview_id=preview_id)
340
+ normalized = risk.get_preview(preview_id).normalized_request
341
+ body = _build_broker_request(normalized, include_order_fields=False)
342
+ data = (await client.post("/positions", json=body, rate_limit_type="trading")).json()
343
+ risk.increment_order_count()
344
+ if wait and "dealReference" in data:
345
+ data["confirmation"] = await _wait_for_confirmation(
346
+ data["dealReference"], timeout_s=timeout
347
+ )
348
+ data["active_account_id"] = sm.account_id
349
+ return data
350
+
351
+ out.record(run(out, _do, label="trade execute-position"), title="Execute position")
352
+
353
+
354
+ @app.command("execute-order")
355
+ def execute_order(
356
+ ctx: typer.Context,
357
+ preview_id: str = typer.Argument(..., help="Preview ID from preview-order."),
358
+ yes: bool = typer.Option(
359
+ False, "--yes", "-y", help="Confirm execution (creates a real order)."
360
+ ),
361
+ wait: bool = typer.Option(True, "--wait/--no-wait", help="Wait for broker confirmation."),
362
+ timeout: float = typer.Option(15.0, "--timeout"),
363
+ ) -> None:
364
+ """Execute a previewed working order (SIDE EFFECT)."""
365
+ out = ctx.obj.out
366
+ sm = get_session_manager()
367
+ client = get_client()
368
+ risk = get_risk_engine()
369
+
370
+ async def _do() -> dict[str, Any]:
371
+ warn_if_live(out)
372
+ await sm.ensure_logged_in()
373
+ risk.validate_execution_guards(confirm=yes, preview_id=preview_id)
374
+ normalized = risk.get_preview(preview_id).normalized_request
375
+ body = _build_broker_request(normalized, include_order_fields=True)
376
+ data = (await client.post("/workingorders", json=body, rate_limit_type="trading")).json()
377
+ risk.increment_order_count()
378
+ if wait and "dealReference" in data:
379
+ data["confirmation"] = await _wait_for_confirmation(
380
+ data["dealReference"], timeout_s=timeout
381
+ )
382
+ data["active_account_id"] = sm.account_id
383
+ return data
384
+
385
+ out.record(run(out, _do, label="trade execute-order"), title="Execute order")
386
+
387
+
388
+ @app.command()
389
+ def close(
390
+ ctx: typer.Context,
391
+ deal_id: str = typer.Argument(..., help="Position deal ID to close."),
392
+ yes: bool = typer.Option(False, "--yes", "-y", help="Confirm closing the position."),
393
+ wait: bool = typer.Option(True, "--wait/--no-wait", help="Wait for broker confirmation."),
394
+ timeout: float = typer.Option(15.0, "--timeout"),
395
+ ) -> None:
396
+ """Close an open position (SIDE EFFECT)."""
397
+ out = ctx.obj.out
398
+ sm = get_session_manager()
399
+ client = get_client()
400
+ risk = get_risk_engine()
401
+
402
+ async def _do() -> dict[str, Any]:
403
+ warn_if_live(out)
404
+ await sm.ensure_logged_in()
405
+ risk.validate_execution_guards(confirm=yes)
406
+ data = (await client.delete(f"/positions/{deal_id}")).json()
407
+ if wait and "dealReference" in data:
408
+ data["confirmation"] = await _wait_for_confirmation(
409
+ data["dealReference"], timeout_s=timeout
410
+ )
411
+ data["active_account_id"] = sm.account_id
412
+ return data
413
+
414
+ out.record(run(out, _do, label="trade close"), title="Close position")
415
+
416
+
417
+ @app.command()
418
+ def cancel(
419
+ ctx: typer.Context,
420
+ deal_id: str = typer.Argument(..., help="Working order deal ID to cancel."),
421
+ yes: bool = typer.Option(False, "--yes", "-y", help="Confirm cancelling the order."),
422
+ wait: bool = typer.Option(True, "--wait/--no-wait", help="Wait for broker confirmation."),
423
+ timeout: float = typer.Option(15.0, "--timeout"),
424
+ ) -> None:
425
+ """Cancel a working order (SIDE EFFECT)."""
426
+ out = ctx.obj.out
427
+ sm = get_session_manager()
428
+ client = get_client()
429
+ risk = get_risk_engine()
430
+
431
+ async def _do() -> dict[str, Any]:
432
+ warn_if_live(out)
433
+ await sm.ensure_logged_in()
434
+ risk.validate_execution_guards(confirm=yes)
435
+ data = (await client.delete(f"/workingorders/{deal_id}")).json()
436
+ if wait and "dealReference" in data:
437
+ data["confirmation"] = await _wait_for_confirmation(
438
+ data["dealReference"], timeout_s=timeout
439
+ )
440
+ data["active_account_id"] = sm.account_id
441
+ return data
442
+
443
+ out.record(run(out, _do, label="trade cancel"), title="Cancel order")
444
+
445
+
446
+ @app.command("amend-position")
447
+ def amend_position(
448
+ ctx: typer.Context,
449
+ deal_id: str = typer.Argument(..., help="Deal ID of the open position to amend."),
450
+ stop_level: float | None = typer.Option(None, "--stop-level"),
451
+ stop_distance: float | None = typer.Option(None, "--stop-distance"),
452
+ profit_level: float | None = typer.Option(None, "--profit-level"),
453
+ profit_distance: float | None = typer.Option(None, "--profit-distance"),
454
+ guaranteed_stop: bool | None = typer.Option(
455
+ None, "--guaranteed-stop/--no-guaranteed-stop", help="Toggle guaranteed stop."
456
+ ),
457
+ trailing_stop: bool | None = typer.Option(
458
+ None, "--trailing-stop/--no-trailing-stop", help="Toggle trailing stop."
459
+ ),
460
+ yes: bool = typer.Option(False, "--yes", "-y", help="Confirm the amendment."),
461
+ wait: bool = typer.Option(True, "--wait/--no-wait", help="Wait for broker confirmation."),
462
+ timeout: float = typer.Option(15.0, "--timeout"),
463
+ ) -> None:
464
+ """Amend the stop-loss / take-profit on an open position (SIDE EFFECT)."""
465
+ out = ctx.obj.out
466
+ body: dict[str, Any] = {}
467
+ for value, key in [
468
+ (stop_level, "stopLevel"),
469
+ (stop_distance, "stopDistance"),
470
+ (profit_level, "profitLevel"),
471
+ (profit_distance, "profitDistance"),
472
+ ]:
473
+ if value is not None:
474
+ body[key] = value
475
+ if guaranteed_stop is not None:
476
+ body["guaranteedStop"] = guaranteed_stop
477
+ if trailing_stop is not None:
478
+ body["trailingStop"] = trailing_stop
479
+ if not body:
480
+ raise typer.BadParameter("Provide at least one stop/profit option to amend.")
481
+
482
+ sm = get_session_manager()
483
+ client = get_client()
484
+ risk = get_risk_engine()
485
+
486
+ async def _do() -> dict[str, Any]:
487
+ warn_if_live(out)
488
+ await sm.ensure_logged_in()
489
+ risk.validate_execution_guards(confirm=yes)
490
+ data = (await client.put(f"/positions/{deal_id}", json=body)).json()
491
+ if wait and "dealReference" in data:
492
+ data["confirmation"] = await _wait_for_confirmation(
493
+ data["dealReference"], timeout_s=timeout
494
+ )
495
+ data["active_account_id"] = sm.account_id
496
+ return data
497
+
498
+ out.record(run(out, _do, label="trade amend-position"), title="Amend position")
499
+
500
+
501
+ @app.command("amend-order")
502
+ def amend_order(
503
+ ctx: typer.Context,
504
+ deal_id: str = typer.Argument(..., help="Deal ID of the working order to amend."),
505
+ level: float | None = typer.Option(None, "--level", help="New trigger level."),
506
+ good_till_date: str | None = typer.Option(None, "--good-till", help="New expiry ISO 8601."),
507
+ stop_level: float | None = typer.Option(None, "--stop-level"),
508
+ stop_distance: float | None = typer.Option(None, "--stop-distance"),
509
+ profit_level: float | None = typer.Option(None, "--profit-level"),
510
+ profit_distance: float | None = typer.Option(None, "--profit-distance"),
511
+ yes: bool = typer.Option(False, "--yes", "-y", help="Confirm the amendment."),
512
+ wait: bool = typer.Option(True, "--wait/--no-wait", help="Wait for broker confirmation."),
513
+ timeout: float = typer.Option(15.0, "--timeout"),
514
+ ) -> None:
515
+ """Amend a working order's level, expiry, or stops/limits (SIDE EFFECT)."""
516
+ out = ctx.obj.out
517
+ body: dict[str, Any] = {}
518
+ if level is not None:
519
+ body["level"] = level
520
+ if good_till_date is not None:
521
+ body["goodTillDate"] = good_till_date
522
+ for value, key in [
523
+ (stop_level, "stopLevel"),
524
+ (stop_distance, "stopDistance"),
525
+ (profit_level, "profitLevel"),
526
+ (profit_distance, "profitDistance"),
527
+ ]:
528
+ if value is not None:
529
+ body[key] = value
530
+ if not body:
531
+ raise typer.BadParameter("Provide at least one field to amend (level, good-till, stop/profit).")
532
+
533
+ sm = get_session_manager()
534
+ client = get_client()
535
+ risk = get_risk_engine()
536
+
537
+ async def _do() -> dict[str, Any]:
538
+ warn_if_live(out)
539
+ await sm.ensure_logged_in()
540
+ risk.validate_execution_guards(confirm=yes)
541
+ data = (await client.put(f"/workingorders/{deal_id}", json=body)).json()
542
+ if wait and "dealReference" in data:
543
+ data["confirmation"] = await _wait_for_confirmation(
544
+ data["dealReference"], timeout_s=timeout
545
+ )
546
+ data["active_account_id"] = sm.account_id
547
+ return data
548
+
549
+ out.record(run(out, _do, label="trade amend-order"), title="Amend order")
@@ -0,0 +1,132 @@
1
+ """capctl watchlist ... — watchlists."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import typer
8
+
9
+ from capital_cli.cli.runner import run
10
+ from capital_cli.core.config import get_config
11
+ from capital_cli.core.errors import ConfirmRequiredError
12
+ from capital_cli.core.http_client import get_client
13
+ from capital_cli.core.session import get_session_manager
14
+
15
+ app = typer.Typer(no_args_is_help=True, help="Watchlists: list, create, add, remove.")
16
+
17
+
18
+ def _require_confirm(yes: bool) -> None:
19
+ if get_config().cap_require_explicit_confirm and not yes:
20
+ raise ConfirmRequiredError()
21
+
22
+
23
+ @app.command("list")
24
+ def list_watchlists(ctx: typer.Context) -> None:
25
+ """List all watchlists."""
26
+ out = ctx.obj.out
27
+ sm = get_session_manager()
28
+ client = get_client()
29
+
30
+ async def _do() -> dict[str, Any]:
31
+ await sm.ensure_logged_in()
32
+ return (await client.get("/watchlists")).json()
33
+
34
+ data = run(out, _do, label="watchlist list")
35
+ if out.json_mode:
36
+ out.raw(data)
37
+ else:
38
+ out.rows(data.get("watchlists", []), ["id", "name"], title="Watchlists")
39
+
40
+
41
+ @app.command()
42
+ def get(ctx: typer.Context, watchlist_id: str = typer.Argument(..., help="Watchlist ID.")) -> None:
43
+ """Get a watchlist and its markets."""
44
+ out = ctx.obj.out
45
+ sm = get_session_manager()
46
+ client = get_client()
47
+
48
+ async def _do() -> dict[str, Any]:
49
+ await sm.ensure_logged_in()
50
+ return (await client.get(f"/watchlists/{watchlist_id}")).json()
51
+
52
+ out.raw(run(out, _do, label="watchlist get"))
53
+
54
+
55
+ @app.command()
56
+ def create(
57
+ ctx: typer.Context,
58
+ name: str = typer.Argument(..., help="Watchlist name."),
59
+ yes: bool = typer.Option(False, "--yes", "-y", help="Confirm creation."),
60
+ ) -> None:
61
+ """Create a new watchlist."""
62
+ out = ctx.obj.out
63
+ sm = get_session_manager()
64
+ client = get_client()
65
+
66
+ async def _do() -> dict[str, Any]:
67
+ _require_confirm(yes)
68
+ await sm.ensure_logged_in()
69
+ return (await client.post("/watchlists", json={"name": name})).json()
70
+
71
+ out.record(run(out, _do, label="watchlist create"), title="Created watchlist")
72
+
73
+
74
+ @app.command()
75
+ def add(
76
+ ctx: typer.Context,
77
+ watchlist_id: str = typer.Argument(..., help="Watchlist ID."),
78
+ epic: str = typer.Argument(..., help="Market EPIC to add."),
79
+ yes: bool = typer.Option(False, "--yes", "-y", help="Confirm."),
80
+ ) -> None:
81
+ """Add a market to a watchlist."""
82
+ out = ctx.obj.out
83
+ sm = get_session_manager()
84
+ client = get_client()
85
+
86
+ async def _do() -> dict[str, Any]:
87
+ _require_confirm(yes)
88
+ await sm.ensure_logged_in()
89
+ return (await client.put(f"/watchlists/{watchlist_id}", json={"epic": epic})).json()
90
+
91
+ out.record(run(out, _do, label="watchlist add"), title="Added to watchlist")
92
+
93
+
94
+ @app.command()
95
+ def remove(
96
+ ctx: typer.Context,
97
+ watchlist_id: str = typer.Argument(..., help="Watchlist ID."),
98
+ epic: str = typer.Argument(..., help="Market EPIC to remove."),
99
+ yes: bool = typer.Option(False, "--yes", "-y", help="Confirm."),
100
+ ) -> None:
101
+ """Remove a market from a watchlist."""
102
+ out = ctx.obj.out
103
+ sm = get_session_manager()
104
+ client = get_client()
105
+
106
+ async def _do() -> dict[str, Any]:
107
+ _require_confirm(yes)
108
+ await sm.ensure_logged_in()
109
+ resp = await client.delete(f"/watchlists/{watchlist_id}/{epic}")
110
+ return resp.json() if resp.text else {"status": "removed"}
111
+
112
+ out.record(run(out, _do, label="watchlist remove"), title="Removed from watchlist")
113
+
114
+
115
+ @app.command()
116
+ def delete(
117
+ ctx: typer.Context,
118
+ watchlist_id: str = typer.Argument(..., help="Watchlist ID."),
119
+ yes: bool = typer.Option(False, "--yes", "-y", help="Confirm deletion."),
120
+ ) -> None:
121
+ """Delete a watchlist."""
122
+ out = ctx.obj.out
123
+ sm = get_session_manager()
124
+ client = get_client()
125
+
126
+ async def _do() -> dict[str, Any]:
127
+ _require_confirm(yes)
128
+ await sm.ensure_logged_in()
129
+ resp = await client.delete(f"/watchlists/{watchlist_id}")
130
+ return resp.json() if resp.text else {"status": "deleted"}
131
+
132
+ out.record(run(out, _do, label="watchlist delete"), title="Deleted watchlist")
@@ -0,0 +1 @@
1
+ """Capital.com core services (HTTP, session, risk, models)."""