"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(identity): resolve Binance crypto pairs
PP14d04441db077
diff --git a/agent/src/tools/symbol_search_tool.py b/agent/src/tools/symbol_search_tool.pyindex 34d1ec019..ad76fd376 100644--- a/agent/src/tools/symbol_search_tool.py+++ b/agent/src/tools/symbol_search_tool.py@@ -1,7 +1,11 @@"""Read-only symbol-search tool: resolve a name/ticker to symbols + market.-Backed by three frozen, IP-throttled public-API clients so the agent never-hits a provider un-throttled and never re-implements transport plumbing:+Backed by the selected Binance connector for exact crypto pairs plus three+frozen, IP-throttled public-API clients so the agent never hits a provider+un-throttled and never re-implements transport plumbing:++* The active Binance profile resolves exact spot-pair spellings against its+ exchange market catalog. It does not guess asset names from prose.* :mod:`backtest.loaders.eastmoney_client` — Eastmoney's free suggest endpointmatches Chinese/English names and tickers across A-shares (.SH/.SZ/.BJ),@@ -52,6 +56,25 @@ _EASTMONEY_SUGGEST_URL = "https://searchapi.eastmoney.com/api/suggest/get"# are deliberately left to the normal fan-out._CANADIAN_SYMBOL_RE = re.compile(r"^[A-Z0-9&.\-]+\.(?:TO|V)\b", re.IGNORECASE)+# Explicit exchange-pair spellings are not equity/name searches. Restrict the+# quote leg to assets used by the built-in crypto connectors so an equity such+# as ``BRK-B`` is never misclassified as a pair.+_CRYPTO_QUOTE_ASSETS = (+ "FDUSD",+ "USDT",+ "USDC",+ "BUSD",+ "TUSD",+ "BTC",+ "ETH",+ "BNB",+ "USD",+)+_CRYPTO_PAIR_RE = re.compile(+ rf"^([A-Z0-9]{{2,15}})[-/]({'|'.join(_CRYPTO_QUOTE_ASSETS)})$",+ re.IGNORECASE,+)+# Eastmoney market-number -> our symbol suffix. Anything else is left unmapped# (those candidates are skipped rather than emitted with a wrong suffix)._EASTMONEY_SUFFIX_BY_MARKET: Dict[str, str] = {@@ -101,7 +124,8 @@ class SymbolSearchTool(BaseTool):"with their market, in the project's symbol convention (A-shares ""600519.SH, Hong Kong 00700.HK, U.S. AAPL.US, Canada TD.TO/PNG.V, plus ""crypto/index/FX from "- "Yahoo). Searches Eastmoney (China/HK/US names and tickers) and Yahoo "+ "Yahoo). Exact crypto pairs are checked against the active Binance "+ "profile; other queries search Eastmoney (China/HK/US names and tickers) and Yahoo ""(global) and, for U.S. equities, attaches the SEC CIK. Use this to turn ""an ambiguous name into a concrete symbol before calling get_market_data "'or get_sec_filings. Example: search_symbol(query="apple", limit=5).'@@ -154,12 +178,31 @@ class SymbolSearchTool(BaseTool):candidates: List[Dict[str, Any]] = []sources: Dict[str, str] = {}+ crypto_pair = _canonical_crypto_pair(query)+ connector_hits, connector_source, connector_status = (+ _search_selected_connector(query, limit)+ )+ if connector_source is not None and connector_status is not None:+ sources[connector_source] = connector_status+ candidates.extend(connector_hits)+em_hits, sources["eastmoney"] = _search_eastmoney(query)candidates.extend(em_hits)yh_hits, sources["yahoo"] = _search_yahoo(query)candidates.extend(yh_hits)+ if crypto_pair is not None:+ # A pair query is an exact instrument assertion. Near-string Yahoo+ # hits such as AETHUSDT-USD are different assets and must not enter+ # the identity ledger as rival candidates (#1234).+ candidates = [+ candidate+ for candidate in candidates+ if _canonical_crypto_pair(str(candidate.get("symbol") or ""))+ == crypto_pair+ ]+# Canada fail-fast: a Canadian ticker must resolve to the Canadian venue# only. Yahoo also returns the US OTC alias of the same company (e.g.# ``BYN.V`` -> ``BYAGF.US``), which would make the grounding ledger see@@ -219,6 +262,85 @@ def _is_canadian_symbol(text: str) -> bool:return bool(_CANADIAN_SYMBOL_RE.match((text or "").strip()))+def _canonical_crypto_pair(value: str) -> str | None:+ """Return an explicit crypto pair in canonical ``BASE-QUOTE`` form."""+ clean = str(value or "").strip().upper()+ matched = _CRYPTO_PAIR_RE.fullmatch(clean)+ if matched:+ return f"{matched.group(1)}-{matched.group(2)}"+ if clean.isalnum():+ for quote in _CRYPTO_QUOTE_ASSETS:+ if clean.endswith(quote) and len(clean) > len(quote) + 1:+ return f"{clean[: -len(quote)]}-{quote}"+ return None+++def _search_selected_connector(+ query: str,+ limit: int,+) -> tuple[List[Dict[str, Any]], str | None, str | None]:+ """Resolve an explicit pair against the active crypto connector, if supported."""+ if _canonical_crypto_pair(query) is None:+ return [], None, None++ # Lazy imports keep the generic symbol tool usable when optional connector+ # dependencies are absent and avoid loading broker configuration at import.+ from src.trading import profiles as trading_profiles+ from src.trading import service as trading_service++ try:+ profile_id = trading_profiles.load_selected_profile_id()+ profile = trading_profiles.profile_by_id(profile_id)+ except (OSError, ValueError) as exc:+ logger.debug("selected connector lookup failed for %r: %s", query, exc)+ return [], None, None++ if profile.connector != "binance":+ return [], None, None++ source = profile.connector+ try:+ payload = trading_service.search_instruments(+ query,+ profile.id,+ limit=limit,+ )+ except Exception as exc: # noqa: BLE001 - one search source is non-fatal+ logger.debug("%s instrument search failed for %r: %s", source, query, exc)+ return [], source, f"connector search failed: {exc}"++ if not isinstance(payload, dict) or str(payload.get("status")).casefold() != "ok":+ message = (+ str(payload.get("error") or payload.get("message") or "unknown error")+ if isinstance(payload, dict)+ else "invalid response"+ )+ return [], source, f"connector search failed: {message}"++ rows = payload.get("instruments")+ rows = rows if isinstance(rows, list) else []+ candidates: List[Dict[str, Any]] = []+ for row in rows:+ if not isinstance(row, dict):+ continue+ symbol = _canonical_crypto_pair(str(row.get("symbol") or ""))+ if symbol is None:+ continue+ candidates.append(+ {+ "symbol": symbol,+ "name": str(row.get("name") or row.get("native_symbol") or "").strip()+ or None,+ "market": "crypto",+ "type": str(row.get("type") or "cryptocurrency"),+ "exchange": str(row.get("exchange") or source).upper(),+ "source": source,+ "profile_id": profile.id,+ }+ )+ return candidates, source, "ok"++def _is_ticker_name_query(query: str) -> bool:"""Whether *query* is a bare all-caps ticker followed by a name hint.@@ -257,6 +379,8 @@ def _search_eastmoney(query: str) -> tuple[List[Dict[str, Any]], str]:``(candidates, status)`` where ``status`` is ``"ok"`` on success or ashort error string when the source failed (candidates is then empty)."""+ if _canonical_crypto_pair(query) is not None:+ return [], f"{_SKIPPED}eastmoney has no crypto exchange-pair coverage"if _is_canadian_symbol(query):logger.info("eastmoney skipped for Canadian symbol %r (no Canada coverage)",diff --git a/agent/src/trading/connectors/binance/classification.py b/agent/src/trading/connectors/binance/classification.pyindex a73310c02..c48879b7a 100644--- a/agent/src/trading/connectors/binance/classification.py+++ b/agent/src/trading/connectors/binance/classification.py@@ -18,6 +18,7 @@ BINANCE_TOOL_CLASS: dict[str, ToolClass] = {"fetch_my_trades": ToolClass.READ,"fetch_ticker": ToolClass.READ,"fetch_ohlcv": ToolClass.READ,+ "load_markets": ToolClass.READ,"fapiprivatev2_get_account": ToolClass.READ,"fapiprivatev3_get_positionrisk": ToolClass.READ,# WRITEdiff --git a/agent/src/trading/connectors/binance/sdk.py b/agent/src/trading/connectors/binance/sdk.pyindex 1c00f0d85..6c5b1a597 100644--- a/agent/src/trading/connectors/binance/sdk.py+++ b/agent/src/trading/connectors/binance/sdk.py@@ -415,6 +415,65 @@ def get_quote(symbol: str, *, config: BinanceConfig | None = None, **_: Any) ->}+def search_instruments(+ query: str,+ *,+ config: BinanceConfig | None = None,+ limit: int = 10,+) -> dict[str, Any]:+ """Resolve an exact spot pair against the selected Binance market catalog.++ Binance's exchange-info catalog has symbols and assets, but no stable+ human-readable asset names. The connector therefore resolves only explicit+ pair spellings (``ETH-USDT``, ``ETH/USDT`` or ``ETHUSDT``) and never guesses+ from prose such as ``Ethereum``.+ """+ cfg = config or load_config()+ _reject_unsupported_usdm_surface(cfg)+ _assert_host(cfg)++ requested = normalize_symbol(query)+ if "/" not in requested:+ return {"status": "ok", "query": query, "instruments": []}++ try:+ bounded_limit = max(1, min(int(limit), 50))+ except (TypeError, ValueError, OverflowError):+ bounded_limit = 10++ markets = _exchange(cfg).load_markets()+ if not isinstance(markets, Mapping):+ raise BinanceConfigError("Binance load_markets returned a non-mapping payload")++ instruments: list[dict[str, Any]] = []+ for key, raw_market in markets.items():+ if not isinstance(raw_market, Mapping):+ continue+ native_symbol = normalize_symbol(str(raw_market.get("symbol") or key))+ if native_symbol != requested:+ continue+ if raw_market.get("spot") is False or raw_market.get("active") is False:+ continue+ base, quote = native_symbol.split("/", 1)+ instruments.append(+ {+ "symbol": f"{base}-{quote}",+ "native_symbol": native_symbol,+ "exchange_symbol": str(raw_market.get("id") or "").strip() or None,+ "base": base,+ "quote": quote,+ "market": "crypto",+ "type": "cryptocurrency",+ "exchange": "BINANCE",+ "active": raw_market.get("active"),+ }+ )+ if len(instruments) >= bounded_limit:+ break++ return {"status": "ok", "query": query, "instruments": instruments}++#: Project/canonical period token → ccxt unified timeframe (lowercase)._TIMEFRAME_MAP = {"1m": "1m", "5m": "5m", "15m": "15m", "30m": "30m",diff --git a/agent/src/trading/service.py b/agent/src/trading/service.pyindex 6397abb4e..c690b0d31 100644--- a/agent/src/trading/service.py+++ b/agent/src/trading/service.py@@ -228,8 +228,18 @@ def search_instruments(include_rates: bool = False,**overrides: Any,) -> dict[str, Any]:- """Search tradable instruments (eToro Public API)."""+ """Search the selected connector's own tradable-instrument universe."""profile = profile_by_id(profile_id)+ if profile.connector == "binance" and profile.transport == "broker_sdk":+ module = _sdk_module(profile.connector)+ return _with_profile(+ profile,+ module.search_instruments(+ query,+ config=module.build_config(profile.config, overrides),+ limit=limit,+ ),+ )if profile.connector != "etoro":return _unsupported_etoro(profile, "instruments.search")module = _sdk_module(profile.connector)diff --git a/agent/tests/test_agent_grounding.py b/agent/tests/test_agent_grounding.pyindex da36d6e60..aef2ba4b2 100644--- a/agent/tests/test_agent_grounding.py+++ b/agent/tests/test_agent_grounding.py@@ -384,6 +384,68 @@ def test_provider_spellings_of_one_instrument_are_one_identity(assert authorization.allowed is True+def test_binance_pair_resolution_authorizes_crypto_consumers(tmp_path: Path) -> None:+ """Issue #1234: an exact connector pair must survive unrelated Yahoo hits."""+ ledger = GroundingLedger(+ run_dir=tmp_path,+ user_message="Check the ETH-USDT orderbook and current price.",+ )+ before_resolution = ledger.authorized_symbols+ resolver = ledger.authorize_tool_call(+ "search_symbol",+ {"query": "ETH-USDT"},+ batch_authorized_symbols=before_resolution,+ call_id="resolve-crypto",+ )+ assert resolver.allowed is True++ ledger.ingest_tool_result(+ tool_name="search_symbol",+ arguments={"query": "ETH-USDT"},+ result=json.dumps(+ {+ "ok": True,+ "source": "symbol_search",+ "data": {+ "query": "ETH-USDT",+ "count": 2,+ "sources": {"binance": "ok", "yahoo": "ok"},+ "candidates": [+ {+ "symbol": "ETH-USDT",+ "market": "crypto",+ "type": "cryptocurrency",+ "exchange": "BINANCE",+ "source": "binance",+ },+ {+ "symbol": "AETHUSDT-USD",+ "market": "global",+ "type": "cryptocurrency",+ "exchange": "CCC",+ "source": "yahoo",+ },+ ],+ },+ }+ ),+ call_id="resolve-crypto",+ success=True,+ )++ authorization = ledger.authorize_tool_call(+ "orderbook_depth",+ {"symbol": "ETH-USDT", "exchange": "binance"},+ batch_authorized_symbols=ledger.authorized_symbols,+ batch_identity_status=ledger.identity_status,+ call_id="crypto-book",+ )++ assert ledger.identity_status == "locked"+ assert ledger.authorized_symbols == {"ETH-USDT"}+ assert authorization.allowed is True++def test_stale_history_identity_does_not_unlock_new_subject(tmp_path: Path) -> None:"""A previous turn's AAPL identity cannot authorize a SpaceX price request."""ledger = GroundingLedger(diff --git a/agent/tests/test_sdk_connectors.py b/agent/tests/test_sdk_connectors.pyindex 32dc64c09..8fc398695 100644--- a/agent/tests/test_sdk_connectors.py+++ b/agent/tests/test_sdk_connectors.py@@ -516,6 +516,91 @@ def test_binance_classification() -> None:assert BINANCE_TOOL_CLASS["create_order"] is ToolClass.WRITEassert BINANCE_TOOL_CLASS["cancel_order"] is ToolClass.WRITEassert BINANCE_TOOL_CLASS["fetch_balance"] is ToolClass.READ+ assert BINANCE_TOOL_CLASS["load_markets"] is ToolClass.READ+++def test_binance_search_instruments_resolves_exact_active_spot_pair(monkeypatch) -> None:+ class FakeExchange:+ def load_markets(self):+ return {+ "ETH/USDT": {+ "id": "ETHUSDT",+ "symbol": "ETH/USDT",+ "spot": True,+ "active": True,+ },+ "ETH/USDT:USDT": {+ "id": "ETHUSDT",+ "symbol": "ETH/USDT:USDT",+ "spot": False,+ "active": True,+ },+ "BTC/USDT": {+ "id": "BTCUSDT",+ "symbol": "BTC/USDT",+ "spot": True,+ "active": True,+ },+ }++ monkeypatch.setattr(bn, "_exchange", lambda _cfg: FakeExchange())++ result = bn.search_instruments(+ "ETHUSDT",+ config=bn.BinanceConfig(profile="paper"),+ )++ assert result == {+ "status": "ok",+ "query": "ETHUSDT",+ "instruments": [+ {+ "symbol": "ETH-USDT",+ "native_symbol": "ETH/USDT",+ "exchange_symbol": "ETHUSDT",+ "base": "ETH",+ "quote": "USDT",+ "market": "crypto",+ "type": "cryptocurrency",+ "exchange": "BINANCE",+ "active": True,+ }+ ],+ }+++def test_binance_search_instruments_does_not_guess_prose(monkeypatch) -> None:+ def _unexpected_exchange(_cfg):+ raise AssertionError("prose lookup must not load the Binance market catalog")++ monkeypatch.setattr(bn, "_exchange", _unexpected_exchange)++ result = bn.search_instruments(+ "Ethereum",+ config=bn.BinanceConfig(profile="paper"),+ )++ assert result == {"status": "ok", "query": "Ethereum", "instruments": []}+++def test_service_routes_instrument_search_to_selected_binance_profile(monkeypatch) -> None:+ captured = {}++ def _search(query, *, config, limit):+ captured.update(query=query, profile=config.profile, limit=limit)+ return {"status": "ok", "instruments": [{"symbol": "ETH-USDT"}]}++ monkeypatch.setattr(bn, "search_instruments", _search)++ result = service.search_instruments(+ "ETH-USDT",+ "binance-paper-trade",+ limit=3,+ )++ assert captured == {"query": "ETH-USDT", "profile": "paper", "limit": 3}+ assert result["profile_id"] == "binance-paper-trade"+ assert result["connector"] == "binance"def test_binance_service_unconfigured(monkeypatch, tmp_path) -> None:diff --git a/agent/tests/test_symbol_search_tool.py b/agent/tests/test_symbol_search_tool.pyindex b7186b703..7287f61db 100644--- a/agent/tests/test_symbol_search_tool.py+++ b/agent/tests/test_symbol_search_tool.py@@ -10,6 +10,8 @@ from __future__ import annotationsimport jsonfrom unittest.mock import patch+from src.trading import profiles as trading_profiles+from src.trading import service as trading_servicefrom src.tools import symbol_search_tool as ss@@ -321,6 +323,60 @@ class TestSymbolSearchSuccess:payload = json.loads(out)assert payload["data"]["sources"]["eastmoney"] == "ok"+ def test_selected_binance_profile_resolves_exact_pair_without_yahoo_collision(+ self, monkeypatch+ ):+ """Issue #1234: an exchange pair must not resolve to a similarly named asset."""+ connector_calls: list[tuple[str, str, int]] = []++ def _search_connector(query: str, profile_id: str, *, limit: int, **_):+ connector_calls.append((query, profile_id, limit))+ return {+ "status": "ok",+ "connector": "binance",+ "profile_id": profile_id,+ "instruments": [+ {+ "symbol": "ETH-USDT",+ "native_symbol": "ETH/USDT",+ "exchange_symbol": "ETHUSDT",+ "market": "crypto",+ "type": "cryptocurrency",+ "exchange": "BINANCE",+ }+ ],+ }++ monkeypatch.setattr(+ trading_profiles,+ "load_selected_profile_id",+ lambda: "binance-paper-trade",+ )+ monkeypatch.setattr(trading_service, "search_instruments", _search_connector)++ yahoo_collision = [+ {+ "symbol": "AETHUSDT-USD",+ "shortname": "Aave Ethereum USDT USD",+ "exchange": "CCC",+ "quoteType": "CRYPTOCURRENCY",+ }+ ]+ with patch.object(+ ss.eastmoney_client,+ "get_json",+ return_value={"QuotationCodeTable": {"Data": []}},+ ), patch.object(ss.yahoo_client, "search", return_value=yahoo_collision):+ data = json.loads(+ ss.SymbolSearchTool().execute(query="ETH-USDT", limit=5)+ )["data"]++ assert connector_calls == [("ETH-USDT", "binance-paper-trade", 5)]+ assert data["sources"]["binance"] == "ok"+ assert [candidate["symbol"] for candidate in data["candidates"]] == [+ "ETH-USDT"+ ]+class TestSymbolSearchErrors:"""Error envelopes and per-source resilience."""@@ -353,6 +409,39 @@ class TestSymbolSearchErrors:symbols = {c["symbol"] for c in payload["data"]["candidates"]}assert "AAPL.US" in symbols+ def test_binance_pair_lookup_failure_rejects_yahoo_near_match(+ self, monkeypatch+ ):+ """A failed exact-pair lookup must not fall back to a different asset."""+ monkeypatch.setattr(+ trading_profiles,+ "load_selected_profile_id",+ lambda: "binance-paper-trade",+ )++ def _fail_connector(*_args, **_kwargs):+ raise RuntimeError("market catalog unavailable")++ monkeypatch.setattr(trading_service, "search_instruments", _fail_connector)+ yahoo_collision = [+ {+ "symbol": "AETHUSDT-USD",+ "shortname": "Aave Ethereum USDT USD",+ "exchange": "CCC",+ "quoteType": "CRYPTOCURRENCY",+ }+ ]+ with patch.object(ss.yahoo_client, "search", return_value=yahoo_collision):+ data = json.loads(+ ss.SymbolSearchTool().execute(query="ETH-USDT", limit=5)+ )["data"]++ assert data["sources"]["binance"] == (+ "connector search failed: market catalog unavailable"+ )+ assert data["sources"]["eastmoney"].startswith("skipped:")+ assert data["candidates"] == []+def test_sec_lookup_failure_recorded_not_fatal(self):with patch.object(ss.eastmoney_client, "get_json", return_value=_eastmoney_payload()