capitalcom-cli 0.6.2__tar.gz → 0.7.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 (88) hide show
  1. {capitalcom_cli-0.6.2/capitalcom_cli.egg-info → capitalcom_cli-0.7.0}/PKG-INFO +15 -3
  2. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/README.md +14 -2
  3. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/__init__.py +1 -1
  4. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/cli/doctor_cmds.py +1 -0
  5. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/cli/runner.py +1 -0
  6. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/core/config.py +27 -0
  7. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/core/errors.py +1 -0
  8. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/core/models.py +6 -0
  9. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/core/risk.py +94 -0
  10. capitalcom_cli-0.7.0/capital_cli/core/state.py +295 -0
  11. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/sdk/risk_policy.py +2 -0
  12. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/services/trading.py +40 -14
  13. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0/capitalcom_cli.egg-info}/PKG-INFO +15 -3
  14. capitalcom_cli-0.7.0/tests/test_config_errors.py +99 -0
  15. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_doctor.py +25 -0
  16. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_errors.py +8 -0
  17. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_risk.py +233 -0
  18. capitalcom_cli-0.7.0/tests/test_state.py +540 -0
  19. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_trade_cmds.py +20 -0
  20. capitalcom_cli-0.6.2/capital_cli/core/state.py +0 -121
  21. capitalcom_cli-0.6.2/tests/test_config_errors.py +0 -34
  22. capitalcom_cli-0.6.2/tests/test_state.py +0 -103
  23. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/LICENSE +0 -0
  24. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/NOTICE +0 -0
  25. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/__main__.py +0 -0
  26. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/cli/__init__.py +0 -0
  27. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/cli/account_cmds.py +0 -0
  28. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/cli/app.py +0 -0
  29. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/cli/context.py +0 -0
  30. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/cli/live_guard.py +0 -0
  31. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/cli/market_cmds.py +0 -0
  32. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/cli/output.py +0 -0
  33. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/cli/session_cmds.py +0 -0
  34. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/cli/stream_cmds.py +0 -0
  35. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/cli/trade_cmds.py +0 -0
  36. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/cli/watchlist_cmds.py +0 -0
  37. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/core/__init__.py +0 -0
  38. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/core/audit.py +0 -0
  39. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/core/http_client.py +0 -0
  40. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/core/rate_limit.py +0 -0
  41. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/core/session.py +0 -0
  42. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/core/utils.py +0 -0
  43. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/core/websocket_client.py +0 -0
  44. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/sdk/__init__.py +0 -0
  45. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/sdk/app.py +0 -0
  46. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/sdk/config.py +0 -0
  47. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/services/__init__.py +0 -0
  48. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/services/accounts.py +0 -0
  49. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/services/confirmations.py +0 -0
  50. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/services/markets.py +0 -0
  51. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/services/streaming.py +0 -0
  52. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capital_cli/services/watchlists.py +0 -0
  53. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capitalcom_cli.egg-info/SOURCES.txt +0 -0
  54. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capitalcom_cli.egg-info/dependency_links.txt +0 -0
  55. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capitalcom_cli.egg-info/entry_points.txt +0 -0
  56. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capitalcom_cli.egg-info/requires.txt +0 -0
  57. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/capitalcom_cli.egg-info/top_level.txt +0 -0
  58. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/pyproject.toml +0 -0
  59. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/setup.cfg +0 -0
  60. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_account_cmds.py +0 -0
  61. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_app.py +0 -0
  62. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_audit.py +0 -0
  63. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_build_broker_request.py +0 -0
  64. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_cli_usage_errors.py +0 -0
  65. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_core_port.py +0 -0
  66. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_coverage_doc_in_sync.py +0 -0
  67. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_credential_cmd.py +0 -0
  68. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_global_flag_hoist.py +0 -0
  69. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_http_client.py +0 -0
  70. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_init_state_singletons.py +0 -0
  71. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_live_guard.py +0 -0
  72. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_market_cmds.py +0 -0
  73. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_output.py +0 -0
  74. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_output_color.py +0 -0
  75. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_output_plain.py +0 -0
  76. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_packaging_metadata.py +0 -0
  77. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_redaction.py +0 -0
  78. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_runner.py +0 -0
  79. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_session_cmds.py +0 -0
  80. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_session_persistence.py +0 -0
  81. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_session_reads.py +0 -0
  82. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_stream_cmds.py +0 -0
  83. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_trade_limit.py +0 -0
  84. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_tz_datetimes.py +0 -0
  85. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_utils.py +0 -0
  86. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_version.py +0 -0
  87. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_watchlist_cmds.py +0 -0
  88. {capitalcom_cli-0.6.2 → capitalcom_cli-0.7.0}/tests/test_websocket_parsing.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: capitalcom-cli
