Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(backtest): settle HOSE lots individually and wire Vietnam into composite

Pham Van Ngoane440bae16df5
diff --git a/agent/backtest/engines/_market_hooks.py b/agent/backtest/engines/_market_hooks.py
index c0f1abadb..116af8fa1 100644
--- a/agent/backtest/engines/_market_hooks.py
+++ b/agent/backtest/engines/_market_hooks.py
@@ -74,6 +74,7 @@ _MARKET_CURRENCY = {
"india_equity": "INR",
"kr_equity": "KRW",
"ca_equity": "CAD",
+ "vietnam_equity": "VND",
# Every crypto pattern in _MARKET_PATTERNS is USDT-quoted, and USDT is
# carried at its USD peg. This is the one approximation in the table: a
# depeg would make a crypto+US book wrong by the depeg amount, which is
diff --git a/agent/backtest/engines/composite.py b/agent/backtest/engines/composite.py
index 5cfe50502..e2b1b039c 100644
--- a/agent/backtest/engines/composite.py
+++ b/agent/backtest/engines/composite.py
@@ -44,6 +44,9 @@ def _build_rule_engines(config: dict, codes: List[str]) -> Dict[str, BaseEngine]
elif market == "kr_equity":
from backtest.engines.korea_equity import KoreaEquityEngine
engines["kr_equity"] = KoreaEquityEngine(config)
+ elif market == "vietnam_equity":
+ from backtest.engines.vietnam_equity import VietnamEquityEngine
+ engines["vietnam_equity"] = VietnamEquityEngine(config)
elif market == "ca_equity":
from backtest.engines.global_equity import GlobalEquityEngine
engines["ca_equity"] = GlobalEquityEngine(config, market="ca")
@@ -161,9 +164,22 @@ class CompositeEngine(BaseEngine):
# ── Stateless method dispatch ──
def can_execute(self, symbol: str, direction: int, bar: pd.Series) -> bool:
- """Market-rule check with T+1 interceptor for A-shares."""
+ """Market-rule check with settlement interceptors for A-shares and HOSE."""
market = self._symbol_market.get(symbol, "a_share")
+ # HOSE: both the T+2 hold and the ±7% band read run state — positions
+ # and the fill ledger for the hold, the close panel for the reference
+ # price — that a stateless rule book does not have. Delegating them
+ # would pass every sell and skip every band check, so the rules are
+ # evaluated against this engine's state using the Vietnam engine's own
+ # implementation, with the sub-engine supplying only the parameters.
+ if market == "vietnam_equity":
+ sub = self._rule_engines.get("vietnam_equity")
+ if sub is not None:
+ from backtest.engines.vietnam_equity import hose_can_execute
+
+ return hose_can_execute(self, sub, symbol, direction, bar)
+
# T+1: intercept here because sub-engine has no access to shared positions
if market == "a_share" and direction == 0:
pos = self.positions.get(symbol)
diff --git a/agent/backtest/engines/vietnam_equity.py b/agent/backtest/engines/vietnam_equity.py
index a2d4e7e56..70a2ff434 100644
--- a/agent/backtest/engines/vietnam_equity.py
+++ b/agent/backtest/engines/vietnam_equity.py
@@ -17,8 +17,11 @@ Market rules:
the cycle is informally called T+1.5. A two-bar hold approximates that: a
daily bar cannot represent the half-day boundary, so the sell is released
on the second following session. No same-day round trip is possible.
- ``vn_settlement_bars`` exists for scenario testing and to absorb a future
- rule change; no shorter equity cycle is in force today.
+ The hold runs from the **newest** opening fill, so scaling into a position
+ re-arms it: the whole holding waits for the added lot rather than riding
+ the first lot's clock. ``vn_settlement_bars`` exists for scenario testing
+ and to absorb a future rule change; no shorter equity cycle is in force
+ today.
- Price band (biên độ dao động): ±7% on HOSE in normal sessions, measured
from the reference price (giá tham chiếu — ordinarily the preceding
session's close, though corporate actions and special sessions adjust it).
@@ -81,6 +84,11 @@ _PRICE_EPS = 1e-9
# before the afternoon session on T+2, so a buy at bar N releases at bar N+2.
_DEFAULT_SETTLEMENT_BARS = 2
+# Fill actions that add quantity to a position. Both start a settlement clock:
+# ``increase`` is a same-direction add that BaseEngine folds into the existing
+# position without moving its entry index.
+_OPENING_ACTIONS = frozenset({"open", "increase"})
+
def hose_tick_size(price: float) -> float:
"""Return the HOSE tick unit (bước giá) applying at *price*.
@@ -132,6 +140,220 @@ def hose_price_limits(base_price: float, band: float) -> tuple[float, float]:
return upper, lower
+def newest_opening_bar_idx(engine: BaseEngine, symbol: str) -> Optional[int]:
+ """Bar index of the most recent opening fill for *symbol* on *engine*.
+
+ ``Position.entry_bar_idx`` alone is not a sound settlement clock.
+ :meth:`BaseEngine._execute_position_increase` folds a same-direction add
+ into the open position — updating size and weighted entry price — but
+ preserves the original entry index, so counting from it would release
+ later-bought shares as soon as the *first* lot settled: a buy on N, an add
+ on N+1 and a full sell on N+2 would pass while the added lot is one session
+ old.
+
+ The fill ledger is immutable evidence of when each opening delta actually
+ executed, so the newest one bounds the hold. Scanning back from the newest
+ fill stops at the first match, which belongs to the open position's own
+ lifecycle whenever a position exists.
+
+ Args:
+ engine: Engine owning the fill ledger — the Vietnam engine in a
+ single-market run, the composite in a cross-market one.
+ symbol: Symbol whose settlement clock is being read.
+
+ Returns:
+ The bar index of the newest opening fill, or ``None`` when the ledger
+ holds no opening fill for *symbol*.
+ """
+ for fill in reversed(getattr(engine, "fill_records", ()) or ()):
+ if fill.symbol == symbol and fill.action in _OPENING_ACTIONS:
+ return int(fill.bar_idx)
+ return None
+
+
+def hose_is_settled(
+ engine: BaseEngine, symbol: str, settlement_bars: int,
+) -> Optional[bool]:
+ """Return whether *symbol*'s position on *engine* has cleared the hold.
+
+ Settlement is counted in sessions rather than calendar days, because a
+ Friday buy settles on Tuesday and a calendar-day comparison would either
+ release it a session early or hold it a session late across the weekend.
+ The newest opening fill and the engine's bar cursor give the exact count.
+
+ The whole position is held until its newest lot settles, rather than only
+ the unsettled quantity being blocked. ``BaseEngine`` keeps one compressed
+ position per symbol with a weighted-average entry and no lot identity, so a
+ partial reduction cannot be shown to consume settled shares only. Holding
+ the position is the conservative reading: it can delay a sell that was
+ partly available, but it can never sell stock that has not arrived.
+
+ State is read from the passed engine rather than from ``self`` so that
+ :class:`~backtest.engines.composite.CompositeEngine` — which owns the
+ positions, fill ledger and bar cursor for every market in a cross-market
+ run — applies this identical rule to its Vietnam leg instead of carrying a
+ second implementation that could drift.
+
+ Args:
+ engine: Engine owning positions, fill ledger and bar cursor.
+ symbol: Symbol whose position is being closed.
+ settlement_bars: Sessions a buy is held before it may be sold.
+
+ Returns:
+ True when the position may be sold on this bar, False while it is still
+ held, and ``None`` when the engine's state cannot answer — leaving the
+ caller to decide how to report an unenforceable hold.
+ """
+ pos = engine.positions.get(symbol)
+ if pos is None:
+ return True
+
+ entry_idx = newest_opening_bar_idx(engine, symbol)
+ if entry_idx is None:
+ # No fill evidence (a position injected directly, as unit tests do).
+ entry_idx = getattr(pos, "entry_bar_idx", None)
+ current_idx = getattr(engine, "_bar_idx", None)
+ if entry_idx is None or current_idx is None:
+ return None
+ return (int(current_idx) - int(entry_idx)) >= int(settlement_bars)
+
+
+def hose_base_price(
+ state: BaseEngine, symbol: str, bar: pd.Series,
+) -> Optional[float]:
+ """Resolve the reference price (giá tham chiếu) for *symbol* on this bar.
+
+ Both sources are strictly historical, so neither leaks the decision bar's
+ own close into the pre-fill check:
+ 1. ``pre_close`` on the bar, when the data source supplies one.
+ 2. The previous row of the close panel that :class:`BaseEngine`
+ pre-extracts for the run.
+
+ An off-grid close is rounded onto the grid, since a reference price is
+ always a tradeable price.
+
+ Args:
+ state: Engine holding the run's close panel and bar cursor.
+ symbol: Symbol whose reference price is wanted.
+ bar: Current bar.
+
+ Returns:
+ The reference price in VND, or ``None`` when no historical close is
+ reachable (first bar of a run, or a rule book with no panel).
+ """
+ candidate: Optional[float] = None
+ if "pre_close" in bar.index:
+ raw = bar["pre_close"]
+ if pd.notna(raw) and float(raw) > 0:
+ candidate = float(raw)
+
+ if candidate is None:
+ close_arr = getattr(state, "_close_arr", None)
+ col = getattr(state, "_code_to_col", {}).get(symbol)
+ row = getattr(state, "_bar_idx", 0) - 1
+ if close_arr is not None and col is not None and row >= 0:
+ raw = close_arr[row, col]
+ if pd.notna(raw) and float(raw) > 0:
+ candidate = float(raw)
+
+ return None if candidate is None else hose_round_down(candidate)
+
+
+def hose_can_execute(
+ state: BaseEngine,
+ rules: "VietnamEquityEngine",
+ symbol: str,
+ direction: int,
+ bar: pd.Series,
+) -> bool:
+ """Apply the HOSE execution rules, reading state and rules separately.
+
+ A single-market run passes the same engine as both arguments. A composite
+ run cannot: it owns the positions, fill ledger, bar cursor and close panel
+ for every market, while the rule parameters (band, tick-quantized slippage,
+ settlement lag) live on the Vietnam sub-engine, which ``CompositeEngine``
+ holds as a stateless rule book. Splitting the two lets the composite apply
+ these rules in full rather than degrading to whichever of them a stateless
+ sub-engine could still answer — which, for the band and the hold, is
+ neither.
+
+ Args:
+ state: Engine owning positions, fill ledger, bar cursor, close panel.
+ rules: Vietnam engine supplying band, slippage and settlement lag.
+ symbol: HOSE symbol (e.g. ``VIC.VN``).
+ direction: 1 (buy), -1 (short — always blocked), 0 (sell/close).
+ bar: Current bar.
+
+ Returns:
+ True if the trade is allowed.
+ """
+ # 1. Short selling: structurally unavailable (see class docstring).
+ if direction == -1:
+ return False
+
+ # 2. T+2 settlement: shares normally arrive before the afternoon of
+ # T+2, so the position cannot be sold before that session.
+ if direction == 0 and not hose_settlement_ok(state, rules, symbol):
+ return False
+
+ # 3. Daily price band ±7% (disabled when falsy).
+ if not rules.price_limit:
+ return True
+
+ base_price = hose_base_price(state, symbol, bar)
+ if base_price is None:
+ if not rules._limit_base_warned:
+ rules._limit_base_warned = True
+ logger.warning(
+ "%s: no reference price available (no 'pre_close' column and "
+ "no prior close panel row) — the HOSE ±%.0f%% band check is "
+ "inactive for this run",
+ symbol,
+ float(rules.price_limit) * 100,
+ )
+ return True
+
+ open_price = float(bar.get("open", bar.get("close", 0.0)) or 0.0)
+ if open_price <= 0:
+ return True # order sizing rejects non-positive prices downstream
+
+ upper, lower = hose_price_limits(base_price, float(rules.price_limit))
+ fill_price = rules.apply_slippage(open_price, direction if direction else -1)
+ if direction == 1 and fill_price >= upper - _PRICE_EPS:
+ return False # giá trần: no ask to buy from
+ if direction == 0 and fill_price <= lower + _PRICE_EPS:
+ return False # giá sàn: no bid to sell into
+ return True
+
+
+def hose_settlement_ok(
+ state: BaseEngine, rules: "VietnamEquityEngine", symbol: str,
+) -> bool:
+ """Return whether *symbol* may be sold, warning once if unenforceable.
+
+ Args:
+ state: Engine owning positions, fill ledger and bar cursor.
+ rules: Vietnam engine supplying the settlement lag and warning latch.
+ symbol: Symbol whose position is being closed.
+
+ Returns:
+ True when the position may be sold on this bar. An engine whose state
+ cannot answer reports True and warns once, rather than blocking every
+ exit for the rest of the run.
+ """
+ settled = hose_is_settled(state, symbol, rules.settlement_bars)
+ if settled is None:
+ if not rules._settlement_warned:
+ rules._settlement_warned = True
+ logger.warning(
+ "%s: no bar cursor available — the HOSE settlement hold is "
+ "inactive for this run",
+ symbol,
+ )
+ return True
+ return settled
+
+
class VietnamEquityEngine(BaseEngine):
"""HOSE cash-equity engine — long-only, T+2 settled.
@@ -193,92 +415,23 @@ class VietnamEquityEngine(BaseEngine):
Returns:
True if the trade is allowed.
"""
- # 1. Short selling: structurally unavailable (see class docstring).
- if direction == -1:
- return False
-
- # 2. T+2 settlement: shares normally arrive before the afternoon of
- # T+2, so the position cannot be sold before that session.
- if direction == 0 and not self._is_settled(symbol):
- return False
-
- # 3. Daily price band ±7% (disabled when falsy).
- if not self.price_limit:
- return True
-
- base_price = self._base_price(symbol, bar)
- if base_price is None:
- if not self._limit_base_warned:
- self._limit_base_warned = True
- logger.warning(
- "%s: no reference price available (no 'pre_close' column and "
- "no prior close panel row) — the HOSE ±%.0f%% band check is "
- "inactive for this run",
- symbol,
- float(self.price_limit) * 100,
- )
- return True
-
- open_price = float(bar.get("open", bar.get("close", 0.0)) or 0.0)
- if open_price <= 0:
- return True # order sizing rejects non-positive prices downstream
-
- upper, lower = hose_price_limits(base_price, float(self.price_limit))
- fill_price = self.apply_slippage(open_price, direction if direction else -1)
- if direction == 1 and fill_price >= upper - _PRICE_EPS:
- return False # giá trần: no ask to buy from
- if direction == 0 and fill_price <= lower + _PRICE_EPS:
- return False # giá sàn: no bid to sell into
- return True
+ # This engine owns both the run state and the rule parameters. A
+ # composite run splits them; see :func:`hose_can_execute`.
+ return hose_can_execute(self, self, symbol, direction, bar)
def _is_settled(self, symbol: str) -> bool:
"""Return whether *symbol*'s open position has cleared settlement.
- Settlement is counted in sessions rather than calendar days, because a
- Friday buy settles on Tuesday and a calendar-day comparison would either
- release it a session early or hold it a session late across the weekend.
- ``Position.entry_bar_idx`` and the engine's own bar cursor give the exact
- session count.
-
- In a cross-market composite run the sub-engines are stateless rule books
- with no bar cursor of their own; there the hold cannot be enforced at
- all, so it is skipped and warned about once rather than applied wrongly.
-
Args:
symbol: Symbol whose position is being closed.
Returns:
True when the position may be sold on this bar.
"""
- pos = self.positions.get(symbol)
- if pos is None:
- return True
-
- entry_idx = getattr(pos, "entry_bar_idx", None)
- current_idx = getattr(self, "_bar_idx", None)
- if entry_idx is None or current_idx is None:
- if not self._settlement_warned:
- self._settlement_warned = True
- logger.warning(
- "%s: no bar cursor available — the HOSE settlement hold is "
- "inactive for this run",
- symbol,
- )
- return True
- return (int(current_idx) - int(entry_idx)) >= self.settlement_bars
+ return hose_settlement_ok(self, self, symbol)
def _base_price(self, symbol: str, bar: pd.Series) -> Optional[float]:
- """Resolve the reference price (giá tham chiếu) for *symbol* on this bar.
-
- Both sources are strictly historical, so neither leaks the decision
- bar's own close into the pre-fill check:
- 1. ``pre_close`` on the bar, when the data source supplies one.
- 2. The previous row of the close panel that :class:`BaseEngine`
- pre-extracts for the run (unavailable in a cross-market composite
- run, whose sub-engines are stateless rule books).
-
- An off-grid close is rounded onto the grid, since a reference price is
- always a tradeable price.
+ """Resolve this run's reference price (giá tham chiếu) for *symbol*.
Args:
symbol: Symbol whose reference price is wanted.
@@ -288,22 +441,7 @@ class VietnamEquityEngine(BaseEngine):
The reference price in VND, or ``None`` when no historical close is
reachable (first bar of a run, or a composite sub-engine).
"""
- candidate: Optional[float] = None
- if "pre_close" in bar.index:
- raw = bar["pre_close"]
- if pd.notna(raw) and float(raw) > 0:
- candidate = float(raw)
-
- if candidate is None:
- close_arr = getattr(self, "_close_arr", None)
- col = getattr(self, "_code_to_col", {}).get(symbol)
- row = getattr(self, "_bar_idx", 0) - 1
- if close_arr is not None and col is not None and row >= 0:
- raw = close_arr[row, col]
- if pd.notna(raw) and float(raw) > 0:
- candidate = float(raw)
-
- return None if candidate is None else hose_round_down(candidate)
+ return hose_base_price(self, symbol, bar)
def round_size(self, raw_size: float, price: float) -> float:
"""Floor the order to whole 100-share board lots.
diff --git a/agent/tests/test_composite_currency_guard.py b/agent/tests/test_composite_currency_guard.py
index 854d37a0b..42edc0bce 100644
--- a/agent/tests/test_composite_currency_guard.py
+++ b/agent/tests/test_composite_currency_guard.py
@@ -28,6 +28,7 @@ class TestCodeCurrency:
("005930.KS", "KRW"),
("TD.TO", "CAD"),
("PNG.V", "CAD"),
+ ("VIC.VN", "VND"),
("IF2406.CFFEX", "CNY"),
],
)
@@ -72,6 +73,18 @@ class TestRejectMixedCurrency:
with pytest.raises(ValueError, match="one settlement currency"):
_reject_mixed_currency(["TD.TO", "AAPL.US"])
+ def test_vnd_is_named_rather_than_marked_unknown(self):
+ # A market with no entry in the table degrades to 'UNKNOWN:<market>',
+ # which still fails closed but names nothing useful in the error.
+ with pytest.raises(ValueError) as excinfo:
+ _reject_mixed_currency(["VIC.VN", "AAPL.US"])
+ message = str(excinfo.value)
+ assert "VND" in message
+ assert "UNKNOWN" not in message
+
+ def test_two_hose_symbols_are_one_currency(self):
+ _reject_mixed_currency(["VIC.VN", "FPT.VN"])
+
def test_the_error_names_every_currency_and_its_codes(self):
with pytest.raises(ValueError) as excinfo:
_reject_mixed_currency(["600519.SH", "AAPL.US", "005930.KS"])
diff --git a/agent/tests/test_composite_vietnam_rules.py b/agent/tests/test_composite_vietnam_rules.py
new file mode 100644
index 000000000..afa141df1
--- /dev/null
+++ b/agent/tests/test_composite_vietnam_rules.py
@@ -0,0 +1,163 @@
+"""Vietnam (HOSE) rules under the cross-market composite engine.
+
+``CompositeEngine`` uses sub-engines as stateless rule books and keeps all
+positions, fills and the close panel itself. Two HOSE rules cannot be answered
+from that stateless side:
+
+ - the T+2 hold needs the position and the fill ledger;
+ - the ±7% band needs the run's close panel to reach a reference price.
+
+Without a ``vietnam_equity`` branch, ``_rule_for`` fell through to whichever
+sub-engine happened to be first, pricing HOSE symbols under another market's
+rules. These tests pin the branch and both intercepted rules.
+
+A mixed book containing ``.VN`` is refused by the single-currency guard before
+it can run, so this path is not reachable end to end today. It is enforced
+anyway: the guard and the rule book are independent, and a market whose rules
+silently vanish in a composite is a trap for whoever relaxes the guard.
+"""
+
+from __future__ import annotations
+
+import numpy as np
+import pandas as pd
+import pytest
+
+from backtest.engines.composite import CompositeEngine, _build_rule_engines
+from backtest.engines.global_equity import GlobalEquityEngine
+from backtest.engines.vietnam_equity import VietnamEquityEngine
+from backtest.models import Position
+
+CODES = ["VIC.VN", "AAPL.US"]
+
+
+def _composite(**overrides) -> CompositeEngine:
+ config = {"initial_cash": 1_000_000_000, "codes": CODES, **overrides}
+ return CompositeEngine(config, CODES)
+
+
+def _hold(engine: CompositeEngine, *, open_bar: int, add_bar: int | None) -> None:
+ """Give the composite a HOSE position with fill evidence."""
+ for bar_idx, action in [(open_bar, "open"), (add_bar, "increase")]:
+ if bar_idx is None:
+ continue
+ engine._bar_idx = bar_idx
+ engine._record_fill(
+ symbol="VIC.VN",
+ timestamp=pd.Timestamp("2026-03-02") + pd.Timedelta(days=bar_idx),
+ action=action,
+ signed_quantity=1_000.0,
+ execution_price=24_250.0,
+ fee=0.0,
+ margin=24_250_000.0,
+ leverage=1.0,
+ reason="signal",
+ )
+ engine.positions["VIC.VN"] = Position(
+ symbol="VIC.VN",
+ direction=1,
+ entry_price=24_250.0,
+ entry_time=pd.Timestamp("2026-03-02"),
+ size=1_000.0 if add_bar is None else 2_000.0,
+ leverage=1.0,
+ entry_bar_idx=open_bar,
+ )
+
+
+class TestRuleEngineWiring:
+ def test_a_vietnam_rule_engine_is_built(self):
+ engines = _build_rule_engines({}, CODES)
+ assert isinstance(engines["vietnam_equity"], VietnamEquityEngine)
+
+ def test_hose_symbols_do_not_borrow_another_markets_rules(self):
+ engine = _composite()
+ assert isinstance(engine._rule_for("VIC.VN"), VietnamEquityEngine)
+ assert isinstance(engine._rule_for("AAPL.US"), GlobalEquityEngine)
+
+ def test_board_lot_still_applies_through_delegation(self):
+ engine = _composite()
+ engine._active_symbol = "VIC.VN"
+ assert engine.round_size(1_234, 24_250.0) == 1_200
+
+
+class TestSettlementInterception:
+ """The hold is enforced against the composite's own state."""
+
+ @pytest.mark.parametrize("bar_idx,allowed", [(0, False), (1, False), (2, True)])
+ def test_hold_is_enforced_not_skipped(self, bar_idx: int, allowed: bool):
+ engine = _composite(price_limit=0)
+ _hold(engine, open_bar=0, add_bar=None)
+ engine._bar_idx = bar_idx
+ bar = pd.Series({"open": 24_250.0, "close": 24_300.0})
+ assert engine.can_execute("VIC.VN", 0, bar) is allowed
+
+ @pytest.mark.parametrize("bar_idx,allowed", [(2, False), (3, True)])
+ def test_hold_runs_from_the_newest_lot(self, bar_idx: int, allowed: bool):
+ engine = _composite(price_limit=0)
+ _hold(engine, open_bar=0, add_bar=1)
+ engine._bar_idx = bar_idx
+ bar = pd.Series({"open": 24_250.0, "close": 24_300.0})
+ assert engine.can_execute("VIC.VN", 0, bar) is allowed
+
+ def test_the_us_leg_is_unaffected(self):
+ engine = _composite(price_limit=0)
+ _hold(engine, open_bar=0, add_bar=None)
+ engine._bar_idx = 0
+ bar = pd.Series({"open": 190.0, "close": 191.0})
+ assert engine.can_execute("AAPL.US", 0, bar) is True
+
+
+class TestBandInterception:
+ def test_buy_at_the_ceiling_is_blocked(self):
+ engine = _composite()
+ # Reference 24,250 -> ceiling 25,900; an open at the ceiling has no ask.
+ bar = pd.Series({"open": 25_900.0, "pre_close": 24_250.0})
+ assert engine.can_execute("VIC.VN", 1, bar) is False
+
+ def test_buy_inside_the_band_is_allowed(self):
+ engine = _composite()
+ bar = pd.Series({"open": 24_500.0, "pre_close": 24_250.0})
+ assert engine.can_execute("VIC.VN", 1, bar) is True
+
+ def test_short_is_still_refused(self):
+ engine = _composite()
+ bar = pd.Series({"open": 24_250.0, "pre_close": 24_250.0})
+ assert engine.can_execute("VIC.VN", -1, bar) is False
+
+ def test_reference_price_comes_from_the_composites_close_panel(self):
+ """The band works off shared bar state, not just a ``pre_close`` column.
+
+ A stateless sub-engine has no close panel, so this is the half of the
+ band rule that silently vanished before the interception: with no
+ ``pre_close`` on the bar there was no reference price and every fill
+ passed.
+ """
+ engine = _composite()
+ # Panel shaped as BaseEngine builds it: (n_dates, n_codes).
+ engine._close_arr = np.array(
+ [[24_250.0, 190.0], [25_900.0, 191.0]], dtype=float,
+ )
+ engine._code_to_col = {"VIC.VN": 0, "AAPL.US": 1}
+ engine._bar_idx = 1 # reference price is row 0 -> 24,250
+
+ at_ceiling = pd.Series({"open": 25_900.0})
+ inside_band = pd.Series({"open": 24_500.0})
+ assert engine.can_execute("VIC.VN", 1, at_ceiling) is False
+ assert engine.can_execute("VIC.VN", 1, inside_band) is True
+
+ def test_band_is_inactive_without_any_reference(self):
+ engine = _composite()
+ engine._bar_idx = 0 # no prior row, no pre_close column
+ assert engine.can_execute("VIC.VN", 1, pd.Series({"open": 24_500.0})) is True
+
+
+class TestMixedBookIsStillRefused:
+ def test_a_vn_book_cannot_run_beside_another_currency(self):
+ engine = _composite()
+ with pytest.raises(ValueError, match="one settlement currency"):
+ engine.run_backtest(
+ {"initial_cash": 1_000_000_000, "codes": CODES},
+ loader=None,
+ signal_engine=None,
+ run_dir=None,
+ )
diff --git a/agent/tests/test_shadow_account.py b/agent/tests/test_shadow_account.py
index 1c05fc231..d563c99dc 100644
--- a/agent/tests/test_shadow_account.py
+++ b/agent/tests/test_shadow_account.py
@@ -493,6 +493,33 @@ def test_group_selection_by_currency_us_crypto_single_group() -> None:
assert set(groups["USD"].keys()) == {"us", "crypto"}
+def test_group_selection_by_currency_names_vnd() -> None:
+ """A HOSE pool groups under VND, not an ``UNKNOWN:`` marker.
+
+ The group key is not merely a label: it names the pool's run directory
+ (``base_dir / currency``) and is rendered into the headline
+ ``_currency_note``. A market missing from the currency table would put a
+ colon into a path — illegal on Windows — and print the marker to the user.
+ """
+ groups = _group_selection_by_currency({"vietnam": ["VIC.VN", "FPT.VN"]})
+
+ assert set(groups.keys()) == {"VND"}
+ assert groups["VND"]["vietnam"] == ["VIC.VN", "FPT.VN"]
+ assert all(":" not in currency for currency in groups)
+
+
+def test_a_hose_pool_is_separated_from_other_currencies() -> None:
+ groups = _group_selection_by_currency({
+ "vietnam": ["VIC.VN"],
+ "us": _LIQUID_BASKETS["us"][:1],
+ })
+
+ assert set(groups.keys()) == {"VND", "USD"}
+ assert groups["VND"] == {"vietnam": ["VIC.VN"]}
+
+
@pytest.mark.unit
def test_run_shadow_backtest_runs_once_per_currency(
profitable_journal: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
diff --git a/agent/tests/test_vietnam_backtest_smoke.py b/agent/tests/test_vietnam_backtest_smoke.py
new file mode 100644
index 000000000..0376c676d
--- /dev/null
+++ b/agent/tests/test_vietnam_backtest_smoke.py
@@ -0,0 +1,117 @@
+"""End-to-end smoke test: backtest runs on Vietnamese (HOSE) symbols.
+
+Drives ``VietnamEquityEngine`` through the real execution path so the market
+rules are exercised as ``BaseEngine`` actually applies them, rather than
+against hand-built state. All data is in-memory; no network access.
+
+The settlement case here is the one unit tests cannot reach: it needs
+``_execute_position_increase`` to run for real, because the defect it guards
+lives in that method's interaction with the settlement clock — an increase
+folds new shares into the open position while preserving its original
+``entry_bar_idx``.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pandas as pd
+
+from backtest.engines.vietnam_equity import VietnamEquityEngine
+
+CODE = "VIC.VN"
+
+# Nine sessions rising 50 VND a bar: every move sits well inside the +/-7%
+# band, so a band block cannot be mistaken for a settlement block.
+_BASE = 24_250.0
+_BARS = pd.DataFrame(
+ {
+ "open": [_BASE + 50 * i for i in range(9)],
+ "high": [_BASE + 50 * i + 150 for i in range(9)],
+ "low": [_BASE + 50 * i - 150 for i in range(9)],
+ "close": [_BASE + 50 * i + 50 for i in range(9)],
+ "volume": [1_000_000] * 9,
+ },
+ index=pd.bdate_range("2026-03-02", periods=9),
+)
+
+
+class _FakeLoader:
+ def fetch(self, *args, **kwargs):
+ return {CODE: _BARS.copy()}
+
+
+class _WeightSignal:
+ """Replay a fixed target-weight path, one weight per bar."""
+
+ def __init__(self, weights: list[float]) -> None:
+ self._weights = weights
+
+ def generate(self, data_map):
+ return {CODE: pd.Series(self._weights, index=data_map[CODE].index)}
+
+
+def _run(weights: list[float], run_dir: Path) -> VietnamEquityEngine:
+ config = {
+ "codes": [CODE],
+ "start_date": "2026-03-02",
+ "end_date": "2026-03-20",
+ "source": "auto",
+ "initial_cash": 1_000_000_000,
+ "slippage": 0.0,
+ # Increases only occur under 'rebalance'; 'hold' never scales in.
+ "position_adjustment": "rebalance",
+ }
+ engine = VietnamEquityEngine(config)
+ engine.run_backtest(config, _FakeLoader(), _WeightSignal(weights), run_dir)
+ return engine
+
+
+def _fills(engine: VietnamEquityEngine) -> list[tuple[int, str]]:
+ return [(f.bar_idx, f.action) for f in engine.fill_records]
+
+
+def test_backtest_completes_on_hose_bars(tmp_path: Path) -> None:
+ # Half weight: a fully invested target cannot fund its own commissions
+ # once equity drifts, which is BaseEngine behaviour and not under test.
+ engine = _run([0.5] * 9, tmp_path)
+ assert engine.fill_records
+ # Every fill lands on a whole board lot and on the tick grid.
+ for fill in engine.fill_records:
+ assert abs(fill.signed_quantity) % 100 == 0
+ assert fill.execution_price % 10 == 0
+
+
+def test_scaling_in_holds_the_whole_position_for_the_new_lot(tmp_path: Path) -> None:
+ """Buy, add, then try to exit one session after the add.
+
+ Weights execute a bar late, so this path is: open on bar 1, increase on
+ bar 3, exit signal acting on bar 4. Bar 4 is T+3 for the first lot but only
+ T+1 for the added one, so the sell must wait for bar 5.
+
+ Reading the clock from ``Position.entry_bar_idx`` instead closes on bar 4 —
+ selling shares that arrived one session earlier.
+ """
+ engine = _run([0.5, 0.5, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], tmp_path)
+
+ assert _fills(engine) == [(1, "open"), (3, "increase"), (5, "close")]
+
+
+def test_no_partial_exit_slips_through_before_the_new_lot_settles(
+ tmp_path: Path,
+) -> None:
+ """A reduction to a smaller non-zero weight is held on the same rule.
+
+ The compressed position carries no lot identity, so a partial sell cannot
+ be shown to consume settled shares only; it waits with the rest.
+ """
+ engine = _run([0.5, 0.5, 1.0, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25], tmp_path)
+
+ reducing = [
+ (idx, action)
+ for idx, action in _fills(engine)
+ if action in {"reduce", "partial_reduction", "close"}
+ ]
+ assert reducing, "expected the weight cut to reduce the position eventually"
+ increase_bar = next(idx for idx, action in _fills(engine) if action == "increase")
+ assert all(idx >= increase_bar + 2 for idx, _ in reducing)
diff --git a/agent/tests/test_vietnam_equity_engine.py b/agent/tests/test_vietnam_equity_engine.py
index 84ad95f30..99229bf39 100644
--- a/agent/tests/test_vietnam_equity_engine.py
+++ b/agent/tests/test_vietnam_equity_engine.py
@@ -13,6 +13,7 @@ from backtest.engines.vietnam_equity import (
hose_round_down,
hose_round_up,
hose_tick_size,
+ newest_opening_bar_idx,
)
from backtest.models import Position
@@ -128,6 +129,104 @@ class TestSettlement:
assert engine.can_execute("VIC.VN", 1, bar) is True
+class TestSettlementAfterScalingIn:
+ """A same-direction add re-arms the hold for the whole position.
+
+ ``BaseEngine._execute_position_increase`` folds an add into the open
+ position but preserves ``entry_bar_idx``, so a clock read from that field
+ alone releases later-bought shares early. These cases pin the fill-ledger
+ clock that replaces it.
+ """
+
+ def _fill(self, engine: VietnamEquityEngine, action: str, bar_idx: int) -> None:
+ engine._bar_idx = bar_idx
+ engine._record_fill(
+ symbol="VIC.VN",
+ timestamp=pd.Timestamp("2026-01-05") + pd.Timedelta(days=bar_idx),
+ action=action,
+ signed_quantity=1_000.0,
+ execution_price=24_250.0,
+ fee=0.0,
+ margin=24_250_000.0,
+ leverage=1.0,
+ reason="signal",
+ )
+
+ def _scaled_in_engine(self, **overrides) -> VietnamEquityEngine:
+ """Buy on bar 0, add on bar 1 — the position still carries entry idx 0."""
+ engine = _engine(price_limit=0, **overrides)
+ self._fill(engine, "open", bar_idx=0)
+ self._fill(engine, "increase", bar_idx=1)
+ engine.positions["VIC.VN"] = Position(
+ symbol="VIC.VN",
+ direction=1,
+ entry_price=24_250.0,
+ entry_time=pd.Timestamp("2026-01-05"),
+ size=2_000.0,
+ leverage=1.0,
+ entry_bar_idx=0, # preserved by the increase — deliberately stale
+ )
+ return engine
+
+ @pytest.mark.parametrize("bar_idx,allowed", [(2, False), (3, True)])
+ def test_hold_runs_from_the_newest_lot(self, bar_idx: int, allowed: bool) -> None:
+ # Bar 2 is T+2 for the first lot but only T+1 for the added one.
+ engine = self._scaled_in_engine()
+ engine._bar_idx = bar_idx
+ bar = pd.Series({"open": 24_250.0, "close": 24_300.0})
+ assert engine.can_execute("VIC.VN", 0, bar) is allowed
+
+ def test_partial_reduction_is_held_too(self) -> None:
+ # The compressed position carries no lot identity, so a partial sell
+ # cannot be shown to consume only settled shares. Hold all of it.
+ engine = self._scaled_in_engine()
+ engine._bar_idx = 2
+ bar = pd.Series({"open": 24_250.0, "close": 24_300.0})
+ assert engine.can_execute("VIC.VN", 0, bar) is False
+ assert engine.positions["VIC.VN"].size == 2_000.0
+
+ def test_buying_more_is_never_held(self) -> None:
+ engine = self._scaled_in_engine()
+ engine._bar_idx = 2
+ bar = pd.Series({"open": 24_250.0, "close": 24_300.0})
+ assert engine.can_execute("VIC.VN", 1, bar) is True
+
+ def test_stale_entry_idx_alone_would_have_released_early(self) -> None:
+ # Guards the regression itself: the position's own field still reads 0,
+ # so a clock built on it would have allowed the bar-2 sell above.
+ engine = self._scaled_in_engine()
+ assert engine.positions["VIC.VN"].entry_bar_idx == 0
+ assert newest_opening_bar_idx(engine, "VIC.VN") == 1
+
+ def test_configurable_lag_still_counts_from_newest(self) -> None:
+ engine = self._scaled_in_engine(vn_settlement_bars=1)
+ engine._bar_idx = 2
+ bar = pd.Series({"open": 24_250.0, "close": 24_300.0})
+ assert engine.can_execute("VIC.VN", 0, bar) is True
+
+ def test_reopened_position_uses_its_own_lot(self) -> None:
+ # A close then a fresh buy starts a new clock; the old fills must not
+ # settle the new position.
+ engine = _engine(price_limit=0)
+ self._fill(engine, "open", bar_idx=0)
+ self._fill(engine, "close", bar_idx=2)
+ self._fill(engine, "open", bar_idx=5)
+ engine.positions["VIC.VN"] = Position(
+ symbol="VIC.VN",
+ direction=1,
+ entry_price=24_250.0,
+ entry_time=pd.Timestamp("2026-01-10"),
+ size=1_000.0,
+ leverage=1.0,
+ entry_bar_idx=5,
+ )
+ bar = pd.Series({"open": 24_250.0, "close": 24_300.0})
+ engine._bar_idx = 6
+ assert engine.can_execute("VIC.VN", 0, bar) is False
+ engine._bar_idx = 7
+ assert engine.can_execute("VIC.VN", 0, bar) is True
+
+
class TestBandBlocking:
def test_buy_blocked_at_ceiling(self) -> None:
engine = _engine()