capitalcom-cli 0.4.0__tar.gz → 0.5.1__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 (86) hide show
  1. {capitalcom_cli-0.4.0/capitalcom_cli.egg-info → capitalcom_cli-0.5.1}/PKG-INFO +86 -14
  2. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/README.md +84 -13
  3. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/capital_cli/__init__.py +1 -1
  4. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/capital_cli/cli/account_cmds.py +17 -60
  5. capitalcom_cli-0.5.1/capital_cli/cli/app.py +165 -0
  6. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/capital_cli/cli/context.py +12 -0
  7. capitalcom_cli-0.5.1/capital_cli/cli/doctor_cmds.py +88 -0
  8. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/capital_cli/cli/market_cmds.py +13 -44
  9. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/capital_cli/cli/output.py +16 -2
  10. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/capital_cli/cli/session_cmds.py +14 -10
  11. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/capital_cli/cli/stream_cmds.py +80 -84
  12. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/capital_cli/cli/trade_cmds.py +104 -172
  13. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/capital_cli/cli/watchlist_cmds.py +7 -39
  14. capitalcom_cli-0.5.1/capital_cli/core/audit.py +74 -0
  15. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/capital_cli/core/config.py +106 -2
  16. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/capital_cli/core/errors.py +41 -53
  17. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/capital_cli/core/http_client.py +3 -7
  18. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/capital_cli/core/models.py +16 -48
  19. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/capital_cli/core/rate_limit.py +2 -35
  20. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/capital_cli/core/risk.py +93 -29
  21. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/capital_cli/core/session.py +56 -8
  22. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/capital_cli/core/state.py +24 -0
  23. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/capital_cli/core/utils.py +15 -5
  24. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/capital_cli/core/websocket_client.py +16 -17
  25. capitalcom_cli-0.5.1/capital_cli/sdk/__init__.py +10 -0
  26. capitalcom_cli-0.5.1/capital_cli/sdk/app.py +68 -0
  27. capitalcom_cli-0.5.1/capital_cli/sdk/config.py +18 -0
  28. capitalcom_cli-0.5.1/capital_cli/sdk/risk_policy.py +32 -0
  29. capitalcom_cli-0.5.1/capital_cli/services/__init__.py +20 -0
  30. capitalcom_cli-0.5.1/capital_cli/services/accounts.py +114 -0
  31. capitalcom_cli-0.5.1/capital_cli/services/confirmations.py +95 -0
  32. capitalcom_cli-0.5.1/capital_cli/services/markets.py +82 -0
  33. capitalcom_cli-0.5.1/capital_cli/services/streaming.py +105 -0
  34. capitalcom_cli-0.5.1/capital_cli/services/trading.py +284 -0
  35. capitalcom_cli-0.5.1/capital_cli/services/watchlists.py +73 -0
  36. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1/capitalcom_cli.egg-info}/PKG-INFO +86 -14
  37. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/capitalcom_cli.egg-info/SOURCES.txt +27 -0
  38. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/capitalcom_cli.egg-info/requires.txt +1 -0
  39. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/pyproject.toml +9 -1
  40. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/tests/test_account_cmds.py +22 -5
  41. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/tests/test_app.py +12 -0
  42. capitalcom_cli-0.5.1/tests/test_audit.py +66 -0
  43. capitalcom_cli-0.5.1/tests/test_build_broker_request.py +29 -0
  44. capitalcom_cli-0.5.1/tests/test_cli_usage_errors.py +24 -0
  45. capitalcom_cli-0.5.1/tests/test_config_errors.py +34 -0
  46. capitalcom_cli-0.5.1/tests/test_coverage_doc_in_sync.py +35 -0
  47. capitalcom_cli-0.5.1/tests/test_credential_cmd.py +176 -0
  48. capitalcom_cli-0.5.1/tests/test_doctor.py +114 -0
  49. capitalcom_cli-0.5.1/tests/test_global_flag_hoist.py +27 -0
  50. capitalcom_cli-0.5.1/tests/test_init_state_singletons.py +41 -0
  51. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/tests/test_market_cmds.py +5 -3
  52. capitalcom_cli-0.5.1/tests/test_redaction.py +35 -0
  53. capitalcom_cli-0.5.1/tests/test_risk.py +282 -0
  54. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/tests/test_runner.py +1 -3
  55. capitalcom_cli-0.5.1/tests/test_session_persistence.py +142 -0
  56. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/tests/test_state.py +2 -2
  57. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/tests/test_stream_cmds.py +56 -11
  58. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/tests/test_trade_cmds.py +109 -9
  59. capitalcom_cli-0.5.1/tests/test_trade_limit.py +18 -0
  60. capitalcom_cli-0.5.1/tests/test_tz_datetimes.py +64 -0
  61. capitalcom_cli-0.5.1/tests/test_utils.py +51 -0
  62. capitalcom_cli-0.5.1/tests/test_version.py +21 -0
  63. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/tests/test_watchlist_cmds.py +2 -2
  64. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/tests/test_websocket_parsing.py +1 -0
  65. capitalcom_cli-0.4.0/capital_cli/cli/app.py +0 -88
  66. capitalcom_cli-0.4.0/tests/test_risk.py +0 -81
  67. capitalcom_cli-0.4.0/tests/test_version.py +0 -9
  68. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/LICENSE +0 -0
  69. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/NOTICE +0 -0
  70. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/capital_cli/__main__.py +0 -0
  71. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/capital_cli/cli/__init__.py +0 -0
  72. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/capital_cli/cli/live_guard.py +0 -0
  73. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/capital_cli/cli/runner.py +0 -0
  74. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/capital_cli/core/__init__.py +0 -0
  75. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/capitalcom_cli.egg-info/dependency_links.txt +0 -0
  76. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/capitalcom_cli.egg-info/entry_points.txt +0 -0
  77. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/capitalcom_cli.egg-info/top_level.txt +0 -0
  78. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/setup.cfg +0 -0
  79. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/tests/test_core_port.py +0 -0
  80. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/tests/test_errors.py +0 -0
  81. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/tests/test_http_client.py +0 -0
  82. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/tests/test_live_guard.py +0 -0
  83. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/tests/test_output.py +0 -0
  84. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/tests/test_output_color.py +0 -0
  85. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/tests/test_output_plain.py +0 -0
  86. {capitalcom_cli-0.4.0 → capitalcom_cli-0.5.1}/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.1
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,9 +34,11 @@ 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)
41
+ [![API coverage](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/SimonTarara62/capitalcom-cli/main/docs/coverage-badge.json)](docs/api-coverage.md)
39
42
 
