Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(backtest): sync sub-engine active symbol before every composite dispatch

Lanre Shittub44ca33b8bde
diff --git a/agent/backtest/engines/composite.py b/agent/backtest/engines/composite.py
index 25e008090..b3b5caf54 100644
--- a/agent/backtest/engines/composite.py
+++ b/agent/backtest/engines/composite.py
@@ -18,6 +18,7 @@ from backtest.engines._market_hooks import (
_interval_span_hours,
_is_china_futures,
_liquidation_mark,
+ _normalize_symbol,
code_currency,
calc_crypto_funding_fee,
check_crypto_liquidation,
@@ -211,20 +212,25 @@ class CompositeEngine(BaseEngine):
def round_size(self, raw_size: float, price: float) -> float:
"""Delegate to active symbol's sub-engine."""
- return self._rule_for(self._active_symbol).round_size(raw_size, price)
+ sub = self._rule_for(self._active_symbol)
+ # ForexEngine/ChinaFuturesEngine/GlobalFuturesEngine read their OWN
+ # _active_symbol (lot grids, per-symbol fee schedules) — a shared
+ # sub-engine instance keeps whatever symbol last synced it, so it
+ # must be refreshed on every dispatch, not just in apply_slippage.
+ sub._active_symbol = self._active_symbol
+ return sub.round_size(raw_size, price)
def calc_commission(
self, size: float, price: float, direction: int, is_open: bool,
) -> float:
"""Delegate to active symbol's sub-engine."""
- return self._rule_for(self._active_symbol).calc_commission(
- size, price, direction, is_open,
- )
+ sub = self._rule_for(self._active_symbol)
+ sub._active_symbol = self._active_symbol
+ return sub.calc_commission(size, price, direction, is_open)
def apply_slippage(self, price: float, direction: int) -> float:
"""Delegate to active symbol's sub-engine."""
sub = self._rule_for(self._active_symbol)
- # ForexEngine needs _active_symbol set on the sub-engine
sub._active_symbol = self._active_symbol
return sub.apply_slippage(price, direction)
@@ -276,10 +282,13 @@ class CompositeEngine(BaseEngine):
self._close_position(symbol, liq_price, timestamp, "liquidation")
elif market == "forex":
+ from backtest.engines.forex import _lot_units
+
forex_sub = self._rule_engines["forex"]
if forex_sub.swap_enabled:
swap = calc_forex_swap(
symbol, timestamp, self.positions,
- forex_sub.lot_size, self._last_swap_dates,
+ _lot_units(_normalize_symbol(symbol), forex_sub.lot_size),
+ self._last_swap_dates,
)
self.capital += swap
diff --git a/agent/tests/test_composite_engine_fallback.py b/agent/tests/test_composite_engine_fallback.py
index 1a488a0d0..6300aa587 100644
--- a/agent/tests/test_composite_engine_fallback.py
+++ b/agent/tests/test_composite_engine_fallback.py
@@ -2,9 +2,11 @@
from __future__ import annotations
+import pandas as pd
import pytest
from backtest.engines.composite import CompositeEngine
+from backtest.models import Position
class TestCompositeEngineFallback:
@@ -50,3 +52,64 @@ class TestCompositeEngineFallback:
engine._rule_engines = {}
with pytest.raises(ValueError, match="No sub-engines available"):
engine._rule_for("UNKNOWN-SYMBOL")
+
+
+class TestSharedSubEngineActiveSymbol:
+ """Two symbols on the same sub-engine must not leak each other's state.
+
+ round_size/calc_commission dispatch through one shared sub-engine
+ instance per market. ForexEngine.round_size and
+ ChinaFuturesEngine.calc_commission both key off the sub-engine's OWN
+ _active_symbol, so it must be refreshed on every call, not just when
+ apply_slippage happens to run first.
+ """
+
+ def test_round_size_reflects_current_symbol_not_last_synced_one(self):
+ config = {"initial_cash": 100_000}
+ engine = CompositeEngine(config, ["EUR/USD", "XAU/USD"])
+
+ # apply_slippage is what used to sync the sub-engine's own
+ # _active_symbol; call it for one symbol, then round_size for a
+ # different one with no apply_slippage call in between (the exact
+ # sequence the capital-fit rescale loop uses).
+ engine._active_symbol = "EUR/USD"
+ engine.apply_slippage(1.1000, 1)
+
+ engine._active_symbol = "XAU/USD"
+ size = engine.round_size(50.0, 2000.0)
+ # Gold's micro lot is 1 oz; FX's is 1000 units. Stale FX state
+ # rounds 50 oz down to zero instead of keeping it.
+ assert size == pytest.approx(50.0)
+
+ def test_calc_commission_reflects_current_symbol_not_last_synced_one(self):
+ config = {"initial_cash": 10_000_000}
+ engine = CompositeEngine(config, ["IF2406.CFFEX", "au2412.SHFE"])
+
+ engine._active_symbol = "IF2406.CFFEX"
+ engine.apply_slippage(4000.0, 1)
+
+ engine._active_symbol = "au2412.SHFE"
+ fee = engine.calc_commission(2.0, 500.0, 1, True)
+ # au (gold) is a flat RMB10/lot fee; IF's stale rate-based formula
+ # would price it at 2 * 500 * 300 * 0.000023 = 6.9 instead.
+ assert fee == pytest.approx(2.0 * 10.0)
+
+ def test_forex_swap_uses_metal_lot_size_not_standard_lot(self):
+ """CompositeEngine.on_bar must size swap lots the way ForexEngine
+ does — metal-aware — not with the raw 100,000-unit standard lot."""
+ config = {"initial_cash": 100_000}
+ engine = CompositeEngine(config, ["EUR/USD", "XAU/USD"])
+ engine.positions["XAU/USD"] = Position(
+ symbol="XAU/USD",
+ direction=1,
+ entry_price=2000.0,
+ entry_time=pd.Timestamp("2025-06-10"),
+ size=100.0,
+ )
+ initial_capital = engine.capital
+ engine.on_bar(
+ "XAU/USD", pd.Series({"close": 2000.0}), pd.Timestamp("2025-06-10 17:00")
+ )
+ # 100 oz is exactly 1 standard gold lot (100 oz/lot); the standard
+ # FX lot (100,000 units) would understate this to 0.001 lots.
+ assert engine.capital == pytest.approx(initial_capital - 1.0, abs=0.01)