"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(loaders): add Binance crypto fallback
tyj147454413-cmdb364d793e4aa
diff --git a/agent/backtest/loaders/binance_loader.py b/agent/backtest/loaders/binance_loader.pynew file mode 100644index 000000000..06cc49f89--- /dev/null+++ b/agent/backtest/loaders/binance_loader.py@@ -0,0 +1,44 @@+"""Binance spot / USD-M perpetual OHLCV loader (via CCXT).++Dedicated source name ``binance`` so it can sit **alongside** ``okx`` in the+crypto auto-fallback chain — not as a replacement. Public market data only;+no API key required.++Use explicitly with ``source="binance"``, or let ``source="auto"`` fall through+to Binance when OKX is unavailable.+"""++from __future__ import annotations++from typing import Any++from backtest.loaders.ccxt_loader import (+ _CCXT_TIMEOUT_MS,+ _ccxt_proxy_config,+)+from backtest.loaders.ccxt_loader import DataLoader as CcxtDataLoader+from backtest.loaders.registry import register+++@register+class DataLoader(CcxtDataLoader):+ """Binance-only crypto OHLCV loader (public REST via CCXT)."""++ name = "binance"+ markets = {"crypto"}+ requires_auth = False++ def _get_exchange(self, instrument_type: str = "spot") -> Any:+ """Always use Binance spot or Binance USD-M (swap), ignore CCXT_EXCHANGE."""+ import ccxt++ if instrument_type == "swap":+ exchange_cls = ccxt.binanceusdm+ else:+ exchange_cls = ccxt.binance++ config: dict[str, Any] = {"enableRateLimit": True, "timeout": _CCXT_TIMEOUT_MS}+ proxies = _ccxt_proxy_config()+ if proxies:+ config["proxies"] = proxies+ return exchange_cls(config)diff --git a/agent/backtest/loaders/registry.py b/agent/backtest/loaders/registry.pyindex 03f0f33fc..7e1c360c4 100644--- a/agent/backtest/loaders/registry.py+++ b/agent/backtest/loaders/registry.py@@ -33,6 +33,7 @@ _registered = FalseVALID_SOURCES: set[str] = {"tushare","okx",+ "binance","yfinance","akshare","baostock",@@ -80,6 +81,7 @@ def _ensure_registered() -> None:_loader_modules = ["backtest.loaders.tushare","backtest.loaders.okx",+ "backtest.loaders.binance_loader","backtest.loaders.yfinance_loader","backtest.loaders.akshare_loader","backtest.loaders.baostock_loader",@@ -132,7 +134,8 @@ FALLBACK_CHAINS: dict[str, list[str]] = {"us_equity": ["yahoo", "stooq", "sina", "eastmoney", "yfinance", "tiingo", "fmp", "finnhub", "alphavantage", "longbridge", "akshare", "local"],"hk_equity": ["eastmoney", "yahoo", "futu", "yfinance", "akshare", "longbridge", "local"],"india_equity": ["yahoo", "yfinance", "india_broker", "local"],- "crypto": ["okx", "ccxt", "yfinance", "local"],+ # OKX first (native), then dedicated Binance, then generic CCXT / Yahoo.+ "crypto": ["okx", "binance", "ccxt", "yfinance", "local"],"futures": ["tushare", "akshare", "local"],"fund": ["tushare", "akshare", "local"],"macro": ["akshare", "tushare", "local"],diff --git a/agent/src/market_data.py b/agent/src/market_data.pyindex 9538b25a9..39c6c3458 100644--- a/agent/src/market_data.py+++ b/agent/src/market_data.py@@ -86,8 +86,20 @@ def fetch_market_data(interval: str = "1D",max_rows: int = DEFAULT_MAX_ROWS,loader_resolver: Callable[[str], type] = get_loader,+ fallback_chain_provider: Callable[[str], list[str]] | None = None,+ max_fallback_attempts: int = 3,) -> dict[str, Any]:- """Fetch normalized OHLCV data through the repository loader layer."""+ """Fetch normalized OHLCV data through the repository loader layer.++ When ``source="auto"`` (or any resolved source), if the chosen loader+ raises during :meth:`fetch` the call falls through to the next source in+ the market's :data:`backtest.loaders.registry.FALLBACK_CHAINS` (e.g. crypto+ OKX → Binance → CCXT → Yahoo). At most ``max_fallback_attempts`` retries+ are attempted before the symbol is recorded as ``_unresolved``.+ """+ from backtest.loaders.base import NoAvailableSourceError+ from backtest.loaders.registry import FALLBACK_CHAINS+results: dict[str, Any] = {}if source == "auto":@@ -98,18 +110,63 @@ def fetch_market_data(else:groups = {source: list(codes)}+ def _chain_for(src: str) -> list[str]:+ """Return the ordered fallback chain for the market containing ``src``.++ Falls back to ``[src]`` so an explicit source outside any chain still+ gets at least one attempt.+ """+ if fallback_chain_provider is not None:+ return fallback_chain_provider(src)+ for market, chain in FALLBACK_CHAINS.items():+ if src in chain:+ return chain+ return [src]+for src, src_codes in groups.items():- loader_cls = loader_resolver(src)- loader = loader_cls()- try:- data_map = loader.fetch(src_codes, start_date, end_date, interval=interval)- except Exception:- logger.exception(- "market-data loader %r failed for %s; codes fall through to _unresolved",- src,- src_codes,+ chain = _chain_for(src)+ # Start the attempt list with the requested source, then the rest of+ # the chain (preserving order, no duplicates).+ attempts: list[str] = []+ for candidate in [src, *chain]:+ if candidate not in attempts:+ attempts.append(candidate)+ attempts = attempts[: max(1, max_fallback_attempts)]++ data_map: dict[str, Any] = {}+ used_source: str | None = None+ last_exc: Exception | None = None+ for attempt_src in attempts:+ try:+ loader_cls = loader_resolver(attempt_src)+ except NoAvailableSourceError as exc:+ last_exc = exc+ logger.debug("loader %r unavailable: %s", attempt_src, exc)+ continue+ except Exception as exc: # noqa: BLE001 — resolver may raise for non-network reasons+ last_exc = exc+ logger.debug("loader %r resolver failed: %s", attempt_src, exc)+ continue+ try:+ loader = loader_cls()+ data_map = loader.fetch(src_codes, start_date, end_date, interval=interval)+ used_source = attempt_src+ if data_map:+ break+ except Exception as exc: # noqa: BLE001 — contained per-symbol fallback+ last_exc = exc+ logger.error(+ "market-data loader %r failed for %s; trying next source in chain: %s",+ attempt_src, src_codes, exc,+ )+ continue++ if used_source and used_source != src:+ logger.info(+ "market-data source %r unavailable for %s; fell back to %r",+ src, src_codes, used_source,)- data_map = {}+for symbol, df in data_map.items():records = df.reset_index().to_dict(orient="records")for row in records:diff --git a/agent/tests/test_binance_fallback.py b/agent/tests/test_binance_fallback.pynew file mode 100644index 000000000..2c4c8f044--- /dev/null+++ b/agent/tests/test_binance_fallback.py@@ -0,0 +1,41 @@+"""Regression coverage for the dedicated Binance crypto fallback."""++from __future__ import annotations++import pandas as pd++from backtest.loaders.registry import FALLBACK_CHAINS+from src import market_data+++def test_market_data_falls_back_from_okx_to_binance() -> None:+ calls: list[str] = []++ def resolver(source: str):+ calls.append(source)++ class FailedLoader:+ def fetch(self, *_args, **_kwargs):+ raise RuntimeError(f"{source} unavailable")++ class BinanceLoader:+ def fetch(self, codes, *_args, **_kwargs):+ frame = pd.DataFrame(+ {"close": [1.0]}, index=pd.to_datetime(["2026-01-01"])+ )+ frame.index.name = "trade_date"+ return {codes[0]: frame}++ return BinanceLoader if source == "binance" else FailedLoader++ result = market_data.fetch_market_data(+ codes=["BTC-USDT"],+ start_date="2026-01-01",+ end_date="2026-01-02",+ source="okx",+ loader_resolver=resolver,+ fallback_chain_provider=lambda _source: FALLBACK_CHAINS["crypto"],+ )++ assert calls[:2] == ["okx", "binance"]+ assert "BTC-USDT" in resultdiff --git a/agent/tests/test_registry.py b/agent/tests/test_registry.pyindex 0269bc003..84ff8c68c 100644--- a/agent/tests/test_registry.py+++ b/agent/tests/test_registry.py@@ -140,10 +140,10 @@ class TestFallbackChains:assert len(chain) > 0, f"Fallback chain for {market} is empty"def test_crypto_chain_includes_yfinance_fallback(self) -> None:- """yfinance is the third-tier fallback for crypto when OKX and CCXT fail."""+ """yfinance is a fallback for crypto when OKX, Binance and CCXT fail."""assert "yfinance" in FALLBACK_CHAINS["crypto"]- # OKX and CCXT should still be preferred- assert FALLBACK_CHAINS["crypto"][:2] == ["okx", "ccxt"]+ # OKX, Binance and CCXT should be preferred in that order+ assert FALLBACK_CHAINS["crypto"][:3] == ["okx", "binance", "ccxt"]def test_chains_ordered_by_ip_ban_risk(self) -> None:"""Equity chains lead with throttle-tolerant public sources and trail@@ -173,7 +173,7 @@ class TestFallbackChains:def test_unchanged_chains_preserved(self) -> None:"""crypto/futures/fund/macro/forex chains must be left untouched."""- assert FALLBACK_CHAINS["crypto"] == ["okx", "ccxt", "yfinance", "local"]+ assert FALLBACK_CHAINS["crypto"] == ["okx", "binance", "ccxt", "yfinance", "local"]assert FALLBACK_CHAINS["futures"] == ["tushare", "akshare", "local"]assert FALLBACK_CHAINS["fund"] == ["tushare", "akshare", "local"]assert FALLBACK_CHAINS["macro"] == ["akshare", "tushare", "local"]@@ -194,6 +194,12 @@ class TestValidSources:}assert new_sources <= VALID_SOURCES+ def test_includes_binance(self) -> None:+ """Binance was added as a dedicated crypto source alongside OKX so the+ market_data fallback chain can fall through without aliasing CCXT. A+ config with ``source: binance`` must validate against VALID_SOURCES."""+ assert "binance" in VALID_SOURCES+def test_covers_all_registered_loaders(self) -> None:"""Every registered loader name must be an accepted config source so anew loader can never be silently rejected by config validation."""