40
43
  ```text
41
44
  $ capctl market search "gold"
@@ -64,11 +67,15 @@ The Capital.com web platform is built for clicking; `capctl` is built for **repe
64
67
 
65
68
  See [practical use cases](docs/use-cases.md) for worked, copy-pasteable scenarios.
66
69
 
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.
70
+ **Scope:** `capctl` is first and foremost a command-line application, but the same
71
+ tested broker engine is also embeddable as an **experimental** Python SDK — see
72
+ [Use as a library](#use-as-a-library-experimental) and [docs/sdk.md](docs/sdk.md).
73
+ The `capital_cli.core.*` internals remain private and may change between releases.
74
+ The CLI itself is short-lived: each command runs as its own process. By default
75
+ (`CAP_PERSIST_SESSION=true`) the short-lived session tokens are cached so
76
+ back-to-back commands reuse one login instead of re-authenticating each time
77
+ (which can trip Capital.com's login-rate limit and return HTTP 429); `capctl
78
+ session login` is mainly a connectivity/account check.
72
79
 
73
80
  ## Features
74
81
 
@@ -79,29 +86,35 @@ tokens are not persisted between separate invocations.
79
86
  - **Real-time streaming** — live price tables, price-level alerts, and portfolio snapshots over WebSocket
80
87
  - **Demo and live environments** — defaults to demo; live requires explicit opt-in
81
88
  - **Built-in rate limiting** — client-side token buckets respect Capital.com's 10 req/s global, 1 req/s session, and trading-burst limits
89
+ - **Session-token caching** — back-to-back commands reuse one login instead of re-authenticating (avoids HTTP 429); on by default, opt out with `CAP_PERSIST_SESSION=false`
90
+ - **Embeddable SDK (experimental)** — the same broker engine ships as an async Python library; see [Use as a library](#use-as-a-library-experimental)
82
91
 
83
92
  ## Installation
84
93
 
85
94
  Requires Python 3.10+.
86
95
 
87
- **One-line install (recommended)** — isolated, global `capctl` command, no clone:
96
+ **One-line install (recommended)** — isolated, global `capctl` command:
88
97
 
89
98
  ```bash
