Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(okx): bound history fetches and handle rate limits

tyj147454413-cmd5ce9a04dca32
diff --git a/agent/backtest/loaders/okx.py b/agent/backtest/loaders/okx.py
index 4143784a6..ab92b79fb 100644
--- a/agent/backtest/loaders/okx.py
+++ b/agent/backtest/loaders/okx.py
@@ -1,11 +1,28 @@
"""OKX spot candle loader (crypto).
Uses OKX V5 public REST API (no auth).
-Supports 1m/5m/15m/30m/1H/4H/1D.
-Up to 300 bars per request; paginates with ``after`` for longer history.
+
+Endpoints
+---------
+- ``/market/candles`` — recent bars only (limited depth; not enough for multi-year
+ backtests).
+- ``/market/history-candles`` — multi-year history; used whenever the requested
+ range is older than a few months or recent endpoint returns empty.
+
+Hardening (2026-07 local audit)
+--------------------------------
+- Explicit proxy support (same env vars as CCXT loader); required on networks
+ that time out direct HTTPS to www.okx.com.
+- Raise / retry on HTTP 429/5xx and OKX business ``code != "0"``.
+- Prefer ``history-candles`` for deep ranges so 2020-era backtests no longer
+ return empty frames.
+- ``is_available()`` does a short probe instead of always returning True.
"""
+from __future__ import annotations
+
import logging
+import os
import time
from typing import Dict, List, Optional
@@ -25,13 +42,45 @@ from backtest.loaders.base import (
from backtest.loaders.registry import register
BASE_URL = "https://www.okx.com/api/v5"
+CANDLES_PATH = f"{BASE_URL}/market/candles"
+HISTORY_CANDLES_PATH = f"{BASE_URL}/market/history-candles"
_MAX_PER_PAGE = 300
-# P12-b parity: OKX already sets a per-request timeout but had no retry
-# budget, so a transient blip dropped the whole symbol and a slow tier
-# could stall ~max_pages*timeout. Bound it like the ccxt loader; retry
-# scheduling is delegated to :mod:`backtest.loaders.base`.
-_OKX_TIMEOUT = positive_env_int("OKX_TIMEOUT_S", 15)
-_OKX_FETCH_BUDGET_S = positive_env_float("OKX_FETCH_BUDGET_S", 60.0)
+# Recent endpoint typically only covers ~months of 1D bars; beyond this age
+# always hit history-candles first.
+_RECENT_ONLY_DAYS = 400
+
+_OKX_TIMEOUT = positive_env_int("OKX_TIMEOUT_S", 20)
+_OKX_FETCH_BUDGET_S = positive_env_float("OKX_FETCH_BUDGET_S", 90.0)
+_OKX_PROBE_TIMEOUT = positive_env_int("OKX_PROBE_TIMEOUT_S", 8)
+
+
+def _first_proxy_env(*names: str) -> str:
+ for name in names:
+ value = os.getenv(name, "").strip() # noqa: env-gate — system proxy vars
+ if value:
+ return value
+ return ""
+
+
+def _okx_proxy_config() -> dict[str, str]:
+ """Build requests proxies from conventional env vars (parity with CCXT)."""
+ all_proxy = _first_proxy_env("ALL_PROXY", "all_proxy")
+ http_proxy = _first_proxy_env("HTTP_PROXY", "http_proxy") or all_proxy
+ https_proxy = _first_proxy_env("HTTPS_PROXY", "https_proxy") or all_proxy or http_proxy
+ proxies: dict[str, str] = {}
+ if http_proxy:
+ proxies["http"] = http_proxy
+ if https_proxy:
+ proxies["https"] = https_proxy
+ return proxies
+
+
+def _okx_session() -> requests.Session:
+ session = requests.Session()
+ proxies = _okx_proxy_config()
+ if proxies:
+ session.proxies.update(proxies)
+ return session
@register
@@ -43,8 +92,22 @@ class DataLoader:
requires_auth = False
def is_available(self) -> bool:
- """Always available (public API, no auth)."""
- return True
+ """Probe public candles with a short timeout (honours proxy env)."""
+ try:
+ session = _okx_session()
+ resp = session.get(
+ CANDLES_PATH,
+ params={"instId": "BTC-USDT", "bar": "1D", "limit": "1"},
+ timeout=_OKX_PROBE_TIMEOUT,
+ )
+ if resp.status_code != 200:
+ logger.warning("OKX probe HTTP %s", resp.status_code)
+ return False
+ data = resp.json()
+ return data.get("code") == "0" and bool(data.get("data"))
+ except Exception as exc: # noqa: BLE001 — availability probe
+ logger.warning("OKX probe failed: %s", exc)
+ return False
def __init__(self) -> None:
"""No credentials required for public candles."""
@@ -86,7 +149,16 @@ class DataLoader:
start_ts = int(pd.Timestamp(start_date).timestamp() * 1000)
end_ts = int((pd.Timestamp(end_date) + pd.Timedelta(days=1)).timestamp() * 1000)
- max_pages = 200 if interval in ("1m", "5m") else 50 if interval in ("15m", "30m") else 20
+ # More pages for minute bars; history endpoint still needs walk-back.
+ if interval in ("1m", "5m"):
+ max_pages = 200
+ elif interval in ("15m", "30m"):
+ max_pages = 80
+ else:
+ max_pages = 40
+
+ use_history = self._should_use_history(start_date)
+ session = _okx_session()
result: Dict[str, pd.DataFrame] = {}
for symbol in codes:
@@ -98,8 +170,14 @@ class DataLoader:
start_date=start_date,
end_date=end_date,
fields=None,
- fetch=lambda symbol=symbol: self._fetch_candles(
- symbol, start_ts, end_ts, interval, max_pages
+ fetch=lambda symbol=symbol, use_history=use_history: self._fetch_candles(
+ session,
+ symbol,
+ start_ts,
+ end_ts,
+ interval,
+ max_pages,
+ prefer_history=use_history,
),
)
if df is not None and not df.empty:
@@ -108,26 +186,77 @@ class DataLoader:
logger.warning("failed to fetch %s: %s", symbol, exc)
return result
+ @staticmethod
+ def _should_use_history(start_date: str) -> bool:
+ """True when the range starts older than recent-only window."""
+ try:
+ start = pd.Timestamp(start_date)
+ age_days = (pd.Timestamp.utcnow().tz_localize(None) - start).days
+ return age_days > _RECENT_ONLY_DAYS
+ except Exception:
+ return True
+
def _fetch_candles(
- self, inst_id: str, start_ts: int, end_ts: int,
- bar: str = "1D", max_pages: int = 20,
+ self,
+ session: requests.Session,
+ inst_id: str,
+ start_ts: int,
+ end_ts: int,
+ bar: str = "1D",
+ max_pages: int = 20,
+ *,
+ prefer_history: bool = True,
) -> Optional[pd.DataFrame]:
- """Paginated candle download.
+ """Paginated candle download (history endpoint for deep ranges)."""
+ endpoints: list[str] = []
+ if prefer_history:
+ endpoints = [HISTORY_CANDLES_PATH, CANDLES_PATH]
+ else:
+ endpoints = [CANDLES_PATH, HISTORY_CANDLES_PATH]
+
+ last_error: Exception | None = None
+ for endpoint in endpoints:
+ try:
+ df = self._paginate(
+ session,
+ endpoint,
+ inst_id,
+ start_ts,
+ end_ts,
+ bar,
+ max_pages,
+ )
+ if df is not None and not df.empty:
+ return df
+ except Exception as exc:
+ last_error = exc
+ logger.warning(
+ "OKX %s failed for %s: %s — trying next endpoint",
+ endpoint.rsplit("/", 1)[-1],
+ inst_id,
+ exc,
+ )
- Args:
- inst_id: OKX instrument id.
- start_ts: Start time (ms).
- end_ts: End time (ms).
- bar: Bar size.
- max_pages: Max pagination rounds.
+ if last_error is not None:
+ logger.warning("OKX empty/failed for %s: %s", inst_id, last_error)
+ else:
+ logger.warning("OKX empty response: %s", inst_id)
+ return None
- Returns:
- OHLCV DataFrame or None.
- """
+ def _paginate(
+ self,
+ session: requests.Session,
+ endpoint: str,
+ inst_id: str,
+ start_ts: int,
+ end_ts: int,
+ bar: str,
+ max_pages: int,
+ ) -> Optional[pd.DataFrame]:
all_rows: list = []
after = str(end_ts)
deadline = time.monotonic() + _OKX_FETCH_BUDGET_S
- label = f"OKX fetch for {inst_id}"
+ label = f"OKX fetch for {inst_id} via {endpoint.rsplit('/', 1)[-1]}"
for _ in range(max_pages):
check_budget(deadline, label, budget_s=_OKX_FETCH_BUDGET_S)
@@ -138,47 +267,85 @@ class DataLoader:
"after": after,
}
- def _do_request() -> dict:
- resp = requests.get(
- f"{BASE_URL}/market/candles",
+ def _do_request(params=params) -> dict:
+ resp = session.get(
+ endpoint,
params=params,
timeout=_OKX_TIMEOUT,
)
- return resp.json()
+ # Transient gateway / rate-limit → raise for retry_with_budget
+ if resp.status_code in {429, 500, 502, 503, 504}:
+ raise requests.HTTPError(
+ f"OKX HTTP {resp.status_code}",
+ response=resp,
+ )
+ resp.raise_for_status()
+ try:
+ data = resp.json()
+ except ValueError as exc:
+ raise requests.RequestException(
+ f"OKX non-JSON response HTTP {resp.status_code}"
+ ) from exc
+ code = str(data.get("code", ""))
+ if code != "0":
+ # Business errors are not always transient; still surface.
+ msg = data.get("msg") or data.get("error_message") or code
+ raise requests.RequestException(f"OKX API code={code} msg={msg}")
+ return data
data = retry_with_budget(
_do_request,
- transient=requests.RequestException,
+ transient=(requests.RequestException, TimeoutError),
deadline=deadline,
label=label,
)
- if data.get("code") != "0" or not data.get("data"):
+ raw_rows = data.get("data") or []
+ if not raw_rows:
break
- rows = data["data"]
- rows = [r for r in rows if r[8] == "1"]
+ # Keep confirmed bars (confirm=="1"); also keep unconfirmed when
+ # it is the only data returned so live partial days are not empty.
+ confirmed = [r for r in raw_rows if len(r) > 8 and str(r[8]) == "1"]
+ rows = confirmed if confirmed else list(raw_rows)
all_rows.extend(rows)
- oldest_ts = int(rows[-1][0]) if rows else start_ts
- if oldest_ts <= start_ts or len(data["data"]) < _MAX_PER_PAGE:
+ oldest_ts = int(raw_rows[-1][0])
+ if oldest_ts <= start_ts or len(raw_rows) < _MAX_PER_PAGE:
break
after = str(oldest_ts)
if not all_rows:
- logger.warning("OKX empty response: %s", inst_id)
return None
- columns = ["ts", "open", "high", "low", "close", "vol", "volCcy", "volCcyQuote", "confirm"]
- df = pd.DataFrame(all_rows, columns=columns)
- df["trade_date"] = pd.to_datetime(df["ts"].astype("int64"), unit="ms")
+ columns = [
+ "ts", "open", "high", "low", "close",
+ "vol", "volCcy", "volCcyQuote", "confirm",
+ ]
+ # Rows may be shorter if API schema changes — pad safely
+ normalized = []
+ for r in all_rows:
+ row = list(r) + [""] * (len(columns) - len(r))
+ normalized.append(row[: len(columns)])
+
+ df = pd.DataFrame(normalized, columns=columns)
+ # OKX daily open is UTC+8 midnight (= 16:00 UTC). Keep absolute UTC
+ # timestamps so multi-source merges stay consistent; floor to second.
+ df["trade_date"] = pd.to_datetime(
+ pd.to_numeric(df["ts"], errors="coerce"),
+ unit="ms",
+ utc=True,
+ ).dt.tz_convert(None)
for col in ["open", "high", "low", "close"]:
df[col] = pd.to_numeric(df[col], errors="coerce")
df["volume"] = pd.to_numeric(df["vol"], errors="coerce").fillna(0)
- df = df.set_index("trade_date").sort_index()
+ df = df.dropna(subset=["trade_date"]).set_index("trade_date").sort_index()
+ df = df[~df.index.duplicated(keep="last")]
start_dt = pd.Timestamp(start_ts, unit="ms")
end_dt = pd.Timestamp(end_ts, unit="ms")
df = df[(df.index >= start_dt) & (df.index < end_dt)]
- df = df[["open", "high", "low", "close", "volume"]].dropna(subset=["open", "high", "low", "close"])
+ df = df[["open", "high", "low", "close", "volume"]].dropna(
+ subset=["open", "high", "low", "close"]
+ )
return df if not df.empty else None
diff --git a/agent/tests/test_okx_loader_bounded.py b/agent/tests/test_okx_loader_bounded.py
index 1b18aec77..3d9b5fce5 100644
--- a/agent/tests/test_okx_loader_bounded.py
+++ b/agent/tests/test_okx_loader_bounded.py
@@ -1,16 +1,15 @@
-"""Regression tests for the P12-b okx.py parity fix — the OKX loader must
-fail fast on a transient disconnect instead of silently dropping the symbol
-or stalling ~max_pages*timeout.
-
-Pre-fix: `_fetch_candles` called requests.get once per page with no retry and
-no wall-clock budget. Post-fix: bounded retry on the transient
-requests.RequestException family + a hard budget raising a clear TimeoutError;
-the happy path still issues one request per page (no behavior change).
+"""Regression tests for the OKX loader — session-based, dual-endpoint,
+proxy-aware, with bounded retry and wall-clock budget.
+
+The loader now uses a ``requests.Session`` (with optional proxy) and tries
+both ``/market/history-candles`` and ``/market/candles`` endpoints.
+Tests mock the session or the helper that creates it.
"""
from __future__ import annotations
import importlib
+from unittest.mock import MagicMock, patch
import pandas as pd
import pytest
@@ -24,21 +23,22 @@ S = int(pd.Timestamp("2026-05-01").timestamp() * 1000)
E = int((pd.Timestamp("2026-05-05") + pd.Timedelta(days=1)).timestamp() * 1000)
-class _Resp:
- def __init__(self, payload):
- self._p = payload
-
- def json(self):
- return self._p
-
-
def _ok_page():
- # one short page (< _MAX_PER_PAGE) so the loop breaks after one call
+ """One short page (< _MAX_PER_PAGE) so the loop breaks after one call."""
ts = int(pd.Timestamp("2026-05-02").timestamp() * 1000)
- return _Resp({"code": "0", "data": [[ts, "1", "2", "0.5", "1.5", "10", "0", "0", "1"]]})
+ resp = MagicMock()
+ resp.status_code = 200
+ resp.json.return_value = {
+ "code": "0",
+ "data": [[ts, "1", "2", "0.5", "1.5", "10", "0", "0", "1"]],
+ }
+ return resp
class _Seq:
+ """Callable that returns items from *script* in order; raises if
+ the item is an exception."""
+
def __init__(self, script):
self.script = script
self.calls = 0
@@ -56,34 +56,46 @@ def _no_sleep(monkeypatch):
monkeypatch.setattr(okx.time, "sleep", lambda *_a, **_k: None)
+# ---------------------------------------------------------------------------
+# _paginate (core request loop with retry_with_budget)
+# ---------------------------------------------------------------------------
+
+
def test_transient_then_success(monkeypatch):
- seq = _Seq([requests.ConnectionError("blip"), requests.ConnectionError("blip"), _ok_page()])
- monkeypatch.setattr(okx.requests, "get", seq)
- df = DataLoader()._fetch_candles("BTC-USDT", S, E, "1D", 20)
+ """Transient errors are retried; after retrying, the page succeeds."""
+ session = MagicMock()
+ seq = _Seq(
+ [requests.ConnectionError("blip"), requests.ConnectionError("blip"), _ok_page()]
+ )
+ session.get = seq
+ df = DataLoader()._paginate(session, okx.CANDLES_PATH, "BTC-USDT", S, E, "1D", 20)
assert seq.calls >= 3
assert df is not None and not df.empty
def test_persistent_disconnect_is_bounded(monkeypatch):
+ session = MagicMock()
seq = _Seq([requests.ConnectionError("down")])
- monkeypatch.setattr(okx.requests, "get", seq)
+ session.get = seq
with pytest.raises(TimeoutError):
- DataLoader()._fetch_candles("BTC-USDT", S, E, "1D", 20)
+ DataLoader()._paginate(session, okx.CANDLES_PATH, "BTC-USDT", S, E, "1D", 20)
assert seq.calls == DEFAULT_MAX_RETRIES + 1 # bounded, not max_pages/forever
def test_non_network_error_not_retried(monkeypatch):
+ session = MagicMock()
seq = _Seq([KeyError("logic bug")])
- monkeypatch.setattr(okx.requests, "get", seq)
+ session.get = seq
with pytest.raises(KeyError):
- DataLoader()._fetch_candles("BTC-USDT", S, E, "1D", 20)
+ DataLoader()._paginate(session, okx.CANDLES_PATH, "BTC-USDT", S, E, "1D", 20)
assert seq.calls == 1
def test_happy_path_single_call(monkeypatch):
+ session = MagicMock()
seq = _Seq([_ok_page()])
- monkeypatch.setattr(okx.requests, "get", seq)
- df = DataLoader()._fetch_candles("BTC-USDT", S, E, "1D", 20)
+ session.get = seq
+ df = DataLoader()._paginate(session, okx.CANDLES_PATH, "BTC-USDT", S, E, "1D", 20)
assert seq.calls == 1
assert list(df.columns) == ["open", "high", "low", "close", "volume"]
@@ -91,9 +103,55 @@ def test_happy_path_single_call(monkeypatch):
def test_wallclock_budget_enforced(monkeypatch):
seq = iter([1000.0, 1000.0, 1_000_000.0])
monkeypatch.setattr(okx.time, "monotonic", lambda: next(seq, 1_000_000.0))
- monkeypatch.setattr(okx.requests, "get", _Seq([requests.ConnectionError("slow")]))
+ session = MagicMock()
+ session.get = _Seq([requests.ConnectionError("slow")])
with pytest.raises(TimeoutError):
- DataLoader()._fetch_candles("BTC-USDT", S, E, "1D", 20)
+ DataLoader()._paginate(session, okx.CANDLES_PATH, "BTC-USDT", S, E, "1D", 20)
+
+
+# ---------------------------------------------------------------------------
+# _fetch_candles (dual-endpoint fallback)
+# ---------------------------------------------------------------------------
+
+
+def test_fetch_candles_tries_history_then_recent(monkeypatch):
+ """When prefer_history=True and history fails, candles endpoint is tried."""
+ loader = DataLoader()
+
+ paginate_calls: list[str] = []
+ original_paginate = DataLoader._paginate
+
+ def _fake_paginate(self, session, endpoint, *args, **kwargs):
+ paginate_calls.append(endpoint)
+ if endpoint == okx.HISTORY_CANDLES_PATH:
+ raise requests.RequestException("history down")
+ # Use the real _paginate for the working endpoint
+ return original_paginate(self, session, endpoint, *args, **kwargs)
+
+ monkeypatch.setattr(DataLoader, "_paginate", _fake_paginate)
+ session = MagicMock()
+ session.get = _Seq([_ok_page()])
+ df = loader._fetch_candles(session, "BTC-USDT", S, E, "1D", 20, prefer_history=True)
+ # history was tried first, then candles
+ assert okx.HISTORY_CANDLES_PATH in paginate_calls[0]
+ assert df is not None
+
+
+def test_fetch_candles_returns_none_when_both_endpoints_fail(monkeypatch):
+ loader = DataLoader()
+
+ def _fail_paginate(*a, **kw):
+ raise requests.RequestException("both down")
+
+ monkeypatch.setattr(DataLoader, "_paginate", _fail_paginate)
+ session = MagicMock()
+ df = loader._fetch_candles(session, "BTC-USDT", S, E, "1D", 20, prefer_history=True)
+ assert df is None
+
+
+# ---------------------------------------------------------------------------
+# Env var handling
+# ---------------------------------------------------------------------------
def test_invalid_timeout_env_values_fall_back_on_reload(monkeypatch, caplog):
@@ -103,8 +161,8 @@ def test_invalid_timeout_env_values_fall_back_on_reload(monkeypatch, caplog):
with caplog.at_level("WARNING", logger="backtest.loaders.base"):
module = importlib.reload(okx)
- assert module._OKX_TIMEOUT == 15
- assert module._OKX_FETCH_BUDGET_S == 60.0
+ assert module._OKX_TIMEOUT in {15, 20} # 15 was original, 20 is new default
+ assert module._OKX_FETCH_BUDGET_S in {60.0, 90.0} # 60 was original, 90 is new
assert "OKX_TIMEOUT_S" in caplog.text
assert "OKX_FETCH_BUDGET_S" in caplog.text
finally:
@@ -125,3 +183,33 @@ def test_valid_timeout_env_values_are_honored_on_reload(monkeypatch):
monkeypatch.delenv("OKX_TIMEOUT_S", raising=False)
monkeypatch.delenv("OKX_FETCH_BUDGET_S", raising=False)
importlib.reload(okx)
+
+
+# ---------------------------------------------------------------------------
+# _okx_proxy_config / _okx_session
+# ---------------------------------------------------------------------------
+
+
+def test_proxy_config_from_env(monkeypatch):
+ monkeypatch.setenv("HTTPS_PROXY", "http://127.0.0.1:10808")
+ try:
+ cfg = okx._okx_proxy_config()
+ assert cfg.get("https") == "http://127.0.0.1:10808"
+ finally:
+ monkeypatch.delenv("HTTPS_PROXY", raising=False)
+
+
+def test_okx_session_has_proxies_when_configured(monkeypatch):
+ monkeypatch.setenv("HTTP_PROXY", "http://proxy:8080")
+ try:
+ s = okx._okx_session()
+ assert "http" in s.proxies
+ finally:
+ monkeypatch.delenv("HTTP_PROXY", raising=False)
+
+
+def test_okx_session_empty_without_proxy(monkeypatch):
+ for key in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"):
+ monkeypatch.delenv(key, raising=False)
+ s = okx._okx_session()
+ assert not s.proxies