"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
Merge PR #2111: match per bar without future-close rejection or zero-volume fills
Haozhe Wu4d89388e6ad4
diff --cc agent/src/tools/paper_trade/README.mdindex 7fe24f952,a11b3b6e4..19c58c2c7--- a/agent/src/tools/paper_trade/README.md+++ b/agent/src/tools/paper_trade/README.md@@@ -128,8 -133,8 +133,10 @@@ remain daily-only. The persistent v1.2branch (`paper-trade-v12-persistence`) and is not wired to any CLI, API or MCPsurface in this PR.--The daily close still anchors price-limit bands and NAV; `path_model` selects the--5m fill reference only. Corporate actions remain fail-closed.++Daily data supplies the prior close for price-limit bands and the final NAV.++The current 5m reference is checked against those bands; an order waits while++its side is blocked by a price limit. Zero-volume bars cannot fill. Corporate++actions remain fail-closed.## Known limitsdiff --cc agent/src/tools/paper_trade/data_5m.pyindex ba7eb3b44,89970d6c0..b2c77641c--- a/agent/src/tools/paper_trade/data_5m.py+++ b/agent/src/tools/paper_trade/data_5m.py@@@ -391,7 -392,7 +392,10 @@@ def _split_session_days)price_columns = list(_PRICE_COLUMNS)had_continuous = not continuous.empty-- bad = continuous[price_columns].isna().any(axis=1) | (continuous[price_columns] <= 0).any(axis=1)++ bad = (~continuous[price_columns].apply(lambda col: col.map(math.isfinite))).any(axis=1) | (continuous[price_columns] <= 0).any(axis=1)++ bad |= (continuous["high"] < continuous[price_columns].max(axis=1)) | (continuous["low"] > continuous[price_columns].min(axis=1))++ if not continuous["volume"].map(math.isfinite).all() or (continuous["volume"] < 0).any():++ raise ValueError("5m data has invalid bar volume")if bad.any():warnings.append(f"5m data: {symbol} on {day} dropped {int(bad.sum())} bar(s) failing the " "price sanity gate (R-V3)"diff --cc agent/src/tools/paper_trade/engine.pyindex 61b2541d4,a81f9cfb1..0772d2f94--- a/agent/src/tools/paper_trade/engine.py+++ b/agent/src/tools/paper_trade/engine.py@@@ -305,7 -300,7 +300,7 @@@ class _MatchSession# Slot 6 limit_up / limit_down: cn_a bands, BEFORE the AM-7 check.# Price limits are about the official daily close, so 5m mode keeps# this anchor; an absent daily close skips the band (never fabricated).-- if self.rules.has_price_limits:++ if self.rules.has_price_limits and not self._five_minute:if close is None:self.warnings.append(f"limit band check skipped for {symbol} on {day.date}: no daily close to anchor the band")@@@ -313,16 -308,13 +308,21 @@@up, down = self._band(symbol, day.date, sym_data)code = self.rules.band_rejection(order.side, close, up, down)if code == "limit_up":- self._reject(day, order, code, f"close {close:.2f} at or above up limit {up:.2f}; buy rejected")- return+ return (code, f"close {close:.2f} at or above up limit {up:.2f}; buy rejected")if code == "limit_down":- self._reject(day, order, code, f"close {close:.2f} at or below down limit {down:.2f}; sell rejected")- return- # 5m: every price decision below uses the session reference price- # (D1 path model); 1d keeps the daily close byte-identically.- ref = self._reference_price(day.date, sym_data) if self._five_minute else close- # Slot 7 limit_not_marketable (AM-7: buy fills only ref ≤ limit,- # sell only ref ≥ limit; fill price = ref).+ return (code, f"close {close:.2f} at or below down limit {down:.2f}; sell rejected")+ return None++ def _fill_gate(self, day: DayPlan, order: Order, ref: float | Decimal) -> tuple[str, str] | None:+ # Slots 7-10 of the frozen AM-14 ladder.++ if self._five_minute and self.rules.has_price_limits:++ sym_data = self.market_data.data[order.symbol]++ up, down = self._band(order.symbol, day.date, sym_data)++ code = self.rules.band_rejection(order.side, ref, up, down)++ if code == "limit_up":++ return (code, f"ref {ref:.2f} at or above up limit {up:.2f}; buy deferred")++ if code == "limit_down":++ return (code, f"ref {ref:.2f} at or below down limit {down:.2f}; sell deferred")if self.rules.limit_order_violation(order.side, ref, order.limit):anchor = "ref" if self._five_minute else "close"detail = (diff --cc agent/src/tools/paper_trade/session_5m.pyindex 000000000,b52d47cbe..d13dd515bmode 000000,100644..100644--- a/agent/src/tools/paper_trade/session_5m.py+++ b/agent/src/tools/paper_trade/session_5m.py@@@ -1,0 -1,113 +1,123 @@@+ """Per-bar cn_a 5-minute session wiring for the paper-trading engine (#1938 phase 2).++ The bar-agnostic :class:`~.order_lifecycle.OrderBook` drives one completed 5m+ session: orders are submitted once for the day, every continuous bar is a+ matching opportunity, and unfilled day orders are canceled at the session+ close. Only ``interval="5m"`` reaches this module; the pt-v1.1 daily path is+ untouched.++ Phase-2 semantics:++ - a market order fills in full at the first continuous bar whose fill gates+ pass; a limit order rests across bars and fills in full at the first bar+ whose reference price satisfies the limit;+ - an order that never fills is canceled by ``settle_day`` at session end (15:00+ on a complete session);+ - no partial fills and no volume-share model (Phase 3);-- the daily close still anchors price-limit bands and NAV, and T+1, board++- daily data supplies the prior-close bands and final NAV; the current bar++ reference controls price-limit eligibility, and T+1, board+ lots, fees and corporate-action gates use the same frozen rules as the+ daily path.++ Determinism: the bar timeline comes from the served 5m frame, order ids are+ positional (``pt-<index>``), and no clock or randomness is read.+ """++ from __future__ import annotations++ from typing import TYPE_CHECKING, Sequence++ from .order_lifecycle import STATUS_OPEN, OrderBook, OrderRequest, assign_ids+ from .rules import money+ from .schema import CANCELED_REASON_CODE, CanceledOrder, Order++ if TYPE_CHECKING:+ from .engine import DayPlan, _MatchSession++ __all__ = ["match_orders_5m"]+++ def _request(order: Order) -> OrderRequest:+ limit = money(order.limit) if order.limit is not None else None+ return OrderRequest(+ symbol=order.symbol,+ side=order.side,+ qty=money(order.qty),+ order_type="limit" if limit is not None else "market",+ limit_price=limit,+ )+++ def _cancel_unfilled(+ session: "_MatchSession", day: "DayPlan", book: OrderBook, by_id: dict[str, Order]+ ) -> None:+ for state in book.settle_day():+ order = by_id[state.order_id]+ session.canceled.append(CanceledOrder(+ trade_date=day.date,+ symbol=order.symbol,+ side=order.side,+ qty=order.qty,+ reason_code=CANCELED_REASON_CODE,+ detail="unfilled day order canceled at session end",+ ))+++ def match_orders_5m(session: "_MatchSession", day: "DayPlan", orders: Sequence[Order]) -> None:+ if not orders:+ return+ requests = [_request(order) for order in orders]+ states = assign_ids(requests)+ by_id = dict(zip(states, orders, strict=True))+ book = OrderBook(states)+++ deferred: dict[str, tuple[str, str]] = {}+ active: list[str] = []+ for order_id, order in by_id.items():+ gate = session._day_gate(day, order)+ if gate is not None:+ book.reject(order_id, gate[0])+ session._reject(day, order, *gate)+ continue+ book.activate(order_id)+ active.append(order_id)++ for symbol in sorted({by_id[order_id].symbol for order_id in active}):+ sym_data = session.market_data.data[symbol]+ bars = sym_data.bars_5m.get(day.date)+ order_ids = [order_id for order_id in active if by_id[order_id].symbol == symbol]+ if bars is None or bars.empty:+ for order_id in order_ids:+ order = by_id[order_id]+ book.reject(order_id, "suspended")+ session._reject(+ day, order, "suspended",+ f"no 5m continuous bars for {symbol} on {day.date}")+ continue+ for _, bar in bars.sort_index().iterrows():++ if float(bar["volume"]) <= 0:++ continue+ ref = session._reference_price_from_bar(bar)+ for order_id in order_ids:+ state = book.get(order_id)+ if state is None or state.status != STATUS_OPEN:+ continue+ order = by_id[order_id]+ gate = session._fill_gate(day, order, ref)+ if gate is not None:+ code, detail = gate- if code == "limit_not_marketable":++ if code in {"limit_not_marketable", "limit_up", "limit_down"}:++ deferred[order_id] = gate+ continue+ book.reject(order_id, code)+ session._reject(day, order, code, detail)+ continue+ book.fill(order_id, money(order.qty), ref)+ session._fill(day.date, order, float(ref))+++ for order_id, gate in deferred.items():++ state = book.get(order_id)++ if state is not None and state.status == STATUS_OPEN and gate[0] != "limit_not_marketable":++ book.reject(order_id, gate[0])++ session._reject(day, by_id[order_id], *gate)+ _cancel_unfilled(session, day, book, by_id)diff --cc agent/tests/test_paper_trade_5m_engine.pyindex 94053a2dd,d6616d17c..bdcf84e07--- a/agent/tests/test_paper_trade_5m_engine.py+++ b/agent/tests/test_paper_trade_5m_engine.py@@@ -420,3 -432,3 +432,27 @@@ def test_5m_request_refuses_a_daily_fraassert outcome.error.code == "INVALID_REQUEST"assert "interval" in outcome.error.messageassert outcome.fills == () and outcome.canceled_orders == ()++++++def test_late_limit_up_does_not_reject_an_earlier_fill():++ outcome = _outcome(orders=[_buy()],++ daily={_SYM: _daily([(_PREV, 10.0), (_DAY, 11.0)])},++ five={_SYM: _normal_5m(close=11.0)})++ assert len(outcome.fills) == 1++ assert outcome.fills[0].price == 10.0++++++def test_order_waits_for_limit_to_reopen():++ bars = _flat_5m(_DAY, 10.0)++ bars.loc[pd.Timestamp(f"{_DAY} 09:35"), ["open", "high", "low", "close"]] = 11.0++ outcome = _outcome(orders=[_buy()], five={_SYM: bars})++ assert len(outcome.fills) == 1++ assert outcome.fills[0].price == 10.0++++++def test_zero_volume_bar_cannot_fill():++ bars = _flat_5m(_DAY, 10.2)++ stamp = pd.Timestamp(f"{_DAY} 09:35")++ bars.loc[stamp, ["open", "high", "low", "close", "volume"]] = [10, 10, 10, 10, 0]++ outcome = _outcome(orders=[_buy()], five={_SYM: bars})++ assert outcome.fills[0].price == 10.2