Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(symbol-resolution): route spot gold aliases through the right path

aminak580cb4c5846f08
diff --git a/agent/src/agent/grounding.py b/agent/src/agent/grounding.py
index d207ab8ad..4cf744983 100644
--- a/agent/src/agent/grounding.py
+++ b/agent/src/agent/grounding.py
@@ -793,10 +793,48 @@ def _infer_venue(symbol: str) -> str | None:
for suffix, venue in suffixes.items():
if upper.endswith(suffix):
return venue
- if "-" in upper or "/" in upper:
- return "crypto_or_fx"
+ # Yahoo's continuous-front-month futures notation (GC=F, CL=F, SI=F, ...).
+ # The exchange category is the venue class. The engine and the
+ # correlation helper mirror this pattern; this is the third copy.
if upper.endswith("=F"):
return "futures"
+ # Yahoo's forex notation (XAUUSD=X, EURUSD=X) is FX.
+ if re.match(r"^[A-Z]{6}=X$", upper):
+ return "forex"
+ # Bare 6-character precious-metal / FX symbols. The whitelist is
+ # ISO 4217 metals + G10 currencies; it intentionally does NOT include
+ # any US-equity prefix. Mirroring the engine ``_MARKET_PATTERNS``.
+ if re.match(
+ r"^(?:XAU|XAG|XPT|XPD|EUR|GBP|JPY|CHF|CAD|AUD|NZD|USD)[A-Z]{3}$",
+ upper,
+ ):
+ return "forex"
+ # Dashed / slashed symbols are NOT categorically crypto. The crypto
+ # resolver (``_canonical_crypto_pair`` in ``src.tools.symbol_search_tool``)
+ # gates the ``USD`` quote leg on a 26-entry base whitelist of Binance /
+ # OKX spot bases (BTC / ETH / BNB / SOL / ADA / XRP / DOGE / TRX / DOT /
+ # MATIC / AVAX / LINK / LTC / BCH / ETC / XLM / ATOM / FIL / APT / NEAR /
+ # ALGO / SAND / MANA / AXS / XAUT / PAXG). ``XAU-USD``, ``EUR-USD``,
+ # ``GBP-USD`` are not in that whitelist, so they are NOT crypto and
+ # are NOT crypto_or_fx — they are forex. Stablecoin quotes (USDT /
+ # USDC / BUSD / TUSD / FDUSD) are unambiguous and accept any alphanumeric
+ # base. Without this guard a bare ``XAUUSD`` query would surface as a
+ # crypto-or-fx hybrid in the runtime registry, contradicting the engine
+ # classifier which already routes it to ``forex`` (see PR #1280).
+ if "-" in upper or "/" in upper:
+ base, sep, quote = upper.partition("-") if "-" in upper else upper.partition("/")
+ if quote in {"FDUSD", "USDT", "USDC", "BUSD", "TUSD"}:
+ return "crypto_or_fx"
+ if quote == "USD" and base in {
+ "BTC", "ETH", "BNB", "SOL", "ADA", "XRP", "DOGE", "TRX", "DOT",
+ "MATIC", "AVAX", "LINK", "LTC", "BCH", "ETC", "XLM", "ATOM",
+ "FIL", "APT", "NEAR", "ALGO", "SAND", "MANA", "AXS", "XAUT", "PAXG",
+ }:
+ return "crypto_or_fx"
+ # Any other dashed / slashed pair is forex-shaped (e.g. ``XAU-USD``,
+ # ``EUR-USD``, ``GBP-USD``); the per-pair engine classifier decides
+ # ``forex`` vs ``crypto`` vs ``futures`` downstream.
+ return "forex"
return None
@@ -845,8 +883,36 @@ def _infer_instrument_type(symbol: str, candidate_type: Any = None) -> str:
return "future"
if upper.endswith(".FX"):
return "forex"
+ # Yahoo's continuous-front-month futures notation (GC=F, CL=F, ...).
+ # Mirrors the engine ``_MARKET_PATTERNS`` and the correlation helper.
+ if re.match(r"^[A-Z]{2,5}=F$", upper):
+ return "future"
+ # Yahoo's forex notation (XAUUSD=X, EURUSD=X).
+ if re.match(r"^[A-Z]{6}=X$", upper):
+ return "forex"
+ # Bare 6-character precious-metal / FX symbols (whitelist).
+ if re.match(
+ r"^(?:XAU|XAG|XPT|XPD|EUR|GBP|JPY|CHF|CAD|AUD|NZD|USD)[A-Z]{3}$",
+ upper,
+ ):
+ return "forex"
+ # Dashed / slashed symbols: crypto only when the quote leg is a
+ # stablecoin OR the base is in the USD-whitelist. The whitelist
+ # mirrors ``_canonical_crypto_pair`` in
+ # ``src.tools.symbol_search_tool``. ``XAU-USD`` / ``EUR-USD`` /
+ # ``GBP-USD`` are NOT crypto and resolve as ``forex`` (the per-pair
+ # engine classifier decides the final market downstream).
if "-" in upper or "/" in upper:
- return "crypto"
+ base, sep, quote = upper.partition("-") if "-" in upper else upper.partition("/")
+ if quote in {"FDUSD", "USDT", "USDC", "BUSD", "TUSD"}:
+ return "crypto"
+ if quote == "USD" and base in {
+ "BTC", "ETH", "BNB", "SOL", "ADA", "XRP", "DOGE", "TRX", "DOT",
+ "MATIC", "AVAX", "LINK", "LTC", "BCH", "ETC", "XLM", "ATOM",
+ "FIL", "APT", "NEAR", "ALGO", "SAND", "MANA", "AXS", "XAUT", "PAXG",
+ }:
+ return "crypto"
+ return "forex"
return "listed_security"
diff --git a/agent/src/tools/symbol_search_tool.py b/agent/src/tools/symbol_search_tool.py
index d34de601b..a461e973a 100644
--- a/agent/src/tools/symbol_search_tool.py
+++ b/agent/src/tools/symbol_search_tool.py
@@ -214,6 +214,25 @@ class SymbolSearchTool(BaseTool):
if _canonical_crypto_pair(str(candidate.get("symbol") or ""))
== crypto_pair
]
+ elif "-" in query or "/" in query or query.endswith("=F") or query.endswith("=X"):
+ # The query is a non-crypto, ticker-shaped symbol (e.g. ``XAUUSD``,
+ # ``EUR/USD``, ``GC=F``, ``XAUUSD=X``). Any candidate Yahoo
+ # returned whose canonical form IS a crypto pair (e.g.
+ # ``VALOUR-BTC-0-SEK.ST`` as a free-text near-string of a gold
+ # query, or ``AETHUSDT-USD`` for ``XAU-USD``) would silently lock
+ # a wrong crypto identity. Drop them. The gate was previously
+ # inverted (#1234 only checked the crypto-pair branch) — a bare
+ # ``XAUUSD`` query then propagated a near-string crypto
+ # candidate that the user's grounded ``_canonical_crypto_pair``
+ # already rejected, but the symbol-search tool never knew. A bare
+ # name query (``apple``, ``tesla``, ``Gold``) is NOT a ticker shape
+ # and falls through to the existing free-text behavior.
+ candidates = [
+ candidate
+ for candidate in candidates
+ if _canonical_crypto_pair(str(candidate.get("symbol") or ""))
+ is None
+ ]
# 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.
diff --git a/agent/tests/test_agent_grounding.py b/agent/tests/test_agent_grounding.py
index aef2ba4b2..5999c2d29 100644
--- a/agent/tests/test_agent_grounding.py
+++ b/agent/tests/test_agent_grounding.py
@@ -13,6 +13,7 @@ from src.agent.context import ContextBuilder
from src.agent.grounding import (
GroundingLedger,
_infer_currency,
+ _infer_instrument_type,
_infer_venue,
_scan_symbols,
_symbol_from_csv_filename,
@@ -545,6 +546,56 @@ def test_explicit_symbol_and_resolver_suffix_alias_are_one_identity(
assert authorization.allowed is True
+ ("symbol", "expected_venue", "expected_type"),
+ [
+ # Spot gold: bare 6-letter, dashed, slashed, Yahoo forex notation.
+ # Before this fix, the shape-based fallback in _infer_venue / _infer_instrument_type
+ # mis-classified any dashed / slashed symbol as crypto_or_fx / crypto.
+ ("XAUUSD", "forex", "forex"),
+ ("XAU-USD", "forex", "forex"),
+ ("XAU/USD", "forex", "forex"),
+ ("XAUUSD=X", "forex", "forex"),
+ # COMEX gold futures via Yahoo continuous-front-month notation.
+ ("GC=F", "futures", "future"),
+ # Tokenized gold stays crypto.
+ ("XAUT-USDT", "crypto_or_fx", "crypto"),
+ ("PAXG-USDT", "crypto_or_fx", "crypto"),
+ # Regression: existing crypto / US equity behavior unchanged.
+ ("BTC-USDT", "crypto_or_fx", "crypto"),
+ ("GLD", None, "listed_security"),
+ ("AAPL.US", "us", "listed_security"),
+ ],
+)
+def test_runtime_registry_classifies_gold_fx_futures_consistently(
+ symbol, expected_venue, expected_type
+) -> None:
+ """The runtime registry must agree with the engine classifier for gold / FX / futures.
+
+ PR #1280 added the metal/FX/futures patterns to the engine
+ ``_MARKET_PATTERNS`` and the correlation helper. This test pins the
+ third copy (the shape-based fallback in
+ ``_infer_venue`` / ``_infer_instrument_type``) to the same
+ whitelist. Without this, a bare ``XAUUSD`` query would surface in
+ the registry as ``venue=None, type=listed_security`` and a dashed
+ ``XAU-USD`` would surface as ``venue=crypto_or_fx, type=crypto``,
+ contradicting the engine's actual classification. The user observed
+ this exact runtime state in the agent before the fix.
+ """
+ assert _infer_venue(symbol) == expected_venue
+ assert _infer_instrument_type(symbol) == expected_type
+ # Quote currency is non-None only for dashed / slashed shapes.
+ if "-" in symbol or "/" in symbol:
+ # Whitelist-based ``USD`` leg: only metals/FX/forex (not crypto).
+ if symbol.endswith("-USD") and symbol not in {"XAUT-USD", "PAXG-USD"}:
+ assert _infer_currency(symbol) == "USD"
+ # Otherwise the trailing 3-5 letter leg is the quote currency.
+ elif symbol.endswith("-USDT") or symbol.endswith("-USDC") or \
+ symbol.endswith("-BUSD") or symbol.endswith("-TUSD") or \
+ symbol.endswith("-FDUSD"):
+ assert _infer_currency(symbol) in {"USDT", "USDC", "BUSD", "TUSD", "FDUSD"}
+
+
def test_resolver_answering_a_different_venue_is_still_conflicting(
tmp_path: Path,
) -> None:
diff --git a/agent/tests/test_symbol_search_tool.py b/agent/tests/test_symbol_search_tool.py
index 9b4127004..f66b17962 100644
--- a/agent/tests/test_symbol_search_tool.py
+++ b/agent/tests/test_symbol_search_tool.py
@@ -762,3 +762,106 @@ class TestCryptoPairWithoutABrokerConnection:
), patch.object(ss.yahoo_client, "search", return_value=[]):
ss.SymbolSearchTool().execute(query="apple", limit=5)
assert called == []
+
+
+class TestSpotGoldCandidateFilter:
+ """Bare gold / FX / futures queries must not lock a wrong crypto identity.
+
+ Yahoo's free-text search can return a near-string crypto pair for a
+ non-crypto query (``XAUUSD`` -> ``VALOUR-BTC-0-SEK.ST`` is a real-world
+ observation). The resolver-side ``_canonical_crypto_pair`` already
+ rejects those candidates, but the symbol-search tool itself used
+ to keep them in the candidate list, propagating the wrong instrument
+ to the identity gate. The fix: when the query is a ticker shape
+ (separator, ``=F``, or ``=X``) but NOT a crypto pair, drop any
+ candidate whose canonical form IS a crypto pair. Free-text name
+ queries (``apple``, ``tesla``) are unaffected.
+ """
+
+ def _run(self, query, yahoo_hits, eastmoney_rows=None):
+ # Default to an empty Eastmoney payload so the test isolates the
+ # Yahoo branch (the layer under test).
+ tool = ss.SymbolSearchTool()
+ em_payload = {"QuotationCodeTable": {"Data": eastmoney_rows or []}}
+ with patch.object(
+ ss.eastmoney_client, "get_json", return_value=em_payload
+ ), patch.object(ss.yahoo_client, "search", return_value=yahoo_hits), \
+ patch.object(ss, "_load_public_markets", return_value={}), \
+ patch.object(ss, "_enrich_us_cik", side_effect=lambda c, s="ok": (c, s)), \
+ patch.object(
+ trading_profiles, "load_selected_profile_id",
+ side_effect=OSError("no connector"),
+ ):
+ out = tool.execute(query=query, limit=10)
+ return json.loads(out)
+
+ def test_xauusdt_drops_near_string_btc_etp(self):
+ """The bug repro: Yahoo returns a Swedish Bitcoin ETP for XAUUSD."""
+ yahoo = [
+ {"symbol": "VALOUR-BTC-0-SEK.ST",
+ "shortname": "Valour Bitcoin Zero SEK",
+ "exchange": "STO", "quoteType": "EQUITY", "index": "XETR"},
+ ]
+ data = self._run("XAUUSD", yahoo)["data"]
+ assert data["count"] == 0
+ assert data["candidates"] == []
+
+ def test_xauusd_slash_drops_near_string_crypto_hits(self):
+ yahoo = [
+ {"symbol": "AETHUSDT-USD", "shortname": "Aave Ethereum USDT",
+ "exchange": "CCC", "quoteType": "CRYPTOCURRENCY", "index": "AETH"},
+ ]
+ data = self._run("XAU/USD", yahoo)["data"]
+ assert data["count"] == 0
+
+ def test_xauusd_x_drops_near_string_crypto_hits(self):
+ yahoo = [
+ {"symbol": "AETHUSDT-USD", "shortname": "Aave Ethereum USDT",
+ "exchange": "CCC", "quoteType": "CRYPTOCURRENCY", "index": "AETH"},
+ ]
+ data = self._run("XAUUSD=X", yahoo)["data"]
+ assert data["count"] == 0
+
+ def test_gc_f_keeps_correct_futures_hit(self):
+ yahoo = [
+ {"symbol": "GC=F", "shortname": "Gold Continuous Front Month",
+ "exchange": "NYM", "quoteType": "FUTURE", "index": "GC"},
+ ]
+ data = self._run("GC=F", yahoo)["data"]
+ assert data["count"] == 1
+ assert data["candidates"][0]["symbol"] == "GC=F"
+
+ def test_xaut_usdt_keeps_tokenized_gold(self):
+ yahoo = [
+ {"symbol": "XAUT-USDT", "shortname": "Tether Gold",
+ "exchange": "CCC", "quoteType": "CRYPTOCURRENCY", "index": "XAUT"},
+ ]
+ data = self._run("XAUT-USDT", yahoo)["data"]
+ assert data["count"] == 1
+ assert data["candidates"][0]["symbol"] == "XAUT-USDT"
+
+ def test_paxg_usdt_keeps_tokenized_gold(self):
+ yahoo = [
+ {"symbol": "PAXG-USDT", "shortname": "Paxos Gold",
+ "exchange": "CCC", "quoteType": "CRYPTOCURRENCY", "index": "PAXG"},
+ ]
+ data = self._run("PAXG-USDT", yahoo)["data"]
+ assert data["count"] == 1
+ assert data["candidates"][0]["symbol"] == "PAXG-USDT"
+
+ def test_free_text_name_query_unaffected(self):
+ """A free-text company name (``apple``) is NOT a ticker shape and
+ must not have crypto candidates stripped. Yahoo's free-text
+ answer may include near-string crypto hits (``BTC-USD``) which
+ the user is allowed to see and choose from.
+ """
+ yahoo = [
+ {"symbol": "BTC-USD", "shortname": "Bitcoin USD",
+ "exchange": "CCC", "quoteType": "CRYPTOCURRENCY", "index": "BTC"},
+ {"symbol": "AAPL.US", "shortname": "Apple Inc.",
+ "exchange": "NMS", "quoteType": "EQUITY", "index": "AAPL"},
+ ]
+ data = self._run("apple", yahoo)["data"]
+ symbols = [c["symbol"] for c in data["candidates"]]
+ assert "BTC-USD" in symbols
+ assert "AAPL.US" in symbols