"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(identity): resolve crypto pairs from the public venue catalogs, no broker needed
Haozhe Wu0ed3770f35c6
diff --git a/agent/src/tools/symbol_search_tool.py b/agent/src/tools/symbol_search_tool.pyindex ad76fd376..d34de601b 100644--- a/agent/src/tools/symbol_search_tool.py+++ b/agent/src/tools/symbol_search_tool.py@@ -185,6 +185,18 @@ class SymbolSearchTool(BaseTool):if connector_source is not None and connector_status is not None:sources[connector_source] = connector_statuscandidates.extend(connector_hits)+ if crypto_pair is not None and not connector_hits:+ # Resolving a pair must not require a broker account. The venue+ # catalogs are public, unauthenticated REST — the same connectivity+ # `orderbook_depth` already uses to serve these very pairs — so a+ # user with no Binance connection still gets an identity instead of+ # nothing (or, before #1234, a near-string Yahoo asset).+ public_hits, public_source, public_status = _search_public_exchanges(+ crypto_pair+ )+ if public_source is not None:+ sources[public_source] = public_status or "ok"+ candidates.extend(public_hits)em_hits, sources["eastmoney"] = _search_eastmoney(query)candidates.extend(em_hits)@@ -275,6 +287,81 @@ def _canonical_crypto_pair(value: str) -> str | None:return None+#: Public, no-auth venue catalogs consulted for an explicit pair, in order.+#: Same venues and same ccxt connectivity as ``orderbook_depth``.+_PUBLIC_CRYPTO_EXCHANGES = ("binance", "okx")+++def _load_public_markets(exchange_id: str) -> Dict[str, Any]:+ """Return one venue's public market catalog via ccxt (no credentials).++ Isolated as its own function so tests monkeypatch exactly this name and+ never open a socket, the same pattern as+ ``orderbook_depth_tool._fetch_raw_book``.++ Args:+ exchange_id: A ccxt exchange id, ``"binance"`` or ``"okx"``.++ Returns:+ ccxt's unified markets mapping, keyed by ``BASE/QUOTE``.++ Raises:+ Exception: Whatever ccxt raises for a network or venue error.+ """+ import ccxt++ exchange = getattr(ccxt, exchange_id)({"enableRateLimit": True, "timeout": 10_000})+ return exchange.load_markets()+++def _search_public_exchanges(+ crypto_pair: str,+) -> tuple[List[Dict[str, Any]], str | None, str | None]:+ """Resolve an exact pair against the public venue catalogs.++ Args:+ crypto_pair: Canonical ``BASE-QUOTE`` spelling.++ Returns:+ ``(candidates, source, status)``; ``source`` is ``None`` only when+ ccxt itself is unavailable.+ """+ base, quote = crypto_pair.split("-", 1)+ ccxt_symbol = f"{base}/{quote}"+ failures: List[str] = []+ for exchange_id in _PUBLIC_CRYPTO_EXCHANGES:+ try:+ markets = _load_public_markets(exchange_id)+ except ImportError:+ return [], None, None+ except Exception as exc: # noqa: BLE001 — one venue is non-fatal+ logger.debug("public %s catalog failed for %r: %s", exchange_id, crypto_pair, exc)+ failures.append(f"{exchange_id}: {exc}")+ continue+ market = markets.get(ccxt_symbol) if isinstance(markets, dict) else None+ if not isinstance(market, dict) or market.get("active") is False:+ continue+ if market.get("spot") is False:+ continue+ return (+ [+ {+ "symbol": crypto_pair,+ "name": None,+ "market": "crypto",+ "type": "cryptocurrency",+ "exchange": exchange_id.upper(),+ "source": "public_exchange",+ }+ ],+ "public_exchange",+ "ok",+ )+ if failures:+ return [], "public_exchange", "; ".join(failures)+ return [], "public_exchange", f"{_SKIPPED}no public venue lists {crypto_pair}"++def _search_selected_connector(query: str,limit: int,diff --git a/agent/tests/test_symbol_search_tool.py b/agent/tests/test_symbol_search_tool.pyindex 7287f61db..9b4127004 100644--- a/agent/tests/test_symbol_search_tool.py+++ b/agent/tests/test_symbol_search_tool.py@@ -431,7 +431,10 @@ class TestSymbolSearchErrors:"quoteType": "CRYPTOCURRENCY",}]- with patch.object(ss.yahoo_client, "search", return_value=yahoo_collision):+ with patch.object(ss.yahoo_client, "search", return_value=yahoo_collision), \+ patch.object(+ ss, "_load_public_markets", side_effect=RuntimeError("venue down")+ ):data = json.loads(ss.SymbolSearchTool().execute(query="ETH-USDT", limit=5))["data"]@@ -440,6 +443,7 @@ class TestSymbolSearchErrors:"connector search failed: market catalog unavailable")assert data["sources"]["eastmoney"].startswith("skipped:")+ assert "venue down" in data["sources"]["public_exchange"]assert data["candidates"] == []def test_sec_lookup_failure_recorded_not_fatal(self):@@ -676,3 +680,85 @@ class TestTickerNameQueryYahooSkip:search.assert_called_once()assert data["sources"]["yahoo"] == "ok"+++class TestCryptoPairWithoutABrokerConnection:+ """Resolving an exchange pair must not require a broker account.++ #1242 routes exact pairs through the *selected* Binance connector, which+ needs a configured profile and credentials. Identity resolution is a+ read-only lookup against a public catalog — the same unauthenticated ccxt+ connectivity ``orderbook_depth`` already uses to serve these pairs — so a+ user with no broker connection must still get an identity rather than+ nothing (or, before #1234, a near-string Yahoo asset).+ """++ @staticmethod+ def _markets(*symbols):+ return {sym: {"symbol": sym, "spot": True, "active": True} for sym in symbols}++ def _run(self, monkeypatch, query, markets_by_exchange, yahoo=None):+ monkeypatch.setattr(+ trading_profiles, "load_selected_profile_id", lambda: "tiger-paper-sdk"+ )++ def _markets(exchange_id):+ payload = markets_by_exchange.get(exchange_id)+ if payload is None:+ raise RuntimeError(f"{exchange_id} unavailable")+ return payload++ monkeypatch.setattr(ss, "_load_public_markets", _markets)+ with patch.object(ss.yahoo_client, "search", return_value=yahoo or []):+ return json.loads(ss.SymbolSearchTool().execute(query=query, limit=5))["data"]++ def test_pair_resolves_with_no_connector_selected(self, monkeypatch):+ data = self._run(+ monkeypatch,+ "ETH-USDT",+ {"binance": self._markets("ETH/USDT", "BTC/USDT")},+ yahoo=[+ {+ "symbol": "AETHUSDT-USD",+ "shortname": "Aave Ethereum USDT USD",+ "exchange": "CCC",+ "quoteType": "CRYPTOCURRENCY",+ }+ ],+ )+ assert [c["symbol"] for c in data["candidates"]] == ["ETH-USDT"]+ assert data["candidates"][0]["exchange"] == "BINANCE"+ assert data["sources"]["public_exchange"] == "ok"++ def test_second_venue_is_consulted_when_the_first_is_down(self, monkeypatch):+ data = self._run(+ monkeypatch, "SOL-USDT", {"okx": self._markets("SOL/USDT")}+ )+ assert [c["symbol"] for c in data["candidates"]] == ["SOL-USDT"]+ assert data["candidates"][0]["exchange"] == "OKX"++ def test_a_pair_no_venue_lists_resolves_to_nothing(self, monkeypatch):+ data = self._run(+ monkeypatch,+ "NOTREAL-USDT",+ {"binance": self._markets("ETH/USDT"), "okx": self._markets("ETH/USDT")},+ )+ assert data["candidates"] == []+ assert data["sources"]["public_exchange"].startswith("skipped:")++ def test_an_equity_query_never_reaches_the_venue_catalogs(self, monkeypatch):+ called: list[str] = []++ def _markets(exchange_id):+ called.append(exchange_id)+ return {}++ monkeypatch.setattr(ss, "_load_public_markets", _markets)+ monkeypatch.setattr(+ trading_profiles, "load_selected_profile_id", lambda: "tiger-paper-sdk"+ )+ with patch.object(+ ss.eastmoney_client, "get_json", return_value=_eastmoney_payload()+ ), patch.object(ss.yahoo_client, "search", return_value=[]):+ ss.SymbolSearchTool().execute(query="apple", limit=5)+ assert called == []