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,96 @@
1
+ """Run core coroutines and translate errors into process exit codes.
2
+
3
+ Centralizes three concerns in one place so commands stay thin:
4
+ 1. domain error -> distinct process exit code,
5
+ 2. pydantic ValidationError -> friendly field-by-field message (exit 2),
6
+ 3. DEBUG timing logs (duration in ms, failure type) for --verbose.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import asyncio
12
+ import logging
13
+ import time
14
+ from collections.abc import Callable, Coroutine
15
+ from typing import Any, TypeVar
16
+
17
+ import typer
18
+ from pydantic import ValidationError
19
+
20
+ from capital_cli.cli.output import Output
21
+ from capital_cli.core.errors import CapitalCLIError, ErrorCode
22
+
23
+ logger = logging.getLogger("capctl")
24
+
25
+ T = TypeVar("T")
26
+
27
+ # Distinct exit codes per error class so scripts can branch on failures.
28
+ # 2 = bad input (matches the conventional CLI "usage error" code).
29
+ EXIT_CODES: dict[str, int] = {
30
+ ErrorCode.INVALID_REQUEST: 2,
31
+ ErrorCode.CONFIG_MISSING: 3,
32
+ ErrorCode.CONFIG_INVALID: 3,
33
+ ErrorCode.TRADING_DISABLED: 4,
34
+ ErrorCode.DRY_RUN_ENABLED: 4,
35
+ ErrorCode.CONFIRM_REQUIRED: 4,
36
+ ErrorCode.EPIC_NOT_ALLOWED: 4,
37
+ ErrorCode.RISK_LIMIT: 4,
38
+ ErrorCode.SESSION_EXPIRED: 5,
39
+ ErrorCode.SESSION_NOT_INITIALIZED: 5,
40
+ ErrorCode.AUTH_FAILED: 5,
41
+ ErrorCode.RATE_LIMITED_LOCAL: 6,
42
+ ErrorCode.BROKER_REJECTED: 7,
43
+ ErrorCode.UPSTREAM_ERROR: 7,
44
+ ErrorCode.UPSTREAM_TIMEOUT: 7,
45
+ ErrorCode.PREVIEW_NOT_FOUND: 8,
46
+ ErrorCode.PREVIEW_EXPIRED: 8,
47
+ ErrorCode.PREVIEW_CHECKS_FAILED: 8,
48
+ }
49
+
50
+
51
+ def _format_validation_error(exc: ValidationError) -> str:
52
+ """Turn a pydantic ValidationError into a one-line, field-by-field message."""
53
+ parts = []
54
+ for err in exc.errors():
55
+ loc = ".".join(str(p) for p in err.get("loc", ())) or "input"
56
+ parts.append(f"{loc}: {err.get('msg', 'invalid')}")
57
+ return "Invalid input — " + "; ".join(parts)
58
+
59
+
60
+ def run(
61
+ out: Output,
62
+ factory: Callable[[], Coroutine[Any, Any, T]],
63
+ *,
64
+ label: str | None = None,
65
+ ) -> T:
66
+ """
67
+ Execute an async factory, rendering any failure and raising typer.Exit.
68
+
69
+ Returns the coroutine result on success. `label` (optional) names the
70
+ command for DEBUG timing logs; omitting it keeps call sites terse.
71
+ """
72
+ started = time.monotonic()
73
+ name = label or "command"
74
+
75
+ def _elapsed_ms() -> float:
76
+ return (time.monotonic() - started) * 1000
77
+
78
+ try:
79
+ result = asyncio.run(factory())
80
+ logger.debug("%s completed in %.0f ms", name, _elapsed_ms())
81
+ return result
82
+ except ValidationError as exc:
83
+ logger.debug("%s failed (ValidationError) in %.0f ms", name, _elapsed_ms())
84
+ out.error(ErrorCode.INVALID_REQUEST, _format_validation_error(exc))
85
+ raise typer.Exit(code=EXIT_CODES[ErrorCode.INVALID_REQUEST]) from exc
86
+ except CapitalCLIError as exc:
87
+ logger.debug("%s failed (%s) in %.0f ms", name, exc.code, _elapsed_ms())
88
+ out.error(exc.code, exc.message)
89
+ raise typer.Exit(code=EXIT_CODES.get(exc.code, 1)) from exc
90
+ except KeyboardInterrupt:
91
+ out.note("Interrupted.")
92
+ raise typer.Exit(code=130) from None
93
+ except Exception as exc: # noqa: BLE001 - top-level CLI guard
94
+ logger.debug("%s failed (%s) in %.0f ms", name, type(exc).__name__, _elapsed_ms())
95
+ out.error(ErrorCode.INTERNAL_ERROR, str(exc))
96
+ raise typer.Exit(code=1) from exc
@@ -0,0 +1,127 @@
1
+ """capctl session ... — session lifecycle."""
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.http_client import get_client
11
+ from capital_cli.core.session import get_session_manager
12
+
13
+ app = typer.Typer(no_args_is_help=True, help="Session lifecycle: login, ping, logout.")
14
+
15
+
16
+ @app.command()
17
+ def status(ctx: typer.Context) -> None:
18
+ """Show current session status (no network call)."""
19
+ out = ctx.obj.out
20
+ sm = get_session_manager()
21
+ out.record(sm.get_status().model_dump(), title="Session status")
22
+
23
+
24
+ @app.command()
25
+ def login(
26
+ ctx: typer.Context,
27
+ force: bool = typer.Option(False, "--force", help="Re-login even if a session is valid."),
28
+ account: str | None = typer.Option(
29
+ None, "--account", "-a", help="Account ID to switch to after login."
30
+ ),
31
+ ) -> None:
32
+ """Create (or verify) a session and store auth tokens."""
33
+ out = ctx.obj.out
34
+ sm = get_session_manager()
35
+
36
+ async def _do():
37
+ data = await sm.login(force=force, account_id=account)
38
+ data["active_account_id"] = sm.account_id
39
+ return data
40
+
41
+ data = run(out, _do, label="session login")
42
+ out.record(
43
+ {"active_account_id": data.get("active_account_id"), "status": "logged in"},
44
+ title="Login",
45
+ )
46
+
47
+
48
+ @app.command()
49
+ def ping(ctx: typer.Context) -> None:
50
+ """Keep the session alive."""
51
+ out = ctx.obj.out
52
+ sm = get_session_manager()
53
+
54
+ async def _do():
55
+ await sm.ensure_logged_in()
56
+ return await sm.ping()
57
+
58
+ out.record(run(out, _do, label="session ping"), title="Ping")
59
+
60
+
61
+ @app.command()
62
+ def logout(ctx: typer.Context) -> None:
63
+ """End the session and clear tokens."""
64
+ out = ctx.obj.out
65
+ sm = get_session_manager()
66
+
67
+ async def _do():
68
+ await sm.logout()
69
+ return {"status": "logged out"}
70
+
71
+ out.record(run(out, _do, label="session logout"), title="Logout")
72
+
73
+
74
+ @app.command()
75
+ def switch(
76
+ ctx: typer.Context, account_id: str = typer.Argument(..., help="Target account ID.")
77
+ ) -> None:
78
+ """Switch the active account."""
79
+ out = ctx.obj.out
80
+ sm = get_session_manager()
81
+
82
+ async def _do():
83
+ await sm.ensure_logged_in()
84
+ data = await sm.switch_account(account_id)
85
+ data["active_account_id"] = sm.account_id
86
+ return data
87
+
88
+ out.record(run(out, _do, label="session switch"), title="Switch account")
89
+
90
+
91
+ @app.command()
92
+ def time(ctx: typer.Context) -> None:
93
+ """Show the broker's current server time (no authentication required)."""
94
+ out = ctx.obj.out
95
+ client = get_client()
96
+
97
+ async def _do() -> dict[str, Any]:
98
+ data = (await client.get("/time")).json()
99
+ return data if isinstance(data, dict) else {"serverTime": data}
100
+
101
+ out.record(run(out, _do, label="session time"), title="Server time")
102
+
103
+
104
+ @app.command()
105
+ def details(ctx: typer.Context) -> None:
106
+ """Show server-side session details (client id, account id, currency, timezone)."""
107
+ out = ctx.obj.out
108
+ sm = get_session_manager()
109
+ client = get_client()
110
+
111
+ async def _do() -> dict[str, Any]:
112
+ await sm.ensure_logged_in()
113
+ return (await client.get("/session")).json()
114
+
115
+ out.record(run(out, _do, label="session details"), title="Session details")
116
+
117
+
118
+ @app.command("encryption-key")
119
+ def encryption_key(ctx: typer.Context) -> None:
120
+ """Fetch the API encryption key and timestamp (used for encrypted-password login)."""
121
+ out = ctx.obj.out
122
+ client = get_client()
123
+
124
+ async def _do() -> dict[str, Any]:
125
+ return (await client.get("/session/encryptionKey")).json()
126
+
127
+ out.record(run(out, _do, label="session encryption-key"), title="Encryption key")
@@ -0,0 +1,263 @@
1
+ """capctl stream ... — real-time WebSocket streaming."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime, timezone
6
+ from typing import Any
7
+
8
+ import typer
9
+ from rich.live import Live
10
+ from rich.table import Table
11
+
12
+ from capital_cli.cli.runner import run
13
+ from capital_cli.core.session import get_session_manager
14
+ from capital_cli.core.websocket_client import get_websocket_client
15
+
16
+ app = typer.Typer(no_args_is_help=True, help="Real-time streaming: prices, alerts, portfolio.")
17
+
18
+
19
+ def _parse_epics(raw: str) -> list[str]:
20
+ epics = [e.strip() for e in raw.split(",") if e.strip()]
21
+ if not epics:
22
+ raise typer.BadParameter("Provide at least one EPIC.")
23
+ if len(epics) > 40:
24
+ raise typer.BadParameter(f"Capital.com allows at most 40 EPICs (got {len(epics)}).")
25
+ return epics
26
+
27
+
28
+ def _price_table(latest: dict[str, Any]) -> Table:
29
+ table = Table(title="Live prices (Ctrl-C to stop)", header_style="bold cyan")
30
+ for col in ["epic", "bid", "offer", "timestamp"]:
31
+ table.add_column(col)
32
+ for epic in sorted(latest):
33
+ tick = latest[epic]
34
+ table.add_row(epic, str(tick["bid"]), str(tick["offer"]), tick["timestamp"])
35
+ return table
36
+
37
+
38
+ def _candle_table(latest: dict[str, Any]) -> Table:
39
+ table = Table(title="Live candles (Ctrl-C to stop)", header_style="bold cyan")
40
+ for col in ["epic", "resolution", "open", "high", "low", "close", "timestamp"]:
41
+ table.add_column(col)
42
+ for key in sorted(latest):
43
+ b = latest[key]
44
+ table.add_row(
45
+ b["epic"],
46
+ b["resolution"],
47
+ str(b["open"]),
48
+ str(b["high"]),
49
+ str(b["low"]),
50
+ str(b["close"]),
51
+ b["timestamp"],
52
+ )
53
+ return table
54
+
55
+
56
+ @app.command()
57
+ def prices(
58
+ ctx: typer.Context,
59
+ epics: str = typer.Argument(..., help="Comma-separated EPICs (max 40)."),
60
+ duration: float = typer.Option(300.0, "--duration", help="Stream duration in seconds."),
61
+ interval: float = typer.Option(
62
+ 1.0, "--interval", help="Min seconds between recorded updates."
63
+ ),
64
+ ) -> None:
65
+ """Stream live bid/offer prices."""
66
+ out = ctx.obj.out
67
+ parsed = _parse_epics(epics)
68
+ sm = get_session_manager()
69
+
70
+ async def _do() -> dict[str, Any]:
71
+ await sm.ensure_logged_in()
72
+ collected: list[dict[str, Any]] = []
73
+ latest: dict[str, Any] = {}
74
+ last_emit = datetime.now(timezone.utc)
75
+ ws = get_websocket_client()
76
+ live = (
77
+ None
78
+ if out.json_mode
79
+ else Live(_price_table(latest), console=out.console, refresh_per_second=4)
80
+ )
81
+ if live:
82
+ live.__enter__()
83
+ try:
84
+ async with ws:
85
+ await ws.subscribe(parsed)
86
+ async for tick in ws.stream(duration=duration):
87
+ row = tick.model_dump()
88
+ latest[row["epic"]] = row
89
+ now = datetime.now(timezone.utc)
90
+ if (now - last_emit).total_seconds() >= interval:
91
+ collected.append(row)
92
+ last_emit = now
93
+ if live:
94
+ live.update(_price_table(latest))
95
+ finally:
96
+ if live:
97
+ live.__exit__(None, None, None)
98
+ return {
99
+ "epics": parsed,
100
+ "duration_s": duration,
101
+ "ticks_received": len(collected),
102
+ "ticks": collected[-100:],
103
+ }
104
+
105
+ data = run(out, _do, label="stream prices")
106
+ if out.json_mode:
107
+ out.raw(data)
108
+ else:
109
+ out.note(f"Collected {data['ticks_received']} updates over {data['duration_s']}s.")
110
+
111
+
112
+ @app.command()
113
+ def alerts(
114
+ ctx: typer.Context,
115
+ epic: str = typer.Argument(..., help="Market EPIC to watch."),
116
+ level: float = typer.Argument(..., help="Trigger price level."),
117
+ direction: str = typer.Option("ABOVE", "--direction", help="ABOVE or BELOW."),
118
+ duration: float = typer.Option(300.0, "--duration", help="Max monitoring seconds."),
119
+ auto_close: bool = typer.Option(
120
+ True, "--auto-close/--keep-open", help="Stop after first trigger."
121
+ ),
122
+ ) -> None:
123
+ """Trigger an alert when a market crosses a price level."""
124
+ out = ctx.obj.out
125
+ sm = get_session_manager()
126
+ direction_u = direction.upper()
127
+ if direction_u not in ("ABOVE", "BELOW"):
128
+ raise typer.BadParameter("--direction must be ABOVE or BELOW.")
129
+
130
+ async def _do() -> dict[str, Any]:
131
+ await sm.ensure_logged_in()
132
+ triggered: list[dict[str, Any]] = []
133
+ ws = get_websocket_client()
134
+ async with ws:
135
+ await ws.subscribe([epic])
136
+ async for tick in ws.stream(duration=duration):
137
+ mid = (tick.bid + tick.offer) / 2
138
+ hit = (direction_u == "ABOVE" and mid >= level) or (
139
+ direction_u == "BELOW" and mid <= level
140
+ )
141
+ if hit:
142
+ event = {
143
+ "epic": tick.epic,
144
+ "condition": f"LEVEL_{direction_u}",
145
+ "trigger_price": level,
146
+ "current_price": mid,
147
+ "timestamp": tick.timestamp,
148
+ }
149
+ triggered.append(event)
150
+ if not out.json_mode:
151
+ out.success(f"ALERT {tick.epic} {direction_u} {level} (now {mid:.2f})")
152
+ if auto_close:
153
+ break
154
+ return {"epic": epic, "level": level, "direction": direction_u, "triggered": triggered}
155
+
156
+ data = run(out, _do, label="stream alerts")
157
+ if out.json_mode:
158
+ out.raw(data)
159
+ elif not data["triggered"]:
160
+ out.note("No alert triggered within the duration.")
161
+
162
+
163
+ @app.command()
164
+ def portfolio(
165
+ ctx: typer.Context,
166
+ duration: float = typer.Option(300.0, "--duration", help="Stream duration in seconds."),
167
+ interval: float = typer.Option(5.0, "--interval", help="Recording interval in seconds."),
168
+ ) -> None:
169
+ """Stream live price snapshots for currently open positions."""
170
+ out = ctx.obj.out
171
+ sm = get_session_manager()
172
+ from capital_cli.core.http_client import get_client
173
+
174
+ async def _do() -> dict[str, Any]:
175
+ await sm.ensure_logged_in()
176
+ client = get_client()
177
+ positions = (await client.get("/positions")).json().get("positions", [])
178
+ epics = [
179
+ p.get("market", {}).get("epic")
180
+ for p in positions
181
+ if p.get("market", {}).get("epic")
182
+ ]
183
+ if not epics:
184
+ return {"positions": 0, "note": "No open positions to stream."}
185
+ snapshots: list[dict[str, Any]] = []
186
+ last_emit = datetime.now(timezone.utc)
187
+ latest: dict[str, Any] = {}
188
+ ws = get_websocket_client()
189
+ async with ws:
190
+ await ws.subscribe(epics[:40])
191
+ async for tick in ws.stream(duration=duration):
192
+ latest[tick.epic] = (tick.bid + tick.offer) / 2
193
+ now = datetime.now(timezone.utc)
194
+ if (now - last_emit).total_seconds() >= interval:
195
+ snapshots.append({"prices": dict(latest), "timestamp": tick.timestamp})
196
+ last_emit = now
197
+ return {"positions": len(epics), "snapshots": snapshots[-50:]}
198
+
199
+ out.raw(run(out, _do, label="stream portfolio"))
200
+
201
+
202
+ @app.command()
203
+ def candles(
204
+ ctx: typer.Context,
205
+ epics: str = typer.Argument(..., help="Comma-separated EPICs (max 40)."),
206
+ resolution: str = typer.Option(
207
+ "MINUTE", "--resolution", help="MINUTE, MINUTE_5, MINUTE_15, MINUTE_30, HOUR, HOUR_4, DAY, WEEK."
208
+ ),
209
+ bar_type: str = typer.Option("classic", "--type", help="classic or heikin-ashi."),
210
+ duration: float = typer.Option(300.0, "--duration", help="Stream duration in seconds."),
211
+ interval: float = typer.Option(
212
+ 0.0, "--interval", help="Min seconds between recorded bars (0 = every update)."
213
+ ),
214
+ ) -> None:
215
+ """Stream live OHLC candlesticks."""
216
+ out = ctx.obj.out
217
+ parsed = _parse_epics(epics)
218
+ if bar_type not in ("classic", "heikin-ashi"):
219
+ raise typer.BadParameter("--type must be classic or heikin-ashi.")
220
+ sm = get_session_manager()
221
+
222
+ async def _do() -> dict[str, Any]:
223
+ await sm.ensure_logged_in()
224
+ collected: list[dict[str, Any]] = []
225
+ latest: dict[str, Any] = {}
226
+ last_emit = datetime.now(timezone.utc)
227
+ ws = get_websocket_client()
228
+ live = (
229
+ None
230
+ if out.json_mode
231
+ else Live(_candle_table(latest), console=out.console, refresh_per_second=4)
232
+ )
233
+ if live:
234
+ live.__enter__()
235
+ try:
236
+ async with ws:
237
+ await ws.subscribe_ohlc(parsed, [resolution], bar_type)
238
+ async for bar in ws.stream_ohlc(duration=duration):
239
+ row = bar.model_dump()
240
+ latest[f"{row['epic']}:{row['resolution']}"] = row
241
+ now = datetime.now(timezone.utc)
242
+ if (now - last_emit).total_seconds() >= interval:
243
+ collected.append(row)
244
+ last_emit = now
245
+ if live:
246
+ live.update(_candle_table(latest))
247
+ finally:
248
+ if live:
249
+ live.__exit__(None, None, None)
250
+ return {
251
+ "epics": parsed,
252
+ "resolution": resolution,
253
+ "type": bar_type,
254
+ "duration_s": duration,
255
+ "bars_received": len(collected),
256
+ "bars": collected[-100:],
257
+ }
258
+
259
+ data = run(out, _do, label="stream candles")
260
+ if out.json_mode:
261
+ out.raw(data)
262
+ else:
263
+ out.note(f"Collected {data['bars_received']} candles over {data['duration_s']}s.")