Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(backtest): define perpetual margin state contracts (#798)

Hongi Nagaputrac5540a92e3ef
diff --git a/agent/backtest/perpetual_risk.py b/agent/backtest/perpetual_risk.py
new file mode 100644
index 000000000..34229b53c
--- /dev/null
+++ b/agent/backtest/perpetual_risk.py
@@ -0,0 +1,235 @@
+"""Pure state and risk contracts for historical USD-M perpetual backtests.
+
+The model is deliberately account-local and deterministic. It does not read
+live exchange state, model open orders, or store mutable mark prices on
+positions.
+
+Maintenance-bracket data comes from the loader's already-validated artifact
+contract (``backtest.loaders.ccxt_loader._validate_bracket_artifact``): a
+symbol, a list of tiers, and a single content-hash version. This module does
+not re-fetch, re-derive, or re-hash brackets — it only re-validates their
+structural invariants (ordering, non-negativity) as a defense-in-depth check
+on whatever the caller passes in.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+import json
+import math
+from typing import Literal
+
+import pandas as pd
+
+
+MarginMode = Literal["isolated", "cross"]
+TerminalStatus = Literal["active", "completed", "account_liquidation"]
+
+
+def _require_finite(name: str, value: float, *, positive: bool = False) -> None:
+ if not math.isfinite(value) or (positive and value <= 0):
+ qualifier = "positive and finite" if positive else "finite"
+ raise ValueError(f"{name} must be {qualifier}")
+
+
+def _timestamp(value: pd.Timestamp, name: str) -> pd.Timestamp:
+ timestamp = pd.Timestamp(value)
+ if pd.isna(timestamp):
+ raise ValueError(f"{name} must be a valid timestamp")
+ return timestamp
+
+
+@dataclass(frozen=True)
+class MaintenanceBracket:
+ """One symbol-specific maintenance-margin bracket.
+
+ Field names and semantics match the loader's bracket-artifact tier
+ records exactly (``bracket_tier``, ``notional_cap``, ``maintenance_rate``,
+ ``cumulative_maintenance_amount``, optional ``notional_coefficient``).
+ """
+
+ bracket_tier: int
+ notional_cap: float
+ maintenance_rate: float
+ cumulative_maintenance_amount: float
+ notional_coefficient: float | None = None
+
+ def __post_init__(self) -> None:
+ if self.bracket_tier < 0:
+ raise ValueError("bracket_tier must be non-negative")
+ _require_finite("notional_cap", self.notional_cap, positive=True)
+ _require_finite("maintenance_rate", self.maintenance_rate)
+ _require_finite(
+ "cumulative_maintenance_amount", self.cumulative_maintenance_amount
+ )
+ if self.maintenance_rate < 0:
+ raise ValueError("maintenance_rate must be non-negative")
+ if self.cumulative_maintenance_amount < 0:
+ raise ValueError("cumulative_maintenance_amount must be non-negative")
+ if self.notional_coefficient is not None:
+ _require_finite("notional_coefficient", self.notional_coefficient)
+
+
+@dataclass(frozen=True)
+class MaintenanceSchedule:
+ """A validated, versioned set of maintenance brackets for one symbol.
+
+ ``version`` is an opaque identifier supplied by the caller — in practice
+ the loader's ``maintenance_bracket_version`` content-hash column. This
+ class does not compute its own hash: the artifact contract
+ (``_validate_bracket_artifact``) is the single source of truth for
+ content integrity, checked once, before this object is ever built.
+ """
+
+ symbol: str
+ version: str
+ brackets: tuple[MaintenanceBracket, ...]
+
+ def __post_init__(self) -> None:
+ if not self.symbol:
+ raise ValueError("symbol must not be empty")
+ if not self.version:
+ raise ValueError("version must not be empty")
+ if not self.brackets:
+ raise ValueError("brackets must not be empty")
+ tiers = [bracket.bracket_tier for bracket in self.brackets]
+ if tiers != sorted(tiers) or len(tiers) != len(set(tiers)):
+ raise ValueError("bracket_tier values must be strictly increasing")
+ caps = [bracket.notional_cap for bracket in self.brackets]
+ if any(current <= previous for previous, current in zip(caps, caps[1:])):
+ raise ValueError("notional caps must be strictly increasing")
+
+ @classmethod
+ def from_loader_columns(
+ cls, symbol: str, maintenance_brackets: str, maintenance_bracket_version: str,
+ ) -> MaintenanceSchedule:
+ """Build a schedule from the loader's ``maintenance_brackets`` /
+ ``maintenance_bracket_version`` DataFrame columns.
+
+ The JSON payload is already-validated tier records (from
+ ``_validate_bracket_artifact``) — this only parses and re-checks
+ structural invariants, it never re-derives the version hash.
+ """
+ try:
+ records = json.loads(maintenance_brackets)
+ except (TypeError, json.JSONDecodeError) as exc:
+ raise ValueError("maintenance_brackets is not valid JSON") from exc
+ if not isinstance(records, list) or not records:
+ raise ValueError("maintenance_brackets must be a non-empty list")
+ brackets = tuple(
+ MaintenanceBracket(
+ bracket_tier=record["bracket_tier"],
+ notional_cap=record["notional_cap"],
+ maintenance_rate=record["maintenance_rate"],
+ cumulative_maintenance_amount=record["cumulative_maintenance_amount"],
+ notional_coefficient=record.get("notional_coefficient"),
+ )
+ for record in records
+ )
+ return cls(symbol=symbol, version=maintenance_bracket_version, brackets=brackets)
+
+
+@dataclass(frozen=True)
+class PositionState:
+ """Exchange-independent open-position accounting state."""
+
+ symbol: str
+ quantity: float
+ entry_price: float
+ leverage: float
+ accumulated_entry_fee: float
+ isolated_margin: float | None
+
+ def __post_init__(self) -> None:
+ if not self.symbol:
+ raise ValueError("symbol must not be empty")
+ _require_finite("quantity", self.quantity)
+ if self.quantity == 0:
+ raise ValueError("quantity must be non-zero")
+ _require_finite("entry_price", self.entry_price, positive=True)
+ _require_finite("leverage", self.leverage, positive=True)
+ _require_finite("accumulated_entry_fee", self.accumulated_entry_fee)
+ if self.accumulated_entry_fee < 0:
+ raise ValueError("accumulated_entry_fee must be non-negative")
+ if self.isolated_margin is not None:
+ _require_finite("isolated_margin", self.isolated_margin, positive=True)
+
+
+@dataclass(frozen=True)
+class AccountState:
+ """Single-asset USDT account state without open-order margin."""
+
+ wallet_balance: float
+ positions: tuple[PositionState, ...]
+ margin_mode: MarginMode
+ terminal_status: TerminalStatus = "active"
+
+ def __post_init__(self) -> None:
+ _require_finite("wallet_balance", self.wallet_balance)
+ if self.margin_mode not in {"isolated", "cross"}:
+ raise ValueError("margin_mode must be 'isolated' or 'cross'")
+ if self.terminal_status not in {"active", "completed", "account_liquidation"}:
+ raise ValueError("unsupported terminal_status")
+ symbols = [position.symbol for position in self.positions]
+ if len(symbols) != len(set(symbols)):
+ raise ValueError("duplicate position symbol")
+
+
+@dataclass(frozen=True)
+class ExecutionFrame:
+ """Normal market-fill input, separate from exchange mark prices."""
+
+ timestamp: pd.Timestamp
+ execution_open: float
+
+ def __post_init__(self) -> None:
+ object.__setattr__(self, "timestamp", _timestamp(self.timestamp, "timestamp"))
+ _require_finite("execution_open", self.execution_open, positive=True)
+
+
+@dataclass(frozen=True)
+class MarketRiskFrame:
+ """Immutable mark, funding, bracket, provenance, and fidelity input.
+
+ ``schedule`` is optional: the loader only attaches bracket columns when
+ a caller supplies a validated artifact (``require_brackets=True`` without
+ one fails closed at the loader level, before data ever reaches here). A
+ frame with ``schedule=None`` is valid for execution/mark/funding-only use.
+ """
+
+ timestamp: pd.Timestamp
+ mark_open: float
+ mark_high: float
+ mark_low: float
+ mark_close: float
+ funding_rate: float | None
+ funding_settlement_time: pd.Timestamp | None
+ schedule: MaintenanceSchedule | None
+ source: str
+ fidelity_flags: tuple[str, ...] = ()
+
+ def __post_init__(self) -> None:
+ timestamp = _timestamp(self.timestamp, "timestamp")
+ object.__setattr__(self, "timestamp", timestamp)
+ for name in ("mark_open", "mark_high", "mark_low", "mark_close"):
+ _require_finite(name, getattr(self, name), positive=True)
+ if self.mark_high < max(self.mark_open, self.mark_low, self.mark_close):
+ raise ValueError("mark_high must contain the mark OHLC range")
+ if self.mark_low > min(self.mark_open, self.mark_high, self.mark_close):
+ raise ValueError("mark_low must contain the mark OHLC range")
+ has_rate = self.funding_rate is not None
+ has_settlement = self.funding_settlement_time is not None
+ if has_rate != has_settlement:
+ raise ValueError("funding rate and settlement timestamp must be paired")
+ if self.funding_rate is not None:
+ _require_finite("funding_rate", self.funding_rate)
+ settlement = _timestamp(
+ self.funding_settlement_time, "funding_settlement_time"
+ )
+ if settlement != timestamp:
+ raise ValueError("funding settlement timestamp must match frame timestamp")
+ object.__setattr__(self, "funding_settlement_time", settlement)
+ if not self.source:
+ raise ValueError("source must not be empty")
+ if len(self.fidelity_flags) != len(set(self.fidelity_flags)):
+ raise ValueError("fidelity_flags must not contain duplicates")
diff --git a/agent/tests/test_perpetual_risk.py b/agent/tests/test_perpetual_risk.py
new file mode 100644
index 000000000..3bfe65eb8
--- /dev/null
+++ b/agent/tests/test_perpetual_risk.py
@@ -0,0 +1,211 @@
+from __future__ import annotations
+
+import json
+from dataclasses import FrozenInstanceError
+
+import pandas as pd
+import pytest
+
+from backtest.perpetual_risk import (
+ AccountState,
+ ExecutionFrame,
+ MaintenanceBracket,
+ MaintenanceSchedule,
+ MarketRiskFrame,
+ PositionState,
+)
+
+
+def _brackets() -> tuple[MaintenanceBracket, ...]:
+ return (
+ MaintenanceBracket(1, 50_000.0, 0.004, 0.0),
+ MaintenanceBracket(2, 250_000.0, 0.005, 50.0),
+ )
+
+
+def _schedule(symbol: str = "BTC-USDT-PERP", version: str = "abc123") -> MaintenanceSchedule:
+ return MaintenanceSchedule(symbol, version, _brackets())
+
+
+def test_schedule_holds_the_given_version_without_recomputing_it() -> None:
+ schedule = _schedule(version="deadbeefcafef00d")
+ assert schedule.version == "deadbeefcafef00d"
+
+
+ "values",
+ [
+ (1, 0.0, 0.004, 0.0), # notional_cap must be positive
+ (1, 50_000.0, -0.001, 0.0), # maintenance_rate must be non-negative
+ (1, 50_000.0, 0.004, -1.0), # cumulative_maintenance_amount must be non-negative
+ (-1, 50_000.0, 0.004, 0.0), # bracket_tier must be non-negative
+ ],
+)
+def test_invalid_bracket_values_are_rejected(values: tuple[int, float, float, float]) -> None:
+ with pytest.raises(ValueError):
+ MaintenanceBracket(*values)
+
+
+def test_bracket_accepts_optional_notional_coefficient() -> None:
+ bracket = MaintenanceBracket(1, 50_000.0, 0.004, 0.0, notional_coefficient=1.5)
+ assert bracket.notional_coefficient == 1.5
+
+
+def test_schedule_requires_strictly_increasing_notional_caps() -> None:
+ with pytest.raises(ValueError, match="notional caps"):
+ MaintenanceSchedule(
+ "BTC-USDT-PERP",
+ "v1",
+ (
+ MaintenanceBracket(1, 250_000.0, 0.005, 50.0),
+ MaintenanceBracket(2, 50_000.0, 0.004, 0.0),
+ ),
+ )
+
+
+def test_schedule_requires_strictly_increasing_bracket_tiers() -> None:
+ with pytest.raises(ValueError, match="bracket_tier"):
+ MaintenanceSchedule(
+ "BTC-USDT-PERP",
+ "v1",
+ (
+ MaintenanceBracket(2, 50_000.0, 0.004, 0.0),
+ MaintenanceBracket(1, 250_000.0, 0.005, 50.0),
+ ),
+ )
+
+
+def test_schedule_rejects_empty_symbol_version_or_brackets() -> None:
+ with pytest.raises(ValueError, match="symbol"):
+ MaintenanceSchedule("", "v1", _brackets())
+ with pytest.raises(ValueError, match="version"):
+ MaintenanceSchedule("BTC-USDT-PERP", "", _brackets())
+ with pytest.raises(ValueError, match="brackets"):
+ MaintenanceSchedule("BTC-USDT-PERP", "v1", ())
+
+
+def test_schedule_from_loader_columns_parses_validated_json() -> None:
+ records = [
+ {
+ "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,
+ "notional_coefficient": 1.2,
+ },
+ ]
+ schedule = MaintenanceSchedule.from_loader_columns(
+ "BTC/USDT:USDT", json.dumps(records), "abc123"
+ )
+ assert schedule.symbol == "BTC/USDT:USDT"
+ assert schedule.version == "abc123"
+ assert schedule.brackets[1].notional_coefficient == 1.2
+
+
+ ("payload", "match"),
+ [
+ ("not-json", "not valid JSON"),
+ ("{}", "non-empty list"),
+ ("[]", "non-empty list"),
+ ],
+)
+def test_schedule_from_loader_columns_rejects_bad_payloads(payload: str, match: str) -> None:
+ with pytest.raises(ValueError, match=match):
+ MaintenanceSchedule.from_loader_columns("BTC/USDT:USDT", payload, "abc123")
+
+
+def test_position_uses_signed_quantity_and_never_stores_mark_price() -> None:
+ position = PositionState(
+ symbol="BTC-USDT-PERP",
+ quantity=-0.5,
+ entry_price=60_000.0,
+ leverage=10.0,
+ accumulated_entry_fee=15.0,
+ isolated_margin=None,
+ )
+
+ assert position.quantity == -0.5
+ assert not hasattr(position, "mark_price")
+ with pytest.raises(FrozenInstanceError):
+ position.quantity = 1.0 # type: ignore[misc]
+
+
[email protected]("quantity", [0.0, float("nan"), float("inf")])
+def test_position_rejects_invalid_quantity(quantity: float) -> None:
+ with pytest.raises(ValueError, match="quantity"):
+ PositionState("BTC-USDT-PERP", quantity, 60_000.0, 10.0, 0.0, None)
+
+
+def test_account_validates_margin_mode_terminal_status_and_unique_symbols() -> None:
+ position = PositionState("BTC-USDT-PERP", 0.1, 60_000.0, 10.0, 3.0, 600.0)
+ account = AccountState(10_000.0, (position,), "isolated", "active")
+ assert account.positions == (position,)
+
+ with pytest.raises(ValueError, match="margin_mode"):
+ AccountState(10_000.0, (), "portfolio", "active")
+ with pytest.raises(ValueError, match="terminal_status"):
+ AccountState(10_000.0, (), "cross", "position_liquidation")
+ with pytest.raises(ValueError, match="duplicate"):
+ AccountState(10_000.0, (position, position), "isolated", "active")
+
+
+def test_execution_and_market_frames_have_distinct_price_contracts() -> None:
+ timestamp = pd.Timestamp("2026-01-01T08:00:00Z")
+ execution = ExecutionFrame(timestamp, execution_open=60_010.0)
+ risk = MarketRiskFrame(
+ timestamp=timestamp,
+ mark_open=60_000.0,
+ mark_high=61_000.0,
+ mark_low=59_000.0,
+ mark_close=60_500.0,
+ funding_rate=0.0001,
+ funding_settlement_time=timestamp,
+ schedule=_schedule(),
+ source="ccxt:binanceusdm",
+ fidelity_flags=(),
+ )
+
+ assert execution.execution_open == 60_010.0
+ assert not hasattr(execution, "mark_open")
+ assert risk.mark_low == 59_000.0
+ assert not hasattr(risk, "execution_open")
+
+
+def test_market_risk_frame_allows_no_bracket_schedule() -> None:
+ """A -PERP fetch without a bracket artifact still yields a usable frame
+ for execution/mark/funding-only consumers — schedule is optional."""
+ timestamp = pd.Timestamp("2026-01-01T00:00:00Z")
+ frame = MarketRiskFrame(
+ timestamp=timestamp,
+ mark_open=60_000.0,
+ mark_high=61_000.0,
+ mark_low=59_000.0,
+ mark_close=60_500.0,
+ funding_rate=None,
+ funding_settlement_time=None,
+ schedule=None,
+ source="ccxt:binanceusdm",
+ )
+ assert frame.schedule is None
+
+
+def test_frames_reject_invalid_prices_and_unpaired_funding_fields() -> None:
+ timestamp = pd.Timestamp("2026-01-01T01:00:00Z")
+ with pytest.raises(ValueError, match="execution_open"):
+ ExecutionFrame(timestamp, execution_open=0.0)
+ with pytest.raises(ValueError, match="funding"):
+ MarketRiskFrame(
+ timestamp=timestamp,
+ mark_open=60_000.0,
+ mark_high=61_000.0,
+ mark_low=59_000.0,
+ mark_close=60_500.0,
+ funding_rate=0.0001,
+ funding_settlement_time=None,
+ schedule=_schedule(),
+ source="ccxt:binanceusdm",
+ fidelity_flags=(),
+ )