90
- pipx install git+https://github.com/SimonTarara62/capitalcom-cli.git
99
+ pipx install capitalcom-cli
91
100
  ```
92
101
 
93
102
  Using [uv](https://docs.astral.sh/uv/) instead of pipx:
94
103
 
95
104
  ```bash
96
- uv tool install git+https://github.com/SimonTarara62/capitalcom-cli.git
105
+ uv tool install capitalcom-cli
97
106
  ```
98
107
 
99
108
  Plain pip (into the active environment):
100
109
 
101
110
  ```bash
102
- pip install git+https://github.com/SimonTarara62/capitalcom-cli.git
111
+ pip install capitalcom-cli
103
112
  ```
104
113
 
114
+ To get the latest unreleased code instead of the last published release, replace
115
+ the package name `capitalcom-cli` with
116
+ `git+https://github.com/SimonTarara62/capitalcom-cli.git` in any command above.
117
+
105
118
  **From a clone (for development):**
106
119
 
107
120
  ```bash
@@ -145,7 +158,7 @@ Credentials are resolved in this order:
145
158
  3. `./.env` in the current directory
146
159
  4. `~/.config/capital-cli/.env`
147
160
 
148
- All settings (one `CAP_*` variable each) and their defaults:
161
+ Main settings and their defaults:
149
162
 
150
163
  | Variable | Default | Purpose |
151
164
  |----------|---------|---------|
@@ -153,6 +166,9 @@ All settings (one `CAP_*` variable each) and their defaults:
153
166
  | `CAP_API_KEY` | — | API key (required) |
154
167
  | `CAP_IDENTIFIER` | — | Login email (required) |
155
168
  | `CAP_API_PASSWORD` | — | API-key custom password (required) |
169
+ | `CAP_API_KEY_CMD` | (none) | Command whose stdout supplies `CAP_API_KEY` (see below) |
170
+ | `CAP_IDENTIFIER_CMD` | (none) | Command whose stdout supplies `CAP_IDENTIFIER` |
171
+ | `CAP_API_PASSWORD_CMD` | (none) | Command whose stdout supplies `CAP_API_PASSWORD` |
156
172
  | `CAP_ALLOW_TRADING` | `false` | Master switch for all trade execution |
157
173
  | `CAP_ALLOWED_EPICS` | (empty) | Comma-separated allowlist, or `ALL` |
158
174
  | `CAP_MAX_POSITION_SIZE` | `1.0` | Per-trade size ceiling |
@@ -162,9 +178,37 @@ All settings (one `CAP_*` variable each) and their defaults:
162
178
  | `CAP_REQUIRE_EXPLICIT_CONFIRM` | `true` | Mutations need `--yes` |
163
179
  | `CAP_DRY_RUN` | `false` | Block all executions regardless of other flags |
164
180
  | `CAP_DEFAULT_ACCOUNT_ID` | (none) | Account selected after login |
181
+ | `CAP_PERSIST_SESSION` | `true` | Cache short-lived session tokens in the state file so back-to-back commands reuse one login (avoids HTTP 429); set `false` to keep tokens in-process only |
165
182
  | `CAP_HTTP_TIMEOUT_S` | `15` | HTTP timeout |
166
183
  | `CAP_LOG_LEVEL` | `WARNING` | `DEBUG` … `CRITICAL` |
167
184
  | `CAP_WS_ENABLED` | `false` | Required for `capctl stream …` |
185
+ | `CAP_AUDIT_LOG` | (none) | File path; appends one JSONL line per executed mutation (no secrets) |
186
+
187
+ Advanced/internal settings (rarely changed; safe defaults):
188
+
189
+ | Variable | Default | Purpose |
190
+ |----------|---------|---------|
191
+ | `CAP_PREVIEW_CACHE_TTL_S` | `120` | How long a `preview_id` stays valid before expiry |
192
+ | `CAP_PING_INTERVAL_S` | `480` | Session keep-alive ping interval |
193
+
194
+ ### Credential-exec helpers (`CAP_*_CMD`)
195
+
196
+ To keep secrets out of plaintext files, source each credential from a command at
197
+ runtime — the AWS `credential_process` / git-credential-helper pattern. Set
198
+ `CAP_API_KEY_CMD`, `CAP_IDENTIFIER_CMD`, and/or `CAP_API_PASSWORD_CMD` to a
199
+ command line; its trimmed stdout becomes the corresponding secret.
200
+
201
+ ```bash
202
+ export CAP_API_PASSWORD_CMD="op read op://Private/capital/api-password"
203
+ export CAP_API_KEY_CMD="pass capital/api-key"
204
+ ```
205
+
206
+ Precedence (highest first): an explicit `CAP_<FIELD>` env var, then the
207
+ `CAP_<FIELD>_CMD` output, then the value in your `.env` file. Commands run with
208
+ `shell=False`, a 10-second timeout, and a non-zero exit / timeout / empty output
209
+ raises a clear configuration error (exit 3). The resolved secret is never logged
210
+ and the command's stdout/stderr is never echoed in error messages. This is
211
+ at-rest hygiene; see [SECURITY.md](SECURITY.md) for the threat model.
168
212
 
169
213
  Trade previews and the daily order counter persist between commands in
170
214
  `~/.config/capital-cli/state.json` (override with `CAPCTL_STATE_FILE`).
@@ -234,9 +278,9 @@ capctl account topup 1000 --yes # demo environment only
234
278
  Read-only:
235
279
 
236
280
  ```bash
