Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(mcp): fail fast eastmoney and US OTC aliases for Canadian symbols

Will Liaoae9900ebbcd3
diff --git a/agent/src/tools/symbol_search_tool.py b/agent/src/tools/symbol_search_tool.py
index 43e9ba293..22480b17a 100644
--- a/agent/src/tools/symbol_search_tool.py
+++ b/agent/src/tools/symbol_search_tool.py
@@ -22,6 +22,7 @@ from __future__ import annotations
import json
import logging
+import re
from typing import Any, Dict, List, Optional
from backtest.loaders import eastmoney_client, sec_edgar_client, yahoo_client
@@ -35,6 +36,14 @@ logger = logging.getLogger(__name__)
# Eastmoney client; this is just the documented endpoint URL + query shape.
_EASTMONEY_SUGGEST_URL = "https://searchapi.eastmoney.com/api/suggest/get"
+# Canadian equity suffixes (TSX ``.TO`` / TSX Venture ``.V``). Eastmoney has NO
+# Canada coverage: querying it with a Canadian ticker returns a non-JSON body
+# (``Expecting value: line 1 column 1 (char 0)``) instead of a clean empty
+# result. We fail fast — skip the endpoint entirely — for these queries, and
+# drop US OTC aliases (e.g. ``BYAGF.US`` for ``BYN.V``) so the grounding
+# ledger never sees one company under two venues (identity_conflict).
+_CANADIAN_SYMBOL_RE = re.compile(r"^[A-Z0-9&.\-]+\.(?:TO|V)$", 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] = {
@@ -134,6 +143,18 @@ class SymbolSearchTool(BaseTool):
yh_hits, sources["yahoo"] = _search_yahoo(query)
candidates.extend(yh_hits)
+ # 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
+ # two venues for one entity and reject every downstream call with
+ # ``identity_conflict``. Keep only ``.TO``/``.V`` candidates here.
+ if _is_canadian_symbol(query):
+ candidates = [
+ c
+ for c in candidates
+ if _is_canadian_symbol(str(c.get("symbol") or ""))
+ ]
+
merged = _merge_candidates(candidates)
merged, sources["sec_edgar"] = _enrich_us_cik(merged)
if sources["sec_edgar"] == _NO_US:
@@ -165,9 +186,28 @@ def _clamp_limit(value: Any) -> int:
return max(1, min(n, _MAX_LIMIT))
+def _is_canadian_symbol(text: str) -> bool:
+ """Whether *text* is a Canadian ticker (TSX ``.TO`` / TSXV ``.V``).
+
+ Used for fail-fast routing: Canadian symbols are served by Yahoo only, so
+ Eastmoney is skipped and US OTC aliases are filtered from the result set.
+
+ Args:
+ text: A symbol or free-text query to test.
+
+ Returns:
+ ``True`` when the text is exactly a Canadian-suffixed ticker.
+ """
+ return bool(_CANADIAN_SYMBOL_RE.match((text or "").strip()))
+
+
def _search_eastmoney(query: str) -> tuple[List[Dict[str, Any]], str]:
"""Query Eastmoney's suggest endpoint and normalize the candidates.
+ Fails fast for Canadian (``.TO``/``.V``) queries: Eastmoney has no Canada
+ coverage and its suggest endpoint returns a non-JSON body for those,
+ so the endpoint is skipped instead of raising a parse error.
+
Args:
query: Free-text name or ticker fragment.
@@ -175,6 +215,12 @@ def _search_eastmoney(query: str) -> tuple[List[Dict[str, Any]], str]:
``(candidates, status)`` where ``status`` is ``"ok"`` on success or a
short error string when the source failed (candidates is then empty).
"""
+ if _is_canadian_symbol(query):
+ logger.info(
+ "eastmoney skipped for Canadian symbol %r (no Canada coverage)",
+ query,
+ )
+ return [], "unsupported: eastmoney has no Canada coverage"
try:
payload = eastmoney_client.get_json(
_EASTMONEY_SUGGEST_URL,
diff --git a/agent/tests/test_symbol_search_tool.py b/agent/tests/test_symbol_search_tool.py
index 8bc0b7d09..393c5fdd0 100644
--- a/agent/tests/test_symbol_search_tool.py
+++ b/agent/tests/test_symbol_search_tool.py
@@ -176,6 +176,98 @@ class TestSymbolSearchSuccess:
assert "sec_edgar" not in payload["data"]["sources"]
mock_cik.assert_not_called()
+ def test_canadian_query_skips_eastmoney_endpoint(self):
+ """A Canadian .V/.TO query fails fast: eastmoney is never contacted."""
+ with patch.object(
+ ss.eastmoney_client, "get_json"
+ ) as mock_em, patch.object(
+ ss.yahoo_client, "search", return_value=_yahoo_quotes()
+ ):
+ out = ss.SymbolSearchTool().execute(query="BYN.V")
+
+ mock_em.assert_not_called()
+ payload = json.loads(out)
+ assert payload["ok"] is True
+ assert payload["data"]["sources"]["eastmoney"] == (
+ "unsupported: eastmoney has no Canada coverage"
+ )
+
+ def test_canadian_query_drops_us_otc_aliases(self):
+ """Yahoo OTC aliases (BYAGF.US) of a Canadian name are filtered out."""
+ quotes = [
+ {
+ "symbol": "BYN.V",
+ "shortname": "Banyan Gold Corp.",
+ "exchange": "VAN",
+ "quoteType": "EQUITY",
+ },
+ {
+ "symbol": "BYAGF.US",
+ "shortname": "Banyan Gold Corp.",
+ "exchange": "PNK",
+ "quoteType": "EQUITY",
+ },
+ ]
+ with patch.object(
+ ss.eastmoney_client, "get_json"
+ ), patch.object(ss.yahoo_client, "search", return_value=quotes):
+ out = ss.SymbolSearchTool().execute(query="BYN.V")
+
+ payload = json.loads(out)
+ symbols = {c["symbol"] for c in payload["data"]["candidates"]}
+ assert symbols == {"BYN.V"}
+ assert "BYAGF.US" not in symbols
+
+ def test_canadian_query_drops_us_otc_aliases_cert(self):
+ """CERT.V OTC alias (CERT.US) is filtered for a Canadian query."""
+ quotes = [
+ {
+ "symbol": "CERT.V",
+ "shortname": "Cerrado Gold Inc.",
+ "exchange": "VAN",
+ "quoteType": "EQUITY",
+ },
+ {
+ "symbol": "CERT.US",
+ "shortname": "Cerrado Gold Inc.",
+ "exchange": "PNK",
+ "quoteType": "EQUITY",
+ },
+ ]
+ with patch.object(
+ ss.eastmoney_client, "get_json"
+ ), patch.object(ss.yahoo_client, "search", return_value=quotes):
+ out = ss.SymbolSearchTool().execute(query="CERT.V")
+
+ payload = json.loads(out)
+ symbols = {c["symbol"] for c in payload["data"]["candidates"]}
+ assert symbols == {"CERT.V"}
+
+ def test_canadian_tsx_to_query_keeps_to_only(self):
+ """A .TO (TSX) query keeps only the .TO candidate, not a US alias."""
+ quotes = [
+ {
+ "symbol": "PDI.TO",
+ "shortname": "Predictive Discovery",
+ "exchange": "TOR",
+ "quoteType": "EQUITY",
+ },
+ {
+ "symbol": "PDIYF.US",
+ "shortname": "Predictive Discovery ADR",
+ "exchange": "PNK",
+ "quoteType": "EQUITY",
+ },
+ ]
+ with patch.object(
+ ss.eastmoney_client, "get_json"
+ ), patch.object(ss.yahoo_client, "search", return_value=quotes):
+ out = ss.SymbolSearchTool().execute(query="PDI.TO")
+
+ payload = json.loads(out)
+ symbols = {c["symbol"] for c in payload["data"]["candidates"]}
+ assert symbols == {"PDI.TO"}
+
class TestSymbolSearchErrors:
"""Error envelopes and per-source resilience."""