|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import json |
| 4 | +import time |
| 5 | +import urllib.error |
| 6 | +import urllib.request |
| 7 | +from collections.abc import Mapping |
| 8 | +from dataclasses import dataclass, field |
| 9 | +from typing import Any, Callable |
| 10 | + |
| 11 | +from .models import QuantConnectCredentials, QuantConnectLiveDeployment, redact_sensitive_payload |
| 12 | + |
| 13 | + |
| 14 | +DEFAULT_QUANTCONNECT_API_BASE_URL = "https://www.quantconnect.com/api/v2" |
| 15 | + |
| 16 | + |
| 17 | +class QuantConnectApiError(RuntimeError): |
| 18 | + def __init__( |
| 19 | + self, |
| 20 | + message: str, |
| 21 | + *, |
| 22 | + status_code: int | None = None, |
| 23 | + payload: Mapping[str, Any] | None = None, |
| 24 | + ) -> None: |
| 25 | + super().__init__(message) |
| 26 | + self.status_code = status_code |
| 27 | + self.payload = dict(payload or {}) |
| 28 | + |
| 29 | + |
| 30 | +@dataclass(frozen=True) |
| 31 | +class QuantConnectRestClient: |
| 32 | + credentials: QuantConnectCredentials |
| 33 | + api_base_url: str = DEFAULT_QUANTCONNECT_API_BASE_URL |
| 34 | + timeout: float = 15.0 |
| 35 | + opener: Any = None |
| 36 | + clock: Callable[[], float] = field(default=time.time, repr=False) |
| 37 | + |
| 38 | + def authenticate(self) -> dict[str, Any]: |
| 39 | + return self.post_json("/authenticate", {}) |
| 40 | + |
| 41 | + def create_live_algorithm(self, deployment: QuantConnectLiveDeployment | Mapping[str, Any]) -> dict[str, Any]: |
| 42 | + payload = deployment.to_payload() if hasattr(deployment, "to_payload") else dict(deployment) |
| 43 | + return self.post_json("/live/create", payload) |
| 44 | + |
| 45 | + def read_live_algorithm(self, *, project_id: int, deploy_id: str) -> dict[str, Any]: |
| 46 | + return self.post_json( |
| 47 | + "/live/read", |
| 48 | + { |
| 49 | + "projectId": int(project_id), |
| 50 | + "deployId": str(deploy_id).strip(), |
| 51 | + }, |
| 52 | + ) |
| 53 | + |
| 54 | + def list_live_algorithms( |
| 55 | + self, |
| 56 | + *, |
| 57 | + project_id: int | None = None, |
| 58 | + status: str | None = None, |
| 59 | + ) -> dict[str, Any]: |
| 60 | + payload: dict[str, Any] = {} |
| 61 | + if project_id is not None: |
| 62 | + payload["projectId"] = int(project_id) |
| 63 | + text_status = str(status or "").strip() |
| 64 | + if text_status: |
| 65 | + payload["status"] = text_status |
| 66 | + return self.post_json("/live/list", payload) |
| 67 | + |
| 68 | + def stop_live_algorithm(self, *, project_id: int) -> dict[str, Any]: |
| 69 | + return self.post_json("/live/update/stop", {"projectId": int(project_id)}) |
| 70 | + |
| 71 | + def liquidate_live_algorithm(self, *, project_id: int) -> dict[str, Any]: |
| 72 | + return self.post_json("/live/update/liquidate", {"projectId": int(project_id)}) |
| 73 | + |
| 74 | + def post_json(self, path: str, payload: Mapping[str, Any] | None = None) -> dict[str, Any]: |
| 75 | + request_payload = dict(payload or {}) |
| 76 | + request = urllib.request.Request( |
| 77 | + self._endpoint(path), |
| 78 | + data=json.dumps(request_payload, ensure_ascii=False).encode("utf-8"), |
| 79 | + headers={ |
| 80 | + **self.credentials.build_auth_headers(clock=self.clock), |
| 81 | + "Content-Type": "application/json", |
| 82 | + }, |
| 83 | + method="POST", |
| 84 | + ) |
| 85 | + |
| 86 | + try: |
| 87 | + with self._opener()(request, timeout=self.timeout) as response: |
| 88 | + status_code = _response_status(response) |
| 89 | + raw_body = response.read() |
| 90 | + except urllib.error.HTTPError as exc: |
| 91 | + status_code = int(exc.code) |
| 92 | + raw_body = exc.read() |
| 93 | + parsed_error = _parse_response_body(raw_body) |
| 94 | + raise QuantConnectApiError( |
| 95 | + f"QuantConnect API request failed with HTTP {status_code}", |
| 96 | + status_code=status_code, |
| 97 | + payload=redact_sensitive_payload(parsed_error), |
| 98 | + ) from exc |
| 99 | + |
| 100 | + result = _parse_response_body(raw_body) |
| 101 | + if status_code < 200 or status_code >= 300: |
| 102 | + raise QuantConnectApiError( |
| 103 | + f"QuantConnect API request failed with HTTP {status_code}", |
| 104 | + status_code=status_code, |
| 105 | + payload=redact_sensitive_payload(result), |
| 106 | + ) |
| 107 | + if result.get("success") is False: |
| 108 | + errors = result.get("errors") |
| 109 | + message = "QuantConnect API request failed" |
| 110 | + if errors: |
| 111 | + message = f"{message}: {errors}" |
| 112 | + raise QuantConnectApiError( |
| 113 | + message, |
| 114 | + status_code=status_code, |
| 115 | + payload=redact_sensitive_payload(result), |
| 116 | + ) |
| 117 | + return result |
| 118 | + |
| 119 | + def _endpoint(self, path: str) -> str: |
| 120 | + base_url = str(self.api_base_url or DEFAULT_QUANTCONNECT_API_BASE_URL).rstrip("/") |
| 121 | + endpoint_path = str(path or "").strip().lstrip("/") |
| 122 | + if not endpoint_path: |
| 123 | + raise ValueError("path must not be empty.") |
| 124 | + return f"{base_url}/{endpoint_path}" |
| 125 | + |
| 126 | + def _opener(self) -> Any: |
| 127 | + return self.opener or urllib.request.urlopen |
| 128 | + |
| 129 | + |
| 130 | +@dataclass(frozen=True) |
| 131 | +class QuantConnectLiveConnector: |
| 132 | + client: QuantConnectRestClient |
| 133 | + |
| 134 | + def deploy(self, deployment: QuantConnectLiveDeployment) -> dict[str, Any]: |
| 135 | + return self.client.create_live_algorithm(deployment) |
| 136 | + |
| 137 | + def running_deployments(self, *, project_id: int | None = None) -> tuple[dict[str, Any], ...]: |
| 138 | + result = self.client.list_live_algorithms(project_id=project_id, status="Running") |
| 139 | + live = result.get("live") or () |
| 140 | + if not isinstance(live, list): |
| 141 | + return () |
| 142 | + return tuple(dict(item) for item in live if isinstance(item, Mapping)) |
| 143 | + |
| 144 | + def stop_project(self, *, project_id: int, liquidate: bool = False) -> dict[str, Any]: |
| 145 | + if liquidate: |
| 146 | + return self.client.liquidate_live_algorithm(project_id=project_id) |
| 147 | + return self.client.stop_live_algorithm(project_id=project_id) |
| 148 | + |
| 149 | + |
| 150 | +def _response_status(response: Any) -> int: |
| 151 | + status = getattr(response, "status", None) |
| 152 | + if status is None: |
| 153 | + status = response.getcode() |
| 154 | + return int(status) |
| 155 | + |
| 156 | + |
| 157 | +def _parse_response_body(raw_body: bytes | str | None) -> dict[str, Any]: |
| 158 | + if raw_body is None or raw_body == b"" or raw_body == "": |
| 159 | + return {} |
| 160 | + if isinstance(raw_body, bytes): |
| 161 | + body_text = raw_body.decode("utf-8") |
| 162 | + else: |
| 163 | + body_text = raw_body |
| 164 | + parsed = json.loads(body_text) |
| 165 | + if not isinstance(parsed, dict): |
| 166 | + raise QuantConnectApiError("QuantConnect API response must decode to an object.") |
| 167 | + return parsed |
0 commit comments