Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(backtest): consume historical USD-M funding + round settlement jitter (#819)

Gordon Lee84eff84a6a9f
diff --git a/agent/backtest/engines/_market_hooks.py b/agent/backtest/engines/_market_hooks.py
index f34e1ea59..9a43fe43a 100644
--- a/agent/backtest/engines/_market_hooks.py
+++ b/agent/backtest/engines/_market_hooks.py
@@ -164,7 +164,8 @@ def calc_crypto_funding_fee(
bar: Current bar data.
timestamp: Bar timestamp.
positions: Shared positions dict.
- funding_rate: Fixed rate per settlement.
+ funding_rate: Fallback fixed rate per settlement, used when the bar
+ carries no historical ``funding_rate`` column.
applied_set: (symbol, date, hour) dedup set — mutated.
daily_done_set: (symbol, date) dedup set — mutated.
@@ -194,6 +195,12 @@ def calc_crypto_funding_fee(
mark_price = float(bar.get("close", pos.entry_price))
notional = pos.size * mark_price
+ # Prefer the bar's historical funding rate when the loader supplied one
+ # (USD-M perpetual data via BASE-USDT-PERP); fall back to the fixed
+ # config rate otherwise so spot-proxy runs keep their behaviour.
+ hist = bar.get("funding_rate")
+ if hist is not None and pd.notna(hist):
+ funding_rate = float(hist)
return notional * funding_rate * pos.direction
diff --git a/agent/backtest/loaders/ccxt_loader.py b/agent/backtest/loaders/ccxt_loader.py
index 5ba0d02c6..1b410896a 100644
--- a/agent/backtest/loaders/ccxt_loader.py
+++ b/agent/backtest/loaders/ccxt_loader.py
@@ -409,9 +409,12 @@ class DataLoader:
)
frame = pd.DataFrame({
+ # Binance settlement timestamps carry millisecond jitter
+ # (e.g. 08:00:00.011); round to the second so they align with
+ # bar timestamps instead of failing the missing-settlement check.
"trade_date": pd.to_datetime(
[row["timestamp"] for row in rows], unit="ms"
- ),
+ ).round("s"),
"funding_rate": pd.to_numeric(
[row["fundingRate"] for row in rows], errors="raise"
),
diff --git a/agent/tests/test_ccxt_perpetual_loader.py b/agent/tests/test_ccxt_perpetual_loader.py
index 3494a33f1..9c33b82ad 100644
--- a/agent/tests/test_ccxt_perpetual_loader.py
+++ b/agent/tests/test_ccxt_perpetual_loader.py
@@ -353,3 +353,27 @@ def test_bracket_artifact_rejects_non_monotonic_brackets() -> None:
])
with pytest.raises(ValueError, match="not strictly increasing"):
_validate_bracket_artifact(artifact, expected_symbol="BTC/USDT:USDT")
+
+
+def test_perpetual_fetch_rounds_funding_settlement_jitter(monkeypatch) -> None:
+ """Binance returns settlement timestamps with millisecond jitter
+ (e.g. ``08:00:00.011``); the loader must round them to the second so
+ they align with bar timestamps instead of raising the
+ missing-settlement error."""
+ start = int(pd.Timestamp("2024-01-01 00:00:00").timestamp() * 1000)
+ exchange = _PerpetualExchange(
+ funding_rows=[{"timestamp": start + 11, "fundingRate": 0.0003}]
+ )
+ 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.0003, 0.0]
+ assert frame["funding_settlement_time"].iloc[0] == pd.Timestamp("2024-01-01")
diff --git a/agent/tests/test_crypto_engine.py b/agent/tests/test_crypto_engine.py
index 1ddbbb71a..2efb9e21d 100644
--- a/agent/tests/test_crypto_engine.py
+++ b/agent/tests/test_crypto_engine.py
@@ -327,3 +327,44 @@ class TestMaintenanceRate:
def test_maximum_tier(self) -> None:
assert _maintenance_rate(100_000_000) == 0.10
+
+
+class TestHistoricalFundingRate:
+ def test_bar_funding_rate_overrides_fixed_rate(self) -> None:
+ """A bar carrying a historical ``funding_rate`` column (USD-M perp
+ data) must be charged at that rate, not the fixed config rate."""
+ engine = _make_engine(funding_rate=0.0001)
+ engine.positions["BTC-USDT-PERP"] = Position(
+ "BTC-USDT-PERP", 1, 60000.0, pd.Timestamp("2025-01-01"), 1.0, leverage=10.0,
+ )
+ initial_capital = engine.capital
+ bar = pd.Series({"close": 60000.0, "open": 60000.0, "funding_rate": 0.0005})
+ ts = pd.Timestamp("2025-01-01 08:00:00")
+ engine.on_bar("BTC-USDT-PERP", bar, ts)
+ # Historical rate: 1.0 × 60000 × 0.0005 = $30 (not $6 from the fixed rate)
+ assert engine.capital == pytest.approx(initial_capital - 30.0)
+
+ def test_negative_historical_funding_pays_longs(self) -> None:
+ engine = _make_engine(funding_rate=0.0001)
+ engine.positions["BTC-USDT-PERP"] = Position(
+ "BTC-USDT-PERP", 1, 60000.0, pd.Timestamp("2025-01-01"), 1.0, leverage=10.0,
+ )
+ initial_capital = engine.capital
+ bar = pd.Series({"close": 60000.0, "open": 60000.0, "funding_rate": -0.0002})
+ ts = pd.Timestamp("2025-01-01 08:00:00")
+ engine.on_bar("BTC-USDT-PERP", bar, ts)
+ # Negative funding: longs receive
+ assert engine.capital == pytest.approx(initial_capital + 12.0)
+
+ def test_nan_funding_rate_falls_back_to_fixed(self) -> None:
+ """Non-settlement bars carry NaN funding_rate — must fall back to
+ the fixed config rate (daily-fallback path), not charge NaN."""
+ engine = _make_engine(funding_rate=0.0001)
+ engine.positions["BTC-USDT-PERP"] = Position(
+ "BTC-USDT-PERP", 1, 60000.0, pd.Timestamp("2025-01-01"), 1.0, leverage=10.0,
+ )
+ initial_capital = engine.capital
+ bar = pd.Series({"close": 60000.0, "open": 60000.0, "funding_rate": float("nan")})
+ ts = pd.Timestamp("2025-01-01 08:00:00")
+ engine.on_bar("BTC-USDT-PERP", bar, ts)
+ assert engine.capital == pytest.approx(initial_capital - 6.0)