Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(backtest): an open that cash below zero cannot fund is skipped, not an abort (#1542)

Haozhe Wud65d56a437cd
diff --git a/agent/backtest/engines/base.py b/agent/backtest/engines/base.py
index 4cb57ebf4..86eda9de0 100644
--- a/agent/backtest/engines/base.py
+++ b/agent/backtest/engines/base.py
@@ -1281,14 +1281,20 @@ class BaseEngine(ABC):
# bisection step (#1470). The sleeve that leaves the basket is
# reported once, after the search, as the rebalance path does.
wanted = [order.symbol for order in planned]
+ # Nothing fits until a candidate proves it does: with cash below
+ # zero (a funding debit leaves it there) not even the empty plan
+ # fits, and the full-scale plan used to fall through to
+ # _execute_open_order and abort the run (#1542).
+ fitting: list[_OpenOrder] = []
low, high = 0.0, 1.0
for _ in range(50):
mid = (low + high) / 2.0
candidate = _plans(mid, observe=False)
if sum(order.cost for order in candidate) <= self.capital + 1e-9:
- low, planned = mid, candidate
+ low, fitting = mid, candidate
else:
high = mid
+ planned = fitting
fitted = {order.symbol for order in planned}
for symbol in wanted:
if symbol not in fitted:
@@ -1757,7 +1763,23 @@ class BaseEngine(ABC):
if projected_capital < -1e-9:
fitted = self._fit_rebalance_opens(opens, reductions, ts)
if fitted is None:
- raise ValueError("insufficient capital for position rebalance")
+ if sum(order.capital_credit for order in reductions) < 0:
+ # The reductions themselves consume cash (a close whose loss
+ # exceeds its margin): no dropping of opens repairs that, so
+ # the bar aborts atomically as #1274 decided.
+ raise ValueError("insufficient capital for position rebalance")
+ # Cash was already below zero (a funding debit can leave it
+ # there) and the reductions only release it: drop every open,
+ # still run the reductions, and report each open (#1542).
+ for order in opens:
+ self._on_plan_rejected(order.symbol, "insufficient_capital", ts)
+ if opens:
+ logger.warning(
+ "Cash below zero at %s; no open or increase fits, dropped: %s",
+ ts,
+ ", ".join(sorted({order.symbol for order in opens})),
+ )
+ fitted = []
opens = fitted
for order in reductions:
@@ -1793,8 +1815,10 @@ class BaseEngine(ABC):
diagnostics see the dropped leg.
Returns the fitted orders, or ``None`` when no scale fits — not even
- an empty open sleeve — which the caller must treat as an atomic
- abort (nothing has been committed at that point).
+ an empty open sleeve; nothing has been committed at that point. The
+ caller aborts atomically when the reductions themselves consume cash
+ (#1274), and otherwise — cash was already below zero — drops every
+ open and still runs the reductions (#1542).
"""
released = sum(order.capital_credit for order in reductions)
diff --git a/agent/tests/test_base_engine.py b/agent/tests/test_base_engine.py
index 6dd3de240..b3c6acdd3 100644
--- a/agent/tests/test_base_engine.py
+++ b/agent/tests/test_base_engine.py
@@ -938,3 +938,50 @@ def test_rebalance_sleeve_below_one_lot_at_full_scale_is_the_lot_rule():
assert engine.plan_rejections[("B", "zero_size")] == 1
assert ("B", "insufficient_capital") not in engine.plan_rejections
assert engine.bar_capitals[0] >= 0.0
+
+
+class _FundingDebitAdjustmentEngine(_AdjustmentEngine):
+ """Debits a fee after every bar, as CompositeEngine's crypto funding does."""
+
+ def __init__(self, **overrides):
+ super().__init__(**overrides)
+ self.rejected: list[tuple[str, str]] = []
+
+ def after_rebalance_bar(self, timestamp, data_map, codes):
+ self.capital -= float(self.config.get("debit", 0.0))
+ return super().after_rebalance_bar(timestamp, data_map, codes)
+
+ def _on_plan_rejected(self, symbol, reason, timestamp):
+ self.rejected.append((symbol, reason))
+
+
+def test_rebalance_with_negative_cash_drops_the_opens_and_keeps_running():
+ """#1542's rebalance sibling: when even an empty open sleeve does not fit
+ (cash below zero, nothing reduced to release it), the run used to abort with
+ 'insufficient capital for position rebalance'. The opens are dropped and
+ reported; the rest of the bar and the run go on.
+
+ A takes all 1,000 of cash on bar 0 and the debit leaves -30. A's weight on
+ the later bars keeps it at exactly 10 shares, so nothing is released.
+ """
+ engine = _FundingDebitAdjustmentEngine(debit=30.0)
+ keep_a = 1_000.0 / 970.0
+ _run_adjustments(engine, {"A": [1.0, keep_a, keep_a], "B": [0.0, 0.2, 0.2]})
+
+ assert engine.bar_capitals[0] == pytest.approx(-30.0)
+ assert _sizes(engine.bar_positions[1]) == {"A": 10.0}
+ assert ("B", "insufficient_capital") in engine.rejected
+ assert len(engine.bar_positions) == 3 # the run reached its last bar
+
+
+def test_rebalance_with_negative_cash_still_executes_its_reductions():
+ """Dropping the opens must not drop the reductions: they only release cash.
+
+ Cash is -300 after bar 0 (equity 700); trimming A to 9 shares releases 100,
+ not enough to bring cash to zero, so no open sleeve fits. The trim happens.
+ """
+ engine = _FundingDebitAdjustmentEngine(debit=300.0)
+ _run_adjustments(engine, {"A": [1.0, 900.0 / 700.0], "B": [0.0, 0.1]})
+
+ assert _sizes(engine.bar_positions[1]) == {"A": 9.0}
+ assert ("B", "insufficient_capital") in engine.rejected
diff --git a/agent/tests/test_plan_rejected.py b/agent/tests/test_plan_rejected.py
index 3e4973cad..89149e5e1 100644
--- a/agent/tests/test_plan_rejected.py
+++ b/agent/tests/test_plan_rejected.py
@@ -406,3 +406,34 @@ def test_insufficient_capital_is_counted_as_unfilled():
metrics = engine._plan_rejection_metrics()
assert metrics["unfilled_plan_rejections"] == 1
assert metrics["unfilled_plan_rejections_by_symbol"] == {"B": {"insufficient_capital": 1}}
+
+
+# ---------------------------------------------------------------------------
+# #1542: an open that no scale can fund when cash is already negative
+# ---------------------------------------------------------------------------
+
+
+class _FundingDebitEngine(_FuturesLotEngine):
+ """Debits a fee after every bar, as CompositeEngine's crypto funding does."""
+
+ def __init__(self, fee: float, **overrides):
+ super().__init__(**overrides)
+ self.fee = fee
+
+ def on_bar(self, symbol, bar, timestamp):
+ self.capital -= self.fee
+
+
+def test_an_open_with_negative_cash_is_skipped_and_reported_in_hold_mode():
+ """With cash below zero no scale fits, not even the empty plan.
+
+ The search only replaced the full-scale plan when a candidate fitted, so the
+ full-scale plan fell through to _execute_open_order and the run aborted with
+ 'planned order for B exceeds available capital'.
+ """
+ engine = _FundingDebitEngine(fee=60.0, position_adjustment="hold")
+ # A takes 10 of 1,000 cash; the per-symbol debit after bar 0 leaves -120.
+ _hold_run(engine, {"A": 100.0, "B": 100.0}, {"A": [1.0, 1.0], "B": [0.0, 0.3]})
+
+ assert _opens(engine) == [("A", 0, 10.0)]
+ assert engine.rejections == [("B", "insufficient_capital", _DATES[1])]