capitalcom-cli 0.4.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 (56) hide show
  1. capitalcom_cli-0.4.0/LICENSE +202 -0
  2. capitalcom_cli-0.4.0/NOTICE +18 -0
  3. capitalcom_cli-0.4.0/PKG-INFO +433 -0
  4. capitalcom_cli-0.4.0/README.md +405 -0
  5. capitalcom_cli-0.4.0/capital_cli/__init__.py +3 -0
  6. capitalcom_cli-0.4.0/capital_cli/__main__.py +6 -0
  7. capitalcom_cli-0.4.0/capital_cli/cli/__init__.py +1 -0
  8. capitalcom_cli-0.4.0/capital_cli/cli/account_cmds.py +189 -0
  9. capitalcom_cli-0.4.0/capital_cli/cli/app.py +88 -0
  10. capitalcom_cli-0.4.0/capital_cli/cli/context.py +45 -0
  11. capitalcom_cli-0.4.0/capital_cli/cli/live_guard.py +12 -0
  12. capitalcom_cli-0.4.0/capital_cli/cli/market_cmds.py +165 -0
  13. capitalcom_cli-0.4.0/capital_cli/cli/output.py +125 -0
  14. capitalcom_cli-0.4.0/capital_cli/cli/runner.py +96 -0
  15. capitalcom_cli-0.4.0/capital_cli/cli/session_cmds.py +127 -0
  16. capitalcom_cli-0.4.0/capital_cli/cli/stream_cmds.py +263 -0
  17. capitalcom_cli-0.4.0/capital_cli/cli/trade_cmds.py +549 -0
  18. capitalcom_cli-0.4.0/capital_cli/cli/watchlist_cmds.py +132 -0
  19. capitalcom_cli-0.4.0/capital_cli/core/__init__.py +1 -0
  20. capitalcom_cli-0.4.0/capital_cli/core/config.py +152 -0
  21. capitalcom_cli-0.4.0/capital_cli/core/errors.py +233 -0
  22. capitalcom_cli-0.4.0/capital_cli/core/http_client.py +297 -0
  23. capitalcom_cli-0.4.0/capital_cli/core/models.py +328 -0
  24. capitalcom_cli-0.4.0/capital_cli/core/rate_limit.py +173 -0
  25. capitalcom_cli-0.4.0/capital_cli/core/risk.py +417 -0
  26. capitalcom_cli-0.4.0/capital_cli/core/session.py +219 -0
  27. capitalcom_cli-0.4.0/capital_cli/core/state.py +97 -0
  28. capitalcom_cli-0.4.0/capital_cli/core/utils.py +87 -0
  29. capitalcom_cli-0.4.0/capital_cli/core/websocket_client.py +480 -0
  30. capitalcom_cli-0.4.0/capitalcom_cli.egg-info/PKG-INFO +433 -0
  31. capitalcom_cli-0.4.0/capitalcom_cli.egg-info/SOURCES.txt +54 -0
  32. capitalcom_cli-0.4.0/capitalcom_cli.egg-info/dependency_links.txt +1 -0
  33. capitalcom_cli-0.4.0/capitalcom_cli.egg-info/entry_points.txt +2 -0
  34. capitalcom_cli-0.4.0/capitalcom_cli.egg-info/requires.txt +15 -0
  35. capitalcom_cli-0.4.0/capitalcom_cli.egg-info/top_level.txt +1 -0
  36. capitalcom_cli-0.4.0/pyproject.toml +66 -0
  37. capitalcom_cli-0.4.0/setup.cfg +4 -0
  38. capitalcom_cli-0.4.0/tests/test_account_cmds.py +139 -0
  39. capitalcom_cli-0.4.0/tests/test_app.py +36 -0
  40. capitalcom_cli-0.4.0/tests/test_core_port.py +61 -0
  41. capitalcom_cli-0.4.0/tests/test_errors.py +21 -0
  42. capitalcom_cli-0.4.0/tests/test_http_client.py +79 -0
  43. capitalcom_cli-0.4.0/tests/test_live_guard.py +33 -0
  44. capitalcom_cli-0.4.0/tests/test_market_cmds.py +88 -0
  45. capitalcom_cli-0.4.0/tests/test_output.py +50 -0
  46. capitalcom_cli-0.4.0/tests/test_output_color.py +64 -0
  47. capitalcom_cli-0.4.0/tests/test_output_plain.py +25 -0
  48. capitalcom_cli-0.4.0/tests/test_risk.py +81 -0
  49. capitalcom_cli-0.4.0/tests/test_runner.py +83 -0
  50. capitalcom_cli-0.4.0/tests/test_session_cmds.py +88 -0
  51. capitalcom_cli-0.4.0/tests/test_state.py +103 -0
  52. capitalcom_cli-0.4.0/tests/test_stream_cmds.py +124 -0
  53. capitalcom_cli-0.4.0/tests/test_trade_cmds.py +276 -0
  54. capitalcom_cli-0.4.0/tests/test_version.py +9 -0
  55. capitalcom_cli-0.4.0/tests/test_watchlist_cmds.py +48 -0
  56. capitalcom_cli-0.4.0/tests/test_websocket_parsing.py +155 -0
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Simon Tarara
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,18 @@
1
+ capitalcom-cli
2
+ Copyright 2026 Simon Tarara
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this software except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+
16
+ This tool is an independent, unofficial client. It is not affiliated with,
17
+ authorized, maintained, sponsored, or endorsed by Capital.com or any of its
18
+ affiliates.
@@ -0,0 +1,433 @@
1
+ Metadata-Version: 2.4
2
+ Name: capitalcom-cli
3
+ Version: 0.4.0
4
+ Summary: Command-line client for the Capital.com Open API
5
+ Author: Simon Tarara
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/SimonTarara62/capitalcom-cli
8
+ Project-URL: Issues, https://github.com/SimonTarara62/capitalcom-cli/issues
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ License-File: NOTICE
13
+ Requires-Dist: typer>=0.12.0
14
+ Requires-Dist: rich>=13.7.0
15
+ Requires-Dist: httpx>=0.27.0
16
+ Requires-Dist: pydantic>=2.0.0
17
+ Requires-Dist: pydantic-settings>=2.0.0
18
+ Requires-Dist: python-dotenv>=1.0.0
19
+ Requires-Dist: websockets>=12.0
20
+ Provides-Extra: dev
21
+ Requires-Dist: pytest>=8.0.0; extra == "dev"
22
+ Requires-Dist: pytest-asyncio>=0.23.0; extra == "dev"
23
+ Requires-Dist: pytest-cov>=4.1.0; extra == "dev"
24
+ Requires-Dist: ruff>=0.3.0; extra == "dev"
25
+ Requires-Dist: mypy>=1.9.0; extra == "dev"
26
+ Requires-Dist: build>=1.2.0; extra == "dev"
27
+ Dynamic: license-file
28
+
29
+ # capctl — Capital.com CLI
30
+
31
+ A fast, scriptable command-line client for the [Capital.com](https://capital.com) Open API, built with Typer and Rich.
32
+
33
+ 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
+ [![CI](https://github.com/SimonTarara62/capitalcom-cli/actions/workflows/ci.yml/badge.svg)](https://github.com/SimonTarara62/capitalcom-cli/actions/workflows/ci.yml)
36
+ [![License: Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE)
37
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/downloads/)
38
+ [![Release](https://img.shields.io/github/v/release/SimonTarara62/capitalcom-cli?sort=semver)](https://github.com/SimonTarara62/capitalcom-cli/releases)
39
+
40
+ ```text
41
+ $ capctl market search "gold"
42
+ Markets
43
+ ┏━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━━━━┓
44
+ ┃ epic ┃ instrumentName ┃ bid ┃ offer ┃ marketStatus ┃
45
+ ┡━━━━━━━━╇━━━━━━━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━━━━┩
46
+ │ GOLD │ Gold │ 2331.05 │ 2331.35 │ TRADEABLE │
47
+ └────────┴────────────────┴─────────┴─────────┴──────────────┘
48
+ ```
49
+
50
+ > **New to this?** The [getting-started guide](docs/getting-started.md) walks you from zero (no account, no API key) to your first practice trade on a demo account. Hit a problem? See [troubleshooting](docs/troubleshooting.md).
51
+
52
+ > **Risk disclaimer:** This is an unofficial tool, not affiliated with or endorsed by Capital.com, and nothing here is financial advice. CFD trading carries a high risk of losing money. The CLI defaults to the **demo** environment and disables trading until you explicitly opt in — keep it that way until you know exactly what you're doing. Use at your own risk.
53
+
54
+ ## Why capctl?
55
+
56
+ The Capital.com web platform is built for clicking; `capctl` is built for **repeating, scripting, and automating**. Anything you do through it can be put in a shell script, a cron job, or a pipeline — with machine-readable JSON output and exit codes you can branch on. And unlike ad-hoc API scripts, every action goes through the same safety layer: demo by default, trading off by default, an explicit market allowlist, size and daily-order limits, and a two-phase preview→execute flow that makes "oops, wrong size" structurally hard.
57
+
58
+ **Who gets value from it:**
59
+
60
+ - **Traders who live in the terminal** — check positions, P&L, and orders in seconds without opening a browser; set a price alert and keep working.
61
+ - **People learning to trade** — practice the full lifecycle (research → preview → execute → manage → close) on a demo account with virtual money, with guardrails on from the start. The [getting-started guide](docs/getting-started.md) assumes zero experience.
62
+ - **Developers building on the Capital.com API** — `--json` output mirrors the real API responses, so `capctl` doubles as an interactive API explorer while you build your own integration; the risk-engine pattern (allowlist, limits, preview/confirm) is reusable as a reference.
63
+ - **Data and automation folks** — pull historical OHLC candles into CSV/pandas, log portfolio snapshots from cron, monitor markets from scripts, wire alerts into anything that can run a shell command.
64
+
65
+ See [practical use cases](docs/use-cases.md) for worked, copy-pasteable scenarios.
66
+
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.
72
+
73
+ ## Features
74
+
75
+ - **Six command groups** covering the main Capital.com Open API workflows — `session`, `market`, `account`, `trade`, `watchlist`, `stream` (see the [API coverage table](docs/api-coverage.md))
76
+ - **Safety-first trading** — trading is off by default; enabling it requires an explicit EPIC allowlist, every execution goes through a two-phase *preview → execute* flow with risk checks, and mutating commands require `--yes`
77
+ - **`--json` everywhere** — every command can emit raw JSON for piping into `jq`, scripts, or CI jobs
78
+ - **Distinct exit codes per failure class** — scripts can branch on *why* a command failed (auth vs. risk-block vs. upstream error)
79
+ - **Real-time streaming** — live price tables, price-level alerts, and portfolio snapshots over WebSocket
80
+ - **Demo and live environments** — defaults to demo; live requires explicit opt-in
81
+ - **Built-in rate limiting** — client-side token buckets respect Capital.com's 10 req/s global, 1 req/s session, and trading-burst limits
82
+
83
+ ## Installation
84
+
85
+ Requires Python 3.10+.
86
+
87
+ **One-line install (recommended)** — isolated, global `capctl` command, no clone:
88
+
89
+ ```bash
90
+ pipx install git+https://github.com/SimonTarara62/capitalcom-cli.git
91
+ ```
92
+
93
+ Using [uv](https://docs.astral.sh/uv/) instead of pipx:
94
+
95
+ ```bash
96
+ uv tool install git+https://github.com/SimonTarara62/capitalcom-cli.git
97
+ ```
98
+
99
+ Plain pip (into the active environment):
100
+
101
+ ```bash
102
+ pip install git+https://github.com/SimonTarara62/capitalcom-cli.git
103
+ ```
104
+
105
+ **From a clone (for development):**
106
+
107
+ ```bash
108
+ git clone https://github.com/SimonTarara62/capitalcom-cli.git
109
+ cd capitalcom-cli
110
+ python3 -m venv .venv && source .venv/bin/activate
111
+ pip install -e .
112
+ ```
113
+
114
+ Verify and enable shell completion (bash/zsh/fish, provided by Typer):
115
+
116
+ ```bash
117
+ capctl --version
118
+ capctl --install-completion
119
+ ```
120
+
121
+ ### Shell completion
122
+
123
+ capctl ships completion for bash, zsh, and fish (via Typer):
124
+
125
+ ```bash
126
+ capctl --install-completion # install for your current shell
127
+ capctl --show-completion # print the script (to inspect or source manually)
128
+ ```
129
+
130
+ Restart your shell (or `source` your rc file) after installing.
131
+
132
+ ## Configuration
133
+
134
+ Generate an API key in the Capital.com platform under **Settings → API integrations**, then:
135
+
136
+ ```bash
137
+ cp .env.example .env
138
+ # edit .env and fill in CAP_API_KEY, CAP_IDENTIFIER, CAP_API_PASSWORD
139
+ ```
140
+
141
+ Credentials are resolved in this order:
142
+
143
+ 1. `--env-file PATH` flag
144
+ 2. `$CAP_ENV_FILE` environment variable
145
+ 3. `./.env` in the current directory
146
+ 4. `~/.config/capital-cli/.env`
147
+
148
+ All settings (one `CAP_*` variable each) and their defaults:
149
+
150
+ | Variable | Default | Purpose |
151
+ |----------|---------|---------|
152
+ | `CAP_ENV` | `demo` | `demo` or `live` |
153
+ | `CAP_API_KEY` | — | API key (required) |
154
+ | `CAP_IDENTIFIER` | — | Login email (required) |
155
+ | `CAP_API_PASSWORD` | — | API-key custom password (required) |
156
+ | `CAP_ALLOW_TRADING` | `false` | Master switch for all trade execution |
157
+ | `CAP_ALLOWED_EPICS` | (empty) | Comma-separated allowlist, or `ALL` |
158
+ | `CAP_MAX_POSITION_SIZE` | `1.0` | Per-trade size ceiling |
159
+ | `CAP_MAX_WORKING_ORDER_SIZE` | `1.0` | Per-order size ceiling |
160
+ | `CAP_MAX_OPEN_POSITIONS` | `3` | Open-position cap |
161
+ | `CAP_MAX_ORDERS_PER_DAY` | `20` | Daily order counter |
162
+ | `CAP_REQUIRE_EXPLICIT_CONFIRM` | `true` | Mutations need `--yes` |
163
+ | `CAP_DRY_RUN` | `false` | Block all executions regardless of other flags |
164
+ | `CAP_DEFAULT_ACCOUNT_ID` | (none) | Account selected after login |
165
+ | `CAP_HTTP_TIMEOUT_S` | `15` | HTTP timeout |
166
+ | `CAP_LOG_LEVEL` | `WARNING` | `DEBUG` … `CRITICAL` |
167
+ | `CAP_WS_ENABLED` | `false` | Required for `capctl stream …` |
168
+
169
+ Trade previews and the daily order counter persist between commands in
170
+ `~/.config/capital-cli/state.json` (override with `CAPCTL_STATE_FILE`).
171
+
172
+ ## Global flags
173
+
174
+ These go **before** the command group:
175
+
176
+ | Flag | Purpose |
177
+ |------|---------|
178
+ | `--json` | Emit raw JSON instead of tables |
179
+ | `--plain` | Tab-delimited rows for piping (no boxes/colors) |
180
+ | `--no-color` | Disable colored output (also honors `NO_COLOR`) |
181
+ | `--demo` / `--live` | Force environment for this invocation |
182
+ | `--env-file PATH` | Use a specific credentials file |
183
+ | `--account ID`, `-a` | Use a specific account |
184
+ | `--verbose`, `-v` | Debug logging (incl. per-command timing) |
185
+ | `--version` | Print version and exit |
186
+
187
+ ## Command reference
188
+
189
+ ### Session
190
+
191
+ ```bash
192
+ capctl session status # local session state (no network call)
193
+ capctl session details # server-side session info (client/account ids, timezone)
194
+ capctl session time # broker server time (no auth)
195
+ capctl session encryption-key # API encryption key for encrypted-password login
196
+ capctl session login [--force] [--account ID]
197
+ capctl session ping # keep the session alive
198
+ capctl session switch ACCOUNT_ID
199
+ capctl session logout
200
+ ```
201
+
202
+ Note: commands that need authentication log in automatically; an explicit `login` is rarely required.
203
+
204
+ ### Market data
205
+
206
+ ```bash
207
+ capctl market search "bitcoin" [--limit 20]
208
+ capctl market search --epics GOLD,SILVER
209
+ capctl market get GOLD # details + dealing rules
210
+ capctl market nav-root # top-level categories
211
+ capctl market nav-node NODE_ID # drill into a category
212
+ capctl market prices GOLD --resolution HOUR --max 48
213
+ capctl market sentiment GOLD # client long/short %
214
+ capctl market sentiment GOLD,SILVER,BTCUSD # batch sentiment for several markets
215
+ capctl market nav-node NODE_ID --limit 50 # cap the number of children returned
216
+ ```
217
+
218
+ Price resolutions: `MINUTE`, `MINUTE_5`, `MINUTE_15`, `MINUTE_30`, `HOUR`, `HOUR_4`, `DAY`, `WEEK`.
219
+
220
+ ### Account
221
+
222
+ ```bash
223
+ capctl account list
224
+ capctl account prefs-get
225
+ capctl account prefs-set --hedging --yes # risk-gated
226
+ capctl account prefs-set --leverage CRYPTOCURRENCIES=2 --leverage CURRENCIES=20 --yes
227
+ capctl account history-activity --last 3600
228
+ capctl account history-transactions --last 86400 [--type DEPOSIT]
229
+ capctl account topup 1000 --yes # demo environment only
230
+ ```
231
+
232
+ ### Trading
233
+
234
+ Read-only:
235
+
236
+ ```bash
237
+ capctl trade positions
238
+ capctl trade position DEAL_ID
239
+ capctl trade orders
240
+ capctl trade confirm DEAL_REFERENCE [--wait --timeout 30]
241
+ ```
242
+
243
+ Two-phase execution — preview first (validates against the risk policy and broker dealing rules, **creates nothing**), then execute with the returned `preview_id`:
244
+
245
+ ```bash
246
+ capctl trade preview-position GOLD BUY 0.5 --stop-distance 10 --profit-distance 20
247
+ # → returns preview_id, risk-check table, estimated entry
248
+
249
+ capctl trade execute-position <preview_id> --yes
250
+ ```
251
+
252
+ Working orders follow the same shape:
253
+
254
+ ```bash
255
+ capctl trade preview-order GOLD BUY LIMIT 2300 0.5 --good-till 2026-07-01T00:00:00
256
+ capctl trade execute-order <preview_id> --yes
257
+ ```
258
+
259
+ Closing and cancelling:
260
+
261
+ ```bash
262
+ capctl trade close DEAL_ID --yes
263
+ capctl trade cancel DEAL_ID --yes
264
+ ```
265
+
266
+ Amending an open position or a pending order (stops, limits, level, expiry):
267
+
268
+ ```bash
269
+ capctl trade amend-position DEAL_ID --stop-level 2300 --profit-level 2450 --yes
270
+ capctl trade amend-order DEAL_ID --level 2310 --good-till 2026-08-01T00:00:00 --yes
271
+ ```
272
+
273
+ Previews expire after 120 seconds. Execution commands wait for broker confirmation by default (`--no-wait` to skip; `--timeout` to tune).
274
+
275
+ ### Watchlists
276
+
277
+ ```bash
278
+ capctl watchlist list
279
+ capctl watchlist get WATCHLIST_ID
280
+ capctl watchlist create "Metals" --yes
281
+ capctl watchlist add WATCHLIST_ID GOLD --yes
282
+ capctl watchlist remove WATCHLIST_ID GOLD --yes
283
+ capctl watchlist delete WATCHLIST_ID --yes
284
+ ```
285
+
286
+ ### Streaming (requires `CAP_WS_ENABLED=true`)
287
+
288
+ ```bash
289
+ capctl stream prices GOLD,SILVER,EURUSD --duration 120 # live updating table
290
+ capctl stream candles GOLD,BTCUSD --resolution MINUTE_5 # live OHLC candlesticks
291
+ capctl stream candles BTCUSD --resolution HOUR --type heikin-ashi
292
+ capctl stream alerts GOLD 2400 --direction ABOVE # beep when crossed
293
+ capctl stream portfolio --duration 300 --interval 5 # snapshots for open positions
294
+ ```
295
+
296
+ Streams stop after `--duration` seconds or Ctrl-C. Capital.com allows at most 40 concurrent EPIC subscriptions.
297
+
298
+ ## Use cases
299
+
300
+ Quick recipes below; for fuller worked scenarios (paper-trading practice, data analysis, cron monitoring, safe automation, API exploration) see [docs/use-cases.md](docs/use-cases.md).
301
+
302
+ **Morning check — one screen of context:**
303
+
304
+ ```bash
305
+ capctl account list && capctl trade positions && capctl trade orders
306
+ ```
307
+
308
+ **Scripting with `--json` and `jq` — extract the GOLD bid:**
309
+
310
+ ```bash
311
+ capctl --json market search --epics GOLD | jq -r '.markets[0].bid'
312
+ ```
313
+
314
+ **Export 200 daily candles to a CSV:**
315
+
316
+ ```bash
317
+ capctl --json market prices GOLD --resolution DAY --max 200 \
318
+ | jq -r '.prices[] | [.snapshotTime, .openPrice.bid, .highPrice.bid, .lowPrice.bid, .closePrice.bid] | @csv' \
319
+ > gold_daily.csv
320
+ ```
321
+
322
+ **Safe trade in the demo environment, end to end:**
323
+
324
+ ```bash
325
+ # .env: CAP_ENV=demo, CAP_ALLOW_TRADING=true, CAP_ALLOWED_EPICS=GOLD
326
+ PREVIEW=$(capctl --json trade preview-position GOLD BUY 0.5 --stop-distance 15 | jq -r .preview_id)
327
+ capctl trade execute-position "$PREVIEW" --yes
328
+ capctl trade positions
329
+ ```
330
+
331
+ **Branch on failure class in a script:**
332
+
333
+ ```bash
334
+ capctl --json trade execute-position "$PREVIEW" --yes
335
+ case $? in
336
+ 0) echo "filled" ;;
337
+ 4) echo "blocked by safety policy (trading disabled / confirm / risk limit)" ;;
338
+ 5) echo "auth problem — check credentials" ;;
339
+ 7) echo "broker/upstream error — retry later" ;;
340
+ esac
341
+ ```
342
+
343
+ **Watch for a breakout while you work:**
344
+
345
+ ```bash
346
+ capctl stream alerts BTCUSD 75000 --direction ABOVE --duration 3600
347
+ ```
348
+
349
+ **Cron-driven snapshot (JSON logs, no tables):**
350
+
351
+ ```bash
352
+ */15 * * * * capctl --json trade positions >> ~/logs/positions.jsonl 2>&1
353
+ ```
354
+
355
+ ## Exit codes
356
+
357
+ | Code | Meaning |
358
+ |------|---------|
359
+ | 0 | Success |
360
+ | 1 | Unexpected internal error |
361
+ | 2 | Invalid input (bad parameter or failed validation) |
362
+ | 3 | Configuration error (missing/invalid credentials) |
363
+ | 4 | Safety policy block (trading disabled, dry-run, confirm required, EPIC not allowed, risk limit) |
364
+ | 5 | Authentication/session failure |
365
+ | 6 | Local rate limit exceeded |
366
+ | 7 | Broker / upstream API error |
367
+ | 8 | Preview not found, expired, or failed checks |
368
+ | 130 | Interrupted (Ctrl-C) |
369
+
370
+ ## Safety model
371
+
372
+ Trade execution must pass **all** of these gates, in order:
373
+
374
+ 1. `CAP_ALLOW_TRADING=true` — master switch (default off)
375
+ 2. `CAP_DRY_RUN=false` — dry-run blocks everything
376
+ 3. `--yes` on the command (when `CAP_REQUIRE_EXPLICIT_CONFIRM=true`)
377
+ 4. A valid, unexpired preview whose risk checks all passed:
378
+ - EPIC is in `CAP_ALLOWED_EPICS`
379
+ - size within `CAP_MAX_POSITION_SIZE`, normalized to the broker's min/max/increment dealing rules
380
+ - daily order counter under `CAP_MAX_ORDERS_PER_DAY`
381
+
382
+ There is no way to skip the preview step for positions and working orders — `execute-*` commands only accept a `preview_id`.
383
+
384
+ **Live trading:** keep `CAP_ENV=demo` until your workflow is proven. Switching to live requires editing `.env` (or passing `--live`) *and* having trading enabled — the defaults protect you twice.
385
+
386
+ ## Architecture
387
+
388
+ ```
389
+ capital_cli/
390
+ ├── core/ # Capital.com services: config, HTTP client, session,
391
+ │ # rate limiter, risk engine, models, errors, WebSocket
392
+ └── cli/ # presentation: Typer apps per command group,
393
+ # Rich/JSON output, async runner with exit-code mapping
394
+ ```
395
+
396
+ The `cli/` layer never talks to the API directly — every command parses arguments, calls a `core` service, and renders the result. All risk validation lives in `core/risk.py`, so safety rules cannot be bypassed by output or argument handling.
397
+
398
+ ## Development
399
+
400
+ ```bash
401
+ pip install -e ".[dev]"
402
+ pytest -q # full test suite
403
+ ruff check . # lint
404
+ mypy capital_cli # type-check the whole package (matches CI)
405
+ ```
406
+
407
+ An opt-in end-to-end suite runs against the real demo API (credentials required):
408
+
409
+ ```bash
410
+ CAPCTL_E2E=1 pytest tests/e2e -m e2e -v
411
+ ```
412
+
413
+ Tests mock the HTTP and WebSocket layers — no network or credentials needed.
414
+
415
+ Or use the task runner: `make check` (lint + typecheck + test), `make docs`, `make e2e`.
416
+
417
+ ## Documentation
418
+
419
+ - [Full CLI reference](docs/CLI.md) — every command and option (auto-generated)
420
+ - [Scripting & automation](docs/scripting.md) — CI credentials, exit codes, jq recipes
421
+ - [Getting started from zero](docs/getting-started.md) — account, API key, install, first trade
422
+ - [Practical use cases](docs/use-cases.md) — what people actually do with capctl, with copy-pasteable scenarios
423
+ - [Troubleshooting](docs/troubleshooting.md) — common errors and exit codes
424
+ - [Contributing](CONTRIBUTING.md) — dev setup and conventions
425
+
426
+ ## License
427
+
428
+ Apache License 2.0 — see [LICENSE](LICENSE) and [NOTICE](NOTICE).
429
+
430
+ Licensed under the Apache License, Version 2.0. You may obtain a copy at
431
+ <http://www.apache.org/licenses/LICENSE-2.0>. Unless required by applicable law
432
+ or agreed to in writing, software distributed under the License is distributed
433
+ on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.