"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
Rebase #1265 onto main and fix the metal/TUSD collision it introduces
aminak589d87a4d888a5
diff --git a/agent/src/agent/grounding.py b/agent/src/agent/grounding.pyindex d13969f46..8ea052796 100644--- a/agent/src/agent/grounding.py+++ b/agent/src/agent/grounding.py@@ -156,11 +156,33 @@ _GENERIC_PRICE_FIELD_ALIASES = {# Project-style canonical symbols. A bare model-generated ticker is still# checked when it appears under a symbol argument key, but it is not accepted# as user-provided identity because it lacks venue information.+#+# A joined crypto pair (``BTCUSDT``, ``ETHUSDT`` …) is recognized alongside+# the dashed/slashed form so a user message like ``Get BTCUSDT spot price``+# seeds an asserted identity and the asserted-symbol conflict check at+# ``_ingest_resolution`` runs against it. The base is restricted to alpha+# so a numeric prefix cannot masquerade as a joined pair, and the suffix+# list is the unambiguous stablecoin set (``USDT`` / ``USDC`` / ``BUSD`` /+# ``TUSD``) — ``USD`` is excluded because too many non-crypto strings end+# in those three letters and over-matching would lock the wrong identity.+_JOINED_CRYPTO_QUOTE_SUFFIXES = ("USDT", "USDC", "BUSD", "TUSD")+# Spot precious metals quoted in USD collide with the TUSD suffix: XPTUSD is+# XPT + USD (platinum), but stripping "TUSD" leaves the alpha base "XP" and+# folds it to XP-TUSD — a crypto pair that does not exist, and the same class+# of misresolution the USD exclusion above exists to prevent. XAU/XAG/XPD do+# not collide today; they are listed together because they are the same kind+# of symbol and a future suffix would collide with them the same way.+_METAL_USD_PAIR_RE = re.compile(r"^(?:XAU|XAG|XPT|XPD)USD$", re.IGNORECASE)+_JOINED_CRYPTO_RE = re.compile(+ r"(?<![A-Za-z0-9_])[A-Z]{2,15}(?:" + "|".join(_JOINED_CRYPTO_QUOTE_SUFFIXES) + r")(?![A-Za-z0-9_])",+ re.IGNORECASE,+)_CANONICAL_SYMBOL_RE = re.compile(r"(?<![A-Za-z0-9_])(?:"r"\d{3,6}\.(?:SH|SZ|BJ|SS|HK|KS|KQ)|"r"[A-Z][A-Z0-9&.-]{0,19}\.(?:US|NS|BO|FX|TO|V)|"r"[A-Z0-9]{2,15}(?:-|/)(?:USDT|USDC|USD|BTC|ETH)|"+ r"[A-Z]{2,15}(?:" + "|".join(_JOINED_CRYPTO_QUOTE_SUFFIXES) + r")|"r"\^[A-Z0-9&.\-]{1,20}|"r"[A-Z0-9]{2,15}=[FX]"r")(?![A-Za-z0-9_])",@@ -571,8 +593,10 @@ def _normalize_symbol(value: Any) -> str:Returns:The canonical spelling — uppercased, with Shanghai's ``.SS`` aliasfolded onto ``.SH``, an exchange prefix rewritten as a suffix, a Hong- Kong code zero-padded, and a crypto pair hyphenated. Text that is not a- symbol is returned uppercased and otherwise untouched.+ Kong code zero-padded, and a crypto pair hyphenated. A joined crypto+ pair with no separator (``BTCUSDT``) is rewritten as the dashed form+ (``BTC-USDT``) so every downstream check sees one identity. Text that+ is not a symbol is returned uppercased and otherwise untouched."""# A fiat/fiat pair is one FX instrument regardless of spelling: ``GBP/USD``# and ``GBPUSD`` are both ``GBPUSD=X``. Checked BEFORE the slash is@@ -592,6 +616,17 @@ def _normalize_symbol(value: Any) -> str:return f"{prefixed.group(2)}.{prefixed.group(1)}"base, dot, suffix = symbol.rpartition(".")if not dot:+ # No separator at all: rewrite a joined crypto pair (``BTCUSDT``)+ # as the dashed form so the dash/slash branch and the canonical+ # regex both match. The base must be all-alpha so a numeric prefix+ # cannot collide with another numeric-code branch downstream.+ joined = _JOINED_CRYPTO_RE.fullmatch(symbol)+ if joined and not _METAL_USD_PAIR_RE.fullmatch(symbol):+ for quote in _JOINED_CRYPTO_QUOTE_SUFFIXES:+ if symbol.endswith(quote) and len(symbol) > len(quote):+ base_part = symbol[: -len(quote)]+ if base_part.isalpha():+ return f"{base_part}-{quote}"return symbolif suffix == "SS":suffix = "SH"diff --git a/agent/tests/test_agent_grounding.py b/agent/tests/test_agent_grounding.pyindex 81a70aec6..07888d7de 100644--- a/agent/tests/test_agent_grounding.py+++ b/agent/tests/test_agent_grounding.py@@ -14,6 +14,8 @@ from src.agent.grounding import (GroundingLedger,_infer_currency,_infer_venue,+ _JOINED_CRYPTO_RE,+ _normalize_symbol,_scan_symbols,_symbol_from_csv_filename,_timestamp_matches_claim_date,@@ -363,6 +365,13 @@ def test_bare_ticker_stays_blocked_when_it_names_more_than_one_identity(("00700.HK", "700.HK"),("00700.HK", "0700.HK"),("BTC-USDT", "BTC/USDT"),+ # Joined crypto pairs (no separator) are the same identity as the+ # dashed/slashed spelling. Without this normalization, a ``BTCUSDT``+ # argument against a locked ``BTC-USDT`` is rejected as+ # ``identity_mismatch`` by ``_match_authorized_symbol``.+ ("BTC-USDT", "BTCUSDT"),+ ("ETH-USDT", "ETHUSDT"),+ ("BTC-USDC", "BTCUSDC"),],)def test_provider_spellings_of_one_instrument_are_one_identity(@@ -384,6 +393,84 @@ def test_provider_spellings_of_one_instrument_are_one_identity(assert authorization.allowed is True+ ("raw", "expected"),+ [+ # The four unambiguous stablecoin suffixes, with several bases.+ ("BTCUSDT", "BTC-USDT"),+ ("ETHUSDT", "ETH-USDT"),+ ("SOLUSDT", "SOL-USDT"),+ ("BTCUSDC", "BTC-USDC"),+ ("BTCBUSD", "BTC-BUSD"),+ ("ETHTUSD", "ETH-TUSD"),+ ("btcusdt", "BTC-USDT"), # case-insensitive+ # Edge: the suffix alone is too short to split (the base must have+ # at least one character).+ ("USDT", "USDT"),+ ("USDC", "USDC"),+ # Edge: a numeric prefix is not a crypto base.+ ("123USDT", "123USDT"),+ # Negatives: existing shapes must be untouched.+ ("BTC-USDT", "BTC-USDT"),+ ("BTC/USD", "BTC-USD"),+ ("VALOUR-BTC-0-SEK.ST", "VALOUR-BTC-0-SEK.ST"),+ ("AAPL.US", "AAPL.US"),+ ("600519.SH", "600519.SH"),+ ],+)+def test_normalize_joined_crypto_pairs(raw: str, expected: str) -> None:+ """A joined crypto pair (no separator) normalizes to its dashed form."""+ assert _normalize_symbol(raw) == expected+++ ("text", "expected"),+ [+ ("BTCUSDT", {"BTC-USDT"}),+ ("BTCUSDT spot price", {"BTC-USDT"}),+ ("ETH/USDT latest price", {"ETH-USDT"}),+ ("BTC-USDT close", {"BTC-USDT"}),+ ("BTCUSDT, ETH-USDT, BTC-USD", {"BTC-USDT", "ETH-USDT", "BTC-USD"}),+ ],+)+def test_scan_symbols_detects_joined_pairs(text: str, expected: set[str]) -> None:+ """A bare joined crypto pair is scanned as the canonical symbol."""+ assert _scan_symbols(text) == expected+++# The other arm of the same decision, pinned as two mechanisms because it is+# two mechanisms. Nothing covered either of them: adding "USD" back to the+# suffix list passed every other test in this file while folding spot gold to+# XAU-USD, the exact tokenized-gold misresolution #1282 exists to stop.+#+# 1. Bare "USD" is kept out of the suffix list, so an FX or metal pair never+# matches the joined-pair regex in the first place.[email protected]("raw", ["XAUUSD", "XAGUSD", "XPDUSD", "EURUSD", "GBPUSD"])+def test_bare_usd_quote_never_matches_the_joined_pair_regex(raw: str) -> None:+ assert _JOINED_CRYPTO_RE.fullmatch(raw) is None+ assert "-USD" not in _normalize_symbol(raw)+++# 2. XPTUSD is the case the suffix list alone cannot catch: it is XPT + USD+# (platinum), but it also ends in "TUSD", so the regex DOES match and the+# alpha base "XP" passes the isalpha guard. Without the metal-pair check it+# normalizes to XP-TUSD — a crypto pair that does not exist. FX pairs have+# canonical_fx_pair as a second line of defence; XAU/XPT are metal codes,+# not fiat codes, so they have none.+def test_metal_usd_pair_is_not_split_on_the_tusd_suffix() -> None:+ assert _JOINED_CRYPTO_RE.fullmatch("XPTUSD") is not None, (+ "precondition: the regex does match, which is why the guard is needed"+ )+ assert _normalize_symbol("XPTUSD") == "XPTUSD"+++# ...and the guard must not swallow genuine pairs quoted in TrueUSD.+def test_genuine_tusd_pairs_still_fold() -> None:+ assert _normalize_symbol("LINKTUSD") == "LINK-TUSD"+ assert _normalize_symbol("ADABUSD") == "ADA-BUSD"+ assert _normalize_symbol("OPUSDT") == "OP-USDT"++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(