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,97 @@
|
|
|
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
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import contextlib
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from .models import PreviewResult
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _default_state_path() -> Path:
|
|
21
|
+
override = os.environ.get("CAPCTL_STATE_FILE")
|
|
22
|
+
if override:
|
|
23
|
+
return Path(override)
|
|
24
|
+
return Path.home() / ".config" / "capital-cli" / "state.json"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class StateStore:
|
|
28
|
+
"""Tiny JSON-file-backed store for previews and the daily order counter."""
|
|
29
|
+
|
|
30
|
+
def __init__(self, path: Path | None = None) -> None:
|
|
31
|
+
self.path = path or _default_state_path()
|
|
32
|
+
|
|
33
|
+
def _read(self) -> dict[str, Any]:
|
|
34
|
+
try:
|
|
35
|
+
return json.loads(self.path.read_text())
|
|
36
|
+
except (OSError, json.JSONDecodeError):
|
|
37
|
+
return {}
|
|
38
|
+
|
|
39
|
+
def _write(self, data: dict[str, Any]) -> None:
|
|
40
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
41
|
+
tmp = self.path.with_name(self.path.name + ".tmp")
|
|
42
|
+
tmp.write_text(json.dumps(data, default=str))
|
|
43
|
+
tmp.replace(self.path)
|
|
44
|
+
with contextlib.suppress(OSError):
|
|
45
|
+
self.path.chmod(0o600)
|
|
46
|
+
|
|
47
|
+
# ----- previews -----
|
|
48
|
+
|
|
49
|
+
def save_preview(self, preview: PreviewResult) -> None:
|
|
50
|
+
data = self._read()
|
|
51
|
+
previews = data.setdefault("previews", {})
|
|
52
|
+
previews[preview.preview_id] = json.loads(preview.model_dump_json())
|
|
53
|
+
self._write(data)
|
|
54
|
+
|
|
55
|
+
def load_preview(self, preview_id: str) -> PreviewResult | None:
|
|
56
|
+
raw = self._read().get("previews", {}).get(preview_id)
|
|
57
|
+
if raw is None:
|
|
58
|
+
return None
|
|
59
|
+
try:
|
|
60
|
+
return PreviewResult.model_validate(raw)
|
|
61
|
+
except Exception: # noqa: BLE001 - corrupt entry is equivalent to missing
|
|
62
|
+
return None
|
|
63
|
+
|
|
64
|
+
def delete_preview(self, preview_id: str) -> None:
|
|
65
|
+
data = self._read()
|
|
66
|
+
if data.get("previews", {}).pop(preview_id, None) is not None:
|
|
67
|
+
self._write(data)
|
|
68
|
+
|
|
69
|
+
# ----- daily order counter -----
|
|
70
|
+
|
|
71
|
+
def get_order_count(self, date: str) -> int:
|
|
72
|
+
counter = self._read().get("order_counter", {})
|
|
73
|
+
return counter.get("count", 0) if counter.get("date") == date else 0
|
|
74
|
+
|
|
75
|
+
def increment_order_count(self, date: str) -> None:
|
|
76
|
+
data = self._read()
|
|
77
|
+
counter = data.get("order_counter", {})
|
|
78
|
+
count = counter.get("count", 0) if counter.get("date") == date else 0
|
|
79
|
+
data["order_counter"] = {"date": date, "count": count + 1}
|
|
80
|
+
self._write(data)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
_state_store: StateStore | None = None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def get_state_store() -> StateStore:
|
|
87
|
+
"""Get or create the global state store instance."""
|
|
88
|
+
global _state_store
|
|
89
|
+
if _state_store is None:
|
|
90
|
+
_state_store = StateStore()
|
|
91
|
+
return _state_store
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def reset_state_store() -> None:
|
|
95
|
+
"""Reset the global state store (mainly for testing)."""
|
|
96
|
+
global _state_store
|
|
97
|
+
_state_store = None
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Utility functions for Capital.com CLI."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from typing import Any, TypeVar
|
|
6
|
+
|
|
7
|
+
T = TypeVar("T")
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
async def poll_until(
|
|
11
|
+
fn: Callable[[], Any],
|
|
12
|
+
condition: Callable[[Any], bool],
|
|
13
|
+
*,
|
|
14
|
+
timeout_s: float = 15.0,
|
|
15
|
+
poll_interval_ms: int = 500,
|
|
16
|
+
initial_delay_ms: int = 200,
|
|
17
|
+
) -> Any | None:
|
|
18
|
+
"""
|
|
19
|
+
Poll a function until a condition is met or timeout.
|
|
20
|
+
|
|
21
|
+
Args:
|
|
22
|
+
fn: Async function to call
|
|
23
|
+
condition: Condition function that checks the result
|
|
24
|
+
timeout_s: Timeout in seconds
|
|
25
|
+
poll_interval_ms: Poll interval in milliseconds
|
|
26
|
+
initial_delay_ms: Initial delay before first poll
|
|
27
|
+
|
|
28
|
+
Returns:
|
|
29
|
+
Result if condition met, None if timeout
|
|
30
|
+
"""
|
|
31
|
+
import time
|
|
32
|
+
|
|
33
|
+
start_time = time.monotonic()
|
|
34
|
+
|
|
35
|
+
# Initial delay
|
|
36
|
+
if initial_delay_ms > 0:
|
|
37
|
+
await asyncio.sleep(initial_delay_ms / 1000.0)
|
|
38
|
+
|
|
39
|
+
attempt = 0
|
|
40
|
+
while True:
|
|
41
|
+
elapsed = time.monotonic() - start_time
|
|
42
|
+
if elapsed >= timeout_s:
|
|
43
|
+
return None
|
|
44
|
+
|
|
45
|
+
try:
|
|
46
|
+
result = await fn()
|
|
47
|
+
if condition(result):
|
|
48
|
+
return result
|
|
49
|
+
except Exception:
|
|
50
|
+
# Continue polling on errors
|
|
51
|
+
pass
|
|
52
|
+
|
|
53
|
+
# Wait before next attempt
|
|
54
|
+
await asyncio.sleep(poll_interval_ms / 1000.0)
|
|
55
|
+
attempt += 1
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def format_iso_datetime(dt: Any | None) -> str | None:
|
|
59
|
+
"""Format datetime to ISO 8601 string."""
|
|
60
|
+
if dt is None:
|
|
61
|
+
return None
|
|
62
|
+
if isinstance(dt, str):
|
|
63
|
+
return dt
|
|
64
|
+
try:
|
|
65
|
+
from datetime import datetime
|
|
66
|
+
|
|
67
|
+
if isinstance(dt, datetime):
|
|
68
|
+
return dt.isoformat() + "Z"
|
|
69
|
+
except Exception:
|
|
70
|
+
pass
|
|
71
|
+
return str(dt)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def parse_float_safe(value: Any, default: float = 0.0) -> float:
|
|
75
|
+
"""Safely parse a value to float."""
|
|
76
|
+
try:
|
|
77
|
+
return float(value)
|
|
78
|
+
except (TypeError, ValueError):
|
|
79
|
+
return default
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def parse_int_safe(value: Any, default: int = 0) -> int:
|
|
83
|
+
"""Safely parse a value to int."""
|
|
84
|
+
try:
|
|
85
|
+
return int(value)
|
|
86
|
+
except (TypeError, ValueError):
|
|
87
|
+
return default
|
|
@@ -0,0 +1,480 @@
|
|
|
1
|
+
"""WebSocket client for Capital.com streaming API."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import json
|
|
5
|
+
import logging
|
|
6
|
+
from collections.abc import AsyncIterator
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
from typing import Any, Optional
|
|
9
|
+
|
|
10
|
+
import websockets
|
|
11
|
+
from websockets.asyncio.client import ClientConnection
|
|
12
|
+
|
|
13
|
+
from .config import get_config
|
|
14
|
+
from .errors import SessionError, UpstreamError
|
|
15
|
+
from .models import OHLCBar, PriceTick
|
|
16
|
+
from .session import get_session_manager
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger(__name__)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _ms_to_iso(ms: Any) -> str:
|
|
22
|
+
"""Convert an epoch-milliseconds value to an ISO 8601 'Z' timestamp."""
|
|
23
|
+
if ms is None:
|
|
24
|
+
return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
|
25
|
+
try:
|
|
26
|
+
return datetime.fromtimestamp(float(ms) / 1000, tz=timezone.utc).isoformat().replace(
|
|
27
|
+
"+00:00", "Z"
|
|
28
|
+
)
|
|
29
|
+
except (TypeError, ValueError, OSError, OverflowError):
|
|
30
|
+
return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# Singleton instance
|
|
34
|
+
_websocket_client: Optional["WebSocketClient"] = None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def get_websocket_client() -> "WebSocketClient":
|
|
38
|
+
"""Get or create WebSocket client singleton."""
|
|
39
|
+
global _websocket_client
|
|
40
|
+
if _websocket_client is None:
|
|
41
|
+
_websocket_client = WebSocketClient()
|
|
42
|
+
return _websocket_client
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class WebSocketClient:
|
|
46
|
+
"""
|
|
47
|
+
WebSocket client for Capital.com streaming API.
|
|
48
|
+
|
|
49
|
+
Handles real-time price streaming with authentication, subscription management,
|
|
50
|
+
and automatic reconnection.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
def __init__(self):
|
|
54
|
+
self.config = get_config()
|
|
55
|
+
self.session_manager = get_session_manager()
|
|
56
|
+
self._ws: ClientConnection | None = None
|
|
57
|
+
self._subscribed_epics: set[str] = set()
|
|
58
|
+
self._subscribed_ohlc: set[str] = set()
|
|
59
|
+
self._ohlc_params: tuple[list[str], list[str], str] | None = None
|
|
60
|
+
self._last_ping: datetime | None = None
|
|
61
|
+
|
|
62
|
+
async def __aenter__(self) -> "WebSocketClient":
|
|
63
|
+
"""Async context manager entry."""
|
|
64
|
+
await self.connect()
|
|
65
|
+
return self
|
|
66
|
+
|
|
67
|
+
async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
|
|
68
|
+
"""Async context manager exit."""
|
|
69
|
+
await self.close()
|
|
70
|
+
|
|
71
|
+
async def connect(self) -> None:
|
|
72
|
+
"""
|
|
73
|
+
Connect to Capital.com WebSocket API.
|
|
74
|
+
|
|
75
|
+
Raises:
|
|
76
|
+
SessionError: If WebSocket is disabled or authentication fails
|
|
77
|
+
UpstreamError: If connection fails
|
|
78
|
+
"""
|
|
79
|
+
if not self.config.cap_ws_enabled:
|
|
80
|
+
raise SessionError(
|
|
81
|
+
"WebSocket streaming is disabled. Set CAP_WS_ENABLED=true to enable."
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
# Ensure we have valid session tokens
|
|
85
|
+
await self.session_manager.ensure_logged_in()
|
|
86
|
+
status = self.session_manager.get_status()
|
|
87
|
+
|
|
88
|
+
if not status.logged_in or not self.session_manager.client.session_tokens:
|
|
89
|
+
raise SessionError("Not logged in. Cannot establish WebSocket connection.")
|
|
90
|
+
|
|
91
|
+
tokens = self.session_manager.client.session_tokens
|
|
92
|
+
ws_url = self.config.ws_url
|
|
93
|
+
|
|
94
|
+
try:
|
|
95
|
+
logger.info(f"Connecting to WebSocket: {ws_url}")
|
|
96
|
+
|
|
97
|
+
# Connect with authentication headers
|
|
98
|
+
self._ws = await websockets.connect(
|
|
99
|
+
ws_url,
|
|
100
|
+
additional_headers={
|
|
101
|
+
"CST": tokens.cst,
|
|
102
|
+
"X-SECURITY-TOKEN": tokens.x_security_token,
|
|
103
|
+
},
|
|
104
|
+
ping_interval=None, # We'll handle pings manually
|
|
105
|
+
close_timeout=5,
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
self._last_ping = datetime.now(timezone.utc)
|
|
109
|
+
logger.info("WebSocket connected successfully")
|
|
110
|
+
|
|
111
|
+
except Exception as e:
|
|
112
|
+
logger.error(f"WebSocket connection failed: {e}")
|
|
113
|
+
raise UpstreamError(f"Failed to connect to WebSocket: {e}") from e
|
|
114
|
+
|
|
115
|
+
async def close(self) -> None:
|
|
116
|
+
"""Close WebSocket connection."""
|
|
117
|
+
if self._ws:
|
|
118
|
+
logger.info("Closing WebSocket connection")
|
|
119
|
+
await self._ws.close()
|
|
120
|
+
self._ws = None
|
|
121
|
+
self._subscribed_epics.clear()
|
|
122
|
+
self._subscribed_ohlc.clear()
|
|
123
|
+
self._ohlc_params = None
|
|
124
|
+
self._last_ping = None
|
|
125
|
+
|
|
126
|
+
async def subscribe(self, epics: list[str]) -> None:
|
|
127
|
+
"""
|
|
128
|
+
Subscribe to price updates for given EPICs.
|
|
129
|
+
|
|
130
|
+
Args:
|
|
131
|
+
epics: List of market EPICs (max 40 per Capital.com limits)
|
|
132
|
+
|
|
133
|
+
Raises:
|
|
134
|
+
ValueError: If too many EPICs requested
|
|
135
|
+
SessionError: If not connected
|
|
136
|
+
"""
|
|
137
|
+
if len(epics) > 40:
|
|
138
|
+
raise ValueError(f"Cannot subscribe to more than 40 EPICs (requested: {len(epics)})")
|
|
139
|
+
|
|
140
|
+
if not self._ws:
|
|
141
|
+
raise SessionError("WebSocket not connected. Call connect() first.")
|
|
142
|
+
|
|
143
|
+
tokens = self.session_manager.client.session_tokens
|
|
144
|
+
if not tokens:
|
|
145
|
+
raise SessionError("Not logged in. Cannot subscribe.")
|
|
146
|
+
|
|
147
|
+
# Capital.com streaming API: a single marketData.subscribe message
|
|
148
|
+
# carrying the session tokens and the full list of EPICs.
|
|
149
|
+
subscribe_msg = {
|
|
150
|
+
"destination": "marketData.subscribe",
|
|
151
|
+
"correlationId": "1",
|
|
152
|
+
"cst": tokens.cst,
|
|
153
|
+
"securityToken": tokens.x_security_token,
|
|
154
|
+
"payload": {"epics": epics},
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
try:
|
|
158
|
+
await self._ws.send(json.dumps(subscribe_msg))
|
|
159
|
+
self._subscribed_epics.update(epics)
|
|
160
|
+
logger.debug(f"Subscribed to {epics}")
|
|
161
|
+
except Exception as e:
|
|
162
|
+
logger.error(f"Failed to subscribe to {epics}: {e}")
|
|
163
|
+
raise UpstreamError(f"Subscription failed for {epics}: {e}") from e
|
|
164
|
+
|
|
165
|
+
async def unsubscribe(self, epics: list[str]) -> None:
|
|
166
|
+
"""
|
|
167
|
+
Unsubscribe from price updates.
|
|
168
|
+
|
|
169
|
+
Args:
|
|
170
|
+
epics: List of market EPICs to unsubscribe from
|
|
171
|
+
"""
|
|
172
|
+
if not self._ws:
|
|
173
|
+
return
|
|
174
|
+
|
|
175
|
+
to_remove = [epic for epic in epics if epic in self._subscribed_epics]
|
|
176
|
+
if not to_remove:
|
|
177
|
+
return
|
|
178
|
+
|
|
179
|
+
tokens = self.session_manager.client.session_tokens
|
|
180
|
+
if not tokens:
|
|
181
|
+
return
|
|
182
|
+
|
|
183
|
+
unsubscribe_msg = {
|
|
184
|
+
"destination": "marketData.unsubscribe",
|
|
185
|
+
"correlationId": "2",
|
|
186
|
+
"cst": tokens.cst,
|
|
187
|
+
"securityToken": tokens.x_security_token,
|
|
188
|
+
"payload": {"epics": to_remove},
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
try:
|
|
192
|
+
await self._ws.send(json.dumps(unsubscribe_msg))
|
|
193
|
+
for epic in to_remove:
|
|
194
|
+
self._subscribed_epics.discard(epic)
|
|
195
|
+
logger.debug(f"Unsubscribed from {to_remove}")
|
|
196
|
+
except Exception as e:
|
|
197
|
+
logger.warning(f"Failed to unsubscribe from {to_remove}: {e}")
|
|
198
|
+
|
|
199
|
+
async def subscribe_ohlc(
|
|
200
|
+
self, epics: list[str], resolutions: list[str], bar_type: str = "classic"
|
|
201
|
+
) -> None:
|
|
202
|
+
"""Subscribe to OHLC candlestick updates for the given EPICs/resolutions."""
|
|
203
|
+
if len(epics) > 40:
|
|
204
|
+
raise ValueError(f"Cannot subscribe to more than 40 EPICs (requested: {len(epics)})")
|
|
205
|
+
if not self._ws:
|
|
206
|
+
raise SessionError("WebSocket not connected. Call connect() first.")
|
|
207
|
+
tokens = self.session_manager.client.session_tokens
|
|
208
|
+
if not tokens:
|
|
209
|
+
raise SessionError("Not logged in. Cannot subscribe.")
|
|
210
|
+
|
|
211
|
+
msg = {
|
|
212
|
+
"destination": "OHLCMarketData.subscribe",
|
|
213
|
+
"correlationId": "3",
|
|
214
|
+
"cst": tokens.cst,
|
|
215
|
+
"securityToken": tokens.x_security_token,
|
|
216
|
+
"payload": {"epics": epics, "resolutions": resolutions, "type": bar_type},
|
|
217
|
+
}
|
|
218
|
+
try:
|
|
219
|
+
await self._ws.send(json.dumps(msg))
|
|
220
|
+
self._ohlc_params = (epics, resolutions, bar_type)
|
|
221
|
+
for epic in epics:
|
|
222
|
+
for res in resolutions:
|
|
223
|
+
self._subscribed_ohlc.add(f"{epic}:{res}:{bar_type}")
|
|
224
|
+
logger.debug(f"Subscribed OHLC {epics} {resolutions} {bar_type}")
|
|
225
|
+
except Exception as e:
|
|
226
|
+
logger.error(f"Failed to subscribe OHLC {epics}: {e}")
|
|
227
|
+
raise UpstreamError(f"OHLC subscription failed for {epics}: {e}") from e
|
|
228
|
+
|
|
229
|
+
async def unsubscribe_ohlc(self) -> None:
|
|
230
|
+
"""Unsubscribe from all current OHLC subscriptions."""
|
|
231
|
+
if not self._ws or not self._ohlc_params:
|
|
232
|
+
return
|
|
233
|
+
tokens = self.session_manager.client.session_tokens
|
|
234
|
+
if not tokens:
|
|
235
|
+
return
|
|
236
|
+
epics, resolutions, bar_type = self._ohlc_params
|
|
237
|
+
msg = {
|
|
238
|
+
"destination": "OHLCMarketData.unsubscribe",
|
|
239
|
+
"correlationId": "4",
|
|
240
|
+
"cst": tokens.cst,
|
|
241
|
+
"securityToken": tokens.x_security_token,
|
|
242
|
+
"payload": {"epics": epics, "resolutions": resolutions, "types": [bar_type]},
|
|
243
|
+
}
|
|
244
|
+
try:
|
|
245
|
+
await self._ws.send(json.dumps(msg))
|
|
246
|
+
self._subscribed_ohlc.clear()
|
|
247
|
+
self._ohlc_params = None
|
|
248
|
+
logger.debug("Unsubscribed OHLC")
|
|
249
|
+
except Exception as e: # noqa: BLE001 - unsubscribe failure is non-fatal
|
|
250
|
+
logger.warning(f"Failed to unsubscribe OHLC: {e}")
|
|
251
|
+
|
|
252
|
+
def _parse_ohlc(self, message: str | bytes) -> OHLCBar | None:
|
|
253
|
+
"""Parse an OHLC candlestick event message; return None for anything else."""
|
|
254
|
+
try:
|
|
255
|
+
data = json.loads(message)
|
|
256
|
+
except (json.JSONDecodeError, ValueError):
|
|
257
|
+
return None
|
|
258
|
+
if not isinstance(data, dict) or data.get("destination") != "ohlc.event":
|
|
259
|
+
return None
|
|
260
|
+
raw_payload = data.get("payload")
|
|
261
|
+
payload: dict[str, Any] = raw_payload if isinstance(raw_payload, dict) else data
|
|
262
|
+
epic = payload.get("epic")
|
|
263
|
+
if not epic or not all(k in payload for k in ("o", "h", "l", "c")):
|
|
264
|
+
return None
|
|
265
|
+
try:
|
|
266
|
+
return OHLCBar(
|
|
267
|
+
epic=epic,
|
|
268
|
+
resolution=str(payload.get("resolution", "MINUTE")),
|
|
269
|
+
type=str(payload.get("type", "classic")),
|
|
270
|
+
price_type=str(payload.get("priceType", "bid")),
|
|
271
|
+
timestamp=_ms_to_iso(payload.get("t")),
|
|
272
|
+
open=float(payload["o"]),
|
|
273
|
+
high=float(payload["h"]),
|
|
274
|
+
low=float(payload["l"]),
|
|
275
|
+
close=float(payload["c"]),
|
|
276
|
+
)
|
|
277
|
+
except (TypeError, ValueError):
|
|
278
|
+
return None
|
|
279
|
+
|
|
280
|
+
async def stream_ohlc(
|
|
281
|
+
self, duration: float = 300.0, reconnect_attempts: int = 3
|
|
282
|
+
) -> AsyncIterator[OHLCBar]:
|
|
283
|
+
"""Stream OHLC candlestick bars (parallel to stream(); yields OHLCBar)."""
|
|
284
|
+
if not self._ws:
|
|
285
|
+
raise SessionError("WebSocket not connected. Call connect() first.")
|
|
286
|
+
|
|
287
|
+
start_time = datetime.now(timezone.utc)
|
|
288
|
+
reconnect_count = 0
|
|
289
|
+
try:
|
|
290
|
+
while True:
|
|
291
|
+
elapsed = (datetime.now(timezone.utc) - start_time).total_seconds()
|
|
292
|
+
if elapsed >= duration:
|
|
293
|
+
logger.info(f"OHLC stream duration {duration}s reached, stopping")
|
|
294
|
+
break
|
|
295
|
+
|
|
296
|
+
if await self._should_ping():
|
|
297
|
+
await self._send_ping()
|
|
298
|
+
|
|
299
|
+
try:
|
|
300
|
+
timeout = min(duration - elapsed, 10.0)
|
|
301
|
+
message = await asyncio.wait_for(self._ws.recv(), timeout=timeout)
|
|
302
|
+
bar = self._parse_ohlc(message)
|
|
303
|
+
if bar:
|
|
304
|
+
yield bar
|
|
305
|
+
except asyncio.TimeoutError:
|
|
306
|
+
continue
|
|
307
|
+
except websockets.exceptions.ConnectionClosed:
|
|
308
|
+
if reconnect_count < reconnect_attempts:
|
|
309
|
+
reconnect_count += 1
|
|
310
|
+
logger.warning(
|
|
311
|
+
f"WebSocket disconnected, reconnecting "
|
|
312
|
+
f"({reconnect_count}/{reconnect_attempts})"
|
|
313
|
+
)
|
|
314
|
+
await asyncio.sleep(2**reconnect_count)
|
|
315
|
+
params = self._ohlc_params
|
|
316
|
+
await self.close()
|
|
317
|
+
await self.connect()
|
|
318
|
+
if params:
|
|
319
|
+
await self.subscribe_ohlc(*params)
|
|
320
|
+
logger.info("Reconnection successful")
|
|
321
|
+
else:
|
|
322
|
+
logger.error(
|
|
323
|
+
f"Max reconnection attempts ({reconnect_attempts}) reached"
|
|
324
|
+
)
|
|
325
|
+
raise UpstreamError(
|
|
326
|
+
"WebSocket connection lost and reconnection failed"
|
|
327
|
+
) from None
|
|
328
|
+
finally:
|
|
329
|
+
if self._ohlc_params:
|
|
330
|
+
await self.unsubscribe_ohlc()
|
|
331
|
+
|
|
332
|
+
async def _send_ping(self) -> None:
|
|
333
|
+
"""Keep the connection alive using the documented application-level ping.
|
|
334
|
+
|
|
335
|
+
Capital.com's streaming session is kept alive by a JSON ``ping`` message
|
|
336
|
+
carrying the session tokens (not just a transport-level PING frame). Falls
|
|
337
|
+
back to a transport ping only if tokens are unavailable.
|
|
338
|
+
"""
|
|
339
|
+
if not self._ws:
|
|
340
|
+
return
|
|
341
|
+
tokens = self.session_manager.client.session_tokens
|
|
342
|
+
try:
|
|
343
|
+
if tokens:
|
|
344
|
+
ping_msg = {
|
|
345
|
+
"destination": "ping",
|
|
346
|
+
"correlationId": "ping",
|
|
347
|
+
"cst": tokens.cst,
|
|
348
|
+
"securityToken": tokens.x_security_token,
|
|
349
|
+
}
|
|
350
|
+
await self._ws.send(json.dumps(ping_msg))
|
|
351
|
+
else:
|
|
352
|
+
await self._ws.ping()
|
|
353
|
+
self._last_ping = datetime.now(timezone.utc)
|
|
354
|
+
logger.debug("Sent keep-alive ping")
|
|
355
|
+
except Exception as e: # noqa: BLE001 - ping failure is non-fatal
|
|
356
|
+
logger.warning(f"Failed to send ping: {e}")
|
|
357
|
+
|
|
358
|
+
async def _should_ping(self) -> bool:
|
|
359
|
+
"""Check if we should send a ping (every 5 minutes)."""
|
|
360
|
+
if not self._last_ping:
|
|
361
|
+
return True
|
|
362
|
+
|
|
363
|
+
elapsed = (datetime.now(timezone.utc) - self._last_ping).total_seconds()
|
|
364
|
+
return elapsed >= 300 # 5 minutes
|
|
365
|
+
|
|
366
|
+
def _parse_message(self, message: str | bytes) -> PriceTick | None:
|
|
367
|
+
"""
|
|
368
|
+
Parse incoming WebSocket message.
|
|
369
|
+
|
|
370
|
+
Args:
|
|
371
|
+
message: Raw JSON message from WebSocket
|
|
372
|
+
|
|
373
|
+
Returns:
|
|
374
|
+
PriceTick if it's a price update, None otherwise
|
|
375
|
+
"""
|
|
376
|
+
try:
|
|
377
|
+
data = json.loads(message)
|
|
378
|
+
|
|
379
|
+
# Check if it's a price update message
|
|
380
|
+
# Capital.com format: {"status": "OK", "destination": "quote",
|
|
381
|
+
# "payload": {"epic": ..., "bid": ..., "ofr": ..., "timestamp": ...}}
|
|
382
|
+
if isinstance(data, dict) and data.get("destination") == "quote":
|
|
383
|
+
payload = data.get("payload", {})
|
|
384
|
+
epic = payload.get("epic")
|
|
385
|
+
|
|
386
|
+
if epic and "bid" in payload and "ofr" in payload:
|
|
387
|
+
return PriceTick(
|
|
388
|
+
epic=epic,
|
|
389
|
+
bid=float(payload["bid"]),
|
|
390
|
+
offer=float(payload["ofr"]),
|
|
391
|
+
timestamp=datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
|
|
392
|
+
change_percent=payload.get("changePercent")
|
|
393
|
+
)
|
|
394
|
+
|
|
395
|
+
# Heartbeat or other message types
|
|
396
|
+
return None
|
|
397
|
+
|
|
398
|
+
except (json.JSONDecodeError, KeyError, ValueError) as e:
|
|
399
|
+
logger.warning(f"Failed to parse WebSocket message: {e}")
|
|
400
|
+
return None
|
|
401
|
+
|
|
402
|
+
async def stream(
|
|
403
|
+
self,
|
|
404
|
+
duration: float = 300.0,
|
|
405
|
+
reconnect_attempts: int = 3
|
|
406
|
+
) -> AsyncIterator[PriceTick]:
|
|
407
|
+
"""
|
|
408
|
+
Stream price updates.
|
|
409
|
+
|
|
410
|
+
Args:
|
|
411
|
+
duration: Stream duration in seconds (default: 5 minutes)
|
|
412
|
+
reconnect_attempts: Number of reconnection attempts on disconnect
|
|
413
|
+
|
|
414
|
+
Yields:
|
|
415
|
+
PriceTick objects as they arrive
|
|
416
|
+
|
|
417
|
+
Raises:
|
|
418
|
+
SessionError: If not connected
|
|
419
|
+
UpstreamError: If connection fails after retries
|
|
420
|
+
"""
|
|
421
|
+
if not self._ws:
|
|
422
|
+
raise SessionError("WebSocket not connected. Call connect() first.")
|
|
423
|
+
|
|
424
|
+
start_time = datetime.now(timezone.utc)
|
|
425
|
+
reconnect_count = 0
|
|
426
|
+
|
|
427
|
+
try:
|
|
428
|
+
while True:
|
|
429
|
+
# Check duration timeout
|
|
430
|
+
elapsed = (datetime.now(timezone.utc) - start_time).total_seconds()
|
|
431
|
+
if elapsed >= duration:
|
|
432
|
+
logger.info(f"Stream duration {duration}s reached, stopping")
|
|
433
|
+
break
|
|
434
|
+
|
|
435
|
+
# Send ping if needed
|
|
436
|
+
if await self._should_ping():
|
|
437
|
+
await self._send_ping()
|
|
438
|
+
|
|
439
|
+
try:
|
|
440
|
+
# Receive message with timeout
|
|
441
|
+
remaining = duration - elapsed
|
|
442
|
+
timeout = min(remaining, 10.0) # Max 10s wait per message
|
|
443
|
+
|
|
444
|
+
message = await asyncio.wait_for(
|
|
445
|
+
self._ws.recv(),
|
|
446
|
+
timeout=timeout
|
|
447
|
+
)
|
|
448
|
+
|
|
449
|
+
# Parse and yield price tick
|
|
450
|
+
tick = self._parse_message(message)
|
|
451
|
+
if tick:
|
|
452
|
+
yield tick
|
|
453
|
+
|
|
454
|
+
except asyncio.TimeoutError:
|
|
455
|
+
# No message received, continue (normal for quiet periods)
|
|
456
|
+
continue
|
|
457
|
+
|
|
458
|
+
except websockets.exceptions.ConnectionClosed:
|
|
459
|
+
# Connection lost, attempt reconnection
|
|
460
|
+
if reconnect_count < reconnect_attempts:
|
|
461
|
+
reconnect_count += 1
|
|
462
|
+
logger.warning(f"WebSocket disconnected, reconnecting ({reconnect_count}/{reconnect_attempts})")
|
|
463
|
+
|
|
464
|
+
await asyncio.sleep(2 ** reconnect_count) # Exponential backoff
|
|
465
|
+
|
|
466
|
+
# Reconnect and resubscribe
|
|
467
|
+
epics_to_restore = list(self._subscribed_epics)
|
|
468
|
+
await self.close()
|
|
469
|
+
await self.connect()
|
|
470
|
+
await self.subscribe(epics_to_restore)
|
|
471
|
+
|
|
472
|
+
logger.info("Reconnection successful")
|
|
473
|
+
else:
|
|
474
|
+
logger.error(f"Max reconnection attempts ({reconnect_attempts}) reached")
|
|
475
|
+
raise UpstreamError("WebSocket connection lost and reconnection failed") from None
|
|
476
|
+
|
|
477
|
+
finally:
|
|
478
|
+
# Cleanup: unsubscribe from all EPICs
|
|
479
|
+
if self._subscribed_epics:
|
|
480
|
+
await self.unsubscribe(list(self._subscribed_epics))
|