"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(tools): dragon-tiger seats rank within each listing reason (#1512)
Haozhe Wu0177a294f6e5
diff --git a/README.md b/README.mdindex e896a8c46..06e0784d1 100644--- a/README.md+++ b/README.md@@ -516,7 +516,7 @@ For a backtest, set `source` in `config.json`:In an Agent conversation, ask explicitly: **"Use Longbridge to fetch QQQ.US historical data."** The explicit source request is separate from `source: "auto"`; `auto` keeps the normal per-market fallback chain.-Beyond OHLCV, **22 read-only data tools** reach into fundamentals & flow — fund flow, dragon-tiger, northbound, margin, block trades, shareholder count, lockup, sector, research reports, news, SEC filings, financial statements, options chains, stock profile, market screening, symbol search, macro, iwencai, institutional holdings (13F), ETF look-through, prediction markets, and research papers — all exposed over MCP. `get_dragon_tiger` returns separate ranked buy- and sell-side seat reports for a specified security and surfaces provider rejections instead of treating them as empty data. An explicit `local:` symbol never silently falls back to a network source.+Beyond OHLCV, **22 read-only data tools** reach into fundamentals & flow — fund flow, dragon-tiger, northbound, margin, block trades, shareholder count, lockup, sector, research reports, news, SEC filings, financial statements, options chains, stock profile, market screening, symbol search, macro, iwencai, institutional holdings (13F), ETF look-through, prediction markets, and research papers — all exposed over MCP. An explicit `local:` symbol never silently falls back to a network source.<!-- QVERIS-START -->### 💎 Optional premium data — QVerisdiff --git a/agent/src/tools/dragon_tiger_tool.py b/agent/src/tools/dragon_tiger_tool.pyindex 51194d864..42db2cc90 100644--- a/agent/src/tools/dragon_tiger_tool.py+++ b/agent/src/tools/dragon_tiger_tool.py@@ -137,13 +137,44 @@ def _appearance_row(raw: dict[str, Any]) -> dict[str, Any]:}+def _seats_by_reason(+ buy_rows: list[dict[str, Any]], sell_rows: list[dict[str, Any]]+) -> list[list[dict[str, Any]]]:+ """Group seat rows by listing reason, each group ranked per side.++ A security listed for several reasons on one day (one ``TRADE_ID`` each)+ has a top-5 buy and sell list per reason, and each report returns all of+ them in one list sorted by amount — a rank over that list mixes reasons.++ Args:+ buy_rows: Buy-side report rows, largest ``BUY`` first.+ sell_rows: Sell-side report rows, largest ``SELL`` first.++ Returns:+ One list per reason, in the order the reasons first appear: its buy+ seats ranked 1..n, then its sell seats ranked 1..n.+ """+ reasons: dict[Any, dict[str, list[dict[str, Any]]]] = {}+ for side, rows in (("BUY", buy_rows), ("SELL", sell_rows)):+ for row in rows:+ reasons.setdefault(row.get("TRADE_ID"), {"BUY": [], "SELL": []})[side].append(row)+ return [+ [+ _seat_row(row, side=side, rank=rank)+ for side in ("BUY", "SELL")+ for rank, row in enumerate(sides[side], start=1)+ ]+ for sides in reasons.values()+ ]++def _seat_row(raw: dict[str, Any], *, side: str, rank: int) -> dict[str, Any]:"""Project a raw seat row to a compact, named record.Args:raw: One live Eastmoney buy- or sell-side seat row.side: The side represented by the report that returned ``raw``.- rank: One-based position in the report's descending order.+ rank: One-based position within its side and listing reason (TRADE_ID).Returns:A flat dict describing one brokerage seat's buy/sell footprint.@@ -293,15 +324,19 @@ class DragonTigerTool(BaseTool):sort_columns="SELL",sort_types="-1",)- seats = [- _seat_row(row, side="BUY", rank=rank)- for rank, row in enumerate(buy_rows, start=1)- ]- seats.extend(- _seat_row(row, side="SELL", rank=rank)- for rank, row in enumerate(sell_rows, start=1)- )+ # Capped by whole reason, so a long day never keeps a reason's buy+ # side and drops its sell side.+ groups = _seats_by_reason(buy_rows, sell_rows)+ seats: list[dict[str, Any]] = []+ kept = 0+ for group in groups:+ if seats and len(seats) + len(group) > _MAX_SEATS:+ break+ seats.extend(group)+ kept += 1data["seats"] = seats[:_MAX_SEATS]+ if kept < len(groups):+ data["seat_reasons_omitted"] = len(groups) - keptreturn data@staticmethoddiff --git a/agent/tests/test_dragon_tiger_tool.py b/agent/tests/test_dragon_tiger_tool.pyindex aee00ed0a..41bee1265 100644--- a/agent/tests/test_dragon_tiger_tool.py+++ b/agent/tests/test_dragon_tiger_tool.py@@ -152,6 +152,65 @@ class TestExecuteSuccess:assert requests[2]["sortColumns"] == "SELL"+def _seat(name: str, amount: float, trade_id: str, side: str) -> dict[str, Any]:+ return {+ "OPERATEDEPT_NAME": name,+ "BUY": amount if side == "BUY" else 0.0,+ "SELL": amount if side == "SELL" else 0.0,+ "NET": amount if side == "BUY" else -amount,+ "EXPLANATION": f"reason {trade_id}",+ "TRADE_ID": trade_id,+ }+++def _seats_payload(rows: list[dict[str, Any]]) -> dict[str, Any]:+ return {"success": True, "result": {"data": rows}}+++class TestSeatsByReason:+ """600721 on 2026-09-21 was listed under three TRADE_IDs; each report+ returns every reason's top 5 in one list sorted by amount."""++ def _run(self, buy: list[dict[str, Any]], sell: list[dict[str, Any]]) -> dict[str, Any]:+ payloads = [_appearance_payload(), _seats_payload(buy), _seats_payload(sell)]+ with patch.object(eastmoney_client, "throttled_get_json", side_effect=payloads):+ return json.loads(DragonTigerTool().execute(date="2026-09-21", code="600721"))["data"]++ def test_rank_restarts_within_each_reason(self) -> None:+ buy = [_seat("A", 9.0, "t1", "BUY"), _seat("B", 8.0, "t2", "BUY"), _seat("C", 7.0, "t1", "BUY")]+ sell = [_seat("D", 6.0, "t2", "SELL"), _seat("E", 5.0, "t1", "SELL")]++ seats = self._run(buy, sell)["seats"]++ ranks = [(s["trade_id"], s["side"], s["seat"], s["rank"]) for s in seats]+ assert ranks == [+ ("t1", "BUY", "A", 1),+ ("t1", "BUY", "C", 2),+ ("t1", "SELL", "E", 1),+ ("t2", "BUY", "B", 1),+ ("t2", "SELL", "D", 1),+ ]++ def test_cap_drops_whole_reasons_not_the_sell_side(self) -> None:+ buy, sell = [], []+ for tid in ("t1", "t2", "t3", "t4"):+ buy += [_seat(f"{tid}-b{i}", 100.0 - i, tid, "BUY") for i in range(5)]+ sell += [_seat(f"{tid}-s{i}", 100.0 - i, tid, "SELL") for i in range(5)]++ data = self._run(buy, sell)++ assert len(data["seats"]) == 30+ assert {s["trade_id"] for s in data["seats"]} == {"t1", "t2", "t3"}+ for tid in ("t1", "t2", "t3"):+ sides = [s["side"] for s in data["seats"] if s["trade_id"] == tid]+ assert sides.count("BUY") == 5 and sides.count("SELL") == 5+ assert data["seat_reasons_omitted"] == 1++ def test_no_omission_marker_when_everything_fits(self) -> None:+ data = self._run([_seat("A", 1.0, "t1", "BUY")], [_seat("B", 1.0, "t1", "SELL")])+ assert "seat_reasons_omitted" not in data++class TestExecuteError:def test_missing_date_returns_error_envelope(self) -> None:out = json.loads(DragonTigerTool().execute())