Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(data): separate USD-M execution and mark prices

zygora59aa5ee9097c
diff --git a/agent/backtest/loaders/ccxt_loader.py b/agent/backtest/loaders/ccxt_loader.py
index c01d0f149..902f6ab0d 100644
--- a/agent/backtest/loaders/ccxt_loader.py
+++ b/agent/backtest/loaders/ccxt_loader.py
@@ -95,12 +95,18 @@ class DataLoader:
def __init__(self) -> None:
pass
- def _get_exchange(self):
- """Create exchange instance."""
+ def _get_exchange(self, instrument_type: str = "spot"):
+ """Create an exchange instance for spot or Binance USD-M swaps."""
import ccxt
from src.config.accessor import get_env_config
exchange_id = get_env_config().data.ccxt_exchange.lower()
+ if instrument_type == "swap":
+ if exchange_id not in {"binance", "binanceusdm"}:
+ raise ValueError(
+ "BASE-USDT-PERP currently requires CCXT_EXCHANGE=binance"
+ )
+ exchange_id = "binanceusdm"
exchange_cls = getattr(ccxt, exchange_id, None)
if exchange_cls is None:
logger.warning("Unknown CCXT exchange %s, falling back to binance", exchange_id)
@@ -143,15 +149,27 @@ class DataLoader:
# opens an exchange object.
exchange_holder: Dict[str, object] = {}
- def get_exchange():
- if "exchange" not in exchange_holder:
- exchange_holder["exchange"] = self._get_exchange()
- return exchange_holder["exchange"]
+ def get_exchange(instrument_type: str):
+ if instrument_type not in exchange_holder:
+ exchange_holder[instrument_type] = self._get_exchange(instrument_type)
+ return exchange_holder[instrument_type]
result: Dict[str, pd.DataFrame] = {}
for code in codes:
+ instrument_type = "spot"
try:
- ccxt_symbol, _instrument_type = _parse_ccxt_symbol(code)
+ ccxt_symbol, instrument_type = _parse_ccxt_symbol(code)
+ exchange = get_exchange(instrument_type)
+
+ def fetch_frame():
+ if instrument_type == "swap":
+ return self._fetch_perpetual(
+ exchange, ccxt_symbol, timeframe, since_ms, end_ms
+ )
+ return self._fetch_one(
+ exchange, ccxt_symbol, timeframe, since_ms, end_ms
+ )
+
df = cached_loader_fetch(
source=self.name,
symbol=code,
@@ -159,19 +177,48 @@ class DataLoader:
start_date=start_date,
end_date=end_date,
fields=None,
- fetch=lambda ccxt_symbol=ccxt_symbol: self._fetch_one(
- get_exchange(), ccxt_symbol, timeframe, since_ms, end_ms
- ),
+ fetch=fetch_frame,
)
if df is not None and not df.empty:
result[code] = df
except Exception as exc:
+ if instrument_type == "swap" or code.strip().upper().endswith("-PERP"):
+ raise
logger.warning("CCXT failed for %s: %s", code, exc)
return result
+ @classmethod
+ def _fetch_perpetual(
+ cls, exchange, symbol: str, timeframe: str, since_ms: int, end_ms: int,
+ ) -> pd.DataFrame:
+ """Fetch aligned trade-price and mark-price candles for one USD-M swap."""
+ trade = cls._fetch_one(exchange, symbol, timeframe, since_ms, end_ms)
+ mark = cls._fetch_one(
+ exchange,
+ symbol,
+ timeframe,
+ since_ms,
+ end_ms,
+ params={"price": "mark"},
+ )
+ if trade is None or mark is None or not trade.index.equals(mark.index):
+ raise ValueError(f"mark-price timestamps are incomplete or unsynchronized for {symbol}")
+
+ result = trade.copy()
+ result["execution_open"] = trade["open"]
+ for column in ("open", "high", "low", "close"):
+ result[f"mark_{column}"] = mark[column]
+ return result
+
@staticmethod
def _fetch_one(
- exchange, symbol: str, timeframe: str, since_ms: int, end_ms: int,
+ exchange,
+ symbol: str,
+ timeframe: str,
+ since_ms: int,
+ end_ms: int,
+ *,
+ params: dict[str, str] | None = None,
) -> Optional[pd.DataFrame]:
"""Paginated OHLCV fetch for one symbol."""
import ccxt
@@ -187,8 +234,14 @@ class DataLoader:
# ``ccxt.NetworkError`` covers RequestTimeout / DDoSProtection /
# ExchangeNotAvailable — the transient family. Anything else
# (e.g. ``ExchangeError`` for a bad symbol) is not retried.
+ def fetch_page():
+ kwargs = {"since": cursor, "limit": limit}
+ if params is not None:
+ kwargs["params"] = params
+ return exchange.fetch_ohlcv(symbol, timeframe, **kwargs)
+
ohlcv = retry_with_budget(
- lambda: exchange.fetch_ohlcv(symbol, timeframe, since=cursor, limit=limit),
+ fetch_page,
transient=ccxt.NetworkError,
deadline=deadline,
label=label,
diff --git a/agent/tests/test_ccxt_perpetual_loader.py b/agent/tests/test_ccxt_perpetual_loader.py
index 8c313b53c..e4ce8f613 100644
--- a/agent/tests/test_ccxt_perpetual_loader.py
+++ b/agent/tests/test_ccxt_perpetual_loader.py
@@ -3,11 +3,38 @@
from __future__ import annotations
import pytest
+import pandas as pd
from backtest.loaders.base import make_loader_cache_key
from backtest.loaders.ccxt_loader import _parse_ccxt_symbol
+def _hourly_rows(opens: list[float]) -> list[list[float]]:
+ start = int(pd.Timestamp("2024-01-01 00:00:00").timestamp() * 1000)
+ hour = 3_600_000
+ return [
+ [start + i * hour, value, value + 2, value - 2, value + 1, 10 + i]
+ for i, value in enumerate(opens)
+ ]
+
+
+class _PerpetualExchange:
+ def __init__(self, *, mark_rows: list[list[float]] | 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])
+ self.calls: list[dict[str, object]] = []
+
+ def fetch_ohlcv(self, symbol, timeframe, since=None, limit=None, params=None):
+ self.calls.append({
+ "symbol": symbol,
+ "timeframe": timeframe,
+ "since": since,
+ "limit": limit,
+ "params": params,
+ })
+ return self.mark_rows if params == {"price": "mark"} else self.trade_rows
+
+
def test_spot_symbol_keeps_existing_ccxt_contract() -> None:
assert _parse_ccxt_symbol("BTC-USDT") == ("BTC/USDT", "spot")
@@ -33,3 +60,43 @@ def test_spot_and_perpetual_cache_keys_cannot_collide() -> None:
spot = make_loader_cache_key(symbol="BTC-USDT", **common)
perpetual = make_loader_cache_key(symbol="BTC-USDT-PERP", **common)
assert spot != perpetual
+
+
+def test_perpetual_fetch_separates_execution_and_mark_prices(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["execution_open"].tolist() == [100.0, 101.0]
+ assert frame["mark_open"].tolist() == [99.0, 100.0]
+ assert frame["mark_high"].tolist() == [101.0, 102.0]
+ assert frame["mark_low"].tolist() == [97.0, 98.0]
+ assert frame["mark_close"].tolist() == [100.0, 101.0]
+ assert exchange.calls[0]["symbol"] == "BTC/USDT:USDT"
+ assert exchange.calls[0]["params"] is None
+ assert exchange.calls[1]["params"] == {"price": "mark"}
+
+
+def test_perpetual_fetch_rejects_unsynchronized_mark_rows(monkeypatch) -> None:
+ mark_rows = _hourly_rows([99.0, 100.0])
+ mark_rows[1][0] += 60_000
+ exchange = _PerpetualExchange(mark_rows=mark_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="mark-price timestamps"):
+ DataLoader().fetch(
+ ["BTC-USDT-PERP"], "2024-01-01", "2024-01-01", interval="1H"
+ )