237
- capctl trade positions
281
+ capctl trade positions [--limit 10] # -n/--limit caps rows shown
238
282
  capctl trade position DEAL_ID
239
- capctl trade orders
283
+ capctl trade orders [--limit 10] # -n/--limit caps rows shown
240
284
  capctl trade confirm DEAL_REFERENCE [--wait --timeout 30]
241
285
  ```
242
286
 
@@ -352,6 +396,33 @@ capctl stream alerts BTCUSD 75000 --direction ABOVE --duration 3600
352
396
  */15 * * * * capctl --json trade positions >> ~/logs/positions.jsonl 2>&1
353
397
  ```
354
398
 
399
+ ## Use as a library (experimental)
400
+
401
+ Beyond the CLI, the same broker engine — risk policy, two-phase preview→execute,
402
+ rate limiting, WebSocket streaming — is available as an embeddable async SDK.
403
+ **CLI** = terminal, scripts, CI; **SDK** = embed the tested engine in your own
404
+ Python (MCP servers, dashboards, n8n nodes).
405
+
406
+ ```python
407
+ from capital_cli.sdk import CapitalComApp, CapitalComConfig, RiskPolicy
408
+ ```
409
+
410
+ ```python
411
+ import asyncio
412
+ from capital_cli.sdk import CapitalComApp
413
+
414
+ async def main():
415
+ async with CapitalComApp() as app:
416
+ gold = await app.markets.get("GOLD")
417
+ print(gold["snapshot"]["bid"])
418
+
419
+ asyncio.run(main())
420
+ ```
421
+
422
+ The SDK is **experimental** until 1.0: import paths and the pydantic models are
423
+ intended-stable but may shift between 0.x minors. See [docs/sdk.md](docs/sdk.md)
424
+ for read-only, preview→execute, streaming, and risk-policy examples.
425
+
355
426
  ## Exit codes
