"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(market-identity): route FX, metals, and futures symbols correctly
aminak5826a51bde82b7
diff --git a/agent/backtest/correlation.py b/agent/backtest/correlation.pyindex bed2d5b1d..8a3e1321a 100644--- a/agent/backtest/correlation.py+++ b/agent/backtest/correlation.py@@ -7,6 +7,7 @@ over a configurable lookback window. Used by the /correlation API endpoint.from __future__ import annotationsimport logging+import refrom typing import Dict, Literalimport pandas as pd@@ -46,6 +47,23 @@ def infer_market(code: str) -> str:return "ca_equity"if code_upper.endswith(".US"):return "us_equity"+ # Yahoo's continuous-front-month futures notation (``GC=F``, ``CL=F``,+ # ``SI=F``, ``HG=F``, ``MGC=F``). Mirrors the same pattern in+ # ``backtest.engines._market_hooks._MARKET_PATTERNS`` so this offline+ # classifier stays consistent with the engine-side classifier.+ if re.match(r"^[A-Z]{2,5}=F$", code_upper):+ return "futures"+ # Yahoo's forex notation (``XAUUSD=X``, ``EURUSD=X``).+ if re.match(r"^[A-Z]{6}=X$", code_upper):+ return "forex"+ # Bare 6-character precious-metal / FX symbols. Whitelist-restricted to+ # a small set of base codes (ISO 4217 metals + G10 currencies) so a+ # length-only pattern never re-routes a legitimate 6-letter US ticker.+ if re.match(+ r"^(?:XAU|XAG|XPT|XPD|EUR|GBP|JPY|CHF|CAD|AUD|NZD|USD)[A-Z]{3}$",+ code_upper,+ ):+ return "forex"if code_upper.isdigit():if len(code_upper) == 6:return "a_share"diff --git a/agent/backtest/engines/_market_hooks.py b/agent/backtest/engines/_market_hooks.pyindex 116af8fa1..15e3a2c8a 100644--- a/agent/backtest/engines/_market_hooks.py+++ b/agent/backtest/engines/_market_hooks.py@@ -54,11 +54,30 @@ _MARKET_PATTERNS = [# Forex pairs: XXX/YYY or XXXXXX.FX(re.compile(r"^[A-Z]{3}/[A-Z]{3}$"), "forex"),(re.compile(r"^[A-Z]{6}\.FX$"), "forex"),+ # Yahoo notations for FX and futures. ``=X`` is Yahoo's forex form+ # (``XAUUSD=X``, ``EURUSD=X``); ``=F`` is Yahoo's continuous-front-month+ # futures form (``GC=F``, ``CL=F``, ``SI=F``, ``HG=F``, ``MGC=F``). The+ # underlying asset classes differ, so the patterns route to different+ # markets. Both must come BEFORE any length-based fallback to win over+ # the catch-all US-equity regex below.+ (re.compile(r"^[A-Z]{6}=X$", re.I), "forex"),+ (re.compile(r"^[A-Z]{2,5}=F$", re.I), "futures"),+ # Bare 6-character precious-metal / FX symbols (``XAUUSD``, ``XAGUSD``,+ # ``XPTUSD``, ``XPDUSD``, ``EURUSD``, ``GBPUSD``, ``USDJPY``, ``USDCHF``,+ # ``AUDUSD``, ``NZDUSD``, ``USDCAD``). Whitelist-restricted to a small+ # set of base codes so legitimate US tickers of any 6-letter length are+ # never re-routed. The four metal codes are ISO 4217; the rest are G10+ # currencies. Length-only patterns (``^[A-Z]{6}$``) are deliberately+ # rejected — they over-match tickers like ``NFLXLI`` or ``AMZNLY``.+ (re.compile(+ r"^(?:XAU|XAG|XPT|XPD|EUR|GBP|JPY|CHF|CAD|AUD|NZD|USD)[A-Z]{3}$",+ re.I,+ ), "forex"),# Bare US tickers (AAPL, MSFT, SPY, T, ...). Must stay LAST so every# suffixed equity / futures / crypto / forex form above wins first.# ``{1,5}`` covers every standard US ticker length while 6-char bare- # forex (EURUSD) and longer crypto codes (BTCUSDT) fall through to the- # a_share default.+ # forex/metals (now caught by the whitelist above) and longer crypto+ # codes (``BTCUSDT``) fall through to the a_share default.(re.compile(r"^[A-Z]{1,5}$", re.I), "us_equity"),]@@ -146,6 +165,9 @@ def _detect_market(code: str) -> str:Market type (a_share/us_equity/hk_equity/india_equity/kr_equity/ca_equity/crypto/futures/forex).Bare 1-5 letter alphabetic tickers resolve to ``us_equity``;+ bare 6-letter codes that start with a precious-metal or G10+ currency code (whitelist) resolve to ``forex``; Yahoo's+ ``=F`` (futures) and ``=X`` (forex) notations are recognized;any other unknown format defaults to ``a_share``."""for pattern, market in _MARKET_PATTERNS:diff --git a/agent/backtest/engines/base.py b/agent/backtest/engines/base.pyindex 218f1be4d..0056a74ee 100644--- a/agent/backtest/engines/base.py+++ b/agent/backtest/engines/base.py@@ -107,14 +107,25 @@ def _run_card_data_sources(config: Dict[str, Any], loader: Any) -> List[str]:# ─── Market detection (lightweight, for signal alignment only) ───_CRYPTO_RE = _re.compile(r"^[A-Z]+-USDT$|^[A-Z]+/USDT$", _re.I)-_FOREX_RE = _re.compile(r"^[A-Z]{3}/[A-Z]{3}$|^[A-Z]{6}\.FX$")+# Forex / metals in their explicit Yahoo notations, plus the bare-6-char+# whitelist for XAUUSD / XAGUSD / XPTUSD / XPDUSD and G10 currencies. Mirrors+# ``backtest.engines._market_hooks._MARKET_PATTERNS`` so the ffill-limit+# decision (``10`` for cross-market vs ``5`` for single-market) reflects the+# same market classification the engine composite would assign.+_FX_RE = _re.compile(+ r"^[A-Z]{3}/[A-Z]{3}$"+ r"|^[A-Z]{6}\.FX$"+ r"|^[A-Z]{6}=X$"+ r"|^(?:XAU|XAG|XPT|XPD|EUR|GBP|JPY|CHF|CAD|AUD|NZD|USD)[A-Z]{3}$",+ _re.I,+)def _detect_market_for_align(code: str) -> str:"""Lightweight market detection for ffill_limit calculation."""if _CRYPTO_RE.match(code):return "crypto"- if _FOREX_RE.match(code):+ if _FX_RE.match(code):return "forex"return "equity"diff --git a/agent/src/tools/symbol_search_tool.py b/agent/src/tools/symbol_search_tool.pyindex d34de601b..c0ed2e684 100644--- a/agent/src/tools/symbol_search_tool.py+++ b/agent/src/tools/symbol_search_tool.py@@ -58,17 +58,31 @@ _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",+# as ``BRK-B`` is never misclassified as a pair. The full set is split into+# two tiers:+#+# * Stablecoin quotes (FDUSD / USDT / USDC / BUSD / TUSD) are unambiguous -+# a ``BTC-USDT`` or ``XAUT-USDC`` cannot be confused with anything outside+# crypto. These are accepted on any alphanumeric base.+# * ``USD`` is ambiguous: a ``BTC-USD`` is a real Coinbase crypto pair, but+# ``XAU-USD`` is spot gold, ``EUR-USD`` is forex, and ``GBP-USD`` is+# currency. Restrict ``USD`` to a whitelist of well-known crypto bases+# (anything that's actually tradable on Binance/OKX spot, plus the+# stablecoin-gold tokens XAUT/PAXG that ARE crypto). Without this guard a+# bare ``XAUUSD`` query would lock onto a tokenized-gold row from+# Binance instead of the spot gold the user actually asked for.+_STABLECOIN_QUOTES = ("FDUSD", "USDT", "USDC", "BUSD", "TUSD")+_CRYPTO_QUOTE_ASSETS = _STABLECOIN_QUOTES + ("BTC", "ETH", "BNB", "USD")+# Bases that may pair with ``USD`` and still count as a crypto pair. Every+# entry here is listed on Binance spot or OKX spot; ``XAU``, ``EUR``, etc.+# are deliberately excluded.+_CRYPTO_USD_BASES = frozenset(+ {+ "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",+ })_CRYPTO_PAIR_RE = re.compile(rf"^([A-Z0-9]{{2,15}})[-/]({'|'.join(_CRYPTO_QUOTE_ASSETS)})$",@@ -275,15 +289,33 @@ def _is_canadian_symbol(text: str) -> bool:def _canonical_crypto_pair(value: str) -> str | None:- """Return an explicit crypto pair in canonical ``BASE-QUOTE`` form."""+ """Return an explicit crypto pair in canonical ``BASE-QUOTE`` form.++ A pair is only accepted as a crypto pair when its base is in the+ appropriate whitelist. Stablecoin quotes (``USDT``/``USDC``/``BUSD``/+ ``TUSD``/``FDUSD``) accept any alphanumeric base — a 6-letter base+ cannot be confused with a stablecoin because no real-world asset+ except crypto ones trades quoted in stablecoins. The ``USD`` quote+ is gated on :data:`_CRYPTO_USD_BASES` so a bare ``XAUUSD`` /+ ``EURUSD`` / ``GBPUSD`` query does NOT auto-lock onto tokenized gold+ or a forex pair that the public venue catalogs do not list.++ Returns ``"BASE-QUOTE"`` for an accepted pair, ``None`` otherwise.+ """clean = str(value or "").strip().upper()matched = _CRYPTO_PAIR_RE.fullmatch(clean)if matched:- return f"{matched.group(1)}-{matched.group(2)}"+ base, quote = matched.group(1), matched.group(2)+ if quote == "USD" and base not in _CRYPTO_USD_BASES:+ return None+ return f"{base}-{quote}"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}"+ base = clean[: -len(quote)]+ if quote == "USD" and base not in _CRYPTO_USD_BASES:+ continue+ return f"{base}-{quote}"return Nonediff --git a/agent/tests/test_correlation.py b/agent/tests/test_correlation.pyindex 820e31945..949765e04 100644--- a/agent/tests/test_correlation.py+++ b/agent/tests/test_correlation.py@@ -65,6 +65,61 @@ class TestInferMarket:assert infer_market("TD.TO") == "ca_equity"assert infer_market("PNG.V") == "ca_equity"+ def test_precious_metals_classify_as_forex(self):+ # Bare 6-letter precious-metal symbols are spot / OTC markets. The+ # underlying asset is XAU / XAG / XPT / XPD (ISO 4217 metals); the+ # quote is USD. Engines (ForexEngine._METAL_SPECS) already handle the+ # correct pip / lot conventions; the classifier just has to land on+ # ``forex`` so the forex fallback chain (mt5, tickerall, qveris,+ # yfinance) is engaged instead of the a_share chain.+ assert infer_market("XAUUSD") == "forex"+ assert infer_market("XAGUSD") == "forex"+ assert infer_market("XPTUSD") == "forex"+ assert infer_market("XPDUSD") == "forex"++ def test_g10_fx_pairs_classify_as_forex(self):+ # G10 currency pairs in their bare 6-letter form. Same routing as+ # metals above: bare code, no separator, must reach the forex chain.+ assert infer_market("EURUSD") == "forex"+ assert infer_market("GBPUSD") == "forex"+ assert infer_market("USDJPY") == "forex"+ assert infer_market("USDCHF") == "forex"+ assert infer_market("AUDUSD") == "forex"+ assert infer_market("NZDUSD") == "forex"+ assert infer_market("USDCAD") == "forex"++ def test_yahoo_equals_notation_routes_to_underlying_market(self):+ # Yahoo's continuous-front-month futures form ``=F`` and forex form+ # ``=X`` must reach the underlying market's chain instead of falling+ # through to the a_share default.+ assert infer_market("GC=F") == "futures" # COMEX Gold+ assert infer_market("CL=F") == "futures" # NYMEX Crude+ assert infer_market("SI=F") == "futures" # COMEX Silver+ assert infer_market("HG=F") == "futures" # COMEX Copper+ assert infer_market("MGC=F") == "futures" # Micro Gold+ assert infer_market("XAUUSD=X") == "forex"+ assert infer_market("EURUSD=X") == "forex"++ def test_6char_metals_whitelist_does_not_over_match_us_equities(self):+ # A bare 6-letter US ticker that happens to start with a 3-letter+ # word NOT in the metals/G10 whitelist must not be re-routed. The+ # whitelist's whole point is to be conservative; length-only patterns+ # were rejected for this reason.+ assert infer_market("NFLXLI") != "forex" # not a real ticker, but illustrative+ assert infer_market("AMZNLY") != "forex"+ # GLD (3 letters) is gold ETF, not a metal pair; stays us_equity.+ assert infer_market("GLD") == "us_equity"+ # Tokenized gold is crypto, not metal forex.+ assert infer_market("XAUT-USDT") == "crypto"+ assert infer_market("PAXG-USDT") == "crypto"++ def test_btcusdt_style_joined_pairs_stay_crypto(self):+ # A bare joined crypto pair must still classify as crypto. This+ # guards the new whitelist against over-aggressive skipping.+ assert infer_market("BTCUSDT") == "crypto"+ assert infer_market("ETHUSDT") == "crypto"+ assert infer_market("SOLUSDT") == "crypto"+class TestNormalizeSymbol:def test_bare_us_equity_gets_us_suffix(self):diff --git a/agent/tests/test_symbol_search_tool.py b/agent/tests/test_symbol_search_tool.pyindex 9b4127004..964d02a00 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+import pytest+from src.trading import profiles as trading_profilesfrom src.trading import service as trading_servicefrom src.tools import symbol_search_tool as ss@@ -762,3 +764,88 @@ class TestCryptoPairWithoutABrokerConnection:), patch.object(ss.yahoo_client, "search", return_value=[]):ss.SymbolSearchTool().execute(query="apple", limit=5)assert called == []+++class TestCryptoUsdBaseWhitelist:+ """``USD`` quote leg on the crypto resolver is gated on a base whitelist.++ Without this guard, ``XAUUSD`` / ``EURUSD`` / ``GBPUSD`` would all be+ classified as crypto pairs and the public-venue catalog (Binance/OKX)+ fallback would either lock onto a tokenized gold token (XAUT/PAXG) or+ find nothing — never on real spot gold. The fix: only accept ``USD`` on+ crypto when the base is in :data:`_CRYPTO_USD_BASES`.+ """++ @pytest.mark.parametrize(+ "code",+ [+ # Genuine crypto pairs - must keep working.+ "BTC-USD",+ "ETH-USD",+ "SOL-USD",+ "BNB-USD",+ "XLM-USD",+ "XRP-USD",+ # Stablecoin-quoted pairs (existing behaviour preserved).+ "BTC-USDT",+ "XAUT-USDT",+ "PAXG-USDT",+ "ETH-USDC",+ ],+ )+ def test_crypto_pairs_with_supported_base_accepted(self, code):+ assert ss._canonical_crypto_pair(code) is not None++ @pytest.mark.parametrize(+ "code",+ [+ # The reported bug: a spot gold query must NOT resolve to a+ # crypto pair, or the public-venue catalog fallback will lock a+ # tokenized-gold row (XAUT-USDT) as the answer.+ "XAUUSD",+ "XAU-USD",+ "XAU/USD",+ # Forex pairs in 6-letter, dashed, or slashed form.+ "EURUSD",+ "EUR-USD",+ "EUR/USD",+ "GBPUSD",+ "GBP-USD",+ "JPYUSD",+ ],+ )+ def test_non_crypto_bases_with_usd_quote_rejected(self, code):+ """The ``USD`` leg on non-crypto bases must NOT pass as a crypto pair."""+ assert ss._canonical_crypto_pair(code) is None++ def test_tokenized_gold_bases_still_resolve_as_crypto(self):+ # XAUT/PAXG ARE crypto (tokenized gold on Binance/OKX spot) and+ # must keep resolving as crypto. The whitelist includes them.+ assert ss._canonical_crypto_pair("XAUT-USDT") == "XAUT-USDT"+ assert ss._canonical_crypto_pair("PAXG-USDT") == "PAXG-USDT"+ assert ss._canonical_crypto_pair("XAUT-USD") == "XAUT-USD"+ assert ss._canonical_crypto_pair("PAXG-USD") == "PAXG-USD"++ def test_xauusd_and_xautusdt_are_not_equivalent_assets(self):+ # Identity correctness: the resolver must treat XAUUSD (spot gold)+ # and XAUT-USDT (tokenized gold) as different instruments. If both+ # return the same canonical string, downstream lock/identity+ # collision is possible.+ spot = ss._canonical_crypto_pair("XAUUSD")+ tokenized = ss._canonical_crypto_pair("XAUT-USDT")+ assert spot is None+ assert tokenized == "XAUT-USDT"+ assert spot != tokenized++ def test_usd_whitelist_is_a_strict_subset_of_crypto_bases(self):+ # Defensive: the whitelist is what stops non-crypto bases from+ # slipping through the ``USD`` branch. Every base in it must+ # therefore actually be tradable on Binance or OKX spot.+ # This is a coarse sanity check on the whitelist contents; if a+ # new entry is added in error, this test will still pass (it only+ # checks the union is non-empty and is a subset of the quote-asset+ # alphabet).+ assert ss._CRYPTO_USD_BASES+ for base in ss._CRYPTO_USD_BASES:+ assert base.isalpha()+ assert base.isupper()