"""Galore bot client using the Python standard library. Keep credentials outside chat.""" import json import os import webbrowser import time import urllib.error import urllib.parse import urllib.request def _origin(url): parsed = urllib.parse.urlsplit(url) if (parsed.path not in ("", "/") or parsed.query or parsed.fragment or parsed.username or parsed.password or not (parsed.scheme == "https" or (parsed.scheme == "http" and parsed.hostname in ("localhost", "127.0.0.1", "::1")))): raise ValueError("Use the Galore HTTPS origin or loopback HTTP for development") return urllib.parse.urlunsplit((parsed.scheme, parsed.netloc, "", "", "")) class _NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, headers, newurl): return None def _post(origin, path, payload, token=None, timeout=30): headers = {"Content-Type": "application/json"} if token: headers["Authorization"] = "Bearer " + token request = urllib.request.Request(origin + path, data=json.dumps(payload).encode(), headers=headers, method="POST") try: with urllib.request.build_opener(_NoRedirect).open(request, timeout=timeout) as response: return response.status, json.load(response) except urllib.error.HTTPError as error: try: return error.code, json.load(error) except (ValueError, UnicodeDecodeError): return error.code, {"error": "Galore returned HTTP " + str(error.code)} def connect(url, label="Python trading bot", on_verification=None, no_browser=False): """Open the browser, wait and return credentials to this process. Use no_browser on a server.""" origin = _origin(url) status, device = _post(origin, "/connect/device/start", {"label": label}) if status != 200: raise RuntimeError(device.get("error", "Galore login unavailable")) if _origin(urllib.parse.urlunsplit((*urllib.parse.urlsplit(device["verification_uri_complete"])[:2], "", "", ""))) != origin: raise RuntimeError("Invalid verification origin") if on_verification: on_verification(device) else: print("Open " + device["verification_uri_complete"] + " and compare code " + device["user_code"]) if not no_browser and not os.environ.get("SSH_CONNECTION") and not os.environ.get("CI"): try: webbrowser.open(device["verification_uri_complete"]) except webbrowser.Error: pass deadline = time.monotonic() + min(float(device["expires_in"]), 900) interval = max(5, float(device["interval"])) while time.monotonic() < deadline: time.sleep(interval) status, result = _post(origin, "/connect/device/poll", {"device_code": device["device_code"]}) if status == 200 and result.get("api_key"): return result if result.get("error") == "slow_down": interval += 5 elif result.get("error") != "authorization_pending": raise RuntimeError(result.get("error", "Galore login failed")) raise TimeoutError("Galore login expired. Start again.") class Galore: def __init__(self, url, token): self.origin = _origin(url) self.token = token def call(self, tool, **arguments): if not tool or len(tool) > 80 or any(c not in "abcdefghijklmnopqrstuvwxyz_" for c in tool): raise ValueError("Invalid Galore tool name") try: status, result = _post(self.origin, "/v1/tools/" + tool, arguments, self.token) except (urllib.error.URLError, TimeoutError, ValueError, RuntimeError): if tool != "report_agent_issue": try: self.report_issue(tool, "Client connection failed or timed out", "connection_failure") except Exception: pass raise if status != 200 or result.get("isError"): message = result.get("error") or "\n".join(c.get("text", "") for c in result.get("content", [])) raise RuntimeError(message or "Galore request failed") return result.get("structuredContent", result) def report_issue(self, operation, message, category="error"): """Send an operator diagnostic automatically, without member approval.""" return self.call("report_agent_issue", operation=operation, message=message, category=category) def workflow(self, steps, request_key, workflow_id=None, timeout=180, on_checkpoint=None): """Run saved reads to completion, reconnecting with the same request key or workflow ID. Save request_key before calling, or persist workflow_id through on_checkpoint. This never replays orders, approvals, signatures, or a separate host connector. """ deadline = time.monotonic() + timeout failures = 0 while time.monotonic() < deadline: tool = "resume_galore_workflow" if workflow_id else "run_galore_workflow" arguments = {"workflow_id": workflow_id, "wait_ms": 20000} if workflow_id else { "steps": steps, "request_key": request_key, "wait_ms": 20000} try: status, envelope = _post(self.origin, "/v1/tools/" + tool, arguments, self.token, timeout=max(0.1, min(30, deadline - time.monotonic()))) except (urllib.error.URLError, ConnectionError, TimeoutError, ValueError): failures += 1 if failures >= 6: raise ConnectionError("Galore is unreachable; saved workflow can be resumed with the same request key") from None time.sleep(max(0, min(5, failures, deadline - time.monotonic()))) continue if status in (429, 500, 502, 503, 504): failures += 1 if failures >= 6: raise ConnectionError("Galore recovery budget reached; the saved workflow is retained") time.sleep(max(0, min(5, failures, deadline - time.monotonic()))) continue if status != 200 or envelope.get("isError"): raise RuntimeError(envelope.get("error") or "Galore rejected workflow access or its read plan") value = envelope.get("structuredContent", {}) failures = 0 workflow_id = value.get("workflow_id", workflow_id) if workflow_id and on_checkpoint: on_checkpoint(workflow_id) if value.get("state") == "completed": return value if value.get("state") not in ("queued", "running", "retrying"): raise RuntimeError(value.get("error") or value.get("next") or "Workflow cannot resume automatically") time.sleep(0.25) raise TimeoutError("Workflow is still saved; resume it with the same request key or workflow ID") def wait_for_approval(self, kind, draft_id, on_review=None, timeout=300): """Wait for the person to sign this exact card, then resume the calling bot.""" args = {"kind": kind, "id": draft_id} link = self.call("request_galore_approval", **args) review_url = link["approval_url"] parsed = urllib.parse.urlsplit(review_url) if _origin(urllib.parse.urlunsplit((parsed.scheme, parsed.netloc, "", "", ""))) != self.origin or parsed.path != "/connect/approve": raise RuntimeError("Invalid review URL") initial = self.call("galore_approval_status", **args) if initial["signed"]: return initial if on_review: on_review(review_url) else: print("Review your rules: " + review_url) if not os.environ.get("SSH_CONNECTION") and not os.environ.get("CI"): try: webbrowser.open(review_url) except webbrowser.Error: pass deadline = time.monotonic() + min(timeout, 900) while time.monotonic() < deadline: result = self.call("galore_approval_status", **args) if result["card_hash"] != initial["card_hash"]: raise RuntimeError("Rules changed. Review the new card.") if result["signed"]: return result if result["status"] not in ("pending", "draft"): raise RuntimeError("Approval cannot continue: " + result["status"]) time.sleep(3) raise TimeoutError("Approval timed out. Check the stored draft status before continuing.") def execute_existing_order(self, policy_id, order, on_progress=None, on_broker_approval=None, timeout=300): """Write operation: check, submit once, then reconcile the original order.""" event_id = order.get("eventId") if not isinstance(event_id, str) or not event_id: raise ValueError("A stable original eventId is required") preview = self.call("preview_existing_order", policy_id=policy_id, order=order) if preview.get("checks") != "passed" or preview.get("sent") is not False: raise RuntimeError("Preflight did not approve this exact order") try: result = self.call("submit_existing_order", policy_id=policy_id, order=order) if on_progress: on_progress(result) if result["state"] in ("filled", "rejected", "canceled", "approval_denied"): return result except Exception as original_error: try: return self.wait_for_existing_order(event_id, on_progress, on_broker_approval, timeout) except Exception: raise original_error return self.wait_for_existing_order(event_id, on_progress, on_broker_approval, timeout) def wait_for_existing_order(self, event_id, on_progress=None, on_broker_approval=None, timeout=300): """Return the brokerage's original trade result, without a second submission.""" deadline = time.monotonic() + min(timeout, 900) approval = None result = {} while time.monotonic() < deadline: result = self.call("existing_order_status", event_id=event_id) if on_progress: on_progress(result) if result["state"] == "approval_required" and result.get("approvalId") != approval: approval = result.get("approvalId") if on_broker_approval: on_broker_approval(result.get("approvalUrl"), result) if result["state"] in ("filled", "rejected", "canceled", "approval_denied", "unknown"): return result time.sleep(3) return dict(result, waitTimedOut=True)