356
427
 
357
428
  | Code | Meaning |
@@ -400,7 +471,7 @@ The `cli/` layer never talks to the API directly — every command parses argume
400
471
  ```bash
401
472
  pip install -e ".[dev]"
402
473
  pytest -q # full test suite
403
- ruff check . # lint
474
+ ruff check capital_cli tests # lint
404
475
  mypy capital_cli # type-check the whole package (matches CI)
405
476
  ```
406
477
 
@@ -417,6 +488,7 @@ Or use the task runner: `make check` (lint + typecheck + test), `make docs`, `ma
417
488
  ## Documentation
418
489
 
419
490
  - [Full CLI reference](docs/CLI.md) — every command and option (auto-generated)
491
+ - [Using capctl as a Python SDK](docs/sdk.md) — experimental async SDK, import paths, examples, versioning
420
492
  - [Scripting & automation](docs/scripting.md) — CI credentials, exit codes, jq recipes
421
493
  - [Getting started from zero](docs/getting-started.md) — account, API key, install, first trade
422
494
  - [Practical use cases](docs/use-cases.md) — what people actually do with capctl, with copy-pasteable scenarios
@@ -5,9 +5,11 @@ 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)
12
+ [![API coverage](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/SimonTarara62/capitalcom-cli/main/docs/coverage-badge.json)](docs/api-coverage.md)
11
13
 
12
14
  ```text
13
15
  $ capctl market search "gold"
@@ -36,11 +38,15 @@ The Capital.com web platform is built for clicking; `capctl` is built for **repe
36
38
 
37
39
  See [practical use cases](docs/use-cases.md) for worked, copy-pasteable scenarios.