3
- Version: 0.6.2
3
+ Version: 0.7.0
4
4
  Summary: Unofficial command-line client for the Capital.com Open API
5
5
  Author: Simon Tarara
6
6
  License: Apache-2.0
@@ -56,6 +56,10 @@ Browse markets, manage accounts and watchlists, preview and execute trades behin
56
56
  [![Release](https://img.shields.io/github/v/release/SimonTarara62/capitalcom-cli?sort=semver)](https://github.com/SimonTarara62/capitalcom-cli/releases)
57
57
  [![CLI + SDK coverage](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/SimonTarara62/capitalcom-cli/main/docs/coverage-badge.json)](docs/api-coverage.md)
58
58
 
59
+ > **Related:** [Capital.com MCP Server](https://github.com/SimonTarara62/capitalcom-mcp-server)
60
+ > — the same broker engine exposed as a Model Context Protocol (MCP) server for
61
+ > LLM clients (Claude, Cursor, ChatGPT, …).
62
+
59
63
  ```text
60
64
  $ capctl market search "gold"
61
65
  Markets
@@ -121,6 +125,12 @@ Using [uv](https://docs.astral.sh/uv/) instead of pipx:
121
125
  uv tool install capitalcom-cli
122
126
  ```
123
127
 
128
+ With [Homebrew](https://brew.sh/) (macOS/Linux):
129
+
130
+ ```bash
131
+ brew install SimonTarara62/tap/capctl
132
+ ```
133
+
124
134
  Plain pip (into the active environment):
125
135
 
126
136
  ```bash
@@ -193,6 +203,7 @@ Main settings and their defaults:
193
203
  | `CAP_MAX_ORDERS_PER_DAY` | `20` | Daily order counter |
194
204
  | `CAP_REQUIRE_EXPLICIT_CONFIRM` | `true` | Mutations need `--yes` |
195
205
  | `CAP_DRY_RUN` | `false` | Block all executions regardless of other flags |
206
+ | `CAP_PREVIEW_REUSE` | `block` | `block`: a preview can be executed once · `allow`: repeatable until it expires · `ask`: reserved for interactive hosts, same as `block` |
196
207
  | `CAP_DEFAULT_ACCOUNT_ID` | (none) | Account selected after login |
197
208
  | `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 |
198
209
  | `CAP_HTTP_TIMEOUT_S` | `15` | HTTP timeout |
@@ -330,7 +341,7 @@ capctl trade amend-position DEAL_ID --stop-level 2300 --profit-level 2450 --yes
330
341
  capctl trade amend-order DEAL_ID --level 2310 --good-till 2026-08-01T00:00:00 --yes
331
342
  ```
332
343
 
333
- Previews expire after 120 seconds. Execution commands wait for broker confirmation by default (`--no-wait` to skip; `--timeout` to tune).
344
+ Previews expire after 120 seconds. A preview is single-use by default: executing the same `preview_id` again fails with `PREVIEW_ALREADY_USED` (set `CAP_PREVIEW_REUSE=allow` to change this). Execution commands wait for broker confirmation by default (`--no-wait` to skip; `--timeout` to tune).
334
345
 
335
346
  ### Watchlists
336
347
 
@@ -454,7 +465,7 @@ read-only, preview→execute, streaming, and risk-policy examples.
454
465
  | 5 | Authentication/session failure |
455
466
  | 6 | Local rate limit exceeded |
456
467
  | 7 | Broker / upstream API error |
457
- | 8 | Preview not found, expired, or failed checks |
468
+ | 8 | Preview not found, expired, already used, or failed checks |
458
469
  | 130 | Interrupted (Ctrl-C) |
459
470
 
460
471
  ## Safety model
@@ -468,6 +479,7 @@ Trade execution must pass **all** of these gates, in order:
468
479
  - EPIC is in `CAP_ALLOWED_EPICS`
469
480
  - size within `CAP_MAX_POSITION_SIZE`, normalized to the broker's min/max/increment dealing rules
470
481
  - daily order counter under `CAP_MAX_ORDERS_PER_DAY`
482
+ 5. The preview has not been executed before (`CAP_PREVIEW_REUSE=block`, the default)
471
483
 
472
484
  There is no way to skip the preview step for positions and working orders — `execute-*` commands only accept a `preview_id`.
473
485
 
@@ -11,6 +11,10 @@ Browse markets, manage accounts and watchlists, preview and execute trades behin
11
11
  [![Release](https://img.shields.io/github/v/release/SimonTarara62/capitalcom-cli?sort=semver)](https://github.com/SimonTarara62/capitalcom-cli/releases)
12
12
  [![CLI + SDK coverage](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/SimonTarara62/capitalcom-cli/main/docs/coverage-badge.json)](docs/api-coverage.md)
13
13
 
14
+ > **Related:** [Capital.com MCP Server](https://github.com/SimonTarara62/capitalcom-mcp-server)
15
+ > — the same broker engine exposed as a Model Context Protocol (MCP) server for
16
+ > LLM clients (Claude, Cursor, ChatGPT, …).
17
+
14
18
  ```text
15
19
  $ capctl market search "gold"
16
20
  Markets
@@ -76,6 +80,12 @@ Using [uv](https://docs.astral.sh/uv/) instead of pipx:
76
80
  uv tool install capitalcom-cli
77
81
  ```
78
82
 
83
+ With [Homebrew](https://brew.sh/) (macOS/Linux):
84
+
85
+ ```bash
86
+ brew install SimonTarara62/tap/capctl
87
+ ```
88
+
79
89
  Plain pip (into the active environment):
80
90
 
81
91
  ```bash
@@ -148,6 +158,7 @@ Main settings and their defaults:
148
158
  | `CAP_MAX_ORDERS_PER_DAY` | `20` | Daily order counter |
149
159
  | `CAP_REQUIRE_EXPLICIT_CONFIRM` | `true` | Mutations need `--yes` |
150
160
  | `CAP_DRY_RUN` | `false` | Block all executions regardless of other flags |
161
+ | `CAP_PREVIEW_REUSE` | `block` | `block`: a preview can be executed once · `allow`: repeatable until it expires · `ask`: reserved for interactive hosts, same as `block` |
151
162
  | `CAP_DEFAULT_ACCOUNT_ID` | (none) | Account selected after login |
152
163
  | `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 |
153
164
  | `CAP_HTTP_TIMEOUT_S` | `15` | HTTP timeout |
@@ -285,7 +296,7 @@ capctl trade amend-position DEAL_ID --stop-level 2300 --profit-level 2450 --yes
285
296
  capctl trade amend-order DEAL_ID --level 2310 --good-till 2026-08-01T00:00:00 --yes
286
297
  ```
287
298
 
288
- Previews expire after 120 seconds. Execution commands wait for broker confirmation by default (`--no-wait` to skip; `--timeout` to tune).
299
+ Previews expire after 120 seconds. A preview is single-use by default: executing the same `preview_id` again fails with `PREVIEW_ALREADY_USED` (set `CAP_PREVIEW_REUSE=allow` to change this). Execution commands wait for broker confirmation by default (`--no-wait` to skip; `--timeout` to tune).
289
300
 
290
301
  ### Watchlists
291
302
 
@@ -409,7 +420,7 @@ read-only, preview→execute, streaming, and risk-policy examples.
409
420
  | 5 | Authentication/session failure |
410
421
  | 6 | Local rate limit exceeded |
411
422
  | 7 | Broker / upstream API error |
412
- | 8 | Preview not found, expired, or failed checks |
423
+ | 8 | Preview not found, expired, already used, or failed checks |
413
424
  | 130 | Interrupted (Ctrl-C) |
414
425
 
415
426
  ## Safety model
@@ -423,6 +434,7 @@ Trade execution must pass **all** of these gates, in order:
423
434
  - EPIC is in `CAP_ALLOWED_EPICS`
424
435
  - size within `CAP_MAX_POSITION_SIZE`, normalized to the broker's min/max/increment dealing rules
425
436
  - daily order counter under `CAP_MAX_ORDERS_PER_DAY`
437
+ 5. The preview has not been executed before (`CAP_PREVIEW_REUSE=block`, the default)
426
438
 
427
439
  There is no way to skip the preview step for positions and working orders — `execute-*` commands only accept a `preview_id`.
428
440
 
@@ -1,3 +1,3 @@
1
1
  """Capital.com command-line client."""
2
2
 
3
- __version__ = "0.6.2"
3
+ __version__ = "0.7.0"
@@ -34,6 +34,7 @@ async def _probe() -> dict[str, Any]:
34
34
  "allow_trading": config.cap_allow_trading,
35
35
  "allowed_epics": config.allowed_epics_list,
36
36
  "dry_run": config.cap_dry_run,
37
+ "preview_reuse": config.cap_preview_reuse.value,
37
38
  "max_orders_per_day": config.cap_max_orders_per_day,
38
39
  "orders_used_today": used,
39
40
  "orders_remaining_today": remaining,
@@ -45,6 +45,7 @@ EXIT_CODES: dict[str, int] = {
45
45
  ErrorCode.PREVIEW_NOT_FOUND: 8,
46
46
  ErrorCode.PREVIEW_EXPIRED: 8,
47
47
  ErrorCode.PREVIEW_CHECKS_FAILED: 8,
48
+ ErrorCode.PREVIEW_ALREADY_USED: 8,
48
49
  }
49
50
 
50
51
 
@@ -24,6 +24,14 @@ class CapEnv(str, Enum):
24
24
  LIVE = "live"
25
25
 
26
26
 
27
+ class PreviewReuse(str, Enum):
28
+ """Policy for executing a preview that was already executed."""
29
+
30
+ BLOCK = "block"
31
+ ALLOW = "allow"
32
+ ASK = "ask"
33
+
34
+
27
35
  def _resolve_env_file() -> str | None:
28
36
  """
29
37
  Resolve which .env file to load.
@@ -84,8 +92,22 @@ class Config(BaseSettings):
84
92
 
85
93
  # Internal defaults
86
94
  cap_preview_cache_ttl_s: int = Field(default=120)
95
+ cap_preview_reuse: PreviewReuse = Field(
96
+ default=PreviewReuse.BLOCK,
97
+ description="Re-executing an already-executed preview: block (default), allow, or ask.",
98
+ )
87
99
  cap_ping_interval_s: int = Field(default=480)
88
100
 
101
+ @field_validator("cap_preview_reuse", mode="before")
102
+ @classmethod
103
+ def normalize_preview_reuse(cls, v: object) -> object:
104
+ if not isinstance(v, str):
105
+ return v
106
+ value = v.strip().lower()
107
+ if value not in {m.value for m in PreviewReuse}:
108
+ raise ValueError(f"CAP_PREVIEW_REUSE must be one of: block, allow, ask (got '{v}')")
109
+ return value
110
+
89
111
  @field_validator("cap_log_level")
90
112
  @classmethod
91
113
  def validate_log_level(cls, v: str) -> str:
@@ -104,6 +126,11 @@ class Config(BaseSettings):
104
126
  )
105
127
  return self
106
128
 
129
+ @property
130
+ def preview_single_use(self) -> bool:
131
+ """True unless previews may be executed more than once."""
132
+ return self.cap_preview_reuse is not PreviewReuse.ALLOW
133
+
107
134
  @property
108
135
  def base_url(self) -> str:
109
136
  if self.cap_env == CapEnv.DEMO:
@@ -38,6 +38,7 @@ class ErrorCode:
38
38
  PREVIEW_NOT_FOUND = "PREVIEW_NOT_FOUND"
39
39
  PREVIEW_EXPIRED = "PREVIEW_EXPIRED"
40
40
  PREVIEW_CHECKS_FAILED = "PREVIEW_CHECKS_FAILED"
41
+ PREVIEW_ALREADY_USED = "PREVIEW_ALREADY_USED"
41
42
 
42
43
  # General errors
43
44
  INVALID_REQUEST = "INVALID_REQUEST"
@@ -174,6 +174,12 @@ class PreviewResult(BaseModel):
174
174
  estimated_entry: float | None = Field(default=None, description="Estimated entry price")
175
175
  estimated_risk_notes: str | None = Field(default=None, description="Risk estimation notes")
176
176
  created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
177
+ executed_at: datetime | None = Field(
178
+ default=None, description="UTC time the preview was claimed for execution"
179
+ )
180
+ deal_reference: str | None = Field(
181
+ default=None, description="Broker deal reference once the order was accepted"
182
+ )
177
183
 
178
184
  def is_expired(self, ttl_seconds: int = 120) -> bool:
179
185
  """Check if preview has expired (2 minutes default)."""
@@ -7,11 +7,16 @@ from typing import Any
7
7
 
8
8
  from .config import get_config
9
9
  from .errors import (
10
+ CapitalCLIError,
10
11
  ConfirmRequiredError,
11
12
  DryRunError,
13
+ ErrorCode,
12
14
  PreviewError,
15
+ RateLimitError,
13
16
  RiskLimitError,
17
+ SessionError,
14
18
  TradingDisabledError,
19
+ UpstreamError,
15
20
  )
16
21
  from .http_client import get_client
17
22
  from .models import (
@@ -26,6 +31,24 @@ from .state import get_state_store
26
31
  logger = logging.getLogger(__name__)
27
32
 
28
33
 
34
+ def order_definitely_not_accepted(exc: BaseException) -> bool:
35
+ """True only when a failed order POST certainly did not reach the broker.
36
+
37
+ That is a 4xx upstream response, an auth failure (401/403), or the local
38
+ rate limiter (request never sent). Anything else (timeout/network error
39
+ with no status, 5xx, unknown exceptions, cancellation) is ambiguous: the
40
+ order may have landed, so the preview claim must be kept.
41
+ """
42
+ if isinstance(exc, RateLimitError):
43
+ return True
44
+ if isinstance(exc, SessionError):
45
+ return exc.code == ErrorCode.AUTH_FAILED
46
+ if isinstance(exc, UpstreamError):
47
+ status = exc.details.get("status_code")
48
+ return isinstance(status, int) and 400 <= status <= 499
49
+ return False
50
+
51
+
29
52
  def _safe_positive_float(value: Any, default: float) -> float:
30
53
  """Coerce a broker-supplied value to a finite, positive float.
31
54
 
@@ -411,6 +434,77 @@ class RiskEngine:
411
434
 
412
435
  return preview
413
436
 
437
+ def claim_preview(self, preview_id: str) -> PreviewResult:
438
+ """Claim a preview for a single execution (call right before the POST).
439
+
440
+ In ``allow`` mode this only returns the preview. Otherwise the claim is
441
+ persisted to the state file and the cache; a preview already claimed
442
+ (in this process or any other) raises PREVIEW_ALREADY_USED. Store
443
+ errors propagate: if the claim cannot be recorded, the order must not
444
+ be sent.
445
+ """
446
+ preview = self.get_preview(preview_id)
447
+ if not self.config.preview_single_use:
448
+ return preview
449
+
450
+ now = datetime.now(timezone.utc)
451
+ deal_reference = preview.deal_reference
452
+ already_used = preview.executed_at is not None
453
+ if not already_used:
454
+ existing = self.state.claim_preview(preview, now)
455
+ if existing is not None:
456
+ already_used = True
457
+ deal_reference = existing.deal_reference or deal_reference
458
+ if already_used:
459
+ if deal_reference:
460
+ message = (
461
+ f"Preview {preview_id} was already executed "
462
+ f"(deal reference {deal_reference}). Create a new preview to trade again."
463
+ )
464
+ else:
465
+ message = (
466
+ f"Preview {preview_id} was already submitted and its outcome is unknown. "
467
+ "Check open positions and orders before creating a new preview."
468
+ )
469
+ raise PreviewError(message, code=ErrorCode.PREVIEW_ALREADY_USED)
470
+
471
+ claimed = preview.model_copy(update={"executed_at": now})
472
+ self._preview_cache[preview_id] = claimed
473
+ return claimed
474
+
475
+ def release_preview_claim(self, preview_id: str) -> None:
476
+ """Clear a claim after the broker definitely did not accept the order (best effort)."""
477
+ if not self.config.preview_single_use:
478
+ return
479
+ cached = self._preview_cache.get(preview_id)
480
+ if cached is not None:
481
+ self._preview_cache[preview_id] = cached.model_copy(
482
+ update={"executed_at": None, "deal_reference": None}
483
+ )
484
+ try:
485
+ self.state.release_preview_claim(preview_id)
486
+ except (OSError, CapitalCLIError) as e:
487
+ # Best effort: the stored claim stays, which fails closed.
488
+ logger.warning(f"Could not release claim for preview {preview_id}: {e}")
489
+
490
+ def record_preview_execution(self, preview_id: str, deal_reference: str | None) -> None:
491
+ """Remember the broker deal reference on a claimed preview (best effort).
492
+
493
+ The order is already placed and the claim already persisted, so a
494
+ store failure here is logged and swallowed.
495
+ """
496
+ if not self.config.preview_single_use or not deal_reference:
497
+ return
498
+ cached = self._preview_cache.get(preview_id)
499
+ if cached is not None:
500
+ self._preview_cache[preview_id] = cached.model_copy(
501
+ update={"deal_reference": deal_reference}
502
+ )
503
+ try:
504
+ self.state.set_preview_deal_reference(preview_id, deal_reference)
505
+ except (OSError, CapitalCLIError) as e:
506
+ logger.warning(f"Could not store deal reference for preview {preview_id}: {e}")
507
+
414
508
  def validate_execution_guards(self, *, confirm: bool, preview_id: str | None = None) -> None:
415
509
  """
416
510
  Validate execution guards before trade execution.
@@ -0,0 +1,295 @@
1
+ """Persistent CLI state shared across capctl invocations.
2
+
3
+ A single-shot CLI process cannot keep the preview cache or the daily order
4
+ counter in memory the way a long-lived server can, so both are stored in a
5
+ small JSON file (default: ~/.config/capital-cli/state.json; override with
6
+ the CAPCTL_STATE_FILE environment variable).
7
+
8
+ Every read-modify-write runs under a portable cross-process lock file
9
+ (``<state path>.lock``, created with ``O_CREAT | O_EXCL``), so a preview can
10
+ be claimed for execution exactly once even across concurrent processes.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import contextlib
16
+ import json
17
+ import os
18
+ import time
19
+ import uuid
20
+ from collections.abc import Iterator
21
+ from datetime import datetime
22
+ from pathlib import Path
23
+ from typing import Any
24
+
25
+ from pydantic import TypeAdapter
26
+
27
+ from .errors import CapitalCLIError, ErrorCode
28
+ from .models import PreviewResult
29
+
30
+ _LOCK_STALE_S = 5.0
31
+ _LOCK_TIMEOUT_S = 10.0
32
+ _LOCK_POLL_S = 0.01
33
+
34
+
35
+ def _default_state_path() -> Path:
36
+ override = os.environ.get("CAPCTL_STATE_FILE")
37
+ if override:
38
+ return Path(override)
39
+ return Path.home() / ".config" / "capital-cli" / "state.json"
40
+
41
+
42
+ class StateStore:
43
+ """Tiny JSON-file-backed store for previews and the daily order counter."""
44
+
45
+ def __init__(self, path: Path | None = None) -> None:
46
+ self.path = path or _default_state_path()
47
+
48
+ @contextlib.contextmanager
49
+ def _locked(self) -> Iterator[None]:
50
+ """Hold the cross-process state lock (not re-entrant).
51
+
52
+ Fails closed with INTERNAL_ERROR if the lock cannot be taken within
53
+ ``_LOCK_TIMEOUT_S``. A lock older than ``_LOCK_STALE_S`` is treated as
54
+ left behind by a crashed process and taken over (see ``_break_stale_lock``).
55
+ """
56
+ self.path.parent.mkdir(parents=True, exist_ok=True)
57
+ lock = self.path.with_name(self.path.name + ".lock")
58
+ token = f"{os.getpid()}-{uuid.uuid4().hex}"
59
+ deadline = time.monotonic() + _LOCK_TIMEOUT_S
60
+ while True:
61
+ if _try_create(lock, token):
62
+ break
63
+ # The deadline applies whatever the reason the lock is unavailable,
64
+ # including a stale lock that cannot be deleted.
65
+ progressed = _break_stale_lock(lock)
66
+ if time.monotonic() >= deadline:
67
+ raise CapitalCLIError(
68
+ ErrorCode.INTERNAL_ERROR,
69
+ f"State file is locked: {lock}. "
70
+ "Remove it if no other capctl process is running.",
71
+ )
72
+ if not progressed:
73
+ time.sleep(_LOCK_POLL_S)
74
+ try:
75
+ yield
76
+ finally:
77
+ # Only remove the lock if it is still ours: if it was taken over as
78
+ # stale, it now belongs to another holder.
79
+ with contextlib.suppress(OSError):
80
+ if lock.read_text() == token:
81
+ lock.unlink()
82
+
83
+ def _read(self) -> dict[str, Any]:
84
+ try:
85
+ return json.loads(self.path.read_text())
86
+ except (OSError, json.JSONDecodeError):
87
+ return {}
88
+
89
+ def _write(self, data: dict[str, Any]) -> None:
90
+ self.path.parent.mkdir(parents=True, exist_ok=True)
91
+ tmp = self.path.with_name(self.path.name + ".tmp")
92
+ tmp.write_text(json.dumps(data, default=str))
93
+ tmp.replace(self.path)
94
+ with contextlib.suppress(OSError):
95
+ self.path.chmod(0o600)
96
+
97
+ # ----- previews -----
98
+
99
+ def save_preview(self, preview: PreviewResult) -> None:
100
+ with self._locked():
101
+ data = self._read()
102
+ previews = data.setdefault("previews", {})
103
+ previews[preview.preview_id] = json.loads(preview.model_dump_json())
104
+ self._write(data)
105
+
106
+ def load_preview(self, preview_id: str) -> PreviewResult | None:
107
+ return _parse_preview(self._read().get("previews", {}).get(preview_id))
108
+
109
+ def delete_preview(self, preview_id: str) -> None:
110
+ with self._locked():
111
+ data = self._read()
112
+ if data.get("previews", {}).pop(preview_id, None) is not None:
113
+ self._write(data)
114
+
115
+ def claim_preview(self, preview: PreviewResult, executed_at: datetime) -> PreviewResult | None:
116
+ """Atomically mark a preview as executed; at most one caller wins.
117
+
118
+ Returns ``None`` when this call won the claim (the stored record, or
119
+ ``preview`` itself if none is stored, now carries ``executed_at``).
120
+ Returns the stored record when it was already claimed. A corrupt
121
+ stored record that still carries ``executed_at`` is refused too (fail
122
+ closed), with a refusal record rebuilt from ``preview``.
123
+ """
124
+ with self._locked():
125
+ data = self._read()
126
+ previews = data.setdefault("previews", {})
127
+ raw = previews.get(preview.preview_id)
128
+ stored = _parse_preview(raw)
129
+ if stored is not None and stored.executed_at is not None:
130
+ return stored
131
+ if stored is None and isinstance(raw, dict) and raw.get("executed_at"):
132
+ return _refusal_from_corrupt(preview, raw, executed_at)
133
+ claimed = (stored or preview).model_copy(update={"executed_at": executed_at})
134
+ previews[preview.preview_id] = json.loads(claimed.model_dump_json())
135
+ self._write(data)
136
+ return None
137
+
138
+ def release_preview_claim(self, preview_id: str) -> None:
139
+ """Clear a claim (the broker definitely did not accept the order)."""
140
+ self._update_preview_record(preview_id, executed_at=None, deal_reference=None)
141
+
142
+ def set_preview_deal_reference(self, preview_id: str, deal_reference: str) -> None:
143
+ self._update_preview_record(preview_id, deal_reference=deal_reference)
144
+
145
+ def _update_preview_record(self, preview_id: str, **fields: Any) -> None:
146
+ with self._locked():
147
+ data = self._read()
148
+ record = data.get("previews", {}).get(preview_id)
149
+ if not isinstance(record, dict):
150
+ return
151
+ record.update(fields)
152
+ self._write(data)
153
+
154
+ # ----- daily order counter -----
155
+
156
+ def get_order_count(self, date: str) -> int:
157
+ counter = self._read().get("order_counter", {})
158
+ return counter.get("count", 0) if counter.get("date") == date else 0
159
+
160
+ def increment_order_count(self, date: str) -> None:
161
+ with self._locked():
162
+ data = self._read()
163
+ counter = data.get("order_counter", {})
164
+ count = counter.get("count", 0) if counter.get("date") == date else 0
165
+ data["order_counter"] = {"date": date, "count": count + 1}
166
+ self._write(data)
167
+
168
+ # ----- session tokens (issue #10) -----
169
+
170
+ def save_session(self, *, env: str, cst: str, x_security_token: str,
171
+ last_used_at: str, account_id: str | None) -> None:
172
+ with self._locked():
173
+ data = self._read()
174
+ data["session"] = {
175
+ "env": env, "cst": cst, "x_security_token": x_security_token,
176
+ "last_used_at": last_used_at, "account_id": account_id,
177
+ }
178
+ self._write(data)
179
+
180
+ def load_session(self, env: str) -> dict[str, Any] | None:
181
+ sess = self._read().get("session")
182
+ if not isinstance(sess, dict) or sess.get("env") != env:
183
+ return None
184
+ if not sess.get("cst") or not sess.get("x_security_token"):
185
+ return None
186
+ return sess
187
+
188
+ def clear_session(self) -> None:
189
+ with self._locked():
190
+ data = self._read()
191
+ if data.pop("session", None) is not None:
192
+ self._write(data)
193
+
194
+
195
+ def _parse_preview(raw: Any) -> PreviewResult | None:
196
+ if raw is None:
197
+ return None
198
+ try:
199
+ return PreviewResult.model_validate(raw)
200
+ except Exception: # noqa: BLE001 - corrupt entry is equivalent to missing
201
+ return None
202
+
203
+
204
+ def _refusal_from_corrupt(
205
+ preview: PreviewResult, raw: dict[str, Any], executed_at: datetime
206
+ ) -> PreviewResult:
207
+ try:
208
+ when = TypeAdapter(datetime).validate_python(raw["executed_at"])
209
+ except Exception: # noqa: BLE001 - unparseable time: fall back to the claim time
210
+ when = executed_at
211
+ ref = raw.get("deal_reference")
212
+ return preview.model_copy(
213
+ update={"executed_at": when, "deal_reference": ref if isinstance(ref, str) else None}
214
+ )
215
+
216
+
217
+ def _try_create(path: Path, content: str = "") -> bool:
218
+ """Atomically create ``path`` holding ``content``; False if it already exists."""
219
+ try:
220
+ fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
221
+ except FileExistsError:
222
+ return False
223
+ except PermissionError:
224
+ # Windows raises PermissionError for a file that is pending deletion;
225
+ # anything else (e.g. an unwritable directory) is a real error.
226
+ if path.exists():
227
+ return False
228
+ raise
229
+ try:
230
+ os.write(fd, content.encode())
231
+ except BaseException:
232
+ os.close(fd)
233
+ with contextlib.suppress(OSError):
234
+ path.unlink()
235
+ raise
236
+ os.close(fd)
237
+ return True
238
+
239
+
240
+ def _is_stale(path: Path) -> bool:
241
+ try:
242
+ return time.time() - path.stat().st_mtime > _LOCK_STALE_S
243
+ except OSError: # vanished (or unreadable) -- not ours to remove
244
+ return False
245
+
246
+
247
+ def _remove(path: Path) -> bool:
248
+ """Delete ``path``; True if it is gone (already-missing counts as gone)."""
249
+ try:
250
+ path.unlink()
251
+ except FileNotFoundError:
252
+ return True
253
+ except OSError: # e.g. owned by another user, immutable, or held open
254
+ return False
255
+ return True
256
+
257
+
258
+ def _break_stale_lock(lock: Path) -> bool:
259
+ """Remove ``lock`` if stale; True only if a stale file was actually removed.
260
+
261
+ Removal happens only while holding a secondary ``<lock>.break`` file
262
+ (also O_EXCL), and staleness is re-checked under it. This closes the
263
+ classic race where two waiters both see a stale lock, one replaces it
264
+ with a fresh lock, and the other then deletes that fresh lock: the
265
+ second breaker re-checks under ``.break`` and sees a fresh lock.
266
+ """
267
+ if not _is_stale(lock):
268
+ return False
269
+ breaker = lock.with_name(lock.name + ".break")
270
+ if not _try_create(breaker):
271
+ # Someone else is breaking. Only clear the breaker itself if it was
272
+ # left behind by a process that crashed mid-takeover.
273
+ return _is_stale(breaker) and _remove(breaker)
274
+ try:
275
+ return _is_stale(lock) and _remove(lock)
276
+ finally:
277
+ with contextlib.suppress(OSError):
278
+ breaker.unlink()
279
+
280
+
281
+ _state_store: StateStore | None = None
282
+
283
+
284
+ def get_state_store() -> StateStore:
285
+ """Get or create the global state store instance."""
286
+ global _state_store
287
+ if _state_store is None:
288
+ _state_store = StateStore()
289
+ return _state_store
290
+
291
+
292
+ def reset_state_store() -> None:
293
+ """Reset the global state store (mainly for testing)."""
294
+ global _state_store
295
+ _state_store = None
@@ -17,6 +17,7 @@ class RiskPolicy:
17
17
  max_orders_per_day: int
18
18
  require_explicit_confirm: bool
19
19
  dry_run: bool
20
+ preview_reuse: str = "block"
20
21
 
21
22
  @classmethod
22
23
  def from_config(cls, config: Config) -> RiskPolicy:
@@ -29,4 +30,5 @@ class RiskPolicy:
29
30
  max_orders_per_day=config.cap_max_orders_per_day,
30
31
  require_explicit_confirm=config.cap_require_explicit_confirm,
31
32
  dry_run=config.cap_dry_run,
33
+ preview_reuse=config.cap_preview_reuse.value,
32
34
  )