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.
- capital_cli/__init__.py +3 -0
- capital_cli/__main__.py +6 -0
- capital_cli/cli/__init__.py +1 -0
- capital_cli/cli/account_cmds.py +189 -0
- capital_cli/cli/app.py +88 -0
- capital_cli/cli/context.py +45 -0
- capital_cli/cli/live_guard.py +12 -0
- capital_cli/cli/market_cmds.py +165 -0
- capital_cli/cli/output.py +125 -0
- capital_cli/cli/runner.py +96 -0
- capital_cli/cli/session_cmds.py +127 -0
- capital_cli/cli/stream_cmds.py +263 -0
- capital_cli/cli/trade_cmds.py +549 -0
- capital_cli/cli/watchlist_cmds.py +132 -0
- capital_cli/core/__init__.py +1 -0
- capital_cli/core/config.py +152 -0
- capital_cli/core/errors.py +233 -0
- capital_cli/core/http_client.py +297 -0
- capital_cli/core/models.py +328 -0
- capital_cli/core/rate_limit.py +173 -0
- capital_cli/core/risk.py +417 -0
- capital_cli/core/session.py +219 -0
- capital_cli/core/state.py +97 -0
- capital_cli/core/utils.py +87 -0
- capital_cli/core/websocket_client.py +480 -0
- capitalcom_cli-0.4.0.dist-info/METADATA +433 -0
- capitalcom_cli-0.4.0.dist-info/RECORD +32 -0
- capitalcom_cli-0.4.0.dist-info/WHEEL +5 -0
- capitalcom_cli-0.4.0.dist-info/entry_points.txt +2 -0
- capitalcom_cli-0.4.0.dist-info/licenses/LICENSE +202 -0
- capitalcom_cli-0.4.0.dist-info/licenses/NOTICE +18 -0
- capitalcom_cli-0.4.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"""Configuration for the Capital.com CLI (env-file aware)."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import os
|
|
5
|
+
from enum import Enum
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from pydantic import Field, field_validator, model_validator
|
|
9
|
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class CapEnv(str, Enum):
|
|
13
|
+
"""Capital.com environment."""
|
|
14
|
+
|
|
15
|
+
DEMO = "demo"
|
|
16
|
+
LIVE = "live"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _resolve_env_file() -> str | None:
|
|
20
|
+
"""
|
|
21
|
+
Resolve which .env file to load.
|
|
22
|
+
|
|
23
|
+
Order: $CAP_ENV_FILE > ./.env > ~/.config/capital-cli/.env > None.
|
|
24
|
+
"""
|
|
25
|
+
explicit = os.environ.get("CAP_ENV_FILE")
|
|
26
|
+
if explicit:
|
|
27
|
+
return explicit
|
|
28
|
+
candidates = [
|
|
29
|
+
Path.cwd() / ".env",
|
|
30
|
+
Path.home() / ".config" / "capital-cli" / ".env",
|
|
31
|
+
]
|
|
32
|
+
for candidate in candidates:
|
|
33
|
+
if candidate.is_file():
|
|
34
|
+
return str(candidate)
|
|
35
|
+
return None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Config(BaseSettings):
|
|
39
|
+
"""Application configuration loaded from environment / .env file."""
|
|
40
|
+
|
|
41
|
+
model_config = SettingsConfigDict(
|
|
42
|
+
env_file_encoding="utf-8",
|
|
43
|
+
case_sensitive=False,
|
|
44
|
+
extra="ignore",
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
# Required credentials
|
|
48
|
+
cap_env: CapEnv = Field(default=CapEnv.DEMO, description="Environment: demo or live")
|
|
49
|
+
cap_api_key: str = Field(..., description="API Key from Capital.com")
|
|
50
|
+
cap_identifier: str = Field(..., description="Login email")
|
|
51
|
+
cap_api_password: str = Field(..., description="API Key custom password")
|
|
52
|
+
|
|
53
|
+
# Trading safety controls
|
|
54
|
+
cap_allow_trading: bool = Field(default=False)
|
|
55
|
+
cap_allowed_epics: str = Field(default="")
|
|
56
|
+
cap_max_position_size: float = Field(default=1.0, gt=0)
|
|
57
|
+
cap_max_working_order_size: float = Field(default=1.0, gt=0)
|
|
58
|
+
cap_max_open_positions: int = Field(default=3, ge=0)
|
|
59
|
+
cap_max_orders_per_day: int = Field(default=20, ge=0)
|
|
60
|
+
cap_require_explicit_confirm: bool = Field(default=True)
|
|
61
|
+
cap_dry_run: bool = Field(default=False)
|
|
62
|
+
|
|
63
|
+
# Optional account/session
|
|
64
|
+
cap_default_account_id: str | None = Field(default=None)
|
|
65
|
+
cap_http_timeout_s: float = Field(default=15.0, gt=0)
|
|
66
|
+
cap_log_level: str = Field(default="WARNING")
|
|
67
|
+
cap_ws_enabled: bool = Field(default=False)
|
|
68
|
+
|
|
69
|
+
# Internal defaults
|
|
70
|
+
cap_preview_cache_ttl_s: int = Field(default=120)
|
|
71
|
+
cap_ping_interval_s: int = Field(default=480)
|
|
72
|
+
|
|
73
|
+
@field_validator("cap_log_level")
|
|
74
|
+
@classmethod
|
|
75
|
+
def validate_log_level(cls, v: str) -> str:
|
|
76
|
+
valid = {"DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"}
|
|
77
|
+
upper_v = v.upper()
|
|
78
|
+
if upper_v not in valid:
|
|
79
|
+
raise ValueError(f"Invalid log level: {v}. Must be one of {valid}")
|
|
80
|
+
return upper_v
|
|
81
|
+
|
|
82
|
+
@model_validator(mode="after")
|
|
83
|
+
def validate_trading_config(self) -> "Config":
|
|
84
|
+
if self.cap_allow_trading and not self.cap_allowed_epics.strip():
|
|
85
|
+
raise ValueError(
|
|
86
|
+
"CAP_ALLOW_TRADING is true but CAP_ALLOWED_EPICS is empty. "
|
|
87
|
+
"Specify allowed EPICs (or 'ALL' for unrestricted)."
|
|
88
|
+
)
|
|
89
|
+
return self
|
|
90
|
+
|
|
91
|
+
@property
|
|
92
|
+
def base_url(self) -> str:
|
|
93
|
+
if self.cap_env == CapEnv.DEMO:
|
|
94
|
+
return "https://demo-api-capital.backend-capital.com"
|
|
95
|
+
return "https://api-capital.backend-capital.com"
|
|
96
|
+
|
|
97
|
+
@property
|
|
98
|
+
def api_base_url(self) -> str:
|
|
99
|
+
return f"{self.base_url}/api/v1"
|
|
100
|
+
|
|
101
|
+
@property
|
|
102
|
+
def ws_url(self) -> str:
|
|
103
|
+
return "wss://api-streaming-capital.backend-capital.com/connect"
|
|
104
|
+
|
|
105
|
+
@property
|
|
106
|
+
def allowed_epics_list(self) -> list[str]:
|
|
107
|
+
if not self.cap_allowed_epics.strip():
|
|
108
|
+
return []
|
|
109
|
+
return [e.strip() for e in self.cap_allowed_epics.split(",") if e.strip()]
|
|
110
|
+
|
|
111
|
+
def is_epic_allowed(self, epic: str) -> bool:
|
|
112
|
+
if not self.cap_allow_trading:
|
|
113
|
+
return False
|
|
114
|
+
allowed = self.allowed_epics_list
|
|
115
|
+
if not allowed:
|
|
116
|
+
return False
|
|
117
|
+
if allowed[0].upper() == "ALL":
|
|
118
|
+
return True
|
|
119
|
+
return epic.upper() in [e.upper() for e in allowed]
|
|
120
|
+
|
|
121
|
+
def setup_logging(self) -> None:
|
|
122
|
+
logging.basicConfig(
|
|
123
|
+
level=getattr(logging, self.cap_log_level),
|
|
124
|
+
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
|
125
|
+
datefmt="%Y-%m-%d %H:%M:%S",
|
|
126
|
+
)
|
|
127
|
+
logging.getLogger("httpx").setLevel(logging.WARNING)
|
|
128
|
+
logging.getLogger("websockets").setLevel(logging.WARNING)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
_config: Config | None = None
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def get_config() -> Config:
|
|
135
|
+
"""Get or lazily build the global config from the resolved env file."""
|
|
136
|
+
global _config
|
|
137
|
+
if _config is None:
|
|
138
|
+
_config = Config(_env_file=_resolve_env_file()) # type: ignore[call-arg]
|
|
139
|
+
_config.setup_logging()
|
|
140
|
+
return _config
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def set_config(config: Config) -> None:
|
|
144
|
+
"""Inject a pre-built config (used by tests and the CLI root callback)."""
|
|
145
|
+
global _config
|
|
146
|
+
_config = config
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def reset_config() -> None:
|
|
150
|
+
"""Reset the global config (forces re-read on next get_config())."""
|
|
151
|
+
global _config
|
|
152
|
+
_config = None
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
"""Error codes and exception handling for Capital.com CLI."""
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from .models import ToolResult
|
|
6
|
+
|
|
7
|
+
# ============================================================
|
|
8
|
+
# Error Codes (from spec section 16)
|
|
9
|
+
# ============================================================
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ErrorCode:
|
|
13
|
+
"""Standard error codes."""
|
|
14
|
+
|
|
15
|
+
# Configuration errors
|
|
16
|
+
CONFIG_MISSING = "CONFIG_MISSING"
|
|
17
|
+
CONFIG_INVALID = "CONFIG_INVALID"
|
|
18
|
+
|
|
19
|
+
# Trading safety errors
|
|
20
|
+
TRADING_DISABLED = "TRADING_DISABLED"
|
|
21
|
+
DRY_RUN_ENABLED = "DRY_RUN_ENABLED"
|
|
22
|
+
CONFIRM_REQUIRED = "CONFIRM_REQUIRED"
|
|
23
|
+
EPIC_NOT_ALLOWED = "EPIC_NOT_ALLOWED"
|
|
24
|
+
RISK_LIMIT = "RISK_LIMIT"
|
|
25
|
+
|
|
26
|
+
# Session errors
|
|
27
|
+
SESSION_EXPIRED = "SESSION_EXPIRED"
|
|
28
|
+
SESSION_NOT_INITIALIZED = "SESSION_NOT_INITIALIZED"
|
|
29
|
+
AUTH_FAILED = "AUTH_FAILED"
|
|
30
|
+
|
|
31
|
+
# Rate limiting
|
|
32
|
+
RATE_LIMITED_LOCAL = "RATE_LIMITED_LOCAL"
|
|
33
|
+
|
|
34
|
+
# Broker/upstream errors
|
|
35
|
+
BROKER_REJECTED = "BROKER_REJECTED"
|
|
36
|
+
UPSTREAM_ERROR = "UPSTREAM_ERROR"
|
|
37
|
+
UPSTREAM_TIMEOUT = "UPSTREAM_TIMEOUT"
|
|
38
|
+
|
|
39
|
+
# Preview/execution errors
|
|
40
|
+
PREVIEW_NOT_FOUND = "PREVIEW_NOT_FOUND"
|
|
41
|
+
PREVIEW_EXPIRED = "PREVIEW_EXPIRED"
|
|
42
|
+
PREVIEW_CHECKS_FAILED = "PREVIEW_CHECKS_FAILED"
|
|
43
|
+
|
|
44
|
+
# General errors
|
|
45
|
+
INVALID_REQUEST = "INVALID_REQUEST"
|
|
46
|
+
NOT_FOUND = "NOT_FOUND"
|
|
47
|
+
INTERNAL_ERROR = "INTERNAL_ERROR"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
# ============================================================
|
|
51
|
+
# Custom Exceptions
|
|
52
|
+
# ============================================================
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class CapitalCLIError(Exception):
|
|
56
|
+
"""Base exception for Capital CLI errors."""
|
|
57
|
+
|
|
58
|
+
def __init__(
|
|
59
|
+
self,
|
|
60
|
+
code: str,
|
|
61
|
+
message: str,
|
|
62
|
+
details: dict[str, Any] | None = None,
|
|
63
|
+
):
|
|
64
|
+
self.code = code
|
|
65
|
+
self.message = message
|
|
66
|
+
self.details = details or {}
|
|
67
|
+
super().__init__(message)
|
|
68
|
+
|
|
69
|
+
def to_tool_result(self) -> ToolResult:
|
|
70
|
+
"""Convert exception to ToolResult."""
|
|
71
|
+
return ToolResult.failure(code=self.code, message=self.message, details=self.details)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class ConfigError(CapitalCLIError):
|
|
75
|
+
"""Configuration error."""
|
|
76
|
+
|
|
77
|
+
def __init__(self, message: str, details: dict[str, Any] | None = None):
|
|
78
|
+
super().__init__(ErrorCode.CONFIG_INVALID, message, details)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class TradingDisabledError(CapitalCLIError):
|
|
82
|
+
"""Trading is disabled."""
|
|
83
|
+
|
|
84
|
+
def __init__(self, message: str = "Trading is disabled. Set CAP_ALLOW_TRADING=true to enable."):
|
|
85
|
+
super().__init__(ErrorCode.TRADING_DISABLED, message)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class DryRunError(CapitalCLIError):
|
|
89
|
+
"""Dry-run mode is enabled."""
|
|
90
|
+
|
|
91
|
+
def __init__(
|
|
92
|
+
self,
|
|
93
|
+
message: str = (
|
|
94
|
+
"Dry-run mode is enabled (CAP_DRY_RUN=true). "
|
|
95
|
+
"Set CAP_DRY_RUN=false to allow executions."
|
|
96
|
+
),
|
|
97
|
+
):
|
|
98
|
+
super().__init__(ErrorCode.DRY_RUN_ENABLED, message)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class ConfirmRequiredError(CapitalCLIError):
|
|
102
|
+
"""Explicit confirmation is required."""
|
|
103
|
+
|
|
104
|
+
def __init__(
|
|
105
|
+
self,
|
|
106
|
+
message: str = "Explicit confirmation required — pass --yes to proceed.",
|
|
107
|
+
):
|
|
108
|
+
super().__init__(ErrorCode.CONFIRM_REQUIRED, message)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class EpicNotAllowedError(CapitalCLIError):
|
|
112
|
+
"""Epic is not in the allowlist."""
|
|
113
|
+
|
|
114
|
+
def __init__(self, epic: str, allowed: list[str]):
|
|
115
|
+
allowed_str = ", ".join(allowed) if allowed else "none"
|
|
116
|
+
message = (
|
|
117
|
+
f"Epic '{epic}' is not in the allowlist (allowed: {allowed_str}). "
|
|
118
|
+
"Add it to CAP_ALLOWED_EPICS to trade it."
|
|
119
|
+
)
|
|
120
|
+
super().__init__(
|
|
121
|
+
ErrorCode.EPIC_NOT_ALLOWED,
|
|
122
|
+
message,
|
|
123
|
+
{"epic": epic, "allowed_epics": allowed},
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class RiskLimitError(CapitalCLIError):
|
|
128
|
+
"""Risk limit exceeded."""
|
|
129
|
+
|
|
130
|
+
def __init__(self, message: str, details: dict[str, Any] | None = None):
|
|
131
|
+
super().__init__(ErrorCode.RISK_LIMIT, message, details)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
class SessionError(CapitalCLIError):
|
|
135
|
+
"""Session-related error."""
|
|
136
|
+
|
|
137
|
+
def __init__(self, message: str, code: str = ErrorCode.SESSION_EXPIRED):
|
|
138
|
+
super().__init__(code, message)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class RateLimitError(CapitalCLIError):
|
|
142
|
+
"""Rate limit exceeded."""
|
|
143
|
+
|
|
144
|
+
def __init__(
|
|
145
|
+
self,
|
|
146
|
+
message: str = "Rate limit exceeded. Please slow down your requests.",
|
|
147
|
+
retry_after: float | None = None,
|
|
148
|
+
):
|
|
149
|
+
details = {"retry_after_seconds": retry_after} if retry_after else None
|
|
150
|
+
super().__init__(ErrorCode.RATE_LIMITED_LOCAL, message, details)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
class BrokerError(CapitalCLIError):
|
|
154
|
+
"""Broker rejected the request."""
|
|
155
|
+
|
|
156
|
+
def __init__(self, message: str, details: dict[str, Any] | None = None):
|
|
157
|
+
super().__init__(ErrorCode.BROKER_REJECTED, message, details)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
class UpstreamError(CapitalCLIError):
|
|
161
|
+
"""Upstream API error."""
|
|
162
|
+
|
|
163
|
+
def __init__(
|
|
164
|
+
self,
|
|
165
|
+
message: str,
|
|
166
|
+
status_code: int | None = None,
|
|
167
|
+
response_body: str | None = None,
|
|
168
|
+
):
|
|
169
|
+
details: dict[str, Any] = {}
|
|
170
|
+
if status_code is not None:
|
|
171
|
+
details["status_code"] = status_code
|
|
172
|
+
if response_body is not None:
|
|
173
|
+
details["response_body"] = response_body
|
|
174
|
+
super().__init__(ErrorCode.UPSTREAM_ERROR, message, details)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class PreviewError(CapitalCLIError):
|
|
178
|
+
"""Preview-related error."""
|
|
179
|
+
|
|
180
|
+
def __init__(self, message: str, code: str = ErrorCode.PREVIEW_NOT_FOUND):
|
|
181
|
+
super().__init__(code, message)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
# ============================================================
|
|
185
|
+
# Error Helper Functions
|
|
186
|
+
# ============================================================
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def handle_exception(exc: Exception) -> ToolResult:
|
|
190
|
+
"""Convert any exception to a ToolResult."""
|
|
191
|
+
if isinstance(exc, CapitalCLIError):
|
|
192
|
+
return exc.to_tool_result()
|
|
193
|
+
|
|
194
|
+
# Unhandled exception
|
|
195
|
+
import traceback
|
|
196
|
+
|
|
197
|
+
return ToolResult.failure(
|
|
198
|
+
code=ErrorCode.INTERNAL_ERROR,
|
|
199
|
+
message=f"Internal error: {str(exc)}",
|
|
200
|
+
details={"traceback": traceback.format_exc()},
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def redact_secrets(data: dict[str, Any], secret_keys: set[str] | None = None) -> dict[str, Any]:
|
|
205
|
+
"""Redact secret values from a dictionary."""
|
|
206
|
+
if secret_keys is None:
|
|
207
|
+
secret_keys = {
|
|
208
|
+
"cap_api_key",
|
|
209
|
+
"cap_api_password",
|
|
210
|
+
"password",
|
|
211
|
+
"encryptedPassword",
|
|
212
|
+
"cst",
|
|
213
|
+
"x_security_token",
|
|
214
|
+
"CST",
|
|
215
|
+
"X-SECURITY-TOKEN",
|
|
216
|
+
"X-CAP-API-KEY",
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
redacted: dict[str, Any] = {}
|
|
220
|
+
for key, value in data.items():
|
|
221
|
+
if any(secret in key.lower() for secret in ["password", "token", "key", "secret"]):
|
|
222
|
+
redacted[key] = "***REDACTED***"
|
|
223
|
+
elif isinstance(value, dict):
|
|
224
|
+
redacted[key] = redact_secrets(value, secret_keys)
|
|
225
|
+
elif isinstance(value, list):
|
|
226
|
+
redacted[key] = [
|
|
227
|
+
redact_secrets(item, secret_keys) if isinstance(item, dict) else item
|
|
228
|
+
for item in value
|
|
229
|
+
]
|
|
230
|
+
else:
|
|
231
|
+
redacted[key] = value
|
|
232
|
+
|
|
233
|
+
return redacted
|
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
"""HTTP client wrapper for Capital.com API."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from collections.abc import Awaitable, Callable
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
|
|
9
|
+
from capital_cli import __version__
|
|
10
|
+
|
|
11
|
+
from .config import get_config
|
|
12
|
+
from .errors import SessionError, UpstreamError, redact_secrets
|
|
13
|
+
from .models import SessionTokens
|
|
14
|
+
from .rate_limit import get_rate_limiter
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class CapitalClient:
|
|
20
|
+
"""HTTP client for Capital.com REST API."""
|
|
21
|
+
|
|
22
|
+
def __init__(self):
|
|
23
|
+
self.config = get_config()
|
|
24
|
+
self.rate_limiter = get_rate_limiter()
|
|
25
|
+
self.session_tokens: SessionTokens | None = None
|
|
26
|
+
self._client: httpx.AsyncClient | None = None
|
|
27
|
+
self._relogin: Callable[[], Awaitable[None]] | None = None
|
|
28
|
+
|
|
29
|
+
def set_relogin(self, callback: Callable[[], Awaitable[None]]) -> None:
|
|
30
|
+
"""Register an async callback used to force a re-login on auth expiry."""
|
|
31
|
+
self._relogin = callback
|
|
32
|
+
|
|
33
|
+
def _get_client(self) -> httpx.AsyncClient:
|
|
34
|
+
"""Get or create HTTP client."""
|
|
35
|
+
if self._client is None:
|
|
36
|
+
self._client = httpx.AsyncClient(
|
|
37
|
+
base_url=self.config.api_base_url,
|
|
38
|
+
timeout=httpx.Timeout(self.config.cap_http_timeout_s),
|
|
39
|
+
headers={
|
|
40
|
+
"Content-Type": "application/json",
|
|
41
|
+
"Accept": "application/json",
|
|
42
|
+
"User-Agent": (
|
|
43
|
+
f"capitalcom-cli/{__version__} "
|
|
44
|
+
"(+https://github.com/SimonTarara62/capitalcom-cli)"
|
|
45
|
+
),
|
|
46
|
+
},
|
|
47
|
+
)
|
|
48
|
+
return self._client
|
|
49
|
+
|
|
50
|
+
async def close(self) -> None:
|
|
51
|
+
"""Close HTTP client."""
|
|
52
|
+
if self._client is not None:
|
|
53
|
+
await self._client.aclose()
|
|
54
|
+
self._client = None
|
|
55
|
+
|
|
56
|
+
def _get_auth_headers(self) -> dict[str, str]:
|
|
57
|
+
"""Get authentication headers."""
|
|
58
|
+
headers: dict[str, str] = {}
|
|
59
|
+
|
|
60
|
+
# Add API key header for session creation
|
|
61
|
+
headers["X-CAP-API-KEY"] = self.config.cap_api_key
|
|
62
|
+
|
|
63
|
+
# Add session tokens if available
|
|
64
|
+
if self.session_tokens:
|
|
65
|
+
headers["CST"] = self.session_tokens.cst
|
|
66
|
+
headers["X-SECURITY-TOKEN"] = self.session_tokens.x_security_token
|
|
67
|
+
self.session_tokens.update_last_used()
|
|
68
|
+
|
|
69
|
+
return headers
|
|
70
|
+
|
|
71
|
+
def _log_request(self, method: str, url: str, **kwargs: Any) -> None:
|
|
72
|
+
"""Log HTTP request (with secret redaction)."""
|
|
73
|
+
if logger.isEnabledFor(logging.DEBUG):
|
|
74
|
+
safe_kwargs = {
|
|
75
|
+
k: redact_secrets(v) if isinstance(v, dict) else v for k, v in kwargs.items()
|
|
76
|
+
}
|
|
77
|
+
logger.debug(f"Request: {method} {url} {safe_kwargs}")
|
|
78
|
+
|
|
79
|
+
def _log_response(self, response: httpx.Response) -> None:
|
|
80
|
+
"""Log HTTP response (with secret redaction)."""
|
|
81
|
+
if logger.isEnabledFor(logging.DEBUG):
|
|
82
|
+
try:
|
|
83
|
+
body = response.json()
|
|
84
|
+
safe_body = redact_secrets(body) if isinstance(body, dict) else body
|
|
85
|
+
logger.debug(f"Response: {response.status_code} {safe_body}")
|
|
86
|
+
except Exception:
|
|
87
|
+
logger.debug(f"Response: {response.status_code} (non-JSON)")
|
|
88
|
+
|
|
89
|
+
async def request(
|
|
90
|
+
self,
|
|
91
|
+
method: str,
|
|
92
|
+
path: str,
|
|
93
|
+
*,
|
|
94
|
+
json: dict[str, Any] | None = None,
|
|
95
|
+
params: dict[str, Any] | None = None,
|
|
96
|
+
rate_limit_type: str = "global",
|
|
97
|
+
retry_on_auth_error: bool = True,
|
|
98
|
+
max_retries: int = 3,
|
|
99
|
+
) -> httpx.Response:
|
|
100
|
+
"""
|
|
101
|
+
Make HTTP request with rate limiting and error handling.
|
|
102
|
+
|
|
103
|
+
Args:
|
|
104
|
+
method: HTTP method
|
|
105
|
+
path: API path (e.g., "/markets")
|
|
106
|
+
json: JSON body
|
|
107
|
+
params: Query parameters
|
|
108
|
+
rate_limit_type: Type of rate limiting ("global", "session", "trading")
|
|
109
|
+
retry_on_auth_error: Whether to retry on auth errors
|
|
110
|
+
max_retries: Max retries for safe operations (GETs)
|
|
111
|
+
|
|
112
|
+
Returns:
|
|
113
|
+
HTTP response
|
|
114
|
+
|
|
115
|
+
Raises:
|
|
116
|
+
UpstreamError: On HTTP errors
|
|
117
|
+
SessionError: On auth errors
|
|
118
|
+
"""
|
|
119
|
+
# Acquire rate limit token
|
|
120
|
+
if rate_limit_type == "session":
|
|
121
|
+
acquired = await self.rate_limiter.acquire_session()
|
|
122
|
+
elif rate_limit_type == "trading":
|
|
123
|
+
acquired = await self.rate_limiter.acquire_trading()
|
|
124
|
+
else:
|
|
125
|
+
acquired = await self.rate_limiter.acquire_global()
|
|
126
|
+
|
|
127
|
+
if not acquired:
|
|
128
|
+
from .errors import RateLimitError
|
|
129
|
+
|
|
130
|
+
raise RateLimitError("Rate limit timeout")
|
|
131
|
+
|
|
132
|
+
# Prepare request
|
|
133
|
+
client = self._get_client()
|
|
134
|
+
url = path
|
|
135
|
+
|
|
136
|
+
self._log_request(method, url, json=json, params=params)
|
|
137
|
+
|
|
138
|
+
# Retry logic
|
|
139
|
+
last_exception: Exception | None = None
|
|
140
|
+
auth_retried = False
|
|
141
|
+
for attempt in range(max_retries):
|
|
142
|
+
headers = self._get_auth_headers()
|
|
143
|
+
try:
|
|
144
|
+
response = await client.request(
|
|
145
|
+
method=method,
|
|
146
|
+
url=url,
|
|
147
|
+
json=json,
|
|
148
|
+
params=params,
|
|
149
|
+
headers=headers,
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
self._log_response(response)
|
|
153
|
+
|
|
154
|
+
# Handle auth errors
|
|
155
|
+
if response.status_code in (401, 403):
|
|
156
|
+
if (
|
|
157
|
+
retry_on_auth_error
|
|
158
|
+
and not auth_retried
|
|
159
|
+
and self._relogin is not None
|
|
160
|
+
and method.upper() == "GET"
|
|
161
|
+
):
|
|
162
|
+
auth_retried = True
|
|
163
|
+
logger.warning("Auth error on GET; re-logging in and retrying once")
|
|
164
|
+
await self._relogin()
|
|
165
|
+
continue
|
|
166
|
+
raise SessionError(
|
|
167
|
+
f"Authentication failed: {response.status_code}",
|
|
168
|
+
code="AUTH_FAILED",
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
# Handle other errors
|
|
172
|
+
if response.status_code >= 400:
|
|
173
|
+
error_body = None
|
|
174
|
+
error_message = response.reason_phrase or "Error"
|
|
175
|
+
|
|
176
|
+
try:
|
|
177
|
+
error_body = response.text
|
|
178
|
+
# Try to extract error from JSON response
|
|
179
|
+
if error_body:
|
|
180
|
+
try:
|
|
181
|
+
error_json = response.json()
|
|
182
|
+
# Capital.com returns {"errorCode": "message"}
|
|
183
|
+
if isinstance(error_json, dict) and "errorCode" in error_json:
|
|
184
|
+
error_message = error_json["errorCode"]
|
|
185
|
+
# Or it might be {"error": "...", "message": "..."}
|
|
186
|
+
elif isinstance(error_json, dict):
|
|
187
|
+
if "message" in error_json:
|
|
188
|
+
error_message = error_json["message"]
|
|
189
|
+
elif "error" in error_json:
|
|
190
|
+
error_message = error_json["error"]
|
|
191
|
+
else:
|
|
192
|
+
# Use full JSON as string
|
|
193
|
+
error_message = str(error_json)
|
|
194
|
+
except Exception:
|
|
195
|
+
# If JSON parsing fails, use raw text (truncate long responses)
|
|
196
|
+
if len(error_body) > 200:
|
|
197
|
+
error_message = error_body[:200] + "..."
|
|
198
|
+
else:
|
|
199
|
+
error_message = error_body
|
|
200
|
+
except Exception:
|
|
201
|
+
pass
|
|
202
|
+
|
|
203
|
+
raise UpstreamError(
|
|
204
|
+
f"HTTP {response.status_code}: {error_message}",
|
|
205
|
+
status_code=response.status_code,
|
|
206
|
+
response_body=error_body,
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
return response
|
|
210
|
+
|
|
211
|
+
except (httpx.TimeoutException, httpx.ConnectError) as e:
|
|
212
|
+
last_exception = e
|
|
213
|
+
logger.warning(f"Request timeout/error (attempt {attempt + 1}/{max_retries}): {e}")
|
|
214
|
+
|
|
215
|
+
# Only retry safe operations (GETs)
|
|
216
|
+
if method.upper() != "GET" or attempt >= max_retries - 1:
|
|
217
|
+
break
|
|
218
|
+
|
|
219
|
+
# Exponential backoff
|
|
220
|
+
import asyncio
|
|
221
|
+
|
|
222
|
+
await asyncio.sleep(min(2**attempt, 10))
|
|
223
|
+
|
|
224
|
+
# All retries failed
|
|
225
|
+
if last_exception:
|
|
226
|
+
raise UpstreamError(
|
|
227
|
+
f"Request failed after {max_retries} attempts: {str(last_exception)}"
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
raise UpstreamError("Request failed for unknown reason")
|
|
231
|
+
|
|
232
|
+
async def get(
|
|
233
|
+
self, path: str, *, params: dict[str, Any] | None = None
|
|
234
|
+
) -> httpx.Response:
|
|
235
|
+
"""Make GET request."""
|
|
236
|
+
return await self.request("GET", path, params=params)
|
|
237
|
+
|
|
238
|
+
async def post(
|
|
239
|
+
self,
|
|
240
|
+
path: str,
|
|
241
|
+
*,
|
|
242
|
+
json: dict[str, Any] | None = None,
|
|
243
|
+
rate_limit_type: str = "global",
|
|
244
|
+
) -> httpx.Response:
|
|
245
|
+
"""Make POST request."""
|
|
246
|
+
return await self.request(
|
|
247
|
+
"POST",
|
|
248
|
+
path,
|
|
249
|
+
json=json,
|
|
250
|
+
rate_limit_type=rate_limit_type,
|
|
251
|
+
max_retries=1, # No retries for POSTs
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
async def put(
|
|
255
|
+
self, path: str, *, json: dict[str, Any] | None = None
|
|
256
|
+
) -> httpx.Response:
|
|
257
|
+
"""Make PUT request."""
|
|
258
|
+
return await self.request(
|
|
259
|
+
"PUT",
|
|
260
|
+
path,
|
|
261
|
+
json=json,
|
|
262
|
+
max_retries=1, # No retries for PUTs
|
|
263
|
+
)
|
|
264
|
+
|
|
265
|
+
async def delete(self, path: str) -> httpx.Response:
|
|
266
|
+
"""Make DELETE request."""
|
|
267
|
+
return await self.request(
|
|
268
|
+
"DELETE",
|
|
269
|
+
path,
|
|
270
|
+
max_retries=1, # No retries for DELETEs
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
# Global client instance
|
|
275
|
+
_client: CapitalClient | None = None
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def get_client() -> CapitalClient:
|
|
279
|
+
"""Get or create the global client instance."""
|
|
280
|
+
global _client
|
|
281
|
+
if _client is None:
|
|
282
|
+
_client = CapitalClient()
|
|
283
|
+
return _client
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
async def close_client() -> None:
|
|
287
|
+
"""Close the global client."""
|
|
288
|
+
global _client
|
|
289
|
+
if _client is not None:
|
|
290
|
+
await _client.close()
|
|
291
|
+
_client = None
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def reset_client() -> None:
|
|
295
|
+
"""Reset the global client (mainly for testing)."""
|
|
296
|
+
global _client
|
|
297
|
+
_client = None
|