38
40
 
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.
41
+ **Scope:** `capctl` is first and foremost a command-line application, but the same
42
+ tested broker engine is also embeddable as an **experimental** Python SDK — see
43
+ [Use as a library](#use-as-a-library-experimental) and [docs/sdk.md](docs/sdk.md).
44
+ The `capital_cli.core.*` internals remain private and may change between releases.
45
+ The CLI itself is short-lived: each command runs as its own process. By default
46
+ (`CAP_PERSIST_SESSION=true`) the short-lived session tokens are cached so
47
+ back-to-back commands reuse one login instead of re-authenticating each time
48
+ (which can trip Capital.com's login-rate limit and return HTTP 429); `capctl
49
+ session login` is mainly a connectivity/account check.
44
50
 
45
51
  ## Features
46
52
 
@@ -51,29 +57,35 @@ tokens are not persisted between separate invocations.
51
57
  - **Real-time streaming** — live price tables, price-level alerts, and portfolio snapshots over WebSocket
52
58
  - **Demo and live environments** — defaults to demo; live requires explicit opt-in
53
59
  - **Built-in rate limiting** — client-side token buckets respect Capital.com's 10 req/s global, 1 req/s session, and trading-burst limits
60
+ - **Session-token caching** — back-to-back commands reuse one login instead of re-authenticating (avoids HTTP 429); on by default, opt out with `CAP_PERSIST_SESSION=false`
61
+ - **Embeddable SDK (experimental)** — the same broker engine ships as an async Python library; see [Use as a library](#use-as-a-library-experimental)
54
62
 
55
63
  ## Installation
56
64
 
57
65
  Requires Python 3.10+.
58
66
 
59
- **One-line install (recommended)** — isolated, global `capctl` command, no clone:
67
+ **One-line install (recommended)** — isolated, global `capctl` command:
60
68
 
61
69
  ```bash
62
- pipx install git+https://github.com/SimonTarara62/capitalcom-cli.git
70
+ pipx install capitalcom-cli
63
71
  ```
64
72
 
65
73
  Using [uv](https://docs.astral.sh/uv/) instead of pipx:
66
74
 
67
75
  ```bash
68
- uv tool install git+https://github.com/SimonTarara62/capitalcom-cli.git
76
+ uv tool install capitalcom-cli
69
77
  ```
70
78
 
71
79
  Plain pip (into the active environment):
72
80
 
73
81
  ```bash
74
- pip install git+https://github.com/SimonTarara62/capitalcom-cli.git
82
+ pip install capitalcom-cli
75
83
  ```
76
84
 
85
+ To get the latest unreleased code instead of the last published release, replace
86
+ the package name `capitalcom-cli` with
87
+ `git+https://github.com/SimonTarara62/capitalcom-cli.git` in any command above.
88
+
77
89
  **From a clone (for development):**
78
90
 
79
91
  ```bash
@@ -117,7 +129,7 @@ Credentials are resolved in this order:
117
129
  3. `./.env` in the current directory
118
130
  4. `~/.config/capital-cli/.env`
119
131
 
120
- All settings (one `CAP_*` variable each) and their defaults:
132
+ Main settings and their defaults:
121
133
 
122
134
  | Variable | Default | Purpose |
123
135
  |----------|---------|---------|
@@ -125,6 +137,9 @@ All settings (one `CAP_*` variable each) and their defaults:
125
137
  | `CAP_API_KEY` | — | API key (required) |
126
138
  | `CAP_IDENTIFIER` | — | Login email (required) |
127
139
  | `CAP_API_PASSWORD` | — | API-key custom password (required) |
140
+ | `CAP_API_KEY_CMD` | (none) | Command whose stdout supplies `CAP_API_KEY` (see below) |
141
+ | `CAP_IDENTIFIER_CMD` | (none) | Command whose stdout supplies `CAP_IDENTIFIER` |
142
+ | `CAP_API_PASSWORD_CMD` | (none) | Command whose stdout supplies `CAP_API_PASSWORD` |
128
143
  | `CAP_ALLOW_TRADING` | `false` | Master switch for all trade execution |
129
144
  | `CAP_ALLOWED_EPICS` | (empty) | Comma-separated allowlist, or `ALL` |
130
145
  | `CAP_MAX_POSITION_SIZE` | `1.0` | Per-trade size ceiling |
@@ -134,9 +149,37 @@ All settings (one `CAP_*` variable each) and their defaults:
134
149
  | `CAP_REQUIRE_EXPLICIT_CONFIRM` | `true` | Mutations need `--yes` |
135
150
  | `CAP_DRY_RUN` | `false` | Block all executions regardless of other flags |
136
151
  | `CAP_DEFAULT_ACCOUNT_ID` | (none) | Account selected after login |
152
+ | `CAP_PERSIST_SESSION` | `true` | Cache short-lived session tokens in the state file so back-to-back commands reuse one login (avoids HTTP 429); set `false` to keep tokens in-process only |
137
153
  | `CAP_HTTP_TIMEOUT_S` | `15` | HTTP timeout |
138
154
  | `CAP_LOG_LEVEL` | `WARNING` | `DEBUG` … `CRITICAL` |
139
155
  | `CAP_WS_ENABLED` | `false` | Required for `capctl stream …` |
156
+ | `CAP_AUDIT_LOG` | (none) | File path; appends one JSONL line per executed mutation (no secrets) |
157
+
158
+ Advanced/internal settings (rarely changed; safe defaults):
159
+
160
+ | Variable | Default | Purpose |
161
+ |----------|---------|---------|
162
+ | `CAP_PREVIEW_CACHE_TTL_S` | `120` | How long a `preview_id` stays valid before expiry |
163
+ | `CAP_PING_INTERVAL_S` | `480` | Session keep-alive ping interval |
164
+
165
+ ### Credential-exec helpers (`CAP_*_CMD`)
166
+
167
+ To keep secrets out of plaintext files, source each credential from a command at
168
+ runtime — the AWS `credential_process` / git-credential-helper pattern. Set
169
+ `CAP_API_KEY_CMD`, `CAP_IDENTIFIER_CMD`, and/or `CAP_API_PASSWORD_CMD` to a
170
+ command line; its trimmed stdout becomes the corresponding secret.
171
+
172
+ ```bash
173
+ export CAP_API_PASSWORD_CMD="op read op://Private/capital/api-password"
174
+ export CAP_API_KEY_CMD="pass capital/api-key"
175
+ ```
176
+
177
+ Precedence (highest first): an explicit `CAP_<FIELD>` env var, then the
178
+ `CAP_<FIELD>_CMD` output, then the value in your `.env` file. Commands run with
179
+ `shell=False`, a 10-second timeout, and a non-zero exit / timeout / empty output
180
+ raises a clear configuration error (exit 3). The resolved secret is never logged
181
+ and the command's stdout/stderr is never echoed in error messages. This is
182
+ at-rest hygiene; see [SECURITY.md](SECURITY.md) for the threat model.
140
183
 
141
184
  Trade previews and the daily order counter persist between commands in
142
185
  `~/.config/capital-cli/state.json` (override with `CAPCTL_STATE_FILE`).
@@ -206,9 +249,9 @@ capctl account topup 1000 --yes # demo environment only
206
249
  Read-only:
207
250
 
208
251
  ```bash
209
- capctl trade positions
252
+ capctl trade positions [--limit 10] # -n/--limit caps rows shown
210
253
  capctl trade position DEAL_ID
211
- capctl trade orders
254
+ capctl trade orders [--limit 10] # -n/--limit caps rows shown
212
255
  capctl trade confirm DEAL_REFERENCE [--wait --timeout 30]
213
256
  ```
214
257
 
@@ -324,6 +367,33 @@ capctl stream alerts BTCUSD 75000 --direction ABOVE --duration 3600
324
367
  */15 * * * * capctl --json trade positions >> ~/logs/positions.jsonl 2>&1
325
368
  ```
326
369
 
370
+ ## Use as a library (experimental)
371
+
372
+ Beyond the CLI, the same broker engine — risk policy, two-phase preview→execute,
373
+ rate limiting, WebSocket streaming — is available as an embeddable async SDK.
374
+ **CLI** = terminal, scripts, CI; **SDK** = embed the tested engine in your own
375
+ Python (MCP servers, dashboards, n8n nodes).
376
+
377
+ ```python
378
+ from capital_cli.sdk import CapitalComApp, CapitalComConfig, RiskPolicy
379
+ ```
380
+
381
+ ```python
382
+ import asyncio
383
+ from capital_cli.sdk import CapitalComApp
384
+
385
+ async def main():
386
+ async with CapitalComApp() as app:
387
+ gold = await app.markets.get("GOLD")
388
+ print(gold["snapshot"]["bid"])
389
+
390
+ asyncio.run(main())
391
+ ```
392
+
393
+ The SDK is **experimental** until 1.0: import paths and the pydantic models are
394
+ intended-stable but may shift between 0.x minors. See [docs/sdk.md](docs/sdk.md)
395
+ for read-only, preview→execute, streaming, and risk-policy examples.
396
+
327
397
  ## Exit codes
328
398
 
329
399
  | Code | Meaning |
@@ -372,7 +442,7 @@ The `cli/` layer never talks to the API directly — every command parses argume
372
442
  ```bash
373
443
  pip install -e ".[dev]"
374
444
  pytest -q # full test suite
375
- ruff check . # lint
445
+ ruff check capital_cli tests # lint
376
446
  mypy capital_cli # type-check the whole package (matches CI)
377
447
  ```
378
448
 
@@ -389,6 +459,7 @@ Or use the task runner: `make check` (lint + typecheck + test), `make docs`, `ma
389
459
  ## Documentation
390
460
 
391
461
  - [Full CLI reference](docs/CLI.md) — every command and option (auto-generated)
462
+ - [Using capctl as a Python SDK](docs/sdk.md) — experimental async SDK, import paths, examples, versioning
392
463
  - [Scripting & automation](docs/scripting.md) — CI credentials, exit codes, jq recipes
393
464
  - [Getting started from zero](docs/getting-started.md) — account, API key, install, first trade
394
465
  - [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.1"
@@ -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")