Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(backtest): add a Vietnam (HOSE) equity engine and route .VN symbols

Pham Van Ngoane0c45d118e45
diff --git a/README.md b/README.md
index 7e40d3071..81ec9da37 100644
--- a/README.md
+++ b/README.md
@@ -560,7 +560,7 @@ Run `vibe-trading alpha list` to browse, `vibe-trading alpha show <id>` for form
</details>
<details>
-<summary><b>Backtest Engines</b> <sub>9 engines + options portfolio, cross-market composite</sub></summary>
+<summary><b>Backtest Engines</b> <sub>10 engines + options portfolio, cross-market composite</sub></summary>
| Engine | Market | Notes |
|--------|--------|-------|
@@ -568,6 +568,7 @@ Run `vibe-trading alpha list` to browse, `vibe-trading alpha show <id>` for form
| **GlobalEquity** | US / HK / Canada | same-session trading; market-specific lots, ticks, and costs |
| **IndiaEquity** | India (NSE/BSE) | T+1, circuit bands, config-driven STT / stamp / SEBI / GST cost stack |
| **KoreaEquity** | Korea (KRX: KOSPI/KOSDAQ) | long-only, ±30% band judged at execution time on the unified tick grid, 2026 0.20% transaction tax |
+| **VietnamEquity** | Vietnam (HOSE) | long-only, T+2 settlement hold, ±7% band on the 10/50/100-VND tick grid, 100-share lots, 0.1% sell-side tax |
| **Crypto** | crypto spot / USD-M perps | funding settlements, execution/mark split |
| **ChinaFutures** · **GlobalFutures** | futures | margin, contract multipliers |
| **Forex** | FX / metals | via the `mt5` loader (local terminal) or the hosted `tickerall` loader (no terminal, any OS) |
diff --git a/README_ar.md b/README_ar.md
index 18423b658..74cfb8e40 100644
--- a/README_ar.md
+++ b/README_ar.md
@@ -556,7 +556,7 @@ LONGBRIDGE_ACCESS_TOKEN=...
</details>
<details>
-<summary><b>محرّكات الاختبار الرجعي</b> <sub>9 محرّكات + محفظة خيارات، ومركّب عبر الأسواق</sub></summary>
+<summary><b>محرّكات الاختبار الرجعي</b> <sub>10 محرّكات + محفظة خيارات، ومركّب عبر الأسواق</sub></summary>
| المحرّك | السوق | ملاحظات |
|--------|-------|---------|
@@ -564,6 +564,7 @@ LONGBRIDGE_ACCESS_TOKEN=...
| **GlobalEquity** | US / HK / كندا | تداول في الجلسة نفسها؛ أحجام وخطوات سعرية وتكاليف حسب السوق |
| **IndiaEquity** | الهند (NSE/BSE) | T+1، ونطاقات القاطع (circuit)، وحزمة تكاليف STT / الدمغة / SEBI / GST قابلة للتهيئة |
| **KoreaEquity** | كوريا (KRX: KOSPI/KOSDAQ) | شراء فقط، ونطاق ±30% يُحكم عليه لحظة التنفيذ على شبكة الخطوة السعرية الموحّدة، وضريبة تداول 0.20% لعام 2026 |
+| **VietnamEquity** | فيتنام (HOSE) | شراء فقط، واحتجاز تسوية T+2، ونطاق ±7% على شبكة الخطوة السعرية 10/50/100 دونغ، ولوت 100 سهم، وضريبة 0.1% على البيع |
| **Crypto** | crypto فوري / عقود USD-M الدائمة | تسويات التمويل، وفصل سعر التنفيذ عن سعر العلامة |
| **ChinaFutures** · **GlobalFutures** | العقود الآجلة | الهامش، ومضاعِفات العقد |
| **Forex** | FX / المعادن | عبر مُحمّل `mt5` |
diff --git a/README_ja.md b/README_ja.md
index b1030a6bd..9c31f01cd 100644
--- a/README_ja.md
+++ b/README_ja.md
@@ -556,7 +556,7 @@ Paper-vs-live is a **structural per-broker runtime guard** (account-id format, h
</details>
<details>
-<summary><b>Backtest Engines</b> <sub>9 engines + options portfolio, cross-market composite</sub></summary>
+<summary><b>Backtest Engines</b> <sub>10 engines + options portfolio, cross-market composite</sub></summary>
| Engine | Market | Notes |
|--------|--------|-------|
@@ -564,6 +564,7 @@ Paper-vs-live is a **structural per-broker runtime guard** (account-id format, h
| **GlobalEquity** | US / HK / カナダ | 同一セッション売買、市場別のロット・呼値・コスト |
| **IndiaEquity** | India (NSE/BSE) | T+1, circuit bands, config-driven STT / stamp / SEBI / GST cost stack |
| **KoreaEquity** | 韓国(KRX:KOSPI/KOSDAQ) | ロングオンリー、統一呼値グリッド上で ±30% 制限値幅を約定時点に判定、2026 年 0.20% の証券取引税 |
+| **VietnamEquity** | ベトナム(HOSE) | ロングオンリー、T+2 決済ホールド、10/50/100 ドンの呼値グリッド上で ±7% 制限値幅、100 株単元、売却側 0.1% 課税 |
| **Crypto** | crypto spot / USD-M perps | funding settlements, execution/mark split |
| **ChinaFutures** · **GlobalFutures** | futures | margin, contract multipliers |
| **Forex** | FX / metals | via the `mt5` loader |
diff --git a/README_ko.md b/README_ko.md
index 7febb6706..ef70a421e 100644
--- a/README_ko.md
+++ b/README_ko.md
@@ -556,7 +556,7 @@ Paper-vs-live는 **구조적 브로커별 런타임 가드**(account-id 형식,
</details>
<details>
-<summary><b>백테스트 엔진</b> <sub>9개 엔진 + 옵션 포트폴리오, 크로스마켓 composite</sub></summary>
+<summary><b>백테스트 엔진</b> <sub>10개 엔진 + 옵션 포트폴리오, 크로스마켓 composite</sub></summary>
| Engine | Market | Notes |
|--------|--------|-------|
@@ -564,6 +564,7 @@ Paper-vs-live는 **구조적 브로커별 런타임 가드**(account-id 형식,
| **GlobalEquity** | US / HK / 캐나다 | 동일 세션 거래, 시장별 주문 단위·호가·비용 |
| **IndiaEquity** | India (NSE/BSE) | T+1, circuit bands, config-driven STT / stamp / SEBI / GST cost stack |
| **KoreaEquity** | 한국 (KRX: KOSPI/KOSDAQ) | 롱 온리, 통합 호가 단위에서 ±30% 가격제한폭을 체결 시점에 판정, 2026년 0.20% 증권거래세 |
+| **VietnamEquity** | 베트남 (HOSE) | 롱 온리, T+2 결제 보유, 10/50/100 VND 호가 단위에서 ±7% 가격제한폭, 100주 단위, 매도측 0.1% 세금 |
| **Crypto** | crypto spot / USD-M perps | funding settlements, execution/mark split |
| **ChinaFutures** · **GlobalFutures** | futures | margin, contract multipliers |
| **Forex** | FX / metals | via the `mt5` loader |
diff --git a/README_zh.md b/README_zh.md
index fff796065..2ce95843c 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -553,7 +553,7 @@ LONGBRIDGE_ACCESS_TOKEN=...
</details>
<details>
-<summary><b>Backtest Engines</b> <sub>9 个引擎 + options portfolio,跨市场 composite</sub></summary>
+<summary><b>Backtest Engines</b> <sub>10 个引擎 + options portfolio,跨市场 composite</sub></summary>
| 引擎 | 市场 | 说明 |
|------|------|------|
@@ -561,6 +561,7 @@ LONGBRIDGE_ACCESS_TOKEN=...
| **GlobalEquity** | 美股 / 港股 / 加拿大 | 支持日内往返;按市场应用手数、最小价位和成本 |
| **IndiaEquity** | 印度(NSE/BSE) | T+1、熔断带、config 驱动的 STT / 印花税 / SEBI / GST 成本栈 |
| **KoreaEquity** | 韩国(KRX:KOSPI/KOSDAQ) | 只做多,统一最小价位网格上于成交时刻判定 ±30% 涨跌停,2026 年 0.20% 证券交易税 |
+| **VietnamEquity** | 越南(HOSE) | 只做多,T+2 交收锁定,10/50/100 越南盾最小价位网格上 ±7% 涨跌停,100 股整手,0.1% 卖出方税 |
| **Crypto** | 加密现货 / USD-M 永续 | 资金费结算、成交价/标记价分离 |
| **ChinaFutures** · **GlobalFutures** | 期货 | 保证金、合约乘数 |
| **Forex** | 外汇 / 贵金属 | 经 `mt5` loader |
diff --git a/agent/SKILL.md b/agent/SKILL.md
index c9333feb4..414c5f5af 100644
--- a/agent/SKILL.md
+++ b/agent/SKILL.md
@@ -1,7 +1,7 @@
---
name: vibe-trading
version: 0.1.13
-description: Professional finance research toolkit — backtesting (9 engines + benchmark comparison panel), factor analysis, Alpha Zoo (462 pre-built alphas across qlib158/alpha101/gtja191/academic/fundamental), options pricing, 89 finance skills, 30 multi-agent swarm teams, Trade Journal analyzer, and Shadow Account (extract → backtest → render) across 25 market-data sources (tushare, yfinance, okx, binance, akshare, baostock, tencent, mootdx, ccxt, futu, mt5, tickerall, local, eastmoney, sina, stooq, yahoo, pykrx, india_broker, qveris, longbridge, plus optional-key finnhub/alphavantage/tiingo/fmp).
+description: Professional finance research toolkit — backtesting (10 engines + benchmark comparison panel), factor analysis, Alpha Zoo (462 pre-built alphas across qlib158/alpha101/gtja191/academic/fundamental), options pricing, 89 finance skills, 30 multi-agent swarm teams, Trade Journal analyzer, and Shadow Account (extract → backtest → render) across 25 market-data sources (tushare, yfinance, okx, binance, akshare, baostock, tencent, mootdx, ccxt, futu, mt5, tickerall, local, eastmoney, sina, stooq, yahoo, pykrx, india_broker, qveris, longbridge, plus optional-key finnhub/alphavantage/tiingo/fmp).
dependencies:
python: ">=3.11,<3.14"
pip:
@@ -23,7 +23,7 @@ mcp:
# Vibe-Trading
-Professional finance research toolkit with AI-powered backtesting (9 engines), multi-agent teams, 89 specialized skills, the **Alpha Zoo** (462 pre-built quantitative alphas across qlib158 / alpha101 / gtja191 / academic / fundamental with one-line CLI benchmarking), and the Shadow Account loop — extract your implicit trading rules from a journal, backtest them across A股/港股/美股/crypto, then see where they would have served you better.
+Professional finance research toolkit with AI-powered backtesting (10 engines), multi-agent teams, 89 specialized skills, the **Alpha Zoo** (462 pre-built quantitative alphas across qlib158 / alpha101 / gtja191 / academic / fundamental with one-line CLI benchmarking), and the Shadow Account loop — extract your implicit trading rules from a journal, backtest them across A股/港股/美股/crypto, then see where they would have served you better.
## Setup
@@ -74,11 +74,12 @@ Feed a CSV broker export (同花顺 / 东财 / 富途 / generic), and the agent
5. `scan_shadow_signals` — list today's symbols that match your shadow's entry cadence (research only).
### Backtesting
-Create and run quantitative strategies across 9 engines (ChinaA, GlobalEquity, IndiaEquity, KoreaEquity, Crypto, ChinaFutures, GlobalFutures, Forex + options) with 25 market-data sources (auto-detect + ordered fallback; the hosted forex `tickerall` source is explicit-only):
+Create and run quantitative strategies across 10 engines (ChinaA, GlobalEquity, IndiaEquity, KoreaEquity, VietnamEquity, Crypto, ChinaFutures, GlobalFutures, Forex + options) with 25 market-data sources (auto-detect + ordered fallback; the hosted forex `tickerall` source is explicit-only):
- **HK/US equities** via yfinance / stooq / yahoo (free, no API key); optionally via **Longbridge** historical OHLCV (`longbridge`, requires the optional SDK and `LONGBRIDGE_APP_KEY` / `LONGBRIDGE_APP_SECRET` / `LONGBRIDGE_ACCESS_TOKEN`). To force it for a run, set `"source": "longbridge"` in `config.json`.
- **Canada equities (TSX/TSXV)** via yahoo / yfinance using Yahoo's canonical `<TICKER>.TO` (TSX, e.g. `TD.TO`) or `<TICKER>.V` (TSXV, e.g. `PNG.V`) suffixes — free, no API key. The GlobalEquity engine uses CAD identity, whole-share orders, configurable Canadian commission/slippage, and the TSX/TSXV price-increment grid.
- **India equities (NSE/BSE)** via yahoo / yfinance using `<SYMBOL>.NS` (NSE, e.g. `RELIANCE.NS`) or `<SCRIP>.BO` (BSE, e.g. `500325.BO`) — free, no API key. The `IndiaEquityEngine` models T+1 delivery, no overnight shorts (set `allow_short` for intraday), configurable circuit bands, 1-share lots, and the STT/stamp-duty/exchange/GST cost stack. Optionally back-fill from your live broker via the `india_broker` source (Shoonya/Dhan; requires broker login).
- **Korea equities (KRX: KOSPI/KOSDAQ)** via pykrx using `<CODE>.KS` (KOSPI, e.g. `005930.KS`) or `<CODE>.KQ` (KOSDAQ, e.g. `247540.KQ`) — free, no API key (`pip install "vibe-trading-ai[krx]"`; yahoo/yfinance fallback needs no extra). pykrx serves **daily bars only** (an intraday request falls through to another source) and its adjusted series is Naver-backed rather than a verbatim KRX print. The `KoreaEquityEngine` models same-day round trips (no T+1), the ±30% daily price limit measured from the previous close and quantized to the KRX tick grid, tick-rounded fills, the 0.20% sell-side transaction tax (2026 rate), and 1-share lots. It is **long-only**: `allow_short` is refused, because KRX covered-short and uptick rules cannot be enforced on daily bars.
+- **Vietnam equities (HOSE)** via yahoo / yfinance using `<TICKER>.VN` (e.g. `VIC.VN`) — no API key. Yahoo officially lists HOSE but not HNX or UPCOM; those venues are unsupported and need the `local` source. yfinance is an unofficial Yahoo client, so availability is best-effort and subject to Yahoo's personal-use terms. The `VietnamEquityEngine` approximates the formal T+2 settlement cycle — shares bought on day T normally become sellable during the afternoon session on T+2, informally called T+1.5 — as a two-bar hold on daily data (`vn_settlement_bars` covers scenario testing and future rule changes). It applies HOSE's normal ±7% band around the reference price, rounding the ceiling down and the floor up to the 10/50/100-VND tick grid, and uses 100-share round lots; odd-lot trading is not modelled. Costs are configurable brokerage plus, for individual investors, 0.1% sell-side personal income tax on gross proceeds. It is **long-only**, because operational cash-equity short selling is not generally available in Vietnam.
- **Cryptocurrency** via OKX or CCXT/100+ exchanges (free, no API key)
- **China A-shares** via AKShare / baostock / tencent / sina / eastmoney / mootdx (free, no API key) — `TUSHARE_TOKEN` optional for premium quality
- **Futures, forex, macro** via AKShare (free, no API key)
diff --git a/agent/backtest/engines/_market_hooks.py b/agent/backtest/engines/_market_hooks.py
index 4ef81201d..c0f1abadb 100644
--- a/agent/backtest/engines/_market_hooks.py
+++ b/agent/backtest/engines/_market_hooks.py
@@ -35,6 +35,9 @@ _MARKET_PATTERNS = [
# Canada equities: Toronto Stock Exchange (TD.TO) and TSX Venture
# (PNG.V). Yahoo carries both suffixes verbatim.
(re.compile(r"^[A-Z0-9&.\-]+\.(TO|V)$", re.I), "ca_equity"),
+ # Vietnam equities: HOSE (VIC.VN). Tickers are three letters in practice;
+ # the class stays broad to admit fund certificates and ETF codes.
+ (re.compile(r"^[A-Z0-9]+\.VN$", re.I), "vietnam_equity"),
(re.compile(r"^[A-Z]+-USDT$", re.I), "crypto"),
(re.compile(r"^[A-Z]+/USDT$", re.I), "crypto"),
# yfinance's native crypto spelling (BTC-USD, ETH-USD). Distinct from
diff --git a/agent/backtest/engines/vietnam_equity.py b/agent/backtest/engines/vietnam_equity.py
new file mode 100644
index 000000000..a2d4e7e56
--- /dev/null
+++ b/agent/backtest/engines/vietnam_equity.py
@@ -0,0 +1,367 @@
+"""Vietnam equity (HOSE) backtest engine.
+
+Models the Ho Chi Minh Stock Exchange cash-equity segment on daily bars.
+Prices are assumed to be quoted in whole VND — the unit Yahoo's ``.VN`` series
+uses — on a coarse tick grid (bước giá) that is modelled explicitly, because a
+percentage-only model produces fill prices that cannot exist and mis-identifies
+locked-band bars.
+
+Market rules:
+ - **Long-only.** Circular 120/2020 defines a covered-short framework, but
+ routine cash-equity short selling is not operationally available, so
+ ``allow_short=True`` is refused at construction rather than simulated.
+ Short exposure in this market is expressed through index futures, which
+ this engine does not cover.
+ - Settlement is formally **T+2**. Since 2022 shares normally arrive before
+ the afternoon session on T+2 and may be sold that afternoon, which is why
+ 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.
+ - 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).
+ First trading days, resumptions after long suspensions and certain
+ ex-right sessions use ±20%; pass ``price_limit`` per run to model those.
+ Set it to ``0`` / ``None`` to disable. HNX (±10%) and UPCOM (±15%) are not
+ served by this engine's data path.
+ - Round lot: 100 shares. HOSE also accepts odd-lot orders of 1-99 shares in
+ a separate board that daily bars cannot represent, so odd-lot trading is
+ deliberately not modelled and sub-lot orders round to zero.
+
+Cost stack (all config-driven; verify against your broker's current schedule
+before trusting absolute cost figures):
+ - Brokerage: 0.15% per side, a common online retail rate [vn_brokerage]
+ - Personal income tax: 0.10% of gross sale proceeds, SELL side only, for
+ individual investors [vn_tax_sell]
+ Levied on proceeds regardless of gain or loss, and unchanged by the 2026
+ personal-income-tax overhaul: Nghị định 253/2026/NĐ-CP keeps listed
+ securities at ``giá chuyển nhượng x 0,1%``. The 20% gain-based rate that
+ took effect 2026-07-01 applies to chuyển nhượng vốn (unlisted capital
+ transfers), not to exchange-traded shares. Other taxpayer classes are
+ treated differently; override the key if you are not modelling an
+ individual investor.
+
+The band arithmetic follows the exchange's published procedure rather than a
+naive ``base * 1.07``: the 7% amount is applied to the reference price and the
+resulting bound is truncated onto the tick unit of the price it lands on, so
+the ceiling (giá trần) and floor (giá sàn) are always tradeable prices.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Optional
+
+import pandas as pd
+
+from backtest.engines.base import BaseEngine
+
+logger = logging.getLogger(__name__)
+
+# HOSE quotation price units (bước giá) for shares and fund certificates:
+# (lower bound inclusive, tick) in VND. Every coarser tick is an exact multiple
+# of every finer one, which keeps the truncation arithmetic stable across band
+# boundaries.
+HOSE_TICK_TABLE: tuple[tuple[float, float], ...] = (
+ (0.0, 10.0),
+ (10_000.0, 50.0),
+ (50_000.0, 100.0),
+)
+
+# Board lot on HOSE's continuous session.
+HOSE_LOT_SIZE = 100
+
+# Tick-grid comparisons only need to survive float representation error: every
+# quantized price is a whole number of dong, so 1e-9 is far below one tick.
+_PRICE_EPS = 1e-9
+
+# Settlement lag in sessions. Under the T+2 cycle shares normally arrive
+# before the afternoon session on T+2, so a buy at bar N releases at bar N+2.
+_DEFAULT_SETTLEMENT_BARS = 2
+
+
+def hose_tick_size(price: float) -> float:
+ """Return the HOSE tick unit (bước giá) applying at *price*.
+
+ Args:
+ price: Price in VND.
+
+ Returns:
+ The tick unit in VND. Prices at or below zero take the finest tick.
+ """
+ tick = HOSE_TICK_TABLE[0][1]
+ for lower, unit in HOSE_TICK_TABLE:
+ if price >= lower:
+ tick = unit
+ else:
+ break
+ return tick
+
+
+def hose_round_down(price: float) -> float:
+ """Quantize *price* down onto the HOSE tick grid."""
+ tick = hose_tick_size(price)
+ return float(int((price + _PRICE_EPS) / tick) * tick)
+
+
+def hose_round_up(price: float) -> float:
+ """Quantize *price* up onto the HOSE tick grid."""
+ tick = hose_tick_size(price)
+ floored = hose_round_down(price)
+ if abs(floored - price) < _PRICE_EPS:
+ return floored
+ return float(floored + tick)
+
+
+def hose_price_limits(base_price: float, band: float) -> tuple[float, float]:
+ """Return the (ceiling, floor) prices for *base_price* under *band*.
+
+ Args:
+ base_price: Reference price (giá tham chiếu) in VND.
+ band: Band as a fraction, e.g. ``0.07`` for HOSE's ±7%.
+
+ Returns:
+ ``(giá trần, giá sàn)`` — both quantized onto the tick grid, the
+ ceiling truncated down and the floor truncated up so that neither
+ bound sits outside the legal band.
+ """
+ upper = hose_round_down(base_price * (1.0 + band))
+ lower = hose_round_up(base_price * (1.0 - band))
+ return upper, lower
+
+
+class VietnamEquityEngine(BaseEngine):
+ """HOSE cash-equity engine — long-only, T+2 settled.
+
+ Config keys (all optional; defaults shown in the module docstring):
+ - price_limit: float fraction or None, default 0.07
+ - slippage: default 0.001
+ - vn_brokerage / vn_tax_sell
+ - vn_settlement_bars: sessions a buy is held before it may be sold,
+ default 2 (approximates the T+2 cycle on daily bars)
+
+ Raises:
+ ValueError: When ``allow_short`` is truthy. Routine short selling is
+ not operationally available in the Vietnamese cash market, so
+ shorting is refused instead of being simulated. A cross-market
+ composite run shares one config across its sub-engines, so pairing
+ ``allow_short`` with a HOSE symbol fails the whole run —
+ deliberately, since the alternative is a HOSE leg that silently
+ never shorts while the rest of the book does.
+ """
+
+ def __init__(self, config: dict):
+ config = {**config, "leverage": 1.0} # cash equity: no leverage
+ super().__init__(config)
+ if config.get("allow_short"):
+ raise ValueError(
+ "VietnamEquityEngine is long-only: routine short selling is not "
+ "operationally available in the Vietnamese cash market, so a short "
+ "book cannot be modelled. Remove 'allow_short' instead of running "
+ "a mis-modelled short book."
+ )
+ self.price_limit = config.get("price_limit", 0.07)
+ self.slippage_rate: float = config.get("slippage", 0.001)
+ # Cost stack
+ self.vn_brokerage: float = config.get("vn_brokerage", 0.0015)
+ self.vn_tax_sell: float = config.get("vn_tax_sell", 0.001)
+ self.settlement_bars: int = int(
+ config.get("vn_settlement_bars", _DEFAULT_SETTLEMENT_BARS)
+ )
+ # One warning per engine when no reference price is derivable.
+ self._limit_base_warned = False
+ self._settlement_warned = False
+
+ def can_execute(self, symbol: str, direction: int, bar: pd.Series) -> bool:
+ """HOSE execution rules.
+
+ The band test compares the *prospective fill price* — this bar's open
+ plus slippage, which is what :class:`BaseEngine` fills at — against
+ bounds derived from the previous bar's close. Deriving the move from the
+ current bar's close instead would be lookahead: ``BaseEngine`` calls this
+ hook before the fill, and the decision bar's close is not known then.
+
+ Args:
+ symbol: HOSE symbol (e.g. ``VIC.VN``).
+ direction: 1 (buy), -1 (short — always blocked), 0 (sell/close).
+ bar: Current bar (needs ``open``; the reference price comes from
+ ``pre_close`` when the source supplies it, else from the prior
+ bar of the run's own close panel).
+
+ 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
+
+ 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
+
+ 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.
+
+ Args:
+ 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 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)
+
+ def round_size(self, raw_size: float, price: float) -> float:
+ """Floor the order to whole 100-share board lots.
+
+ HOSE accepts odd-lot orders of 1-99 shares on a separate board that a
+ daily bar cannot represent, so odd-lot trading is deliberately not
+ modelled: a sub-lot order rounds to zero rather than being filled at
+ the continuous-session price.
+
+ Args:
+ raw_size: Unrounded share count.
+ price: Fill price in VND (unused; lot size is price-independent).
+
+ Returns:
+ Share count as a whole multiple of the board lot.
+ """
+ lots = int(max(raw_size, 0) // HOSE_LOT_SIZE)
+ return float(lots * HOSE_LOT_SIZE)
+
+ def calc_commission(self, size: float, price: float, direction: int, is_open: bool) -> float:
+ """Vietnam cost stack: bilateral brokerage + sell-side personal income tax.
+
+ The tax follows the actual trade side rather than open/close: a closing
+ trade on a long book is a sell (taxable). ``BaseEngine`` passes the
+ position direction on both hooks, so the side is derivable even though
+ this engine is long-only.
+
+ Args:
+ size: Share count.
+ price: Fill price in VND.
+ direction: 1 for a long book, -1 for a short book.
+ is_open: True for the opening leg, False for the closing leg.
+
+ Returns:
+ Total cost in VND for this leg.
+ """
+ notional = size * price
+ comm = notional * self.vn_brokerage
+ is_sell = (direction < 0) if is_open else (direction > 0)
+ if is_sell:
+ comm += notional * self.vn_tax_sell
+ return comm
+
+ def apply_slippage(self, price: float, direction: int) -> float:
+ """Vietnam slippage (configurable), quantized onto the HOSE tick grid.
+
+ A slipped price is snapped away from the trader — buys up to the next
+ valid ask, sells down to the next valid bid — because no fill can land
+ between ticks.
+
+ Args:
+ price: Reference price in VND.
+ direction: 1 to buy, -1 to sell.
+
+ Returns:
+ A valid HOSE price, never below one tick.
+ """
+ slipped = price * (1 + direction * self.slippage_rate)
+ if direction > 0:
+ return hose_round_up(slipped)
+ return max(hose_round_down(slipped), hose_tick_size(slipped))
diff --git a/agent/backtest/runner.py b/agent/backtest/runner.py
index f0e8b965c..cd6d2779d 100644
--- a/agent/backtest/runner.py
+++ b/agent/backtest/runner.py
@@ -1295,6 +1295,13 @@ def _create_market_engine(source: str, config: dict, codes: List[str]):
from backtest.engines.korea_equity import KoreaEquityEngine
return KoreaEquityEngine(config)
+ # Vietnam equity routing — same reason as India and Korea: its effective
+ # source (``yahoo``) has no Wave-1 branch and would fall through to the
+ # default.
+ if "vietnam_equity" in markets:
+ from backtest.engines.vietnam_equity import VietnamEquityEngine
+ return VietnamEquityEngine(config)
+
# Original routing (Wave 1)
if source in ("okx", "ccxt"):
from backtest.engines.crypto import CryptoEngine
diff --git a/agent/tests/test_vietnam_equity.py b/agent/tests/test_vietnam_equity.py
index 22684154e..fc552af10 100644
--- a/agent/tests/test_vietnam_equity.py
+++ b/agent/tests/test_vietnam_equity.py
@@ -50,18 +50,6 @@ class TestFallbackChain:
assert "vietnam_equity" in DataLoader.markets
-class TestSymbolsAreNotAutoRouted:
- """``.VN`` deliberately does not auto-detect yet.
-
- Classifying ``.VN`` as ``vietnam_equity`` without an execution engine to
- match would route a HOSE backtest through engine selection that has no
- Vietnam branch. Detection lands with the engine, not with the data.
- """
-
- def test_vn_is_not_yet_classified_as_vietnam_equity(self) -> None:
- assert _detect_market("VIC.VN") != "vietnam_equity"
-
-
class TestFetch:
"""The loader returns a normalized frame for a HOSE symbol."""
diff --git a/agent/tests/test_vietnam_equity_engine.py b/agent/tests/test_vietnam_equity_engine.py
new file mode 100644
index 000000000..84ad95f30
--- /dev/null
+++ b/agent/tests/test_vietnam_equity_engine.py
@@ -0,0 +1,174 @@
+"""Tests for the Vietnam (HOSE) equity engine."""
+
+from __future__ import annotations
+
+import pandas as pd
+import pytest
+
+from backtest.engines._market_hooks import _detect_market
+from backtest.engines.vietnam_equity import (
+ HOSE_LOT_SIZE,
+ VietnamEquityEngine,
+ hose_price_limits,
+ hose_round_down,
+ hose_round_up,
+ hose_tick_size,
+)
+from backtest.models import Position
+
+
+def _engine(**overrides) -> VietnamEquityEngine:
+ config = {"initial_capital": 1_000_000_000.0, **overrides}
+ return VietnamEquityEngine(config)
+
+
+class TestMarketDetection:
+ def test_vn_symbols_route_to_vietnam(self) -> None:
+ assert _detect_market("VIC.VN") == "vietnam_equity"
+ assert _detect_market("vic.vn") == "vietnam_equity"
+
+ def test_tsx_venture_still_routes_to_canada(self) -> None:
+ # ``.V`` and ``.VN`` are distinct suffixes; neither may claim the other.
+ assert _detect_market("PNG.V") == "ca_equity"
+
+
+class TestTickGrid:
+ @pytest.mark.parametrize(
+ "price,tick",
+ [(5_000, 10.0), (9_990, 10.0), (10_000, 50.0), (49_950, 50.0),
+ (50_000, 100.0), (122_300, 100.0)],
+ )
+ def test_tick_size_bands(self, price: float, tick: float) -> None:
+ assert hose_tick_size(price) == tick
+
+ def test_round_down_and_up(self) -> None:
+ assert hose_round_down(24_267) == 24_250
+ assert hose_round_up(24_267) == 24_300
+
+ def test_on_grid_price_is_unchanged(self) -> None:
+ assert hose_round_down(24_250) == 24_250
+ assert hose_round_up(24_250) == 24_250
+
+
+class TestPriceBand:
+ def test_published_worked_example(self) -> None:
+ # HOSE convention: the ceiling truncates down and the floor rounds up,
+ # so both bounds stay inside the +/-7% band.
+ assert hose_round_down(122_301) == 122_300
+ assert hose_round_up(106_299) == 106_300
+
+ def test_band_bounds_are_on_grid(self) -> None:
+ upper, lower = hose_price_limits(24_250, 0.07)
+ assert upper == 25_900
+ assert lower == 22_600
+ assert upper % hose_tick_size(upper) == 0
+ assert lower % hose_tick_size(lower) == 0
+
+
+class TestLotSize:
+ def test_orders_floor_to_whole_lots(self) -> None:
+ engine = _engine()
+ assert engine.round_size(1_234, 24_250) == 1_200
+ assert engine.round_size(HOSE_LOT_SIZE, 24_250) == HOSE_LOT_SIZE
+
+ def test_sub_lot_order_is_not_executable(self) -> None:
+ # HOSE accepts odd lots on a separate board; not modelled here.
+ assert _engine().round_size(99, 24_250) == 0
+
+ def test_negative_size_floors_to_zero(self) -> None:
+ assert _engine().round_size(-500, 24_250) == 0
+
+
+class TestShortSelling:
+ def test_allow_short_is_refused(self) -> None:
+ with pytest.raises(ValueError, match="long-only"):
+ _engine(allow_short=True)
+
+ def test_short_direction_blocked(self) -> None:
+ engine = _engine()
+ bar = pd.Series({"open": 24_250.0, "close": 24_300.0})
+ assert engine.can_execute("VIC.VN", -1, bar) is False
+
+
+class TestSettlement:
+ """T+2 cycle: a buy at bar N is sellable from bar N+2."""
+
+ def _open_position(self, engine: VietnamEquityEngine, entry_idx: int) -> None:
+ engine.positions["VIC.VN"] = Position(
+ symbol="VIC.VN",
+ direction=1,
+ entry_price=24_250.0,
+ entry_time=pd.Timestamp("2026-01-05"),
+ size=1_000.0,
+ leverage=1.0,
+ entry_bar_idx=entry_idx,
+ )
+
+ @pytest.mark.parametrize("elapsed,allowed", [(0, False), (1, False), (2, True), (5, True)])
+ def test_sell_is_held_until_settlement(self, elapsed: int, allowed: bool) -> None:
+ engine = _engine(price_limit=0)
+ self._open_position(engine, entry_idx=10)
+ engine._bar_idx = 10 + elapsed
+ bar = pd.Series({"open": 24_250.0, "close": 24_300.0})
+ assert engine.can_execute("VIC.VN", 0, bar) is allowed
+
+ def test_settlement_lag_is_configurable(self) -> None:
+ # Scenario testing / future rule changes: the hold follows config.
+ engine = _engine(price_limit=0, vn_settlement_bars=1)
+ self._open_position(engine, entry_idx=10)
+ engine._bar_idx = 11
+ bar = pd.Series({"open": 24_250.0, "close": 24_300.0})
+ assert engine.can_execute("VIC.VN", 0, bar) is True
+
+ def test_buy_is_never_held(self) -> None:
+ engine = _engine(price_limit=0)
+ self._open_position(engine, entry_idx=10)
+ engine._bar_idx = 10
+ bar = pd.Series({"open": 24_250.0, "close": 24_300.0})
+ assert engine.can_execute("VIC.VN", 1, bar) is True
+
+
+class TestBandBlocking:
+ def test_buy_blocked_at_ceiling(self) -> None:
+ engine = _engine()
+ # 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_allowed_inside_band(self) -> None:
+ engine = _engine()
+ bar = pd.Series({"open": 24_500.0, "pre_close": 24_250.0})
+ assert engine.can_execute("VIC.VN", 1, bar) is True
+
+ def test_band_check_inactive_without_reference(self) -> None:
+ engine = _engine()
+ bar = pd.Series({"open": 24_500.0})
+ assert engine.can_execute("VIC.VN", 1, bar) is True
+
+
+class TestCostStack:
+ def test_buy_pays_brokerage_only(self) -> None:
+ engine = _engine()
+ cost = engine.calc_commission(1_000, 24_250.0, direction=1, is_open=True)
+ assert cost == pytest.approx(1_000 * 24_250.0 * 0.0015)
+
+ def test_sell_adds_transfer_tax(self) -> None:
+ engine = _engine()
+ notional = 1_000 * 24_250.0
+ cost = engine.calc_commission(1_000, 24_250.0, direction=1, is_open=False)
+ # 0.1% of gross proceeds on top of brokerage, levied on gain or loss.
+ assert cost == pytest.approx(notional * (0.0015 + 0.001))
+
+
+class TestSlippage:
+ def test_buy_slips_up_onto_the_grid(self) -> None:
+ engine = _engine(slippage=0.001)
+ filled = engine.apply_slippage(24_250.0, 1)
+ assert filled == hose_round_up(24_250.0 * 1.001)
+ assert filled % hose_tick_size(filled) == 0
+
+ def test_sell_slips_down_onto_the_grid(self) -> None:
+ engine = _engine(slippage=0.001)
+ filled = engine.apply_slippage(24_250.0, -1)
+ assert filled == hose_round_down(24_250.0 * 0.999)
+ assert filled % hose_tick_size(filled) == 0