capitalcom-cli 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,417 @@
1
+ """Risk engine and preview cache for trade validation."""
2
+
3
+ import logging
4
+ from datetime import datetime
5
+ from typing import Any
6
+
7
+ from .config import get_config
8
+ from .errors import (
9
+ ConfirmRequiredError,
10
+ DryRunError,
11
+ PreviewError,
12
+ TradingDisabledError,
13
+ )
14
+ from .http_client import get_client
15
+ from .models import (
16
+ Direction,
17
+ PreviewPositionRequest,
18
+ PreviewResult,
19
+ PreviewWorkingOrderRequest,
20
+ RiskCheck,
21
+ )
22
+ from .state import get_state_store
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+
27
+ class RiskEngine:
28
+ """
29
+ Risk engine for trade validation and preview caching.
30
+
31
+ Implements:
32
+ - Trading enable/disable checks
33
+ - Epic allowlist validation
34
+ - Size limit validation
35
+ - Position/order count limits
36
+ - Preview cache with TTL
37
+ - Size normalization
38
+ """
39
+
40
+ def __init__(self):
41
+ self.config = get_config()
42
+ self.client = get_client()
43
+ self.state = get_state_store()
44
+
45
+ # Preview cache: {preview_id: PreviewResult} (in-process fast path;
46
+ # the persistent copy in StateStore is the source of truth)
47
+ self._preview_cache: dict[str, PreviewResult] = {}
48
+
49
+ def _check_daily_limit(self) -> RiskCheck:
50
+ """Check if daily order limit is reached (persisted across invocations)."""
51
+ today = datetime.utcnow().date().isoformat()
52
+ count = self.state.get_order_count(today)
53
+
54
+ if count >= self.config.cap_max_orders_per_day:
55
+ return RiskCheck(
56
+ check="daily_order_limit",
57
+ passed=False,
58
+ message=f"Daily order limit reached ({self.config.cap_max_orders_per_day})",
59
+ )
60
+
61
+ return RiskCheck(
62
+ check="daily_order_limit",
63
+ passed=True,
64
+ message=f"Daily orders: {count}/{self.config.cap_max_orders_per_day}",
65
+ )
66
+
67
+ def increment_order_count(self) -> None:
68
+ """Increment the persisted daily order counter."""
69
+ today = datetime.utcnow().date().isoformat()
70
+ self.state.increment_order_count(today)
71
+
72
+ async def _get_market_details(self, epic: str) -> dict[str, Any]:
73
+ """Fetch market details including dealing rules."""
74
+ response = await self.client.get(f"/markets/{epic}")
75
+ return response.json()
76
+
77
+ def _validate_size(
78
+ self,
79
+ size: float,
80
+ min_size: float,
81
+ max_size: float,
82
+ increment: float,
83
+ *,
84
+ auto_normalize: bool,
85
+ ) -> tuple[float, RiskCheck]:
86
+ """Validate the requested size against broker dealing rules WITHOUT silently
87
+ changing it.
88
+
89
+ Returns (effective_size, check). The effective size equals the requested
90
+ size, except that increment misalignment is rounded ONLY when auto_normalize
91
+ is True. Sizes below the broker minimum or above the broker maximum always
92
+ fail (they are never silently clamped to the boundary).
93
+ """
94
+ if size < min_size:
95
+ return size, RiskCheck(
96
+ check="size",
97
+ passed=False,
98
+ message=f"Size {size} is below the broker minimum {min_size}. Use at least {min_size}.",
99
+ )
100
+ if size > max_size:
101
+ return size, RiskCheck(
102
+ check="size",
103
+ passed=False,
104
+ message=f"Size {size} is above the broker maximum {max_size}. Use at most {max_size}.",
105
+ )
106
+ rounded = round(size / increment) * increment if increment else size
107
+ tol = max(increment * 1e-4, 1e-9)
108
+ if abs(rounded - size) <= tol:
109
+ return size, RiskCheck(check="size", passed=True, message=f"Size {size} is valid.")
110
+ if not auto_normalize:
111
+ return size, RiskCheck(
112
+ check="size",
113
+ passed=False,
114
+ message=(
115
+ f"Size {size} is not a multiple of the broker increment {increment}. "
116
+ f"Nearest valid size is {rounded}. Re-run with --auto-normalize-size to use {rounded}."
117
+ ),
118
+ )
119
+ if rounded < min_size or rounded > max_size:
120
+ return size, RiskCheck(
121
+ check="size",
122
+ passed=False,
123
+ message=f"Size {size} rounds to {rounded}, outside the broker range [{min_size}, {max_size}].",
124
+ )
125
+ return rounded, RiskCheck(
126
+ check="size",
127
+ passed=True,
128
+ message=f"Size normalized from {size} to {rounded} (increment {increment}).",
129
+ )
130
+
131
+ async def preview_position(
132
+ self, request: PreviewPositionRequest
133
+ ) -> PreviewResult:
134
+ """
135
+ Preview a position and validate against risk policy.
136
+
137
+ Args:
138
+ request: Position preview request
139
+
140
+ Returns:
141
+ Preview result with checks and normalized values
142
+ """
143
+ checks: list[RiskCheck] = []
144
+
145
+ # Check 1: Trading enabled
146
+ if not self.config.cap_allow_trading:
147
+ checks.append(
148
+ RiskCheck(
149
+ check="trading_enabled",
150
+ passed=False,
151
+ message="Trading is disabled (CAP_ALLOW_TRADING=false)",
152
+ )
153
+ )
154
+ return PreviewResult(
155
+ normalized_request={},
156
+ checks=checks,
157
+ all_checks_passed=False,
158
+ )
159
+
160
+ checks.append(
161
+ RiskCheck(check="trading_enabled", passed=True, message="Trading is enabled")
162
+ )
163
+
164
+ # Check 2: Epic allowlist
165
+ if not self.config.is_epic_allowed(request.epic):
166
+ checks.append(
167
+ RiskCheck(
168
+ check="epic_allowed",
169
+ passed=False,
170
+ message=f"Epic '{request.epic}' not in allowlist",
171
+ )
172
+ )
173
+ return PreviewResult(
174
+ normalized_request={},
175
+ checks=checks,
176
+ all_checks_passed=False,
177
+ )
178
+
179
+ checks.append(
180
+ RiskCheck(check="epic_allowed", passed=True, message=f"Epic '{request.epic}' is allowed")
181
+ )
182
+
183
+ # Check 3: Daily order limit
184
+ daily_check = self._check_daily_limit()
185
+ checks.append(daily_check)
186
+
187
+ if not daily_check.passed:
188
+ return PreviewResult(
189
+ normalized_request={},
190
+ checks=checks,
191
+ all_checks_passed=False,
192
+ )
193
+
194
+ # Fetch market details
195
+ try:
196
+ market_data = await self._get_market_details(request.epic)
197
+ except Exception as e:
198
+ logger.error(f"Failed to fetch market details for {request.epic}: {e}")
199
+ checks.append(
200
+ RiskCheck(
201
+ check="market_details",
202
+ passed=False,
203
+ message=f"Failed to fetch market details: {str(e)}",
204
+ )
205
+ )
206
+ return PreviewResult(
207
+ normalized_request={},
208
+ checks=checks,
209
+ all_checks_passed=False,
210
+ )
211
+
212
+ checks.append(
213
+ RiskCheck(check="market_details", passed=True, message="Market details fetched")
214
+ )
215
+
216
+ # Extract dealing rules
217
+ dealing_rules = market_data.get("dealingRules", {})
218
+ min_deal_size = dealing_rules.get("minDealSize", {}).get("value", 0.1)
219
+ max_deal_size = dealing_rules.get("maxDealSize", {}).get("value", 1000.0)
220
+ min_size_increment = dealing_rules.get("minSizeIncrement", {}).get("value", 0.1)
221
+
222
+ # Check 4: Validate size against broker dealing rules (no silent changes)
223
+ effective_size, size_check = self._validate_size(
224
+ request.size,
225
+ min_deal_size,
226
+ max_deal_size,
227
+ min_size_increment,
228
+ auto_normalize=request.auto_normalize_size,
229
+ )
230
+ checks.append(size_check)
231
+ if not size_check.passed:
232
+ return PreviewResult(
233
+ normalized_request={"requested_size": request.size},
234
+ checks=checks,
235
+ all_checks_passed=False,
236
+ )
237
+
238
+ # Check 5: Max position size policy
239
+ if effective_size > self.config.cap_max_position_size:
240
+ checks.append(
241
+ RiskCheck(
242
+ check="max_position_size",
243
+ passed=False,
244
+ message=f"Size {effective_size} exceeds policy limit {self.config.cap_max_position_size}",
245
+ )
246
+ )
247
+ return PreviewResult(
248
+ normalized_request={},
249
+ checks=checks,
250
+ all_checks_passed=False,
251
+ )
252
+
253
+ checks.append(
254
+ RiskCheck(
255
+ check="max_position_size",
256
+ passed=True,
257
+ message=f"Size {effective_size} within limit {self.config.cap_max_position_size}",
258
+ )
259
+ )
260
+
261
+ # Build normalized request (mode='json' to serialize enums as strings)
262
+ normalized_request = request.model_dump(mode="json")
263
+ normalized_request["size"] = effective_size
264
+
265
+ # Extract snapshot for entry price estimate
266
+ snapshot = market_data.get("snapshot", {})
267
+ estimated_entry = None
268
+ if request.direction == Direction.BUY:
269
+ estimated_entry = snapshot.get("offer")
270
+ else:
271
+ estimated_entry = snapshot.get("bid")
272
+
273
+ # Create preview result
274
+ result = PreviewResult(
275
+ normalized_request=normalized_request,
276
+ checks=checks,
277
+ all_checks_passed=all(c.passed for c in checks),
278
+ estimated_entry=estimated_entry,
279
+ estimated_risk_notes="Preview only; actual execution may differ based on market conditions.",
280
+ )
281
+
282
+ # Cache the preview
283
+ self._preview_cache[result.preview_id] = result
284
+ self.state.save_preview(result)
285
+ logger.info(f"Created preview {result.preview_id} for {request.epic}")
286
+
287
+ return result
288
+
289
+ async def preview_working_order(
290
+ self, request: PreviewWorkingOrderRequest
291
+ ) -> PreviewResult:
292
+ """Preview a working order (similar to position preview)."""
293
+ # Convert to position request for validation
294
+ position_request = PreviewPositionRequest(
295
+ epic=request.epic,
296
+ direction=request.direction,
297
+ size=request.size,
298
+ guaranteed_stop=request.guaranteed_stop,
299
+ trailing_stop=request.trailing_stop,
300
+ stop_level=request.stop_level,
301
+ stop_distance=request.stop_distance,
302
+ stop_amount=request.stop_amount,
303
+ profit_level=request.profit_level,
304
+ profit_distance=request.profit_distance,
305
+ profit_amount=request.profit_amount,
306
+ auto_normalize_size=request.auto_normalize_size,
307
+ )
308
+
309
+ # Run position checks
310
+ result = await self.preview_position(position_request)
311
+
312
+ # Add working order specific fields
313
+ if result.all_checks_passed:
314
+ result.normalized_request["type"] = request.type.value
315
+ result.normalized_request["level"] = request.level
316
+ if request.good_till_date:
317
+ result.normalized_request["good_till_date"] = request.good_till_date
318
+
319
+ return result
320
+
321
+ def get_preview(self, preview_id: str) -> PreviewResult:
322
+ """
323
+ Get a cached preview result.
324
+
325
+ Args:
326
+ preview_id: Preview ID
327
+
328
+ Returns:
329
+ Preview result
330
+
331
+ Raises:
332
+ PreviewError: If preview not found or expired
333
+ """
334
+ preview = self._preview_cache.get(preview_id)
335
+ if preview is None:
336
+ preview = self.state.load_preview(preview_id)
337
+
338
+ if not preview:
339
+ raise PreviewError(f"Preview {preview_id} not found", code="PREVIEW_NOT_FOUND")
340
+
341
+ if preview.is_expired(self.config.cap_preview_cache_ttl_s):
342
+ self._preview_cache.pop(preview_id, None)
343
+ self.state.delete_preview(preview_id)
344
+ raise PreviewError(f"Preview {preview_id} expired", code="PREVIEW_EXPIRED")
345
+
346
+ return preview
347
+
348
+ def validate_execution_guards(
349
+ self, *, confirm: bool, preview_id: str | None = None
350
+ ) -> None:
351
+ """
352
+ Validate execution guards before trade execution.
353
+
354
+ Args:
355
+ confirm: Explicit confirmation flag
356
+ preview_id: Optional preview ID to validate
357
+
358
+ Raises:
359
+ TradingDisabledError: If trading is disabled
360
+ DryRunError: If dry-run mode is enabled
361
+ ConfirmRequiredError: If confirmation is required but not provided
362
+ PreviewError: If preview not found or checks failed
363
+ """
364
+ # Guard 1: Trading enabled
365
+ if not self.config.cap_allow_trading:
366
+ raise TradingDisabledError()
367
+
368
+ # Guard 2: Dry-run mode
369
+ if self.config.cap_dry_run:
370
+ raise DryRunError()
371
+
372
+ # Guard 3: Explicit confirmation
373
+ if self.config.cap_require_explicit_confirm and not confirm:
374
+ raise ConfirmRequiredError()
375
+
376
+ # Guard 4: Preview validation
377
+ if preview_id:
378
+ preview = self.get_preview(preview_id)
379
+ if not preview.all_checks_passed:
380
+ raise PreviewError(
381
+ "Preview checks failed, cannot execute",
382
+ code="PREVIEW_CHECKS_FAILED",
383
+ )
384
+
385
+ def validate_mutation_guards(self, *, confirm: bool) -> None:
386
+ """Validate guards for account/settings mutations (not trade execution).
387
+
388
+ Unlike trade execution, this does NOT require CAP_ALLOW_TRADING — changing
389
+ account preferences is risk-sensitive but is not opening or closing a trade.
390
+ Still blocked by dry-run mode and the explicit-confirm requirement.
391
+
392
+ Raises:
393
+ DryRunError: If dry-run mode is enabled.
394
+ ConfirmRequiredError: If confirmation is required but not provided.
395
+ """
396
+ if self.config.cap_dry_run:
397
+ raise DryRunError()
398
+ if self.config.cap_require_explicit_confirm and not confirm:
399
+ raise ConfirmRequiredError()
400
+
401
+
402
+ # Global risk engine instance
403
+ _risk_engine: RiskEngine | None = None
404
+
405
+
406
+ def get_risk_engine() -> RiskEngine:
407
+ """Get or create the global risk engine instance."""
408
+ global _risk_engine
409
+ if _risk_engine is None:
410
+ _risk_engine = RiskEngine()
411
+ return _risk_engine
412
+
413
+
414
+ def reset_risk_engine() -> None:
415
+ """Reset the global risk engine (mainly for testing)."""
416
+ global _risk_engine
417
+ _risk_engine = None
@@ -0,0 +1,219 @@
1
+ """Session management for Capital.com API."""
2
+
3
+ import asyncio
4
+ import logging
5
+ from datetime import datetime
6
+ from typing import Any
7
+
8
+ from .config import get_config
9
+ from .errors import SessionError
10
+ from .http_client import get_client
11
+ from .models import SessionStatus, SessionTokens
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ class SessionManager:
17
+ """
18
+ Manages session lifecycle for Capital.com API.
19
+
20
+ Handles:
21
+ - Login (POST /session)
22
+ - Token storage (CST, X-SECURITY-TOKEN)
23
+ - Auto-refresh on expiry
24
+ - Keep-alive (GET /ping)
25
+ - Logout (DELETE /session)
26
+ """
27
+
28
+ def __init__(self):
29
+ self.config = get_config()
30
+ self.client = get_client()
31
+ self.client.set_relogin(self._force_relogin)
32
+ self.tokens: SessionTokens | None = None
33
+ self.account_id: str | None = None
34
+ self._login_lock = asyncio.Lock()
35
+
36
+ async def _force_relogin(self) -> None:
37
+ """Re-login callback used by the HTTP client on auth expiry."""
38
+ await self.login(force=True)
39
+
40
+ async def login(
41
+ self, *, force: bool = False, account_id: str | None = None
42
+ ) -> dict[str, Any]:
43
+ """
44
+ Create a new session.
45
+
46
+ Args:
47
+ force: Force login even if session is valid
48
+ account_id: Account ID to switch to after login
49
+
50
+ Returns:
51
+ Login response data
52
+ """
53
+ async with self._login_lock:
54
+ # Check if already logged in
55
+ if not force and self.tokens and not self.tokens.is_expired():
56
+ logger.debug("Session still valid, skipping login")
57
+ return {"message": "Session already active"}
58
+
59
+ logger.info(f"Logging in to {self.config.cap_env.value} environment")
60
+
61
+ # Prepare login request
62
+ login_data = {
63
+ "identifier": self.config.cap_identifier,
64
+ "password": self.config.cap_api_password,
65
+ "encryptedPassword": False,
66
+ }
67
+
68
+ try:
69
+ # POST /session with special rate limit
70
+ response = await self.client.post(
71
+ "/session",
72
+ json=login_data,
73
+ rate_limit_type="session",
74
+ )
75
+
76
+ # Extract tokens from headers
77
+ cst = response.headers.get("CST")
78
+ x_security_token = response.headers.get("X-SECURITY-TOKEN")
79
+
80
+ if not cst or not x_security_token:
81
+ raise SessionError("Login response missing required tokens")
82
+
83
+ # Store tokens
84
+ self.tokens = SessionTokens(
85
+ cst=cst,
86
+ x_security_token=x_security_token,
87
+ )
88
+
89
+ # Update client tokens
90
+ self.client.session_tokens = self.tokens
91
+
92
+ # Parse response body
93
+ response_data = response.json()
94
+
95
+ # Extract account ID if present
96
+ if "currentAccountId" in response_data:
97
+ self.account_id = response_data["currentAccountId"]
98
+
99
+ logger.info(f"Login successful, account: {self.account_id}")
100
+
101
+ # Switch account if requested
102
+ target_account = account_id or self.config.cap_default_account_id
103
+ if target_account and target_account != self.account_id:
104
+ await self.switch_account(target_account)
105
+
106
+ return response_data
107
+
108
+ except Exception as e:
109
+ logger.error(f"Login failed: {e}")
110
+ self.tokens = None
111
+ self.client.session_tokens = None
112
+ raise
113
+
114
+ async def switch_account(self, account_id: str) -> dict[str, Any]:
115
+ """
116
+ Switch to a different account.
117
+
118
+ Args:
119
+ account_id: Target account ID
120
+
121
+ Returns:
122
+ Response data
123
+ """
124
+ if not self.tokens:
125
+ raise SessionError("Not logged in", code="SESSION_NOT_INITIALIZED")
126
+
127
+ logger.info(f"Switching to account: {account_id}")
128
+
129
+ response = await self.client.put(
130
+ "/session",
131
+ json={"accountId": account_id},
132
+ )
133
+
134
+ # Update stored account ID
135
+ self.account_id = account_id
136
+
137
+ return response.json()
138
+
139
+ async def ping(self) -> dict[str, Any]:
140
+ """
141
+ Keep session alive.
142
+
143
+ Returns:
144
+ Ping response
145
+ """
146
+ if not self.tokens:
147
+ raise SessionError("Not logged in", code="SESSION_NOT_INITIALIZED")
148
+
149
+ logger.debug("Pinging session")
150
+ response = await self.client.get("/ping")
151
+ return response.json() if response.text else {"status": "ok"}
152
+
153
+ async def logout(self) -> None:
154
+ """End session and clear tokens."""
155
+ if not self.tokens:
156
+ logger.debug("Not logged in, nothing to logout")
157
+ return
158
+
159
+ try:
160
+ logger.info("Logging out")
161
+ await self.client.delete("/session")
162
+ except Exception as e:
163
+ logger.warning(f"Logout request failed: {e}")
164
+ finally:
165
+ # Clear tokens regardless of response
166
+ self.tokens = None
167
+ self.account_id = None
168
+ self.client.session_tokens = None
169
+
170
+ async def ensure_logged_in(self) -> None:
171
+ """Ensure session is active, refresh if needed."""
172
+ if not self.tokens:
173
+ logger.info("No session, logging in")
174
+ await self.login()
175
+ return
176
+
177
+ if self.tokens.is_expired():
178
+ logger.info("Session expired, re-logging in")
179
+ await self.login(force=True)
180
+
181
+ def get_status(self) -> SessionStatus:
182
+ """Get current session status."""
183
+ if not self.tokens:
184
+ return SessionStatus(
185
+ env=self.config.cap_env.value,
186
+ base_url=self.config.base_url,
187
+ logged_in=False,
188
+ )
189
+
190
+ # Calculate expiry estimate
191
+ age = (datetime.utcnow() - self.tokens.last_used_at).total_seconds()
192
+ expires_in = max(0, int(540 - age)) # 9 minutes = 540 seconds
193
+
194
+ return SessionStatus(
195
+ env=self.config.cap_env.value,
196
+ base_url=self.config.base_url,
197
+ logged_in=True,
198
+ account_id=self.account_id,
199
+ last_used_at=self.tokens.last_used_at.isoformat() + "Z",
200
+ expires_in_s_estimate=expires_in,
201
+ )
202
+
203
+
204
+ # Global session manager instance
205
+ _session_manager: SessionManager | None = None
206
+
207
+
208
+ def get_session_manager() -> SessionManager:
209
+ """Get or create the global session manager instance."""
210
+ global _session_manager
211
+ if _session_manager is None:
212
+ _session_manager = SessionManager()
213
+ return _session_manager
214
+
215
+
216
+ def reset_session_manager() -> None:
217
+ """Reset the global session manager (mainly for testing)."""
218
+ global _session_manager
219
+ _session_manager = None