Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(backtest): settle perpetual funding by bar span on 8h+ intervals

Yufeng He3b5a6b632c8a
diff --git a/agent/backtest/engines/_market_hooks.py b/agent/backtest/engines/_market_hooks.py
index 55cbe43f6..de248bab0 100644
--- a/agent/backtest/engines/_market_hooks.py
+++ b/agent/backtest/engines/_market_hooks.py
@@ -225,6 +225,19 @@ _TIER_TABLE = [
FUNDING_HOURS = {0, 8, 16}
+def _interval_span_hours(interval: str) -> float | None:
+ """Bar span in hours for a runner interval token, ``None`` when unknown.
+
+ The runner accepts only 1m/5m/15m/30m/1H/4H/1D, so ``m`` is minutes here
+ (there is no monthly token to confuse it with).
+ """
+ token = str(interval).strip()
+ for suffix, scale in (("m", 1 / 60), ("H", 1.0), ("D", 24.0)):
+ if token.endswith(suffix) and token[: -len(suffix)].isdigit():
+ return int(token[: -len(suffix)]) * scale
+ return None
+
+
def _maintenance_rate(notional_usd: float) -> float:
"""Look up tiered maintenance margin rate."""
for tier_max, rate in _TIER_TABLE:
@@ -241,6 +254,7 @@ def calc_crypto_funding_fee(
funding_rate: float,
applied_set: set,
daily_done_set: set,
+ bar_span_hours: float | None = None,
) -> float:
"""Calculate crypto funding fee for one symbol.
@@ -253,6 +267,12 @@ def calc_crypto_funding_fee(
carries no historical ``funding_rate`` column.
applied_set: (symbol, date, hour) dedup set — mutated.
daily_done_set: (symbol, date) dedup set — mutated.
+ bar_span_hours: Bar span in hours when known. At 8h or wider the
+ settlement count comes from the span (``max(1, span // 8)`` per
+ bar), because a daily bar can never land on the 8h/16h slots:
+ without this a daily-bar run charges a third of the documented
+ funding model (#1290). Narrower bars keep the slot logic below
+ unchanged.
Returns:
Fee amount (positive = longs pay, negative = longs receive).
@@ -263,7 +283,14 @@ def calc_crypto_funding_fee(
current_date = timestamp.date()
hour = timestamp.hour if hasattr(timestamp, "hour") else 0
- if hour in FUNDING_HOURS:
+ settlements = 1
+ if bar_span_hours is not None and bar_span_hours >= 8:
+ settlements = max(1, int(bar_span_hours // 8))
+ key = (symbol, current_date, hour)
+ if key in applied_set:
+ return 0.0
+ applied_set.add(key)
+ elif hour in FUNDING_HOURS:
key = (symbol, current_date, hour)
if key in applied_set:
return 0.0
@@ -286,7 +313,7 @@ def calc_crypto_funding_fee(
hist = bar.get("funding_rate")
if hist is not None and pd.notna(hist):
funding_rate = float(hist)
- return notional * funding_rate * pos.direction
+ return notional * funding_rate * pos.direction * settlements
def check_crypto_liquidation(
diff --git a/agent/backtest/engines/composite.py b/agent/backtest/engines/composite.py
index 6046bc2e3..cc91330a6 100644
--- a/agent/backtest/engines/composite.py
+++ b/agent/backtest/engines/composite.py
@@ -15,6 +15,7 @@ import pandas as pd
from backtest.engines.base import BaseEngine
from backtest.engines._market_hooks import (
_detect_market,
+ _interval_span_hours,
_is_china_futures,
code_currency,
calc_crypto_funding_fee,
@@ -132,6 +133,8 @@ class CompositeEngine(BaseEngine):
# Forex dedup state
self._last_swap_dates: dict = {}
+ self._run_interval = str(config.get("interval", "1D"))
+
def run_backtest(self, config: dict, *args, **kwargs):
"""Run the pipeline, refusing a code set that spans currencies.
@@ -255,6 +258,7 @@ class CompositeEngine(BaseEngine):
symbol, bar, timestamp, self.positions,
crypto_sub.funding_rate,
self._funding_applied, self._funding_daily_done,
+ _interval_span_hours(self._run_interval),
)
self.capital -= fee
diff --git a/agent/backtest/engines/crypto.py b/agent/backtest/engines/crypto.py
index 72c253297..67b9ae5a0 100644
--- a/agent/backtest/engines/crypto.py
+++ b/agent/backtest/engines/crypto.py
@@ -17,6 +17,7 @@ import pandas as pd
from backtest.engines.base import BaseEngine
from backtest.engines._market_hooks import (
+ _interval_span_hours,
calc_crypto_funding_fee,
check_crypto_liquidation,
)
@@ -603,6 +604,7 @@ class CryptoEngine(BaseEngine):
fee = calc_crypto_funding_fee(
symbol, bar, timestamp, self.positions,
self.funding_rate, self._funding_applied, self._funding_daily_done,
+ _interval_span_hours(self._run_interval),
)
self.capital -= fee
diff --git a/agent/tests/test_crypto_engine.py b/agent/tests/test_crypto_engine.py
index e87b25560..3af6833d3 100644
--- a/agent/tests/test_crypto_engine.py
+++ b/agent/tests/test_crypto_engine.py
@@ -261,7 +261,7 @@ class TestSlippage:
class TestFundingFee:
def test_funding_deducted_at_settlement_hour(self) -> None:
- engine = _make_engine(funding_rate=0.0001)
+ engine = _make_engine(funding_rate=0.0001, interval="1H")
engine.positions["BTC-USDT"] = Position(
"BTC-USDT", 1, 60000.0, pd.Timestamp("2025-01-01"), 1.0, leverage=10.0,
)
@@ -273,7 +273,7 @@ class TestFundingFee:
assert engine.capital == pytest.approx(initial_capital - 6.0)
def test_non_settlement_hour_applies_daily_fallback(self) -> None:
- """Non-settlement hour still applies funding once per day (daily bar support)."""
+ """Daily interval settles 3x per day (span-based count, #1290)."""
engine = _make_engine(funding_rate=0.0001)
engine.positions["BTC-USDT"] = Position(
"BTC-USDT", 1, 60000.0, pd.Timestamp("2025-01-01"), 1.0, leverage=10.0,
@@ -282,8 +282,8 @@ class TestFundingFee:
bar = _make_bar(close=60000.0)
ts = pd.Timestamp("2025-01-01 05:00:00") # not settlement hour
engine.on_bar("BTC-USDT", bar, ts)
- # Daily fallback: applies once even at non-settlement hour
- assert engine.capital == pytest.approx(initial_capital - 6.0)
+ # Daily bars settle 3x per bar regardless of which hour the bar prints
+ assert engine.capital == pytest.approx(initial_capital - 18.0)
def test_short_receives_funding(self) -> None:
engine = _make_engine(funding_rate=0.0001)
@@ -342,12 +342,35 @@ class TestFundingFee:
after_day3 = engine.capital
assert after_day3 < after_day2 # fee deducted again
- # Each day: 1 × 60000 × 0.0001 = $6
- assert initial - after_day3 == pytest.approx(18.0)
+ # Each day: 3 × 60000 × 0.0001 = $18; three days = $54
+ assert initial - after_day3 == pytest.approx(54.0)
+
+ def test_intraday_four_hour_bars_keep_slot_and_fallback(self) -> None:
+ """4H bars are below the span threshold: slot + daily fallback, as before."""
+ engine = _make_engine(funding_rate=0.0001, interval="4H")
+ engine.positions["BTC-USDT"] = Position(
+ "BTC-USDT", 1, 60000.0, pd.Timestamp("2025-01-01"), 1.0, leverage=10.0,
+ )
+ initial = engine.capital
+ bar = _make_bar(close=60000.0)
+ # 00:00 slot, 04:00 fallback, 08:00 slot, 16:00 slot -> 4 settlements
+ for hour in (0, 4, 8, 12, 16, 20):
+ engine.on_bar("BTC-USDT", bar, pd.Timestamp(f"2025-01-01 {hour:02d}:00:00"))
+ assert initial - engine.capital == pytest.approx(4 * 6.0)
+
+ def test_interval_span_hours_parser(self) -> None:
+ from backtest.engines._market_hooks import _interval_span_hours
+
+ assert _interval_span_hours("1m") == pytest.approx(1 / 60)
+ assert _interval_span_hours("30m") == pytest.approx(0.5)
+ assert _interval_span_hours("1H") == 1.0
+ assert _interval_span_hours("4H") == 4.0
+ assert _interval_span_hours("1D") == 24.0
+ assert _interval_span_hours("nonsense") is None
def test_multi_symbol_funding(self) -> None:
"""Each symbol gets independent funding settlement."""
- engine = _make_engine(funding_rate=0.0001)
+ engine = _make_engine(funding_rate=0.0001, interval="1H")
engine.positions["BTC-USDT"] = Position(
"BTC-USDT", 1, 60000.0, pd.Timestamp("2025-01-01"), 1.0, leverage=10.0,
)
@@ -463,7 +486,7 @@ 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 = _make_engine(funding_rate=0.0001, interval="1H")
engine.positions["BTC-USDT-PERP"] = Position(
"BTC-USDT-PERP", 1, 60000.0, pd.Timestamp("2025-01-01"), 1.0, leverage=10.0,
)
@@ -475,7 +498,7 @@ class TestHistoricalFundingRate:
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 = _make_engine(funding_rate=0.0001, interval="1H")
engine.positions["BTC-USDT-PERP"] = Position(
"BTC-USDT-PERP", 1, 60000.0, pd.Timestamp("2025-01-01"), 1.0, leverage=10.0,
)
@@ -489,7 +512,7 @@ class TestHistoricalFundingRate:
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 = _make_engine(funding_rate=0.0001, interval="1H")
engine.positions["BTC-USDT-PERP"] = Position(
"BTC-USDT-PERP", 1, 60000.0, pd.Timestamp("2025-01-01"), 1.0, leverage=10.0,
)