capitalcom-cli 0.4.0__tar.gz → 0.5.0__tar.gz

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.
Files changed (85) hide show
  1. {capitalcom_cli-0.4.0/capitalcom_cli.egg-info → capitalcom_cli-0.5.0}/PKG-INFO +78 -12
  2. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/README.md +76 -11
  3. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/capital_cli/__init__.py +1 -1
  4. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/capital_cli/cli/account_cmds.py +17 -60
  5. capitalcom_cli-0.5.0/capital_cli/cli/app.py +165 -0
  6. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/capital_cli/cli/context.py +12 -0
  7. capitalcom_cli-0.5.0/capital_cli/cli/doctor_cmds.py +88 -0
  8. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/capital_cli/cli/market_cmds.py +13 -44
  9. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/capital_cli/cli/output.py +16 -2
  10. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/capital_cli/cli/session_cmds.py +14 -10
  11. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/capital_cli/cli/stream_cmds.py +80 -84
  12. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/capital_cli/cli/trade_cmds.py +104 -172
  13. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/capital_cli/cli/watchlist_cmds.py +7 -39
  14. capitalcom_cli-0.5.0/capital_cli/core/audit.py +74 -0
  15. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/capital_cli/core/config.py +106 -2
  16. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/capital_cli/core/errors.py +41 -53
  17. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/capital_cli/core/http_client.py +3 -7
  18. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/capital_cli/core/models.py +16 -48
  19. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/capital_cli/core/rate_limit.py +2 -35
  20. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/capital_cli/core/risk.py +89 -29
  21. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/capital_cli/core/session.py +56 -8
  22. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/capital_cli/core/state.py +24 -0
  23. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/capital_cli/core/utils.py +15 -5
  24. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/capital_cli/core/websocket_client.py +16 -17
  25. capitalcom_cli-0.5.0/capital_cli/sdk/__init__.py +10 -0
  26. capitalcom_cli-0.5.0/capital_cli/sdk/app.py +68 -0
  27. capitalcom_cli-0.5.0/capital_cli/sdk/config.py +18 -0
  28. capitalcom_cli-0.5.0/capital_cli/sdk/risk_policy.py +32 -0
  29. capitalcom_cli-0.5.0/capital_cli/services/__init__.py +20 -0
  30. capitalcom_cli-0.5.0/capital_cli/services/accounts.py +114 -0
  31. capitalcom_cli-0.5.0/capital_cli/services/confirmations.py +95 -0
  32. capitalcom_cli-0.5.0/capital_cli/services/markets.py +82 -0
  33. capitalcom_cli-0.5.0/capital_cli/services/streaming.py +105 -0
  34. capitalcom_cli-0.5.0/capital_cli/services/trading.py +284 -0
  35. capitalcom_cli-0.5.0/capital_cli/services/watchlists.py +73 -0
  36. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0/capitalcom_cli.egg-info}/PKG-INFO +78 -12
  37. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/capitalcom_cli.egg-info/SOURCES.txt +26 -0
  38. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/capitalcom_cli.egg-info/requires.txt +1 -0
  39. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/pyproject.toml +9 -1
  40. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/tests/test_account_cmds.py +22 -5
  41. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/tests/test_app.py +12 -0
  42. capitalcom_cli-0.5.0/tests/test_audit.py +66 -0
  43. capitalcom_cli-0.5.0/tests/test_build_broker_request.py +29 -0
  44. capitalcom_cli-0.5.0/tests/test_cli_usage_errors.py +24 -0
  45. capitalcom_cli-0.5.0/tests/test_config_errors.py +34 -0
  46. capitalcom_cli-0.5.0/tests/test_credential_cmd.py +176 -0
  47. capitalcom_cli-0.5.0/tests/test_doctor.py +114 -0
  48. capitalcom_cli-0.5.0/tests/test_global_flag_hoist.py +27 -0
  49. capitalcom_cli-0.5.0/tests/test_init_state_singletons.py +41 -0
  50. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/tests/test_market_cmds.py +5 -3
  51. capitalcom_cli-0.5.0/tests/test_redaction.py +35 -0
  52. capitalcom_cli-0.5.0/tests/test_risk.py +234 -0
  53. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/tests/test_runner.py +1 -3
  54. capitalcom_cli-0.5.0/tests/test_session_persistence.py +142 -0
  55. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/tests/test_state.py +2 -2
  56. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/tests/test_stream_cmds.py +56 -11
  57. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/tests/test_trade_cmds.py +109 -9
  58. capitalcom_cli-0.5.0/tests/test_trade_limit.py +18 -0
  59. capitalcom_cli-0.5.0/tests/test_tz_datetimes.py +64 -0
  60. capitalcom_cli-0.5.0/tests/test_utils.py +51 -0
  61. capitalcom_cli-0.5.0/tests/test_version.py +21 -0
  62. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/tests/test_watchlist_cmds.py +2 -2
  63. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/tests/test_websocket_parsing.py +1 -0
  64. capitalcom_cli-0.4.0/capital_cli/cli/app.py +0 -88
  65. capitalcom_cli-0.4.0/tests/test_risk.py +0 -81
  66. capitalcom_cli-0.4.0/tests/test_version.py +0 -9
  67. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/LICENSE +0 -0
  68. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/NOTICE +0 -0
  69. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/capital_cli/__main__.py +0 -0
  70. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/capital_cli/cli/__init__.py +0 -0
  71. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/capital_cli/cli/live_guard.py +0 -0
  72. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/capital_cli/cli/runner.py +0 -0
  73. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/capital_cli/core/__init__.py +0 -0
  74. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/capitalcom_cli.egg-info/dependency_links.txt +0 -0
  75. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/capitalcom_cli.egg-info/entry_points.txt +0 -0
  76. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/capitalcom_cli.egg-info/top_level.txt +0 -0
  77. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/setup.cfg +0 -0
  78. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/tests/test_core_port.py +0 -0
  79. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/tests/test_errors.py +0 -0
  80. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/tests/test_http_client.py +0 -0
  81. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/tests/test_live_guard.py +0 -0
  82. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/tests/test_output.py +0 -0
  83. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/tests/test_output_color.py +0 -0
  84. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/tests/test_output_plain.py +0 -0
  85. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.0}/tests/test_session_cmds.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: capitalcom-cli
