"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(paper-trade): match symbols on a shared timeline
Haozhe Wub840d299a98a
diff --git a/agent/src/tools/paper_trade/README.md b/agent/src/tools/paper_trade/README.mdindex 25d27846a..7b48452f1 100644--- a/agent/src/tools/paper_trade/README.md+++ b/agent/src/tools/paper_trade/README.md@@ -137,6 +137,13 @@ still in `open_orders()`) exists in the lifecycle but is not reached whileevery fill is all-or-none. These statuses are internal; no result field orsurface exposes them.+The matcher walks a shared chronological timeline across the supplied symbol+frames, so later proceeds cannot fund an earlier order. At a shared timestamp,+orders are evaluated in caller submission order, including the cash check;+there is no implicit sell-first priority. Each symbol tracks its own first+positive-volume bar for the better-price rule. This engine behavior does not+relax the public tool's single-symbol provider limit below.+The 5m leg uses Tushare `stk_mins` and is resolved separately from the dailychain: Tencent's raw loader serves daily bars only. The measured provider limitis one symbol per step (1 call/minute, 1 call/hour and 2 calls/day; a refused@@ -192,8 +199,10 @@ cannot fill. Corporate actions remain fail-closed.- **5m strategy UNIVERSE is strict.** An order on a position outside thedeclared `UNIVERSE` fails the whole call, so such a position cannot be reducedby a 5m strategy step; use the 1d step for that.-- **Matching changes are versioned.** `pt-rules-v3` identifies the immediate- price-limit market cancellation; `pt-rules-v2` identified the corrected+- **Matching changes are versioned.** `pt-rules-v4` identifies chronological+ matching across symbols and submission order at shared timestamps.+ `pt-rules-v3` identified the immediate price-limit market cancellation;+ `pt-rules-v2` identified the correctedfull/partial order statuses and 5m limit-fill rules. Each rule version has adifferent engine fingerprint even with identical bars and model settings;archived results retain their original version.diff --git a/agent/src/tools/paper_trade/rules.py b/agent/src/tools/paper_trade/rules.pyindex 26c3f60cc..8a2faf6f5 100644--- a/agent/src/tools/paper_trade/rules.py+++ b/agent/src/tools/paper_trade/rules.py@@ -60,7 +60,7 @@ __all__ = [#: price-limit / settlement / order-status / matching semantics change, so a stored fingerprint can never#: claim a rule set the engine no longer implements. It is a constant only: no#: fee, lot or matching behaviour in this module depends on it.-RULES_VERSION = "pt-rules-v3"+RULES_VERSION = "pt-rules-v4"#: AM-14 frozen rejection decision order — first match wins (REQUIREMENTS §2#: hard semantics 3a). ``limit_up``/``limit_down`` share one frozen slot anddiff --git a/agent/src/tools/paper_trade/session_5m.py b/agent/src/tools/paper_trade/session_5m.pyindex 0d9798bab..ee7712eb0 100644--- a/agent/src/tools/paper_trade/session_5m.py+++ b/agent/src/tools/paper_trade/session_5m.py@@ -31,8 +31,10 @@ Phase-2/3 semantics:lots, fees and corporate-action gates use the same frozen rules as thedaily path.-Determinism: the bar timeline comes from the served 5m frame, order ids are-positional (``pt-<index>``), and no clock or randomness is read.+Determinism: all served 5m frames share a timestamp-ordered timeline. Orders+at the same timestamp execute in submission order, with a first-live-bar flag+per symbol. Order ids are positional (``pt-<index>``); no clock or randomness+is read."""from __future__ import annotations@@ -120,6 +122,9 @@ def match_orders_5m(session: "_MatchSession", day: "DayPlan", orders: Sequence[Obook.activate(order_id)active.append(order_id)+ # One account has one cash ledger: walk timestamps across all symbols,+ # never an entire symbol's day before another symbol's morning.+ timeline: dict[Any, dict[str, Any]] = {}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)@@ -132,50 +137,60 @@ def match_orders_5m(session: "_MatchSession", day: "DayPlan", orders: Sequence[Oday, order, "suspended",f"no 5m continuous bars for {symbol} on {day.date}")continue- live_bar = 0- for _, bar in bars.sort_index().iterrows():+ for timestamp, bar in bars.iterrows():+ timeline.setdefault(timestamp, {})[symbol] = bar++ seen_live: set[str] = set()+ for timestamp in sorted(timeline):+ matching_bars: dict[str, tuple[Any, Decimal, bool]] = {}+ for symbol, bar in timeline[timestamp].items():if float(bar["volume"]) <= 0:# A zero-volume bar is not a matching opportunity, so it can# neither fill nor consume the first-bar marketable branch.continueref = session._reference_price_from_bar(bar)- first_bar = live_bar == 0- live_bar += 1- for order_id in order_ids:- state = book.get(order_id)- if state is None or state.status not in _ACTIVE_STATUSES:+ matching_bars[symbol] = (bar, ref, symbol not in seen_live)+ seen_live.add(symbol)+ # Same-timestamp orders consume cash in caller submission order,+ # matching the existing ordering within a single symbol.+ for order_id in active:+ state = book.get(order_id)+ if state is None or state.status not in _ACTIVE_STATUSES:+ continue+ order = by_id[order_id]+ if order.symbol not in matching_bars:+ continue+ bar, ref, first_bar = matching_bars[order.symbol]+ if order.limit is None:+ price = ref+ else:+ # Trigger/price split: the bar range decides whether a+ # resting limit fills, and it fills at the 委托价; only the+ # first continuous bar can fill at a strictly better+ # reference. A limit that never triggers rests untouched.+ price = _limit_fill_price(order, ref, bar, first_bar=first_bar)+ if price is None:continue- order = by_id[order_id]- if order.limit is None:- price = ref- else:- # Trigger/price split: the bar range decides whether a- # resting limit fills, and it fills at the 委托价; only the- # first continuous bar can fill at a strictly better- # reference. A limit that never triggers rests untouched.- price = _limit_fill_price(order, ref, bar, first_bar=first_bar)- if price is None:- continue- gate = session._fill_gate(day, order, price)- if gate is not None:- code, detail = gate- if code in {"limit_up", "limit_down"}:- if order.limit is None:- # No later bar may revive a canceled market order.- # Pending-cancel is excluded from matching and is- # settled to canceled exactly once at day end.- book.request_cancel(order_id)- price_limit_cancels[order_id] = gate- session.events.append(SessionEvent(- trade_date=day.date, symbol=order.symbol,- event_type="price_limit", detail=detail))- # A blocked limit order remains open until another- # bar can match it, or it expires at session end.- continue- book.reject(order_id, code)- session._reject(day, order, code, detail)+ gate = session._fill_gate(day, order, price)+ if gate is not None:+ code, detail = gate+ if code in {"limit_up", "limit_down"}:+ if order.limit is None:+ # No later bar may revive a canceled market order.+ # Pending-cancel is excluded from matching and is+ # settled to canceled exactly once at day end.+ book.request_cancel(order_id)+ price_limit_cancels[order_id] = gate+ session.events.append(SessionEvent(+ trade_date=day.date, symbol=order.symbol,+ event_type="price_limit", detail=detail))+ # A blocked limit order remains open until another+ # bar can match it, or it expires at session end.continue- book.fill(order_id, money(order.qty), price)- session._fill(day.date, order, float(price))+ book.reject(order_id, code)+ session._reject(day, order, code, detail)+ continue+ book.fill(order_id, money(order.qty), price)+ session._fill(day.date, order, float(price))_cancel_unfilled(session, day, book, by_id, price_limit_cancels)diff --git a/agent/tests/test_paper_trade_5m_engine.py b/agent/tests/test_paper_trade_5m_engine.pyindex 7e320d8a8..1757c9cef 100644--- a/agent/tests/test_paper_trade_5m_engine.py+++ b/agent/tests/test_paper_trade_5m_engine.py@@ -211,6 +211,69 @@ def _sell(limit=None, qty=100, symbol=_SYM):return order[email protected](("seller", "buyer"), [(_OTHER, _SYM), (_SYM, _OTHER)])[email protected]("sale_before_purchase", [False, True])+def test_multiple_symbols_share_a_chronological_cash_ledger(seller, buyer, sale_before_purchase):+ labels = _session_labels()+ sale_label = labels[0] if sale_before_purchase else labels[-1]+ purchase_label = labels[-1] if sale_before_purchase else labels[0]+ prices = {label: 10.0 for label in labels}+ prices[sale_label] = 10.6+ sell_bars = _intraday(_DAY, prices)+ buy_bars = _flat_5m(_DAY, 10.0)+ buy_bars.loc[buy_bars.index < pd.Timestamp(f"{_DAY} {purchase_label}"), "volume"] = 0+ daily = {symbol: _daily([(_PREV, 10.0), (_DAY, 10.0)]) for symbol in (seller, buyer)}+ kwargs = dict(+ # A first-live-bar buy limit must still get the better price even+ # when another symbol has already traded earlier in this session.+ orders=[_sell(limit=10.5, symbol=seller), _buy(limit=10.5, symbol=buyer)],+ cash=0.0, positions=[{"symbol": seller, "qty": 100, "avg_cost": 10.0}],+ daily=daily, five={seller: sell_bars, buyer: buy_bars}, symbols=(seller, buyer),+ )+ result = _outcome(**kwargs)+ assert result.error is None+ if sale_before_purchase:+ assert [(f.symbol, f.side, f.price) for f in result.fills] == [+ (seller, "sell", 10.6), (buyer, "buy", 10.0),+ ]+ assert result.rejected_orders == ()+ assert result.end_state.cash == 49.45+ else:+ assert [(f.symbol, f.side, f.price) for f in result.fills] == [(seller, "sell", 10.5)]+ assert [(r.symbol, r.reason_code) for r in result.rejected_orders] == [(buyer, "insufficient_cash")]+ assert result.end_state.cash == 1044.46++ # Loader dictionary order and row order must not determine execution time.+ kwargs["five"] = {buyer: buy_bars.iloc[::-1], seller: sell_bars.iloc[::-1]}+ kwargs["symbols"] = (buyer, seller)+ replay = _outcome(**kwargs)+ assert replay.fills == result.fills+ assert replay.rejected_orders == result.rejected_orders+ assert replay.end_state == result.end_state+ assert replay.engine_fingerprint == result.engine_fingerprint++[email protected](("seller", "buyer"), [(_OTHER, _SYM), (_SYM, _OTHER)])[email protected]("buy_first", [False, True])+def test_same_timestamp_uses_submission_order_across_symbols(seller, buyer, buy_first):+ daily = {symbol: _daily([(_PREV, 10.0), (_DAY, 10.0)]) for symbol in (seller, buyer)}+ orders = [_sell(symbol=seller), _buy(symbol=buyer)]+ if buy_first:+ orders.reverse()+ result = _outcome(+ orders=orders, cash=20.0, positions=[{"symbol": seller, "qty": 100, "avg_cost": 10.0}],+ daily=daily, five={seller: _flat_5m(_DAY, 10.0), buyer: _flat_5m(_DAY, 10.0)},+ symbols=(seller, buyer),+ )+ assert result.error is None+ expected = [(seller, "sell")] if buy_first else [(seller, "sell"), (buyer, "buy")]+ assert [(f.symbol, f.side) for f in result.fills] == expected+ assert [(r.symbol, r.reason_code) for r in result.rejected_orders] == (+ [(buyer, "insufficient_cash")] if buy_first else []+ )+ assert result.end_state.cash == (1014.49 if buy_first else 9.48)++def test_market_buy_fills_at_the_first_continuous_bar() -> None:outcome = _outcome(orders=[_buy()])diff --git a/agent/tests/test_paper_trade_v12_schema.py b/agent/tests/test_paper_trade_v12_schema.pyindex c04f22c06..9b8d6e85a 100644--- a/agent/tests/test_paper_trade_v12_schema.py+++ b/agent/tests/test_paper_trade_v12_schema.py@@ -262,10 +262,10 @@ def test_engine_fingerprint_matches_the_frozen_formula() -> None:"bar_fingerprint": _HEX_A,})- assert rules.RULES_VERSION == "pt-rules-v3"+ assert rules.RULES_VERSION == "pt-rules-v4"assert actual != state_hash.engine_fingerprint(interval="5m", path_model="bar_close", fill_model="all_or_none",- bar_fingerprint=_HEX_A, rules_version="pt-rules-v1",+ bar_fingerprint=_HEX_A, rules_version="pt-rules-v3",)assert actual == manualassert re.fullmatch(r"[0-9a-f]{64}", actual)