Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(data): add historical USD-M funding settlements and maintenance brackets

zygoracfe579086fe5
diff --git a/agent/backtest/loaders/ccxt_loader.py b/agent/backtest/loaders/ccxt_loader.py
index 902f6ab0d..51e8de519 100644
--- a/agent/backtest/loaders/ccxt_loader.py
+++ b/agent/backtest/loaders/ccxt_loader.py
@@ -7,6 +7,8 @@ No API key required for public market data.
from __future__ import annotations
+import hashlib
+import json
import logging
import os
import re
@@ -39,6 +41,7 @@ _INTERVAL_MAP = {
# scheduling is delegated to :mod:`backtest.loaders.base`.
_CCXT_TIMEOUT_MS = positive_env_int("CCXT_TIMEOUT_MS", 15_000)
_CCXT_FETCH_BUDGET_S = positive_env_float("CCXT_FETCH_BUDGET_S", 60.0)
+_FUNDING_HOURS = {0, 8, 16}
def _parse_ccxt_symbol(code: str) -> tuple[str, str]:
@@ -208,8 +211,135 @@ class DataLoader:
result["execution_open"] = trade["open"]
for column in ("open", "high", "low", "close"):
result[f"mark_{column}"] = mark[column]
+
+ funding = cls._fetch_funding_history(exchange, symbol, since_ms, end_ms)
+ if funding.index.has_duplicates:
+ raise ValueError(f"duplicate funding settlement for {symbol}")
+ required = result.index[result.index.hour.isin(_FUNDING_HOURS)]
+ missing = required.difference(funding.index)
+ if not missing.empty:
+ raise ValueError(
+ f"funding settlement data is missing for {symbol}: "
+ f"{', '.join(str(ts) for ts in missing)}"
+ )
+
+ result["funding_rate"] = 0.0
+ result["funding_settlement_time"] = pd.NaT
+ aligned = funding.index.intersection(result.index)
+ if not aligned.empty:
+ result.loc[aligned, "funding_rate"] = funding.loc[aligned, "funding_rate"]
+ result.loc[aligned, "funding_settlement_time"] = aligned
+
+ brackets, version = cls._fetch_maintenance_brackets(exchange, symbol)
+ result["maintenance_brackets"] = json.dumps(brackets)
+ result["maintenance_bracket_version"] = version
return result
+ @staticmethod
+ def _fetch_funding_history(
+ exchange, symbol: str, since_ms: int, end_ms: int,
+ ) -> pd.DataFrame:
+ """Fetch bounded historical funding settlements for one USD-M swap."""
+ import ccxt
+
+ rows: list[dict] = []
+ cursor = since_ms
+ limit = 1000
+ deadline = time.monotonic() + _CCXT_FETCH_BUDGET_S
+ label = f"ccxt funding fetch for {symbol}"
+
+ for _ in range(200):
+ check_budget(deadline, label, budget_s=_CCXT_FETCH_BUDGET_S)
+ page = retry_with_budget(
+ lambda: exchange.fetch_funding_rate_history(
+ symbol, since=cursor, limit=limit
+ ),
+ transient=ccxt.NetworkError,
+ deadline=deadline,
+ label=label,
+ )
+ if not page:
+ break
+ rows.extend(page)
+ last_ts = int(page[-1]["timestamp"])
+ if last_ts >= end_ms or len(page) < limit:
+ break
+ cursor = last_ts + 1
+
+ if not rows:
+ return pd.DataFrame(
+ {"funding_rate": pd.Series(dtype=float)},
+ index=pd.DatetimeIndex([], name="trade_date"),
+ )
+
+ frame = pd.DataFrame({
+ "trade_date": pd.to_datetime(
+ [row["timestamp"] for row in rows], unit="ms"
+ ),
+ "funding_rate": pd.to_numeric(
+ [row["fundingRate"] for row in rows], errors="raise"
+ ),
+ }).set_index("trade_date").sort_index()
+ start_dt = pd.Timestamp(since_ms, unit="ms")
+ end_dt = pd.Timestamp(end_ms, unit="ms")
+ return frame[(frame.index >= start_dt) & (frame.index < end_dt)]
+
+ @staticmethod
+ def _fetch_maintenance_brackets(exchange, symbol: str) -> tuple[list[dict], str]:
+ """Fetch the current versioned maintenance-margin bracket schedule.
+
+ CCXT/Binance expose only the *current* bracket table (no history), so
+ each bracket record is stamped with a content hash rather than an
+ exchange-provided version: any change to the schedule changes the
+ hash, giving downstream consumers a fail-closed way to detect a stale
+ or mismatched bracket set.
+ """
+ import ccxt
+
+ try:
+ raw = retry_with_budget(
+ lambda: exchange.fetch_leverage_tiers([symbol]),
+ transient=ccxt.NetworkError,
+ deadline=time.monotonic() + _CCXT_FETCH_BUDGET_S,
+ label=f"ccxt bracket fetch for {symbol}",
+ )
+ tiers = raw.get(symbol) if raw else None
+ except Exception as exc:
+ raise ValueError(f"maintenance bracket fetch failed for {symbol}: {exc}") from exc
+
+ if not tiers:
+ raise ValueError(f"maintenance bracket data is missing for {symbol}")
+
+ brackets: list[dict] = []
+ for tier in tiers:
+ info = tier.get("info") or {}
+ try:
+ bracket_tier = int(info["bracket"])
+ notional_cap = float(info["notionalCap"])
+ maintenance_rate = float(info["maintMarginRatio"])
+ cumulative_maintenance_amount = float(info["cum"])
+ except (KeyError, TypeError, ValueError) as exc:
+ raise ValueError(
+ f"maintenance bracket for {symbol} is missing a required field: {exc}"
+ ) from exc
+ brackets.append({
+ "bracket_tier": bracket_tier,
+ "notional_cap": notional_cap,
+ "maintenance_rate": maintenance_rate,
+ "cumulative_maintenance_amount": cumulative_maintenance_amount,
+ })
+
+ brackets.sort(key=lambda row: row["bracket_tier"])
+ caps = [row["notional_cap"] for row in brackets]
+ if caps != sorted(caps) or len(caps) != len(set(caps)):
+ raise ValueError(
+ f"maintenance bracket notional caps for {symbol} are not strictly increasing"
+ )
+
+ blob = json.dumps(brackets, sort_keys=True, separators=(",", ":")).encode("utf-8")
+ version = hashlib.sha256(blob).hexdigest()[:16]
+ return brackets, version
+
@staticmethod
def _fetch_one(
exchange,
diff --git a/agent/tests/test_ccxt_perpetual_loader.py b/agent/tests/test_ccxt_perpetual_loader.py
index e4ce8f613..29cb63486 100644
--- a/agent/tests/test_ccxt_perpetual_loader.py
+++ b/agent/tests/test_ccxt_perpetual_loader.py
@@ -2,6 +2,8 @@
from __future__ import annotations
+import json
+
import pytest
import pandas as pd
@@ -18,10 +20,29 @@ def _hourly_rows(opens: list[float]) -> list[list[float]]:
]
+_DEFAULT_BRACKETS = [
+ {"bracket": 1, "notionalCap": 50_000, "maintMarginRatio": 0.004, "cum": 0.0},
+ {"bracket": 2, "notionalCap": 250_000, "maintMarginRatio": 0.005, "cum": 50.0},
+]
+
+
class _PerpetualExchange:
- def __init__(self, *, mark_rows: list[list[float]] | None = None) -> None:
+ def __init__(
+ self,
+ *,
+ mark_rows: list[list[float]] | None = None,
+ funding_rows: list[dict[str, object]] | None = None,
+ brackets: list[dict[str, object]] | None = None,
+ ) -> None:
self.trade_rows = _hourly_rows([100.0, 101.0])
self.mark_rows = mark_rows if mark_rows is not None else _hourly_rows([99.0, 100.0])
+ start = int(pd.Timestamp("2024-01-01 00:00:00").timestamp() * 1000)
+ self.funding_rows = (
+ funding_rows
+ if funding_rows is not None
+ else [{"timestamp": start, "fundingRate": 0.0}]
+ )
+ self.brackets = _DEFAULT_BRACKETS if brackets is None else brackets
self.calls: list[dict[str, object]] = []
def fetch_ohlcv(self, symbol, timeframe, since=None, limit=None, params=None):
@@ -34,6 +55,31 @@ class _PerpetualExchange:
})
return self.mark_rows if params == {"price": "mark"} else self.trade_rows
+ def fetch_funding_rate_history(self, symbol, since=None, limit=None):
+ self.calls.append({
+ "funding_symbol": symbol,
+ "since": since,
+ "limit": limit,
+ })
+ return self.funding_rows
+
+ def fetch_leverage_tiers(self, symbols):
+ self.calls.append({"bracket_symbols": symbols})
+ [symbol] = symbols
+ return {
+ symbol: [
+ {
+ "tier": row["bracket"],
+ "minNotional": 0,
+ "maxNotional": row["notionalCap"],
+ "maintenanceMarginRate": row["maintMarginRatio"],
+ "maxLeverage": 1,
+ "info": row,
+ }
+ for row in self.brackets
+ ]
+ }
+
def test_spot_symbol_keeps_existing_ccxt_contract() -> None:
assert _parse_ccxt_symbol("BTC-USDT") == ("BTC/USDT", "spot")
@@ -100,3 +146,169 @@ def test_perpetual_fetch_rejects_unsynchronized_mark_rows(monkeypatch) -> None:
DataLoader().fetch(
["BTC-USDT-PERP"], "2024-01-01", "2024-01-01", interval="1H"
)
+
+
+def test_perpetual_fetch_aligns_explicit_zero_funding_settlement(monkeypatch) -> None:
+ exchange = _PerpetualExchange()
+ monkeypatch.setattr(
+ "backtest.loaders.ccxt_loader.DataLoader._get_exchange",
+ lambda _self, instrument_type="spot": exchange,
+ )
+
+ from backtest.loaders.ccxt_loader import DataLoader
+
+ frame = DataLoader().fetch(
+ ["BTC-USDT-PERP"], "2024-01-01", "2024-01-01", interval="1H"
+ )["BTC-USDT-PERP"]
+
+ assert frame["funding_rate"].tolist() == [0.0, 0.0]
+ assert frame["funding_settlement_time"].iloc[0] == pd.Timestamp("2024-01-01")
+ assert pd.isna(frame["funding_settlement_time"].iloc[1])
+
+
+def test_perpetual_fetch_rejects_missing_required_funding_settlement(monkeypatch) -> None:
+ exchange = _PerpetualExchange(funding_rows=[])
+ monkeypatch.setattr(
+ "backtest.loaders.ccxt_loader.DataLoader._get_exchange",
+ lambda _self, instrument_type="spot": exchange,
+ )
+
+ from backtest.loaders.ccxt_loader import DataLoader
+
+ with pytest.raises(ValueError, match="funding settlement"):
+ DataLoader().fetch(
+ ["BTC-USDT-PERP"], "2024-01-01", "2024-01-01", interval="1H"
+ )
+
+
+def test_perpetual_fetch_rejects_duplicate_funding_settlement(monkeypatch) -> None:
+ start = int(pd.Timestamp("2024-01-01 00:00:00").timestamp() * 1000)
+ exchange = _PerpetualExchange(funding_rows=[
+ {"timestamp": start, "fundingRate": 0.0001},
+ {"timestamp": start, "fundingRate": 0.0002},
+ ])
+ monkeypatch.setattr(
+ "backtest.loaders.ccxt_loader.DataLoader._get_exchange",
+ lambda _self, instrument_type="spot": exchange,
+ )
+
+ from backtest.loaders.ccxt_loader import DataLoader
+
+ with pytest.raises(ValueError, match="duplicate funding settlement"):
+ DataLoader().fetch(
+ ["BTC-USDT-PERP"], "2024-01-01", "2024-01-01", interval="1H"
+ )
+
+
+def test_perpetual_fetch_attaches_versioned_maintenance_brackets(monkeypatch) -> None:
+ exchange = _PerpetualExchange()
+ monkeypatch.setattr(
+ "backtest.loaders.ccxt_loader.DataLoader._get_exchange",
+ lambda _self, instrument_type="spot": exchange,
+ )
+
+ from backtest.loaders.ccxt_loader import DataLoader
+
+ frame = DataLoader().fetch(
+ ["BTC-USDT-PERP"], "2024-01-01", "2024-01-01", interval="1H"
+ )["BTC-USDT-PERP"]
+
+ versions = frame["maintenance_bracket_version"].unique().tolist()
+ assert len(versions) == 1
+ assert isinstance(versions[0], str) and versions[0]
+
+ brackets = json.loads(frame["maintenance_brackets"].iloc[0])
+ assert brackets == [
+ {
+ "bracket_tier": 1,
+ "notional_cap": 50_000.0,
+ "maintenance_rate": 0.004,
+ "cumulative_maintenance_amount": 0.0,
+ },
+ {
+ "bracket_tier": 2,
+ "notional_cap": 250_000.0,
+ "maintenance_rate": 0.005,
+ "cumulative_maintenance_amount": 50.0,
+ },
+ ]
+ assert frame["maintenance_brackets"].nunique() == 1
+
+
+def test_perpetual_fetch_bracket_version_changes_with_bracket_contents(monkeypatch) -> None:
+ from backtest.loaders.ccxt_loader import DataLoader
+
+ exchange_a = _PerpetualExchange()
+ monkeypatch.setattr(
+ "backtest.loaders.ccxt_loader.DataLoader._get_exchange",
+ lambda _self, instrument_type="spot": exchange_a,
+ )
+ frame_a = DataLoader().fetch(
+ ["BTC-USDT-PERP"], "2024-01-01", "2024-01-01", interval="1H"
+ )["BTC-USDT-PERP"]
+
+ exchange_b = _PerpetualExchange(brackets=[
+ {"bracket": 1, "notionalCap": 50_000, "maintMarginRatio": 0.005, "cum": 0.0},
+ ])
+ monkeypatch.setattr(
+ "backtest.loaders.ccxt_loader.DataLoader._get_exchange",
+ lambda _self, instrument_type="spot": exchange_b,
+ )
+ frame_b = DataLoader().fetch(
+ ["BTC-USDT-PERP"], "2024-01-01", "2024-01-01", interval="1H"
+ )["BTC-USDT-PERP"]
+
+ assert (
+ frame_a["maintenance_bracket_version"].iloc[0]
+ != frame_b["maintenance_bracket_version"].iloc[0]
+ )
+
+
+def test_perpetual_fetch_rejects_empty_maintenance_brackets(monkeypatch) -> None:
+ exchange = _PerpetualExchange(brackets=[])
+ monkeypatch.setattr(
+ "backtest.loaders.ccxt_loader.DataLoader._get_exchange",
+ lambda _self, instrument_type="spot": exchange,
+ )
+
+ from backtest.loaders.ccxt_loader import DataLoader
+
+ with pytest.raises(ValueError, match="maintenance bracket"):
+ DataLoader().fetch(
+ ["BTC-USDT-PERP"], "2024-01-01", "2024-01-01", interval="1H"
+ )
+
+
+def test_perpetual_fetch_rejects_maintenance_bracket_missing_field(monkeypatch) -> None:
+ exchange = _PerpetualExchange(brackets=[
+ {"bracket": 1, "notionalCap": 50_000, "maintMarginRatio": 0.004},
+ ])
+ monkeypatch.setattr(
+ "backtest.loaders.ccxt_loader.DataLoader._get_exchange",
+ lambda _self, instrument_type="spot": exchange,
+ )
+
+ from backtest.loaders.ccxt_loader import DataLoader
+
+ with pytest.raises(ValueError, match="maintenance bracket"):
+ DataLoader().fetch(
+ ["BTC-USDT-PERP"], "2024-01-01", "2024-01-01", interval="1H"
+ )
+
+
+def test_perpetual_fetch_rejects_non_monotonic_maintenance_brackets(monkeypatch) -> None:
+ exchange = _PerpetualExchange(brackets=[
+ {"bracket": 1, "notionalCap": 250_000, "maintMarginRatio": 0.004, "cum": 0.0},
+ {"bracket": 2, "notionalCap": 50_000, "maintMarginRatio": 0.005, "cum": 50.0},
+ ])
+ monkeypatch.setattr(
+ "backtest.loaders.ccxt_loader.DataLoader._get_exchange",
+ lambda _self, instrument_type="spot": exchange,
+ )
+
+ from backtest.loaders.ccxt_loader import DataLoader
+
+ with pytest.raises(ValueError, match="maintenance bracket"):
+ DataLoader().fetch(
+ ["BTC-USDT-PERP"], "2024-01-01", "2024-01-01", interval="1H"
+ )