"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(backtest): fill liquidation at the adverse mark used for its check (#1291)
cgycorey6da964b017a5
diff --git a/agent/backtest/engines/_market_hooks.py b/agent/backtest/engines/_market_hooks.pyindex 890b2a498..22dfeba01 100644--- a/agent/backtest/engines/_market_hooks.py+++ b/agent/backtest/engines/_market_hooks.py@@ -289,6 +289,23 @@ def calc_crypto_funding_fee(return notional * funding_rate * pos.direction+def _liquidation_mark(bar: pd.Series, pos: Position) -> float:+ """Adverse price the liquidation check and the fill both use.++ Bar high for a short, low for a long -- mirroring the strict path's+ "adverse" convention (perpetual_risk._mark_price) -- falling back to the+ close, then the entry price, for bars without high/low. Detection and+ execution share the same mark so a wick trigger never fills at a better+ price than the venue that liquidated it.+ """+ mark_price = bar.get("high" if pos.direction < 0 else "low")+ if mark_price is None or pd.isna(mark_price):+ mark_price = bar.get("close")+ if mark_price is None or pd.isna(mark_price):+ mark_price = pos.entry_price+ return float(mark_price)++def check_crypto_liquidation(symbol: str,bar: pd.Series,@@ -296,33 +313,17 @@ def check_crypto_liquidation() -> bool:"""Check if a crypto position should be liquidated.- Args:- symbol: Instrument code.- bar: Current bar data.- positions: Shared positions dict.-- Returns:- True if liquidation should be triggered.- Does NOT execute the liquidation -- caller handles that.+ Fires when equity in the position (margin + unrealized) falls at or below+ the maintenance margin, marked at the adverse extremum so an intra-bar+ wick counts. A 1x long is exempt because its bankruptcy price is zero; a+ 1x short is not -- margin is the full notional and a 2x adverse move+ zeroes it. Does NOT execute the liquidation -- the caller handles that."""pos = positions.get(symbol)- # A 1x long's bankruptcy price is zero, so leverage <= 1 exempts a 1x long.- # A 1x short has no such floor: margin is the full notional, a 2x- # adverse move makes margin + unrealized negative, and the position- # would ride an impossible state on the books (#1291).if pos is None or (pos.leverage <= 1.0 and pos.direction > 0):return False- # Mark at the adverse extremum -- bar high for a short, low for a long --- # mirroring the strict path's "adverse" price convention, and fall back to- # the close when the bar lacks high/low (#1291). With high/low present a- # wick through maintenance triggers; close-only bars keep legacy behavior.- mark_price = bar.get("high" if pos.direction < 0 else "low")- if mark_price is None or pd.isna(mark_price):- mark_price = bar.get("close")- if mark_price is None or pd.isna(mark_price):- mark_price = pos.entry_price- mark_price = float(mark_price)+ mark_price = _liquidation_mark(bar, pos)margin = pos.size * pos.entry_price / pos.leverageunrealized = pos.direction * pos.size * (mark_price - pos.entry_price)diff --git a/agent/backtest/engines/composite.py b/agent/backtest/engines/composite.pyindex edd2652f3..c4470c3c3 100644--- a/agent/backtest/engines/composite.py+++ b/agent/backtest/engines/composite.py@@ -16,6 +16,7 @@ from backtest.engines.base import BaseEnginefrom backtest.engines._market_hooks import (_detect_market,_is_china_futures,+ _liquidation_mark,code_currency,calc_crypto_funding_fee,check_crypto_liquidation,@@ -261,11 +262,9 @@ class CompositeEngine(BaseEngine):if check_crypto_liquidation(symbol, bar, self.positions):pos = self.positions.get(symbol)if pos is not None:- # The hook may fire on the bar's adverse extremum (high/low);- # daily bars cannot observe intra-bar timing, so the fill is- # priced at the close and then slippaged adversely.- mark_price = float(bar.get("close", pos.entry_price))- liq_price = crypto_sub.apply_slippage(mark_price, -pos.direction)+ # Fill at the same adverse mark the hook used for the check so+ # a wick trigger never exits at a better price than the venue.+ liq_price = crypto_sub.apply_slippage(_liquidation_mark(bar, pos), -pos.direction)self._close_position(symbol, liq_price, timestamp, "liquidation")elif market == "forex":diff --git a/agent/backtest/engines/crypto.py b/agent/backtest/engines/crypto.pyindex d08ff584d..be85b8288 100644--- a/agent/backtest/engines/crypto.py+++ b/agent/backtest/engines/crypto.py@@ -17,6 +17,7 @@ import pandas as pdfrom backtest.engines.base import BaseEnginefrom backtest.engines._market_hooks import (+ _liquidation_mark,calc_crypto_funding_fee,check_crypto_liquidation,)@@ -609,9 +610,7 @@ class CryptoEngine(BaseEngine):if check_crypto_liquidation(symbol, bar, self.positions):pos = self.positions.get(symbol)if pos is not None:- # The hook may fire on the bar's adverse extremum (high/low);- # daily bars cannot observe intra-bar timing, so the fill is- # priced at the close and then slippaged adversely.- mark_price = float(bar.get("close", pos.entry_price))- liq_price = self.apply_slippage(mark_price, -pos.direction)+ # Fill at the same adverse mark the hook used for the check so+ # a wick trigger never exits at a better price than the venue.+ liq_price = self.apply_slippage(_liquidation_mark(bar, pos), -pos.direction)self._close_position(symbol, liq_price, timestamp, "liquidation")diff --git a/agent/tests/test_crypto_engine.py b/agent/tests/test_crypto_engine.pyindex d95533f7c..8b10e52a4 100644--- a/agent/tests/test_crypto_engine.py+++ b/agent/tests/test_crypto_engine.py@@ -437,8 +437,8 @@ class TestLiquidation:def test_wick_only_trigger_liquidates(self) -> None:"""A levered long whose low pierces maintenance is liquidated even when- the close recovers; the fill is priced at the close (#1291)."""- engine = _make_engine(leverage=2.0)+ the close recovers; the fill is priced at the adverse mark (bar low)."""+ engine = _make_engine(leverage=2.0, slippage=0.0)engine.positions["BTC-USDT"] = Position("BTC-USDT", 1, 100.0, pd.Timestamp("2025-01-01"), 10.0, leverage=2.0,)@@ -450,6 +450,23 @@ class TestLiquidation:assert "BTC-USDT" not in engine.positionsassert len(engine.trades) == 1assert engine.trades[0].exit_reason == "liquidation"+ assert engine.trades[0].exit_price == pytest.approx(30.0)++ def test_1x_short_liquidates_through_twice_the_entry_price(self) -> None:+ """#1291: a 1x short must be liquidated, not exempted at 2x adverse."""+ engine = _make_engine(leverage=1.0, slippage=0.0)+ engine.positions["BTC-USDT"] = Position(+ "BTC-USDT", -1, 100.0, pd.Timestamp("2025-01-01"), 10.0, leverage=1.0,+ )+ # Margin is the full notional (1000); the 2x adverse bar zeroes it:+ # equity 0 <= maint (2000 * 0.004 = 8), filled at the adverse high.+ bar = pd.Series({"close": 200.0, "high": 200.0, "low": 101.0})+ ts = pd.Timestamp("2025-01-02")+ engine.on_bar("BTC-USDT", bar, ts)+ assert "BTC-USDT" not in engine.positions+ assert len(engine.trades) == 1+ assert engine.trades[0].exit_reason == "liquidation"+ assert engine.trades[0].exit_price == pytest.approx(200.0)# ---------------------------------------------------------------------------