3
- Version: 0.4.0
3
+ Version: 0.5.0
4
4
  Summary: Command-line client for the Capital.com Open API
5
5
  Author: Simon Tarara
6
6
  License: Apache-2.0
@@ -11,6 +11,7 @@ Description-Content-Type: text/markdown
11
11
  License-File: LICENSE
12
12
  License-File: NOTICE
13
13
  Requires-Dist: typer>=0.12.0
14
+ Requires-Dist: click>=8.0
14
15
  Requires-Dist: rich>=13.7.0
15
16
  Requires-Dist: httpx>=0.27.0
16
17
  Requires-Dist: pydantic>=2.0.0
@@ -33,6 +34,7 @@ A fast, scriptable command-line client for the [Capital.com](https://capital.com
33
34
  Browse markets, manage accounts and watchlists, preview and execute trades behind multiple safety guardrails, and stream real-time prices — from your terminal, in human-readable tables or raw JSON for automation.
34
35
 
35
36
  [![CI](https://github.com/SimonTarara62/capitalcom-cli/actions/workflows/ci.yml/badge.svg)](https://github.com/SimonTarara62/capitalcom-cli/actions/workflows/ci.yml)
37
+ [![PyPI](https://img.shields.io/pypi/v/capitalcom-cli.svg)](https://pypi.org/project/capitalcom-cli/)
36
38
  [![License: Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE)
37
39
  [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/downloads/)
38
40
  [![Release](https://img.shields.io/github/v/release/SimonTarara62/capitalcom-cli?sort=semver)](https://github.com/SimonTarara62/capitalcom-cli/releases)
@@ -64,11 +66,13 @@ The Capital.com web platform is built for clicking; `capctl` is built for **repe
64
66
 
65
67
  See [practical use cases](docs/use-cases.md) for worked, copy-pasteable scenarios.
66
68
 
67
- **Scope:** `capctl` is a command-line application, not a stable Python SDK — the
68
- internal `capital_cli.*` modules may change between releases without notice. It is
69
- also short-lived: each command runs as its own process and may create its own API
70
- session. `capctl session login` is mainly a connectivity/account check; session
71
- tokens are not persisted between separate invocations.
69
+ **Scope:** `capctl` is first and foremost a command-line application, but the same
70
+ tested broker engine is also embeddable as an **experimental** Python SDK — see
71
+ [Use as a library](#use-as-a-library-experimental) and [docs/sdk.md](docs/sdk.md).
72
+ The `capital_cli.core.*` internals remain private and may change between releases.
73
+ The CLI itself is short-lived: each command runs as its own process and may create
74
+ its own API session. `capctl session login` is mainly a connectivity/account check;
75
+ session tokens are not persisted between separate invocations.
72
76
 
73
77
  ## Features
74
78
 
@@ -84,24 +88,28 @@ tokens are not persisted between separate invocations.
84
88
 
85
89
  Requires Python 3.10+.
86
90
 
87
- **One-line install (recommended)** — isolated, global `capctl` command, no clone:
91
+ **One-line install (recommended)** — isolated, global `capctl` command:
88
92
 
89
93
  ```bash
90
- pipx install git+https://github.com/SimonTarara62/capitalcom-cli.git
94
+ pipx install capitalcom-cli
91
95
  ```
92
96
 
93
97
  Using [uv](https://docs.astral.sh/uv/) instead of pipx:
94
98
 
95
99
  ```bash
96
- uv tool install git+https://github.com/SimonTarara62/capitalcom-cli.git
100
+ uv tool install capitalcom-cli
97
101
  ```
98
102
 
99
103
  Plain pip (into the active environment):
100
104
 
101
105
  ```bash
102
- pip install git+https://github.com/SimonTarara62/capitalcom-cli.git
106
+ pip install capitalcom-cli
103
107
  ```
104
108
 
109
+ To get the latest unreleased code instead of the last published release, replace
110
+ the package name `capitalcom-cli` with
111
+ `git+https://github.com/SimonTarara62/capitalcom-cli.git` in any command above.
112
+
105
113
  **From a clone (for development):**
106
114
 
107
115
  ```bash
@@ -145,7 +153,7 @@ Credentials are resolved in this order:
145
153
  3. `./.env` in the current directory
146
154
  4. `~/.config/capital-cli/.env`
147
155
 
148
- All settings (one `CAP_*` variable each) and their defaults:
156
+ Main settings and their defaults:
149
157
 
150
158
  | Variable | Default | Purpose |
151
159
  |----------|---------|---------|
@@ -153,6 +161,9 @@ All settings (one `CAP_*` variable each) and their defaults:
153
161
  | `CAP_API_KEY` | — | API key (required) |
154
162
  | `CAP_IDENTIFIER` | — | Login email (required) |
155
163
  | `CAP_API_PASSWORD` | — | API-key custom password (required) |
164
+ | `CAP_API_KEY_CMD` | (none) | Command whose stdout supplies `CAP_API_KEY` (see below) |
165
+ | `CAP_IDENTIFIER_CMD` | (none) | Command whose stdout supplies `CAP_IDENTIFIER` |
166
+ | `CAP_API_PASSWORD_CMD` | (none) | Command whose stdout supplies `CAP_API_PASSWORD` |
156
167
  | `CAP_ALLOW_TRADING` | `false` | Master switch for all trade execution |
157
168
  | `CAP_ALLOWED_EPICS` | (empty) | Comma-separated allowlist, or `ALL` |
158
169
  | `CAP_MAX_POSITION_SIZE` | `1.0` | Per-trade size ceiling |
@@ -165,6 +176,33 @@ All settings (one `CAP_*` variable each) and their defaults:
165
176
  | `CAP_HTTP_TIMEOUT_S` | `15` | HTTP timeout |
166
177
  | `CAP_LOG_LEVEL` | `WARNING` | `DEBUG` … `CRITICAL` |
167
178
  | `CAP_WS_ENABLED` | `false` | Required for `capctl stream …` |
179
+ | `CAP_AUDIT_LOG` | (none) | File path; appends one JSONL line per executed mutation (no secrets) |
180
+
181
+ Advanced/internal settings (rarely changed; safe defaults):
182
+
183
+ | Variable | Default | Purpose |
184
+ |----------|---------|---------|
185
+ | `CAP_PREVIEW_CACHE_TTL_S` | `120` | How long a `preview_id` stays valid before expiry |
186
+ | `CAP_PING_INTERVAL_S` | `480` | Session keep-alive ping interval |
187
+
188
+ ### Credential-exec helpers (`CAP_*_CMD`)
189
+
190
+ To keep secrets out of plaintext files, source each credential from a command at
191
+ runtime — the AWS `credential_process` / git-credential-helper pattern. Set
192
+ `CAP_API_KEY_CMD`, `CAP_IDENTIFIER_CMD`, and/or `CAP_API_PASSWORD_CMD` to a
193
+ command line; its trimmed stdout becomes the corresponding secret.
194
+
195
+ ```bash
196
+ export CAP_API_PASSWORD_CMD="op read op://Private/capital/api-password"
197
+ export CAP_API_KEY_CMD="pass capital/api-key"
198
+ ```
199
+
200
+ Precedence (highest first): an explicit `CAP_<FIELD>` env var, then the
201
+ `CAP_<FIELD>_CMD` output, then the value in your `.env` file. Commands run with
202
+ `shell=False`, a 10-second timeout, and a non-zero exit / timeout / empty output
203
+ raises a clear configuration error (exit 3). The resolved secret is never logged
204
+ and the command's stdout/stderr is never echoed in error messages. This is
205
+ at-rest hygiene; see [SECURITY.md](SECURITY.md) for the threat model.
168
206
 
169
207
  Trade previews and the daily order counter persist between commands in
170
208
  `~/.config/capital-cli/state.json` (override with `CAPCTL_STATE_FILE`).
@@ -352,6 +390,33 @@ capctl stream alerts BTCUSD 75000 --direction ABOVE --duration 3600
352
390
  */15 * * * * capctl --json trade positions >> ~/logs/positions.jsonl 2>&1
353
391
  ```
354
392
 
393
+ ## Use as a library (experimental)
394
+
395
+ Beyond the CLI, the same broker engine — risk policy, two-phase preview→execute,
396
+ rate limiting, WebSocket streaming — is available as an embeddable async SDK.
397
+ **CLI** = terminal, scripts, CI; **SDK** = embed the tested engine in your own
398
+ Python (MCP servers, dashboards, n8n nodes).
399
+
400
+ ```python
401
+ from capital_cli.sdk import CapitalComApp, CapitalComConfig, RiskPolicy
402
+ ```
403
+
404
+ ```python
405
+ import asyncio
406
+ from capital_cli.sdk import CapitalComApp
407
+
408
+ async def main():
409
+ async with CapitalComApp() as app:
410
+ gold = await app.markets.get("GOLD")
411
+ print(gold["snapshot"]["bid"])
412
+
413
+ asyncio.run(main())
414
+ ```
415
+
416
+ The SDK is **experimental** until 1.0: import paths and the pydantic models are
417
+ intended-stable but may shift between 0.x minors. See [docs/sdk.md](docs/sdk.md)
418
+ for read-only, preview→execute, streaming, and risk-policy examples.
419
+
355
420
  ## Exit codes
356
421
 
357
422
  | Code | Meaning |
@@ -400,7 +465,7 @@ The `cli/` layer never talks to the API directly — every command parses argume
400
465
  ```bash
401
466
  pip install -e ".[dev]"
402
467
  pytest -q # full test suite
403
- ruff check . # lint
468
+ ruff check capital_cli tests # lint
404
469
  mypy capital_cli # type-check the whole package (matches CI)
405
470
  ```
406
471
 
@@ -417,6 +482,7 @@ Or use the task runner: `make check` (lint + typecheck + test), `make docs`, `ma
417
482
  ## Documentation
418
483
 
419
484
  - [Full CLI reference](docs/CLI.md) — every command and option (auto-generated)
485
+ - [Using capctl as a Python SDK](docs/sdk.md) — experimental async SDK, import paths, examples, versioning
420
486
  - [Scripting & automation](docs/scripting.md) — CI credentials, exit codes, jq recipes
421
487
  - [Getting started from zero](docs/getting-started.md) — account, API key, install, first trade
422
488
  - [Practical use cases](docs/use-cases.md) — what people actually do with capctl, with copy-pasteable scenarios
@@ -5,6 +5,7 @@ A fast, scriptable command-line client for the [Capital.com](https://capital.com
5
5
  Browse markets, manage accounts and watchlists, preview and execute trades behind multiple safety guardrails, and stream real-time prices — from your terminal, in human-readable tables or raw JSON for automation.
6
6
 
7
7
  [![CI](https://github.com/SimonTarara62/capitalcom-cli/actions/workflows/ci.yml/badge.svg)](https://github.com/SimonTarara62/capitalcom-cli/actions/workflows/ci.yml)
8
+ [![PyPI](https://img.shields.io/pypi/v/capitalcom-cli.svg)](https://pypi.org/project/capitalcom-cli/)
8
9
  [![License: Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE)
9
10
  [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/downloads/)
10
11
  [![Release](https://img.shields.io/github/v/release/SimonTarara62/capitalcom-cli?sort=semver)](https://github.com/SimonTarara62/capitalcom-cli/releases)
@@ -36,11 +37,13 @@ The Capital.com web platform is built for clicking; `capctl` is built for **repe
36
37
 
37
38
  See [practical use cases](docs/use-cases.md) for worked, copy-pasteable scenarios.
38
39
 
39
- **Scope:** `capctl` is a command-line application, not a stable Python SDK — the
40
- internal `capital_cli.*` modules may change between releases without notice. It is
41
- also short-lived: each command runs as its own process and may create its own API
42
- session. `capctl session login` is mainly a connectivity/account check; session
43
- tokens are not persisted between separate invocations.
40
+ **Scope:** `capctl` is first and foremost a command-line application, but the same
41
+ tested broker engine is also embeddable as an **experimental** Python SDK — see
42
+ [Use as a library](#use-as-a-library-experimental) and [docs/sdk.md](docs/sdk.md).
43
+ The `capital_cli.core.*` internals remain private and may change between releases.
44
+ The CLI itself is short-lived: each command runs as its own process and may create
45
+ its own API session. `capctl session login` is mainly a connectivity/account check;
46
+ session tokens are not persisted between separate invocations.
44
47
 
45
48
  ## Features
46
49
 
@@ -56,24 +59,28 @@ tokens are not persisted between separate invocations.
56
59
 
57
60
  Requires Python 3.10+.
58
61
 
59
- **One-line install (recommended)** — isolated, global `capctl` command, no clone:
62
+ **One-line install (recommended)** — isolated, global `capctl` command:
60
63
 
61
64
  ```bash
62
- pipx install git+https://github.com/SimonTarara62/capitalcom-cli.git
65
+ pipx install capitalcom-cli
63
66
  ```
64
67
 
65
68
  Using [uv](https://docs.astral.sh/uv/) instead of pipx:
66
69
 
67
70
  ```bash
68
- uv tool install git+https://github.com/SimonTarara62/capitalcom-cli.git
71
+ uv tool install capitalcom-cli
69
72
  ```
70
73
 
71
74
  Plain pip (into the active environment):
72
75
 
73
76
  ```bash
74
- pip install git+https://github.com/SimonTarara62/capitalcom-cli.git
77
+ pip install capitalcom-cli
75
78
  ```
76
79
 
80
+ To get the latest unreleased code instead of the last published release, replace
81
+ the package name `capitalcom-cli` with
82
+ `git+https://github.com/SimonTarara62/capitalcom-cli.git` in any command above.
83
+
77
84
  **From a clone (for development):**
78
85
 
79
86
  ```bash
@@ -117,7 +124,7 @@ Credentials are resolved in this order:
117
124
  3. `./.env` in the current directory
118
125
  4. `~/.config/capital-cli/.env`
119
126
 
120
- All settings (one `CAP_*` variable each) and their defaults:
127
+ Main settings and their defaults:
121
128
 
122
129
  | Variable | Default | Purpose |
123
130
  |----------|---------|---------|
@@ -125,6 +132,9 @@ All settings (one `CAP_*` variable each) and their defaults:
125
132
  | `CAP_API_KEY` | — | API key (required) |
126
133
  | `CAP_IDENTIFIER` | — | Login email (required) |
127
134
  | `CAP_API_PASSWORD` | — | API-key custom password (required) |
135
+ | `CAP_API_KEY_CMD` | (none) | Command whose stdout supplies `CAP_API_KEY` (see below) |
136
+ | `CAP_IDENTIFIER_CMD` | (none) | Command whose stdout supplies `CAP_IDENTIFIER` |
137
+ | `CAP_API_PASSWORD_CMD` | (none) | Command whose stdout supplies `CAP_API_PASSWORD` |
128
138
  | `CAP_ALLOW_TRADING` | `false` | Master switch for all trade execution |
129
139
  | `CAP_ALLOWED_EPICS` | (empty) | Comma-separated allowlist, or `ALL` |
130
140
  | `CAP_MAX_POSITION_SIZE` | `1.0` | Per-trade size ceiling |
@@ -137,6 +147,33 @@ All settings (one `CAP_*` variable each) and their defaults:
137
147
  | `CAP_HTTP_TIMEOUT_S` | `15` | HTTP timeout |
138
148
  | `CAP_LOG_LEVEL` | `WARNING` | `DEBUG` … `CRITICAL` |
139
149
  | `CAP_WS_ENABLED` | `false` | Required for `capctl stream …` |
150
+ | `CAP_AUDIT_LOG` | (none) | File path; appends one JSONL line per executed mutation (no secrets) |
151
+
152
+ Advanced/internal settings (rarely changed; safe defaults):
153
+
154
+ | Variable | Default | Purpose |
155
+ |----------|---------|---------|
156
+ | `CAP_PREVIEW_CACHE_TTL_S` | `120` | How long a `preview_id` stays valid before expiry |
157
+ | `CAP_PING_INTERVAL_S` | `480` | Session keep-alive ping interval |
158
+
159
+ ### Credential-exec helpers (`CAP_*_CMD`)
160
+
161
+ To keep secrets out of plaintext files, source each credential from a command at
162
+ runtime — the AWS `credential_process` / git-credential-helper pattern. Set
163
+ `CAP_API_KEY_CMD`, `CAP_IDENTIFIER_CMD`, and/or `CAP_API_PASSWORD_CMD` to a
164
+ command line; its trimmed stdout becomes the corresponding secret.
165
+
166
+ ```bash
167
+ export CAP_API_PASSWORD_CMD="op read op://Private/capital/api-password"
168
+ export CAP_API_KEY_CMD="pass capital/api-key"
169
+ ```
170
+
171
+ Precedence (highest first): an explicit `CAP_<FIELD>` env var, then the
172
+ `CAP_<FIELD>_CMD` output, then the value in your `.env` file. Commands run with
173
+ `shell=False`, a 10-second timeout, and a non-zero exit / timeout / empty output
174
+ raises a clear configuration error (exit 3). The resolved secret is never logged
175
+ and the command's stdout/stderr is never echoed in error messages. This is
176
+ at-rest hygiene; see [SECURITY.md](SECURITY.md) for the threat model.
140
177
 
141
178
  Trade previews and the daily order counter persist between commands in
142
179
  `~/.config/capital-cli/state.json` (override with `CAPCTL_STATE_FILE`).
@@ -324,6 +361,33 @@ capctl stream alerts BTCUSD 75000 --direction ABOVE --duration 3600
324
361
  */15 * * * * capctl --json trade positions >> ~/logs/positions.jsonl 2>&1
325
362
  ```
326
363
 
364
+ ## Use as a library (experimental)
365
+
366
+ Beyond the CLI, the same broker engine — risk policy, two-phase preview→execute,
367
+ rate limiting, WebSocket streaming — is available as an embeddable async SDK.
368
+ **CLI** = terminal, scripts, CI; **SDK** = embed the tested engine in your own
369
+ Python (MCP servers, dashboards, n8n nodes).
370
+
371
+ ```python
372
+ from capital_cli.sdk import CapitalComApp, CapitalComConfig, RiskPolicy
373
+ ```
374
+
375
+ ```python
376
+ import asyncio
377
+ from capital_cli.sdk import CapitalComApp
378
+
379
+ async def main():
380
+ async with CapitalComApp() as app:
381
+ gold = await app.markets.get("GOLD")
382
+ print(gold["snapshot"]["bid"])
383
+
384
+ asyncio.run(main())
385
+ ```
386
+
387
+ The SDK is **experimental** until 1.0: import paths and the pydantic models are
388
+ intended-stable but may shift between 0.x minors. See [docs/sdk.md](docs/sdk.md)
389
+ for read-only, preview→execute, streaming, and risk-policy examples.
390
+
327
391
  ## Exit codes
328
392
 
329
393
  | Code | Meaning |
@@ -372,7 +436,7 @@ The `cli/` layer never talks to the API directly — every command parses argume
372
436
  ```bash
373
437
  pip install -e ".[dev]"
374
438
  pytest -q # full test suite
375
- ruff check . # lint
439
+ ruff check capital_cli tests # lint
376
440
  mypy capital_cli # type-check the whole package (matches CI)
377
441
  ```
378
442
 
@@ -389,6 +453,7 @@ Or use the task runner: `make check` (lint + typecheck + test), `make docs`, `ma
389
453
  ## Documentation
390
454
 
391
455
  - [Full CLI reference](docs/CLI.md) — every command and option (auto-generated)
456
+ - [Using capctl as a Python SDK](docs/sdk.md) — experimental async SDK, import paths, examples, versioning
392
457
  - [Scripting & automation](docs/scripting.md) — CI credentials, exit codes, jq recipes
393
458
  - [Getting started from zero](docs/getting-started.md) — account, API key, install, first trade
394
459
  - [Practical use cases](docs/use-cases.md) — what people actually do with capctl, with copy-pasteable scenarios
@@ -1,3 +1,3 @@
1
1
  """Capital.com command-line client."""
2
2
 
3
- __version__ = "0.4.0"
3
+ __version__ = "0.5.0"
@@ -7,11 +7,7 @@ from typing import Any
7
7
  import typer
8
8
 
9
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.risk import get_risk_engine
14
- from capital_cli.core.session import get_session_manager
10
+ from capital_cli.services.accounts import AccountService
15
11
 
16
12
  app = typer.Typer(no_args_is_help=True, help="Accounts: list, preferences, history.")
17
13
 
@@ -20,14 +16,9 @@ app = typer.Typer(no_args_is_help=True, help="Accounts: list, preferences, histo
20
16
  def list_accounts(ctx: typer.Context) -> None:
21
17
  """List all trading accounts."""
22
18
  out = ctx.obj.out
23
- sm = get_session_manager()
24
- client = get_client()
25
19
 
26
20
  async def _do() -> dict[str, Any]:
27
- await sm.ensure_logged_in()
28
- data = (await client.get("/accounts")).json()
29
- data["active_account_id"] = sm.account_id
30
- return data
21
+ return await AccountService().list()
31
22
 
32
23
  data = run(out, _do, label="account list")
33
24
  if out.json_mode:
@@ -54,12 +45,9 @@ def list_accounts(ctx: typer.Context) -> None:
54
45
  def prefs_get(ctx: typer.Context) -> None:
55
46
  """Get account preferences (hedging, leverage)."""
56
47
  out = ctx.obj.out
57
- sm = get_session_manager()
58
- client = get_client()
59
48
 
60
49
  async def _do() -> dict[str, Any]:
61
- await sm.ensure_logged_in()
62
- return (await client.get("/accounts/preferences")).json()
50
+ return await AccountService().get_preferences()
63
51
 
64
52
  out.record(run(out, _do, label="account prefs-get"), title="Account preferences")
65
53
 
@@ -92,19 +80,10 @@ def prefs_set(
92
80
  if hedging is None and not leverages:
93
81
  raise typer.BadParameter("Provide --hedging/--no-hedging and/or --leverage.")
94
82
 
95
- sm = get_session_manager()
96
- client = get_client()
97
- risk = get_risk_engine()
98
-
99
83
  async def _do() -> dict[str, Any]:
100
- await sm.ensure_logged_in()
101
- risk.validate_mutation_guards(confirm=yes)
102
- body: dict[str, Any] = {}
103
- if hedging is not None:
104
- body["hedgingMode"] = hedging
105
- if leverages:
106
- body["leverages"] = leverages
107
- return (await client.put("/accounts/preferences", json=body)).json()
84
+ return await AccountService().set_preferences(
85
+ hedging=hedging, leverages=leverages, confirm=yes
86
+ )
108
87
 
109
88
  out.record(run(out, _do, label="account prefs-set"), title="Updated preferences")
110
89
 
@@ -120,21 +99,15 @@ def history_activity(
120
99
  ) -> None:
121
100
  """Get account activity history."""
122
101
  out = ctx.obj.out
123
- sm = get_session_manager()
124
- client = get_client()
125
102
 
126
103
  async def _do() -> dict[str, Any]:
127
- await sm.ensure_logged_in()
128
- params: dict[str, Any] = {"lastPeriod": last_period}
129
- if from_date:
130
- params["from"] = from_date
131
- if to_date:
132
- params["to"] = to_date
133
- if detailed:
134
- params["detailed"] = "true"
135
- if deal_id:
136
- params["dealId"] = deal_id
137
- return (await client.get("/history/activity", params=params)).json()
104
+ return await AccountService().history_activity(
105
+ last_period=last_period,
106
+ from_date=from_date,
107
+ to_date=to_date,
108
+ detailed=detailed,
109
+ deal_id=deal_id,
110
+ )
138
111
 
139
112
  out.raw(run(out, _do, label="account history-activity"))
140
113
 
@@ -149,19 +122,11 @@ def history_transactions(
149
122
  ) -> None:
150
123
  """Get transaction history."""
151
124
  out = ctx.obj.out
152
- sm = get_session_manager()
153
- client = get_client()
154
125
 
155
126
  async def _do() -> dict[str, Any]:
156
- await sm.ensure_logged_in()
157
- params: dict[str, Any] = {"lastPeriod": last_period}
158
- if type_:
159
- params["type"] = type_
160
- if from_date:
161
- params["from"] = from_date
162
- if to_date:
163
- params["to"] = to_date
164
- return (await client.get("/history/transactions", params=params)).json()
127
+ return await AccountService().history_transactions(
128
+ last_period=last_period, type_=type_, from_date=from_date, to_date=to_date
129
+ )
165
130
 
166
131
  out.raw(run(out, _do, label="account history-transactions"))
167
132
 
@@ -174,16 +139,8 @@ def topup(
174
139
  ) -> None:
175
140
  """Top up the demo account balance (demo environment only)."""
176
141
  out = ctx.obj.out
177
- sm = get_session_manager()
178
- client = get_client()
179
- config = get_config()
180
142
 
181
143
  async def _do() -> dict[str, Any]:
182
- if config.cap_env.value != "demo":
183
- raise typer.BadParameter("Demo top-up is only available with --demo / CAP_ENV=demo.")
184
- if config.cap_require_explicit_confirm and not yes:
185
- raise ConfirmRequiredError()
186
- await sm.ensure_logged_in()
187
- return (await client.post("/accounts/topUp", json={"amount": amount})).json()
144
+ return await AccountService().demo_topup(amount, confirm=yes)
188
145
 
189
146
  out.record(run(out, _do, label="account topup"), title="Demo top-up")
@@ -0,0 +1,165 @@
1
+ """Root Typer application: global options and sub-command wiring."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json as _json
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ import typer
10
+
11
+ from capital_cli import __version__
12
+ from capital_cli.cli import (
13
+ account_cmds,
14
+ doctor_cmds,
15
+ market_cmds,
16
+ session_cmds,
17
+ stream_cmds,
18
+ trade_cmds,
19
+ watchlist_cmds,
20
+ )
21
+ from capital_cli.cli.context import init_state
22
+
23
+ app = typer.Typer(
24
+ no_args_is_help=True,
25
+ add_completion=True,
26
+ help="capctl — command-line client for the Capital.com Open API.",
27
+ epilog=(
28
+ "Getting started:\n"
29
+ " capctl doctor # check env, credentials, and trading status\n"
30
+ " capctl session login # create a session and store auth tokens"
31
+ ),
32
+ rich_markup_mode="rich",
33
+ # Disable Typer's pretty-exceptions wrapper so Click UsageErrors propagate to
34
+ # run_cli() (which renders them as structured JSON under --json). Otherwise
35
+ # newer Typer intercepts and renders them as a Rich traceback + exit 1.
36
+ pretty_exceptions_enable=False,
37
+ )
38
+
39
+
40
+ def _version_callback(value: bool) -> None:
41
+ if value:
42
+ if "--json" in sys.argv:
43
+ typer.echo(_json.dumps({"name": "capctl", "version": __version__}))
44
+ else:
45
+ typer.echo(f"capctl {__version__}")
46
+ raise typer.Exit()
47
+
48
+
49
+ @app.callback()
50
+ def main(
51
+ ctx: typer.Context,
52
+ json_output: bool = typer.Option(False, "--json", help="Emit raw JSON instead of tables."),
53
+ env_file: Path | None = typer.Option(
54
+ None, "--env-file", help="Path to a .env credentials file."
55
+ ),
56
+ demo: bool = typer.Option(False, "--demo", help="Force the demo environment."),
57
+ live: bool = typer.Option(False, "--live", help="Force the live environment."),
58
+ account: str | None = typer.Option(
59
+ None, "--account", "-a", help="Account ID to use for this invocation."
60
+ ),
61
+ verbose: bool = typer.Option(False, "--verbose", "-v", help="Enable debug logging."),
62
+ no_color: bool = typer.Option(
63
+ False, "--no-color", help="Disable colored output (also honors NO_COLOR)."
64
+ ),
65
+ plain: bool = typer.Option(
66
+ False, "--plain", help="Tab-delimited rows for piping (no boxes/colors)."
67
+ ),
68
+ version: bool | None = typer.Option(
69
+ None,
70
+ "--version",
71
+ callback=_version_callback,
72
+ is_eager=True,
73
+ help="Show version and exit.",
74
+ ),
75
+ ) -> None:
76
+ """Global options applied to every subcommand."""
77
+ if demo and live:
78
+ raise typer.BadParameter("Use only one of --demo / --live.")
79
+ env = "demo" if demo else "live" if live else None
80
+ ctx.obj = init_state(
81
+ json_mode=json_output,
82
+ env_file=env_file,
83
+ env=env,
84
+ account=account,
85
+ verbose=verbose,
86
+ no_color=no_color,
87
+ plain=plain,
88
+ )
89
+
90
+
91
+ app.add_typer(session_cmds.app, name="session")
92
+ app.add_typer(market_cmds.app, name="market")
93
+ app.add_typer(account_cmds.app, name="account")
94
+ app.add_typer(trade_cmds.app, name="trade")
95
+ app.add_typer(watchlist_cmds.app, name="watchlist")
96
+ app.add_typer(stream_cmds.app, name="stream")
97
+ app.command(name="doctor")(doctor_cmds.doctor)
98
+
99
+
100
+ _GLOBAL_FLAGS = {"--json", "--plain", "--no-color"}
101
+
102
+
103
+ def _hoist_global_flags(argv: list[str]) -> list[str]:
104
+ """Move boolean global flags (e.g. trailing --json) ahead of the subcommand
105
+ so `capctl session status --json` works like `capctl --json session status`."""
106
+ if len(argv) < 2:
107
+ return argv
108
+ prog, rest = argv[0], argv[1:]
109
+ hoisted = [a for a in rest if a in _GLOBAL_FLAGS]
110
+ if not hoisted:
111
+ return argv
112
+ remaining = [a for a in rest if a not in _GLOBAL_FLAGS]
113
+ return [prog, *hoisted, *remaining]
114
+
115
+
116
+ def run_cli() -> None:
117
+ """Console-script entry point. Renders Click usage errors as JSON when --json is set.
118
+
119
+ Exceptions are matched by duck typing rather than by ``click.exceptions.*``
120
+ classes: newer Typer (>=0.26) vendors its own copy of click as
121
+ ``typer._click``, so the raised ``UsageError`` is *not* an instance of the
122
+ installed ``click``'s ``UsageError``. All click usage errors expose
123
+ ``format_message()`` and ``exit_code``; ``Abort`` is identified by name.
124
+ """
125
+ sys.argv = _hoist_global_flags(sys.argv)
126
+ json_mode = "--json" in sys.argv
127
+ try:
128
+ result = app(standalone_mode=False)
129
+ except SystemExit:
130
+ raise
131
+ except BaseException as exc: # noqa: BLE001 - top-level CLI guard, re-raises below
132
+ if type(exc).__name__ == "Abort":
133
+ sys.exit(130)
134
+ # click/typer UsageError family: has format_message() (+ exit_code, usually 2)
135
+ if hasattr(exc, "format_message"):
136
+ code = getattr(exc, "exit_code", 2) or 2
137
+ if json_mode:
138
+ sys.stderr.write(
139
+ _json.dumps(
140
+ {
141
+ "ok": False,
142
+ "error": {
143
+ "code": "INVALID_REQUEST",
144
+ "message": exc.format_message(),
145
+ },
146
+ }
147
+ )
148
+ + "\n"
149
+ )
150
+ else:
151
+ show = getattr(exc, "show", None)
152
+ if callable(show):
153
+ show() # default Click rendering to stderr
154
+ else:
155
+ sys.stderr.write(f"Error: {exc.format_message()}\n")
156
+ sys.exit(code)
157
+ # plain Exit (no message): propagate its exit code
158
+ exit_code = getattr(exc, "exit_code", None)
159
+ if exit_code is not None:
160
+ sys.exit(exit_code or 0)
161
+ raise
162
+ # standalone_mode=False makes Typer/Click *return* the command's exit code
163
+ # (from typer.Exit raised inside run()) instead of sys.exit-ing. Propagate it.
164
+ if isinstance(result, int):
165
+ sys.exit(result)
@@ -8,6 +8,11 @@ from pathlib import Path
8
8
 
9
9
  from capital_cli.cli.output import Output
10
10
  from capital_cli.core.config import reset_config
11
+ from capital_cli.core.http_client import reset_client
12
+ from capital_cli.core.rate_limit import reset_rate_limiter
13
+ from capital_cli.core.risk import reset_risk_engine
14
+ from capital_cli.core.session import reset_session_manager
15
+ from capital_cli.core.state import reset_state_store
11
16
 
12
17
 
13
18
  @dataclass
@@ -41,5 +46,12 @@ def init_state(
41
46
  os.environ["CAP_DEFAULT_ACCOUNT_ID"] = account
42
47
  if verbose:
43
48
  os.environ["CAP_LOG_LEVEL"] = "DEBUG"
49
+ # Reset config AND every singleton that captured the old config, so global
50
+ # overrides (e.g. switching --demo -> --live) take effect on the next call.
44
51
  reset_config()
52
+ reset_client()
53
+ reset_session_manager()
54
+ reset_risk_engine()
55
+ reset_rate_limiter()
56
+ reset_state_store()
45
57
  return AppState(out=Output(json_mode=json_mode, no_color=no_color or None, plain=plain))