Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(loaders): add tickerall hosted MetaTrader 5 data source

miguelangelo786d1f398bd717
diff --git a/README.md b/README.md
index 3aa58dfde..47a408242 100644
--- a/README.md
+++ b/README.md
@@ -358,6 +358,7 @@ One `get_market_data` call, **23 free market-data sources** (plus the optional *
| `okx` · `ccxt` · `binance` | crypto | none | OKX + 100+ exchanges + Binance historical / USD-M perps |
| `futu` | HK / A | OpenD | optional local FutuOpenD |
| `mt5` | forex / metals | MT5 terminal | MetaTrader 5 (Exness-style) forex / metal bars, 1m–1D |
+| `tickerall` | forex / metals | key + account (read-only) | same broker MT5 feed, **hosted** — no local terminal, any OS (explicit-only, never in auto fallback) |
| `pykrx` | Korea (KRX: KOSPI/KOSDAQ) | none | daily KOSPI / KOSDAQ bars for `.KS` / `.KQ` (optional `krx` extra) |
| `india_broker` | India (NSE/BSE) | broker login | read-only Shoonya / Dhan bars for `.NS` / `.BO` (fallback-chain tail) |
| `local` | any | none | your own CSV / Parquet / DuckDB via `local:` prefix |
@@ -568,7 +569,7 @@ Run `vibe-trading alpha list` to browse, `vibe-trading alpha show <id>` for form
| **KoreaEquity** | Korea (KRX: KOSPI/KOSDAQ) | long-only, ±30% band judged at execution time on the unified tick grid, 2026 0.20% transaction tax |
| **Crypto** | crypto spot / USD-M perps | funding settlements, execution/mark split |
| **ChinaFutures** · **GlobalFutures** | futures | margin, contract multipliers |
-| **Forex** | FX / metals | via the `mt5` loader |
+| **Forex** | FX / metals | via the `mt5` loader (local terminal) or the hosted `tickerall` loader (no terminal, any OS) |
| **Composite** | cross-market | one shared capital pool across markets (`source="auto"`) |
| **options_portfolio** | options | multi-leg, Greeks, payoff/scenario |
diff --git a/agent/.env.example b/agent/.env.example
index e844e6e3c..08de7b415 100644
--- a/agent/.env.example
+++ b/agent/.env.example
@@ -176,10 +176,13 @@ TUSHARE_TOKEN=your-tushare-token
# ALPHAVANTAGE_API_KEY=xxx # optional US-equity OHLCV fallback provider (selectable get_market_data source)
# TIINGO_API_KEY=xxx # optional US-equity OHLCV fallback provider (selectable get_market_data source)
# FMP_API_KEY=xxx # optional US-equity OHLCV fallback provider (selectable get_market_data source)
+# TICKERALL_API_KEY=xxx # optional hosted MetaTrader 5 forex/metals feed — EXPLICIT source="tickerall" only, never an automatic fallback (no local terminal; https://tickerall.com)
+# TICKERALL_ACCOUNT_ID=xxx # required alongside the key: history is served per connected broker account (read-only)
+# TICKERALL_BASE_URL=xxx # optional endpoint override (defaults to the public API)
# FRED_API_KEY=xxx # macro series (get_macro_series tool)
# VIBE_TRADING_IWENCAI_KEY=xxx # A-share natural-language research search (iwencai_search tool)
# VIBE_TRADING_SEC_UA="Your Name [email protected]" # SEC EDGAR compliant contact User-Agent (optional; a built-in default UA also works)
-# Optional per-source request-spacing overrides for batch jobs — VIBE_TRADING_{EASTMONEY,SINA,STOOQ,YAHOO,SEC,FINNHUB,ALPHAVANTAGE,TIINGO,FMP,FRED,IWENCAI,THS}_MIN_INTERVAL (seconds).
+# Optional per-source request-spacing overrides for batch jobs — VIBE_TRADING_{EASTMONEY,SINA,STOOQ,YAHOO,SEC,FINNHUB,ALPHAVANTAGE,TIINGO,FMP,TICKERALL,FRED,IWENCAI,THS}_MIN_INTERVAL (seconds).
# OCR engine for scanned PDF pages and images (auto by default).
# auto — local engines only (privacy: never sends pages to cloud)
diff --git a/agent/SKILL.md b/agent/SKILL.md
index a6c8a6d24..c9333feb4 100644
--- a/agent/SKILL.md
+++ b/agent/SKILL.md
@@ -1,7 +1,7 @@
---
name: vibe-trading
version: 0.1.13
-description: Professional finance research toolkit — backtesting (9 engines + benchmark comparison panel), factor analysis, Alpha Zoo (462 pre-built alphas across qlib158/alpha101/gtja191/academic/fundamental), options pricing, 89 finance skills, 30 multi-agent swarm teams, Trade Journal analyzer, and Shadow Account (extract → backtest → render) across 24 market-data sources (tushare, yfinance, okx, binance, akshare, baostock, tencent, mootdx, ccxt, futu, mt5, local, eastmoney, sina, stooq, yahoo, pykrx, india_broker, qveris, longbridge, plus optional-key finnhub/alphavantage/tiingo/fmp).
+description: Professional finance research toolkit — backtesting (9 engines + benchmark comparison panel), factor analysis, Alpha Zoo (462 pre-built alphas across qlib158/alpha101/gtja191/academic/fundamental), options pricing, 89 finance skills, 30 multi-agent swarm teams, Trade Journal analyzer, and Shadow Account (extract → backtest → render) across 25 market-data sources (tushare, yfinance, okx, binance, akshare, baostock, tencent, mootdx, ccxt, futu, mt5, tickerall, local, eastmoney, sina, stooq, yahoo, pykrx, india_broker, qveris, longbridge, plus optional-key finnhub/alphavantage/tiingo/fmp).
dependencies:
python: ">=3.11,<3.14"
pip:
@@ -74,7 +74,7 @@ Feed a CSV broker export (同花顺 / 东财 / 富途 / generic), and the agent
5. `scan_shadow_signals` — list today's symbols that match your shadow's entry cadence (research only).
### Backtesting
-Create and run quantitative strategies across 9 engines (ChinaA, GlobalEquity, IndiaEquity, KoreaEquity, Crypto, ChinaFutures, GlobalFutures, Forex + options) with 24 market-data sources (auto-detect + ordered fallback):
+Create and run quantitative strategies across 9 engines (ChinaA, GlobalEquity, IndiaEquity, KoreaEquity, Crypto, ChinaFutures, GlobalFutures, Forex + options) with 25 market-data sources (auto-detect + ordered fallback; the hosted forex `tickerall` source is explicit-only):
- **HK/US equities** via yfinance / stooq / yahoo (free, no API key); optionally via **Longbridge** historical OHLCV (`longbridge`, requires the optional SDK and `LONGBRIDGE_APP_KEY` / `LONGBRIDGE_APP_SECRET` / `LONGBRIDGE_ACCESS_TOKEN`). To force it for a run, set `"source": "longbridge"` in `config.json`.
- **Canada equities (TSX/TSXV)** via yahoo / yfinance using Yahoo's canonical `<TICKER>.TO` (TSX, e.g. `TD.TO`) or `<TICKER>.V` (TSXV, e.g. `PNG.V`) suffixes — free, no API key. The GlobalEquity engine uses CAD identity, whole-share orders, configurable Canadian commission/slippage, and the TSX/TSXV price-increment grid.
- **India equities (NSE/BSE)** via yahoo / yfinance using `<SYMBOL>.NS` (NSE, e.g. `RELIANCE.NS`) or `<SCRIP>.BO` (BSE, e.g. `500325.BO`) — free, no API key. The `IndiaEquityEngine` models T+1 delivery, no overnight shorts (set `allow_short` for intraday), configurable circuit bands, 1-share lots, and the STT/stamp-duty/exchange/GST cost stack. Optionally back-fill from your live broker via the `india_broker` source (Shoonya/Dhan; requires broker login).
@@ -82,6 +82,7 @@ Create and run quantitative strategies across 9 engines (ChinaA, GlobalEquity, I
- **Cryptocurrency** via OKX or CCXT/100+ exchanges (free, no API key)
- **China A-shares** via AKShare / baostock / tencent / sina / eastmoney / mootdx (free, no API key) — `TUSHARE_TOKEN` optional for premium quality
- **Futures, forex, macro** via AKShare (free, no API key)
+- **Forex / metals with no local terminal** via the hosted **TickerAll** MetaTrader 5 feed (`source="tickerall"`, `TICKERALL_API_KEY` + `TICKERALL_ACCOUNT_ID`, read-only) — the same broker feed as the `mt5` loader but over a hosted API on any OS. **Explicit-only** (never an automatic fallback).
- **HK & A-share equities** via Futu (broker login required, optional)
- **Local CSV/parquet bars** via the `local` loader (offline, no network)
- **Premium cross-market data** via QVeris (optional API key)
@@ -148,7 +149,7 @@ Use `load_skill(name)` to access full methodology docs with code templates.
| `analyze_options` | Black-Scholes price + Greeks | None |
| `analyze_options_payoff` | Multi-leg expiry payoff + spot/IV scenarios | None |
| `pattern_recognition` | Detect chart patterns (H&S, double top, etc.) | None |
-| `get_market_data` | Fetch OHLCV data (auto-detect + ordered fallback across 24 sources) | None* |
+| `get_market_data` | Fetch OHLCV data (auto-detect + ordered fallback across 25 sources) | None* |
| `get_fund_flow` | Capital fund-flow (main/retail net inflow) | None* |
| `get_dragon_tiger` | Dragon-tiger list (龙虎榜) top buyer/seller seats | None* |
| `get_northbound_flow` | Northbound (Stock Connect) net flow | None* |
diff --git a/agent/backtest/loaders/registry.py b/agent/backtest/loaders/registry.py
index 1dcb00aa5..1bdcf284e 100644
--- a/agent/backtest/loaders/registry.py
+++ b/agent/backtest/loaders/registry.py
@@ -54,6 +54,7 @@ VALID_SOURCES: set[str] = {
"pykrx",
"longbridge",
"mt5",
+ "tickerall",
"local",
"auto",
}
@@ -104,6 +105,7 @@ def _ensure_registered() -> None:
"backtest.loaders.pykrx_loader",
"backtest.loaders.longbridge",
"backtest.loaders.mt5_loader",
+ "backtest.loaders.tickerall_loader",
"backtest.loaders.local_loader",
]
import importlib
@@ -121,7 +123,8 @@ def _ensure_registered() -> None:
# unavailable ``local`` request can degrade into an unrelated network source.
# An explicit ``local`` request that is unavailable is a config problem the user
# must see, not something to paper over with a Yahoo/Tencent fetch.
-_NO_NETWORK_FALLBACK_SOURCES: frozenset[str] = frozenset({"local", "qveris"}) # QVERIS-INTEGRATION
+# ``tickerall`` joins for the same reason (explicit-only, the user's own broker key).
+_NO_NETWORK_FALLBACK_SOURCES: frozenset[str] = frozenset({"local", "qveris", "tickerall"}) # QVERIS-INTEGRATION
# ---------------------------------------------------------------------------
@@ -224,11 +227,15 @@ def get_loader_cls_with_fallback(source: str) -> Type[Any]:
# auto-resolver, so falling back through it would fetch network data the
# user never asked for and mask a Data Bridge config problem. Fail loudly.
if source in _NO_NETWORK_FALLBACK_SOURCES:
+ hint = {
+ "local": "Check your Data Bridge config "
+ "(~/.vibe-trading/data-bridge/config.yaml) — it must exist and "
+ "list at least one source.",
+ "tickerall": "Set TICKERALL_API_KEY and TICKERALL_ACCOUNT_ID.",
+ }.get(source, "")
raise NoAvailableSourceError(
f"Data source '{source}' is unavailable and does not fall back to a "
- f"network source. Check your local Data Bridge config "
- f"(~/.vibe-trading/data-bridge/config.yaml) — it must exist and list "
- f"at least one source."
+ f"network source. {hint}".rstrip()
)
# Source unavailable — try same-market fallback
diff --git a/agent/backtest/loaders/tickerall_loader.py b/agent/backtest/loaders/tickerall_loader.py
new file mode 100644
index 000000000..ef3abcce1
--- /dev/null
+++ b/agent/backtest/loaders/tickerall_loader.py
@@ -0,0 +1,457 @@
+"""TickerAll hosted MetaTrader 5 data loader - forex/metals/CFD OHLCV over HTTP.
+
+TickerAll (https://tickerall.com) is a hosted MetaTrader 5 API: it serves a
+broker account's own candle history over REST, so backtests can pull forex,
+metals, and index/CFD bars with the broker's exact symbols and session times
+WITHOUT a local MetaTrader 5 terminal - no Windows, no Wine, no VM. It
+complements the ``mt5`` loader (which needs a running, logged-in local terminal)
+by covering the same forex market from any operating system.
+
+Selection (opt-in, EXPLICIT-only): this loader is NOT part of any automatic
+fallback chain. It runs only when a backtest names ``source="tickerall"``
+explicitly, and only when ``TICKERALL_API_KEY`` and ``TICKERALL_ACCOUNT_ID`` are
+configured (an account id is required because history is served per connected
+account). When either is unset, :meth:`DataLoader.is_available` is ``False``.
+``TICKERALL_BASE_URL`` overrides the endpoint (defaults to the public API). Never
+joining the automatic chain keeps a user's own broker credential off the default
+path: it is used only when the operator deliberately asks for it.
+
+Read-only USAGE, not a read-only credential: every request here is an HTTP
+**GET** to ``/candles`` / ``/symbols`` for the configured account - no trade or
+mutation path exists in this module. A full TickerAll key can reach multiple
+accounts and place orders, so for a backtest provision a dedicated **read-only**
+key (the "Read-only" option in the TickerAll dashboard) - it reads data but the
+server rejects any trade or account mutation on it.
+
+API format (Bearer-authenticated), date-range mode:
+ ``GET {base}/v1/accounts/{account_id}/candles?symbol=SYM&from=ISO&to=ISO&timeframe=TF``
+returns ``{candles: [{timestamp, open, high, low, close, tickVolume}, ...],
+truncated: bool, coverage: "complete"|..., stopReason: str, ...}`` with
+``timestamp`` in epoch seconds. The endpoint answers the exact ``[from, to]``
+window and reports whether it could serve the whole of it. **A partial answer is
+an error, not a silently short series** - and the endpoint signals incompleteness
+two ways, BOTH of which raise :class:`IncompleteHistoryError` (so the caller narrows
+the range rather than backtesting on a quietly-clipped series):
+ (a) a served (200) response flagged ``truncated`` (the history walk stopped early);
+ (b) a 400 ``{"error": "range_too_large", "maxWindowDays", "maxBars"}`` when the
+ requested window is wider than one request may carry (e.g. > ~5 years of daily
+ bars). Without (b) this 400 would be swallowed as a skipped symbol - the exact
+ silent-truncation this loader must avoid.
+
+Broker account-type suffixes (e.g. Exness ``EURUSDm``) are resolved from the
+account's own symbol list (fetched once and memoized per ``(base_url, account)``),
+so callers pass plain codes (``EURUSD``, ``EUR/USD``) and results are keyed by
+the ORIGINAL input code.
+
+Every request routes through :mod:`backtest.loaders._http` so calls share one
+process-wide minimum-spacing gate and a reused session.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any, Dict, List, Optional, Tuple
+
+import pandas as pd
+
+from backtest.loaders._http import resolve_min_interval, throttled_get_json
+from backtest.loaders.base import cached_loader_fetch, validate_date_range
+from backtest.loaders.registry import register
+
+logger = logging.getLogger(__name__)
+
+_API_KEY_ENV = "TICKERALL_API_KEY"
+_ACCOUNT_ENV = "TICKERALL_ACCOUNT_ID"
+_DEFAULT_BASE_URL = "https://api.tickerall.com"
+
+# Shared throttle/session bucket for every TickerAll request in this process.
+_HOST_KEY = "tickerall"
+_MIN_INTERVAL_ENV = "VIBE_TRADING_TICKERALL_MIN_INTERVAL"
+_DEFAULT_MIN_INTERVAL_S = 0.25
+
+#: The candles endpoint runs a deep-history walk for a multi-year window, which can
+#: take well over the shared 15s default. Give it room: a too-short read timeout would
+#: otherwise surface as a swallowed per-symbol skip (a silent gap) on a large window -
+#: exactly the quiet-failure this loader is meant to avoid.
+_CANDLES_TIMEOUT_S = 90.0
+
+#: Project interval token → TickerAll timeframe token. Lowercase ``1h``/``4h``/
+#: ``1d``/``1w`` alias the project-style tokens; ``1m`` (minute) and ``1M``
+#: (month) differ by case, matching the ``mt5`` loader.
+_INTERVAL_MAP = {
+ "1m": "M1", "5m": "M5", "15m": "M15", "30m": "M30",
+ "1H": "H1", "1h": "H1", "4H": "H4", "4h": "H4",
+ "1D": "D1", "1d": "D1", "1W": "W1", "1w": "W1", "1M": "MN1",
+}
+
+# TickerAll candles carry these numeric fields; emitted in this column order.
+_OHLCV_FIELDS = ("open", "high", "low", "close", "volume")
+
+#: (base_url, account_id) → broker symbol names memo (mt5 ``symbols_get`` parity).
+#: Keyed by BOTH base URL and account so two accounts - or the same account id on
+#: a different endpoint (staging vs prod) - never share a resolution.
+_symbol_cache: Dict[Tuple[str, str], List[str]] = {}
+
+
+class IncompleteHistoryError(RuntimeError):
+ """The API could not serve the whole requested window (a partial/truncated walk).
+
+ Raised instead of returning a silently-short series, so a backtest fails
+ loudly and the caller can narrow the date range or lower the timeframe.
+ """
+
+
+def _api_key() -> str:
+ """Return the TickerAll API key from config, stripped (``""`` if unset)."""
+ from src.config.accessor import get_env_config
+
+ return get_env_config().data.tickerall_api_key.strip()
+
+
+def _account_id() -> str:
+ """Return the configured TickerAll account id, stripped (``""`` if unset)."""
+ from src.config.accessor import get_env_config
+
+ return get_env_config().data.tickerall_account_id.strip()
+
+
+def _base_url() -> str:
+ """Return the API base URL (config override or the public default), no trailing slash."""
+ from src.config.accessor import get_env_config
+
+ raw = (get_env_config().data.tickerall_base_url or "").strip()
+ return (raw or _DEFAULT_BASE_URL).rstrip("/")
+
+
+def _min_interval() -> float:
+ """Resolve the per-call minimum spacing, honoring the env override."""
+ return resolve_min_interval(_MIN_INTERVAL_ENV, _DEFAULT_MIN_INTERVAL_S)
+
+
+def _auth_headers(api_key: str) -> Dict[str, str]:
+ """Bearer auth headers for the hosted API."""
+ return {"Authorization": f"Bearer {api_key}", "Accept": "application/json"}
+
+
+def _to_query_base(code: str) -> str:
+ """``EUR/USD`` / ``EURUSD.FX`` → ``EURUSD`` (upper, separators stripped)."""
+ token = code.strip().upper()
+ if token.endswith(".FX"):
+ token = token[: -len(".FX")]
+ for separator in ("/", "-", "_", " "):
+ token = token.replace(separator, "")
+ return token
+
+
+def _resolve_symbol(base: str, account_id: str, api_key: str) -> str:
+ """Map a base symbol to the account's exact broker symbol (Exness ``EURUSDm``).
+
+ Mirrors mt5's ``symbols_get(f"{base}*")`` resolution against the account's
+ memoized symbol list: an exact normalized match first, else a normalized
+ prefix match, shortest broker name winning (so ``EURUSDm`` beats ``EURUSDz``).
+ Falls back to ``base`` when the list is unavailable or has no match.
+ """
+ names = _account_symbols(account_id, api_key)
+ if not names:
+ return base
+ exact = [n for n in names if _to_query_base(n) == base]
+ if exact:
+ return min(exact, key=lambda n: (len(n), n))
+ prefixed = [n for n in names if _to_query_base(n).startswith(base)]
+ if prefixed:
+ return min(prefixed, key=lambda n: (len(n), n))
+ return base
+
+
+def _account_symbols(account_id: str, api_key: str) -> List[str]:
+ """Broker symbol names for one account, fetched once and memoized ([] on failure).
+
+ Memoized per ``(base_url, account_id)`` so the same account id on two
+ endpoints - or two accounts - never share a resolution.
+ """
+ base = _base_url()
+ cache_key = (base, account_id)
+ cached = _symbol_cache.get(cache_key)
+ if cached is not None:
+ return cached
+ try:
+ payload = throttled_get_json(
+ f"{base}/v1/accounts/{account_id}/symbols",
+ host_key=_HOST_KEY,
+ min_interval=_min_interval(),
+ headers=_auth_headers(api_key),
+ )
+ names = _symbol_names(payload)
+ except Exception as exc: # noqa: BLE001 - symbol resolution is best-effort
+ logger.debug("tickerall: symbol list unavailable: %s", exc)
+ names = []
+ _symbol_cache[cache_key] = names
+ return names
+
+
+def _symbol_names(payload: Any) -> List[str]:
+ """Extract symbol name strings from a /symbols body (array or {symbols|data})."""
+ items = payload
+ if isinstance(payload, dict):
+ items = payload.get("symbols") or payload.get("data") or []
+ names: List[str] = []
+ for item in items or []:
+ if isinstance(item, str):
+ names.append(item)
+ elif isinstance(item, dict):
+ name = item.get("symbol") or item.get("name")
+ if isinstance(name, str):
+ names.append(name)
+ return names
+
+
+@register
+class DataLoader:
+ """TickerAll hosted-MT5 forex/metals OHLCV loader (key-gated, HTTP, no terminal)."""
+
+ name = "tickerall"
+ markets = {"forex"}
+ #: The hosted API key + account id are the auth surface (fmp/mt5 precedent).
+ requires_auth = True
+
+ def __init__(self) -> None: # never raises - registry availability contract
+ pass
+
+ def is_available(self) -> bool:
+ """Available when both ``TICKERALL_API_KEY`` and ``TICKERALL_ACCOUNT_ID`` are set."""
+ return bool(_api_key() and _account_id())
+
+ def fetch(
+ self,
+ codes: List[str],
+ start_date: str,
+ end_date: str,
+ *,
+ interval: str = "1D",
+ fields: Optional[List[str]] = None,
+ ) -> Dict[str, pd.DataFrame]:
+ """Fetch OHLCV frames keyed by the original input codes.
+
+ A transient per-symbol failure (network blip, one bad symbol) logs and
+ skips so it never poisons the batch. An :class:`IncompleteHistoryError`
+ (the API served only part of the requested window) is NOT swallowed - it
+ propagates so the backtest fails loudly instead of running on a quietly
+ clipped series.
+
+ Args:
+ codes: Project symbols (e.g. ``["EURUSD", "XAUUSD"]``).
+ start_date: Inclusive start date, ``YYYY-MM-DD``.
+ end_date: Inclusive end date, ``YYYY-MM-DD``.
+ interval: Bar size token (``1m``/``5m``/``15m``/``30m``/``1H``/``4H``/
+ ``1D``/``1W``/``1M``); unknown tokens are rejected.
+ fields: Ignored - the API returns a fixed OHLCV schema.
+
+ Returns:
+ Mapping ``{symbol: DataFrame(trade_date, open, high, low, close,
+ volume)}`` for every symbol with data. ``volume`` is the bar's
+ ``tickVolume``, NaN when absent (e.g. bid-only deep-history bars).
+
+ Raises:
+ ValueError: If ``start_date`` > ``end_date`` (via
+ :func:`validate_date_range`).
+ IncompleteHistoryError: If the API could not serve the whole
+ requested window for a symbol (truncated / partial coverage).
+ """
+ validate_date_range(start_date, end_date)
+ timeframe = _INTERVAL_MAP.get(str(interval).strip())
+ if timeframe is None:
+ # Reject unknown tokens; do not silently fetch D1 under the caller's key.
+ logger.warning("tickerall unsupported interval %r; rejecting", interval)
+ return {}
+ if not self.is_available():
+ logger.warning("tickerall fetch skipped: %s / %s not set", _API_KEY_ENV, _ACCOUNT_ENV)
+ return {}
+
+ # Cache identity = account id + the FULL base URL (scheme+host+path), so two
+ # accounts, or one account on two endpoints that share a host but not a path
+ # (.../a vs .../b), never collide (the on-disk key hashes these).
+ account_id = _account_id()
+ cache_scope = f"{account_id}@{_base_url()}"
+
+ result: Dict[str, pd.DataFrame] = {}
+ for code in codes:
+ clean = code.strip()
+ if not clean:
+ continue
+ try:
+ frame = cached_loader_fetch(
+ source=self.name,
+ symbol=f"{cache_scope}:{_to_query_base(clean)}",
+ timeframe=interval,
+ start_date=start_date,
+ end_date=end_date,
+ fields=None,
+ fetch=lambda c=clean: self._fetch_one(c, start_date, end_date, timeframe),
+ )
+ except IncompleteHistoryError:
+ # A partial window is a hard error - fail loud, never a short series.
+ raise
+ except Exception as exc: # noqa: BLE001 - one symbol never poisons the batch
+ logger.warning("tickerall failed for %s: %s", clean, exc)
+ continue
+ if frame is not None and not frame.empty:
+ result[code] = frame
+ return result
+
+ def _fetch_one(
+ self, code: str, start_date: str, end_date: str, timeframe: str
+ ) -> Optional[pd.DataFrame]:
+ """Fetch and parse one symbol's bars over HTTP; ``None`` on no data.
+
+ Uses the endpoint's exact date-range mode (``from``/``to``) and honors its
+ completeness signal: a truncated/partial answer raises
+ :class:`IncompleteHistoryError` rather than returning a short frame.
+ """
+ api_key = _api_key()
+ account_id = _account_id()
+ if not (api_key and account_id):
+ return None
+ symbol = _resolve_symbol(_to_query_base(code), account_id, api_key)
+ if not symbol:
+ return None
+ try:
+ payload = throttled_get_json(
+ f"{_base_url()}/v1/accounts/{account_id}/candles",
+ host_key=_HOST_KEY,
+ min_interval=_min_interval(),
+ headers=_auth_headers(api_key),
+ params={
+ "symbol": symbol,
+ "from": f"{start_date}T00:00:00Z",
+ "to": f"{end_date}T23:59:59Z",
+ "timeframe": timeframe,
+ },
+ timeout=_CANDLES_TIMEOUT_S,
+ )
+ except Exception as exc: # noqa: BLE001 - inspected, then re-raised
+ # A 'range_too_large' 400 = the window is wider than one request may carry;
+ # that is INCOMPLETE history, so surface it loudly instead of letting the
+ # batch loop swallow it as a skipped symbol. Anything else propagates.
+ _reraise_if_range_too_large(exc, symbol, start_date, end_date)
+ raise
+ _raise_if_incomplete(payload, symbol, start_date, end_date)
+ return _parse_candles(payload, start_date, end_date)
+
+
+def _reraise_if_range_too_large(exc: Exception, symbol: str, start_date: str, end_date: str) -> None:
+ """Convert the endpoint's ``range_too_large`` 400 into :class:`IncompleteHistoryError`.
+
+ A window wider than the endpoint's per-request limit is rejected up front with
+ HTTP 400 ``{"error": "range_too_large", "maxWindowDays": N, "maxBars": M}`` (NOT a
+ 200 with ``truncated``). That is the caller asking for more history than one
+ request can carry - an incomplete answer - so it must fail loudly rather than be
+ swallowed as a transient per-symbol skip. Any other error is left to propagate
+ unchanged (the batch loop then skips just that symbol). Duck-typed on ``.response``
+ so the loader needs no ``requests`` import.
+ """
+ resp = getattr(exc, "response", None)
+ if resp is None or getattr(resp, "status_code", None) != 400:
+ return
+ try:
+ body = resp.json()
+ except Exception: # noqa: BLE001 - a non-JSON 400 is not our signal
+ return
+ if not isinstance(body, dict) or body.get("error") != "range_too_large":
+ return
+ raise IncompleteHistoryError(
+ f"tickerall: the requested window for {symbol} [{start_date}, {end_date}] exceeds the "
+ f"API's per-request limit (max {body.get('maxWindowDays')} days / {body.get('maxBars')} bars); "
+ f"narrow the date range or use a coarser timeframe"
+ ) from exc
+
+
+def _raise_if_incomplete(payload: Any, symbol: str, start_date: str, end_date: str) -> None:
+ """Raise :class:`IncompleteHistoryError` when a 200 response is short of the window.
+
+ A served response reports ``truncated`` (the walk could not cover the range) and a
+ ``coverage`` string; either non-complete means a short answer, ``stopReason`` says why.
+ A response carrying candles but NEITHER signal cannot be verified as complete, so it is
+ rejected rather than trusted - a 2-bar answer to a 6-year request is not silently
+ accepted. The 400 ``range_too_large`` path is handled by :func:`_reraise_if_range_too_large`.
+ """
+ if not isinstance(payload, dict):
+ return
+ has_candles = bool(payload.get("candles") or payload.get("data"))
+ if has_candles and "truncated" not in payload and "coverage" not in payload:
+ raise IncompleteHistoryError(
+ f"tickerall: candles for {symbol} over [{start_date}, {end_date}] carried no "
+ f"completeness signal (truncated/coverage); cannot confirm the full window was served"
+ )
+ truncated = bool(payload.get("truncated"))
+ coverage = payload.get("coverage")
+ incomplete_coverage = isinstance(coverage, str) and coverage not in ("complete", "full")
+ if not (truncated or incomplete_coverage):
+ return
+ reason = payload.get("stopReason") or ("partial" if incomplete_coverage else "truncated")
+ raise IncompleteHistoryError(
+ f"tickerall: incomplete history for {symbol} over [{start_date}, {end_date}] "
+ f"(stopReason={reason}); narrow the date range or use a coarser timeframe"
+ )
+
+
+def _parse_candles(
+ payload: Any, start_date: str, end_date: str
+) -> Optional[pd.DataFrame]:
+ """Convert a TickerAll candles body into an ascending OHLCV frame, trimmed to the window.
+
+ Args:
+ payload: Decoded JSON body (a list, or ``{candles|data: [...]}``) where
+ each bar has ``timestamp`` (epoch seconds) plus ``open/high/low/close``
+ and ``volume`` or ``tickVolume``.
+ start_date: Inclusive window start, ``YYYY-MM-DD``.
+ end_date: Inclusive window end, ``YYYY-MM-DD``.
+
+ Returns:
+ DataFrame indexed by ``trade_date`` with float ``open/high/low/close/
+ volume`` columns, or ``None`` when no usable in-window rows are present.
+ """
+ items = payload
+ if isinstance(payload, dict):
+ items = payload.get("candles") or payload.get("data") or []
+ if not items:
+ return None
+
+ rows = []
+ for bar in items:
+ if not isinstance(bar, dict) or "timestamp" not in bar:
+ continue
+ volume = bar.get("volume")
+ if volume is None:
+ volume = bar.get("tickVolume")
+ rows.append(
+ {
+ "trade_date": bar["timestamp"],
+ "open": bar.get("open"),
+ "high": bar.get("high"),
+ "low": bar.get("low"),
+ "close": bar.get("close"),
+ "volume": volume,
+ }
+ )
+ if not rows:
+ return None
+
+ df = pd.DataFrame(rows)
+ # timestamp is epoch seconds; index is tz-naive UTC to match the other loaders.
+ df["trade_date"] = pd.to_datetime(df["trade_date"], unit="s", utc=True).dt.tz_localize(None)
+ for field in _OHLCV_FIELDS:
+ # Cast to float (not just to_numeric) so integer tick volume does not
+ # leave the column int64 and break the float-OHLCV contract.
+ df[field] = pd.to_numeric(df[field], errors="coerce").astype(float)
+
+ df = df.set_index("trade_date").sort_index()
+ df = df[list(_OHLCV_FIELDS)].dropna(subset=["open", "high", "low", "close"])
+
+ # The endpoint answers the exact [from, to] window; trim defensively to the
+ # inclusive window (end inclusive of its whole day) in case an edge bar slips in.
+ start_ts = pd.Timestamp(start_date)
+ end_ts = pd.Timestamp(end_date) + pd.Timedelta(days=1)
+ df = df[(df.index >= start_ts) & (df.index < end_ts)]
+ if df.empty:
+ return None
+ return df
diff --git a/agent/backtest/metrics.py b/agent/backtest/metrics.py
index e6ea5d500..3b2f2ddeb 100644
--- a/agent/backtest/metrics.py
+++ b/agent/backtest/metrics.py
@@ -24,6 +24,9 @@ _TRADING_DAYS = {
# existing
"tushare": 252, "yfinance": 252, "okx": 365, "akshare": 252, "ccxt": 365,
"mootdx": 252, "futu": 252, "mt5": 260,
+ # tickerall serves the same broker forex/CFD feed as mt5 (hosted, no local
+ # terminal), so it mirrors mt5's 24x5 annualisation everywhere in this table.
+ "tickerall": 260,
# crypto
"binance": 365,
# A-share equity
@@ -59,7 +62,7 @@ _BARS_PER_DAY = {
# crypto (24h)
"okx": 1440, "ccxt": 1440, "binance": 1440,
# forex/CFD (24h intraday)
- "mt5": 1440,
+ "mt5": 1440, "tickerall": 1440,
# Indian equity (6.25h session)
"india_broker": 375,
# Korean equity (6.5h session, 09:00-15:30 KST)
@@ -71,7 +74,7 @@ _BARS_PER_DAY = {
"tushare": 48, "akshare": 48, "baostock": 48, "tencent": 48,
"eastmoney": 48, "sina": 48, "mootdx": 48, "futu": 48,
"okx": 288, "ccxt": 288, "binance": 288,
- "mt5": 288,
+ "mt5": 288, "tickerall": 288,
"india_broker": 75,
"pykrx": 78,
},
@@ -81,7 +84,7 @@ _BARS_PER_DAY = {
"tushare": 16, "akshare": 16, "baostock": 16, "tencent": 16,
"eastmoney": 16, "sina": 16, "mootdx": 16, "futu": 16,
"okx": 96, "ccxt": 96, "binance": 96,
- "mt5": 96,
+ "mt5": 96, "tickerall": 96,
"india_broker": 25,
"pykrx": 26,
},
@@ -91,7 +94,7 @@ _BARS_PER_DAY = {
"tushare": 8, "akshare": 8, "baostock": 8, "tencent": 8,
"eastmoney": 8, "sina": 8, "mootdx": 8, "futu": 8,
"okx": 48, "ccxt": 48, "binance": 48,
- "mt5": 48,
+ "mt5": 48, "tickerall": 48,
"india_broker": 13,
"pykrx": 13,
},
@@ -101,7 +104,7 @@ _BARS_PER_DAY = {
"tushare": 4, "akshare": 4, "baostock": 4, "tencent": 4,
"eastmoney": 4, "sina": 4, "mootdx": 4, "futu": 4,
"okx": 24, "ccxt": 24, "binance": 24,
- "mt5": 24,
+ "mt5": 24, "tickerall": 24,
"india_broker": 7,
"pykrx": 7,
},
@@ -111,7 +114,7 @@ _BARS_PER_DAY = {
"tushare": 1, "akshare": 1, "baostock": 1, "tencent": 1,
"eastmoney": 1, "sina": 1, "mootdx": 1, "futu": 1,
"okx": 6, "ccxt": 6, "binance": 6,
- "mt5": 6,
+ "mt5": 6, "tickerall": 6,
"india_broker": 2,
"pykrx": 2,
},
@@ -121,7 +124,7 @@ _BARS_PER_DAY = {
"tushare": 1, "akshare": 1, "baostock": 1, "tencent": 1,
"eastmoney": 1, "sina": 1, "mootdx": 1, "futu": 1,
"okx": 1, "ccxt": 1, "binance": 1,
- "mt5": 1,
+ "mt5": 1, "tickerall": 1,
"india_broker": 1,
"pykrx": 1,
},
diff --git a/agent/src/config/env_schema.py b/agent/src/config/env_schema.py
index d371e32fd..b4ca033a3 100644
--- a/agent/src/config/env_schema.py
+++ b/agent/src/config/env_schema.py
@@ -188,6 +188,9 @@ class DataConfig(_EnvBase):
aliyun_iqs_api_key: str = Field(alias="ALIYUN_IQS_API_KEY", default="")
qveris_api_key: str = Field(alias="QVERIS_API_KEY", default="")
qveris_base_url: str = Field(alias="QVERIS_BASE_URL", default="")
+ tickerall_api_key: str = Field(alias="TICKERALL_API_KEY", default="")
+ tickerall_account_id: str = Field(alias="TICKERALL_ACCOUNT_ID", default="")
+ tickerall_base_url: str = Field(alias="TICKERALL_BASE_URL", default="")
rsshub_base_url: str = Field(alias="RSSHUB_BASE_URL", default="")
dashscope_api_key: str = Field(alias="DASHSCOPE_API_KEY", default="")
longbridge_app_key: str = Field(alias="LONGBRIDGE_APP_KEY", default="")
diff --git a/agent/src/skills/data-routing/SKILL.md b/agent/src/skills/data-routing/SKILL.md
index 7c9ef3754..76875ac1a 100644
--- a/agent/src/skills/data-routing/SKILL.md
+++ b/agent/src/skills/data-routing/SKILL.md
@@ -29,6 +29,7 @@ per-source skill.
| mootdx | A-shares (TDX servers, never-banned) | No | China network | data-routing |
| futu | A/HK/US via OpenD gateway | Yes (OpenD running) | Local gateway | data-routing (runner-internal) |
| mt5 | Forex & metals (your broker's MT5 feed) | Yes (running, logged-in MT5 terminal; optional `~/.vibe-trading/mt5.json`) | Local terminal (Windows) | data-routing (runner-internal) |
+| tickerall | Forex & metals (same broker MT5 feed, hosted) | Yes (`TICKERALL_API_KEY` + `TICKERALL_ACCOUNT_ID`; read-only) | Hosted API (any OS, no terminal) | data-routing (runner-internal; **explicit `source=tickerall` only**) |
| local | User CSV/parquet on disk | No | Offline | data-routing (runner-internal) |
| eastmoney | A-shares, HK, US equities | No (IP-throttled) | Unrestricted | data-routing |
| sina | US equities (daily OHLCV) | No (IP-throttled) | Unrestricted | data-routing |
@@ -103,7 +104,7 @@ same-market sources automatically. Only set a concrete source when the user asks
`.TO` / `.V` suffixes (for example `TD.TO`, `PNG.V`).
- **Crypto**: okx (single exchange) > ccxt (multi-exchange).
- **Futures / macro**: tushare > akshare.
-- **Forex / metals**: mt5 (local MetaTrader 5 terminal, Windows) > akshare.
+- **Forex / metals**: mt5 (local MetaTrader 5 terminal, Windows) > akshare. TickerAll (`source="tickerall"`) is a hosted, no-terminal alternative to the *same* broker feed (any OS) — opt-in and **explicit-only**: it never joins this automatic chain, so a user's broker credential is used only when deliberately requested.
## Symbol Format Reference
diff --git a/agent/tests/test_registry.py b/agent/tests/test_registry.py
index 986946c14..6ae7ca855 100644
--- a/agent/tests/test_registry.py
+++ b/agent/tests/test_registry.py
@@ -187,6 +187,15 @@ class TestFallbackChains:
# the previous chain unchanged.
assert FALLBACK_CHAINS["forex"] == ["mt5", "akshare", "yfinance", "local"]
+ def test_tickerall_is_explicit_only_never_a_fallback(self) -> None:
+ """TickerAll is a valid explicit source but must NEVER join an automatic
+ fallback chain. It reads a user's own broker account over a hosted API, so
+ it runs only on a deliberate ``source="tickerall"`` request - never silently
+ as a degradation target for another source. This guards that contract."""
+ assert "tickerall" in VALID_SOURCES
+ for market, chain in FALLBACK_CHAINS.items():
+ assert "tickerall" not in chain, f"tickerall must not be in the {market} fallback chain"
+
# ---------------------------------------------------------------------------
# VALID_SOURCES
@@ -305,6 +314,32 @@ class TestGetLoaderWithFallback:
# The error must point the user at the Data Bridge config, not a network hop.
assert "data-bridge" in msg.lower() or "config" in msg.lower()
+ def test_explicit_tickerall_does_not_fall_through_to_network(self) -> None:
+ """An explicit unavailable 'tickerall' must raise, never silently degrade to a
+ public forex source (akshare/yfinance) via its markets — it reads the user's own
+ broker account, so a missing key is a config error to surface, not paper over."""
+ class _FakeTickerall:
+ name = "tickerall"
+ markets = {"forex"}
+ requires_auth = True
+
+ def is_available(self) -> bool:
+ return False
+
+ def fetch(self, codes, start_date, end_date, *, interval="1D", fields=None):
+ return {}
+
+ with patch.dict(LOADER_REGISTRY, {
+ "tickerall": _FakeTickerall,
+ "fake_available": _FakeAvailableLoader, # an available loader listed in the forex chain
+ }, clear=True):
+ with patch.dict(FALLBACK_CHAINS, {"forex": ["fake_available"]}):
+ with pytest.raises(NoAvailableSourceError) as excinfo:
+ get_loader_cls_with_fallback("tickerall")
+ msg = str(excinfo.value)
+ assert "tickerall" in msg
+ assert "TICKERALL_API_KEY" in msg
+
# ---------------------------------------------------------------------------
# Issue #50 — loaders that explode in __init__ (e.g. Tushare with no token)
diff --git a/agent/tests/test_tickerall_loader.py b/agent/tests/test_tickerall_loader.py
new file mode 100644
index 000000000..7339bbfbf
--- /dev/null
+++ b/agent/tests/test_tickerall_loader.py
@@ -0,0 +1,419 @@
+"""Tests for tickerall_loader: the four review-contract guarantees plus parsing.
+
+All HTTP is mocked at :func:`backtest.loaders._http.throttled_get_json` (imported
+into the loader module), so no test touches a live TickerAll endpoint. The four
+contract points these tests pin down:
+
+ 1. Explicit-only - registered as a valid source, never in a fallback chain.
+ 2. Read-only - every request is a GET to a read endpoint; no write path.
+ 3. Cache identity - both the symbol memo and the frame cache key include the
+ account id AND the base URL, so two accounts never collide.
+ 4. Partial = error - a truncated/partial window raises IncompleteHistoryError
+ rather than returning a silently short series.
+"""
+
+from unittest.mock import patch
+
+import pandas as pd
+import pytest
+
+from backtest.loaders import tickerall_loader as tl
+from backtest.loaders.tickerall_loader import (
+ DataLoader,
+ IncompleteHistoryError,
+ _parse_candles,
+ _to_query_base,
+)
+
+# 2024-01-03 and 2024-01-04 at 00:00:00 UTC, epoch seconds.
+_TS_JAN3 = 1704240000
+_TS_JAN4 = 1704326400
+_TS_DEC1 = 1701388800 # 2023-12-01, before a Jan window (trim target)
+
+# Descending order on purpose: the parser must sort ascending.
+_EURUSD_BARS = [
+ {"timestamp": _TS_JAN4, "open": 1.09, "high": 1.10, "low": 1.08, "close": 1.095, "tickVolume": 200},
+ {"timestamp": _TS_JAN3, "open": 1.10, "high": 1.11, "low": 1.09, "close": 1.10, "tickVolume": 100},
+]
+
+
+def _resp(bars, *, truncated=False, coverage="full", stop_reason=None):
+ """A range-mode /candles body: {candles, truncated, coverage, stopReason, ...}."""
+ return {
+ "candles": list(bars),
+ "served": len(bars),
+ "count": len(bars),
+ "coverage": coverage,
+ "truncated": truncated,
+ "stopReason": stop_reason,
+ }
+
+
+def _route(symbols=None, candles=None):
+ """Build a throttled_get_json side_effect routing by endpoint."""
+ def _side(url, **kwargs):
+ if url.endswith("/symbols"):
+ return symbols if symbols is not None else []
+ if url.endswith("/candles"):
+ return candles if candles is not None else _resp([])
+ raise AssertionError(f"unexpected URL {url}")
+ return _side
+
+
+def _set_creds(monkeypatch, key="secret", account="acct1", base="https://api.tickerall.com"):
+ """Patch the loader's config accessors directly (no config-cache dependency)."""
+ monkeypatch.setattr(tl, "_api_key", lambda: key)
+ monkeypatch.setattr(tl, "_account_id", lambda: account)
+ monkeypatch.setattr(tl, "_base_url", lambda: base)
+
+
+def requests_like_http_error(resp):
+ """An exception shaped like ``requests.HTTPError``: it carries a ``.response`` with
+ ``.status_code`` + ``.json()`` — what ``throttled_get_json``'s ``raise_for_status``
+ raises, and what ``_reraise_if_range_too_large`` duck-types on."""
+ err = Exception("HTTP error")
+ err.response = resp
+ return err
+
+
[email protected](autouse=True)
+def _clear_symbol_cache():
+ """The loader memoizes the account symbol map per process; isolate each test."""
+ tl._symbol_cache.clear()
+ yield
+ tl._symbol_cache.clear()
+
+
+# ---------------------------------------------------------------------------
+# (1) Explicit-only + registration
+# ---------------------------------------------------------------------------
+class TestRegistrationAndExplicitOnly:
+ def test_registered_in_registry(self):
+ from backtest.loaders import registry
+
+ registry._ensure_registered()
+ assert registry.LOADER_REGISTRY.get("tickerall") is DataLoader
+
+ def test_in_valid_sources(self):
+ from backtest.loaders import registry
+
+ assert "tickerall" in registry.VALID_SOURCES
+
+ def test_never_in_any_fallback_chain(self):
+ """Contract 1: explicit-only. A user's broker credential is used only on a
+ deliberate source="tickerall" request, never silently as a fallback."""
+ from backtest.loaders import registry
+
+ for market, chain in registry.FALLBACK_CHAINS.items():
+ assert "tickerall" not in chain, f"tickerall must not be in the {market} chain"
+
+ def test_metadata(self):
+ assert DataLoader.name == "tickerall"
+ assert DataLoader.markets == {"forex"}
+ assert DataLoader.requires_auth is True
+
+
+class TestIsAvailable:
+ """Availability is gated on BOTH the key and the account id being set."""
+
+ def test_available_with_key_and_account(self, monkeypatch):
+ _set_creds(monkeypatch)
+ assert DataLoader().is_available() is True
+
+ def test_unavailable_without_key(self, monkeypatch):
+ _set_creds(monkeypatch, key="")
+ assert DataLoader().is_available() is False
+
+ def test_unavailable_without_account(self, monkeypatch):
+ _set_creds(monkeypatch, account="")
+ assert DataLoader().is_available() is False
+
+
+class TestSymbolMapping:
+ """Base-symbol normalization strips separators and the .FX suffix."""
+
+ def test_slash_pair(self):
+ assert _to_query_base("EUR/USD") == "EURUSD"
+
+ def test_fx_suffix(self):
+ assert _to_query_base("EURUSD.FX") == "EURUSD"
+
+ def test_uppercased_and_stripped(self):
+ assert _to_query_base("xau_usd") == "XAUUSD"
+
+
+class TestSymbolResolution:
+ """Broker-suffix resolution against the account's own symbol list."""
+
+ def test_exact_match_shortest_wins(self, monkeypatch):
+ _set_creds(monkeypatch)
+ with patch.object(tl, "throttled_get_json", side_effect=_route(symbols=["EURUSDz", "EURUSDm"])):
+ assert tl._resolve_symbol("EURUSD", "acct1", "secret") == "EURUSDm"
+
+ def test_prefix_match_when_no_exact(self, monkeypatch):
+ _set_creds(monkeypatch)
+ with patch.object(tl, "throttled_get_json", side_effect=_route(symbols=["EURUSDmicro"])):
+ assert tl._resolve_symbol("EURUSD", "acct1", "secret") == "EURUSDmicro"
+
+ def test_falls_back_to_base_when_list_empty(self, monkeypatch):
+ _set_creds(monkeypatch)
+ with patch.object(tl, "throttled_get_json", side_effect=_route(symbols=[])):
+ assert tl._resolve_symbol("EURUSD", "acct1", "secret") == "EURUSD"
+
+
+# ---------------------------------------------------------------------------
+# (2) Read-only
+# ---------------------------------------------------------------------------
+class TestReadOnly:
+ def test_only_get_read_endpoints_are_touched(self, monkeypatch):
+ """Contract 2: every request is a GET to a read endpoint; the module has
+ no trade/order/mutation path."""
+ _set_creds(monkeypatch)
+ seen = []
+
+ def _side(url, **kwargs):
+ seen.append(url)
+ if url.endswith("/symbols"):
+ return ["EURUSDm"]
+ return _resp(_EURUSD_BARS)
+
+ with patch.object(tl, "throttled_get_json", side_effect=_side):
+ DataLoader().fetch(["EURUSD"], "2024-01-03", "2024-01-04", interval="1D")
+
+ assert seen, "expected at least one request"
+ assert all(u.endswith("/symbols") or u.endswith("/candles") for u in seen)
+ # The loader imports only the GET helper - there is no write surface.
+ assert not hasattr(tl, "throttled_post_json")
+
+
+# ---------------------------------------------------------------------------
+# (3) Cache identity includes account id + base URL
+# ---------------------------------------------------------------------------
+class TestCacheIdentity:
+ def test_frame_cache_key_includes_account_and_base_host(self, monkeypatch):
+ """Contract 3: the frame cache key carries the account + base host, so two
+ accounts (or two endpoints) never share a cached series."""
+ _set_creds(monkeypatch, account="ACCT9", base="https://staging.example.com")
+ captured = {}
+
+ def _fake_cached(*, source, symbol, timeframe, start_date, end_date, fields, fetch):
+ captured["source"] = source
+ captured["symbol"] = symbol
+ return fetch()
+
+ monkeypatch.setattr(tl, "cached_loader_fetch", _fake_cached)
+ with patch.object(tl, "throttled_get_json", side_effect=_route(candles=_resp(_EURUSD_BARS))):
+ DataLoader().fetch(["EURUSD"], "2024-01-01", "2024-01-31", interval="1D")
+
+ assert "ACCT9" in captured["symbol"]
+ assert "staging.example.com" in captured["symbol"]
+
+ def test_symbol_memo_not_shared_across_base_urls(self, monkeypatch):
+ """The symbol memo is keyed by (base_url, account): the SAME account id on
+ two endpoints resolves independently (no cross-endpoint bleed)."""
+ calls = []
+
+ def _side(url, **kwargs):
+ calls.append(url)
+ return ["EURUSDm"]
+
+ monkeypatch.setattr(tl, "_api_key", lambda: "k")
+ monkeypatch.setattr(tl, "_account_id", lambda: "ACCT")
+ monkeypatch.setattr(tl, "_base_url", lambda: "https://a.example.com")
+ with patch.object(tl, "throttled_get_json", side_effect=_side):
+ tl._account_symbols("ACCT", "k")
+ monkeypatch.setattr(tl, "_base_url", lambda: "https://b.example.com")
+ with patch.object(tl, "throttled_get_json", side_effect=_side):
+ tl._account_symbols("ACCT", "k")
+
+ assert len([u for u in calls if u.endswith("/symbols")]) == 2
+
+ def test_frame_cache_key_distinguishes_paths_on_same_host(self, monkeypatch):
+ """Two endpoints that share a host but differ in PATH must not collide - the
+ frame cache key carries the full base URL, not just host[:port]."""
+ captured = []
+
+ def _fake_cached(*, source, symbol, timeframe, start_date, end_date, fields, fetch):
+ captured.append(symbol)
+ return fetch()
+
+ monkeypatch.setattr(tl, "cached_loader_fetch", _fake_cached)
+ for base in ("https://h.example.com/a", "https://h.example.com/b"):
+ _set_creds(monkeypatch, account="ACCT", base=base)
+ with patch.object(tl, "throttled_get_json", side_effect=_route(candles=_resp(_EURUSD_BARS))):
+ DataLoader().fetch(["EURUSD"], "2024-01-01", "2024-01-31", interval="1D")
+
+ assert captured[0] != captured[1]
+ assert "/a" in captured[0] and "/b" in captured[1]
+
+
+# ---------------------------------------------------------------------------
+# (4) Partial history is an error, not a short series + range mode
+# ---------------------------------------------------------------------------
+class TestRangeModeAndCompleteness:
+ def test_fetch_uses_from_to_range_not_hours(self, monkeypatch):
+ _set_creds(monkeypatch)
+ seen = {}
+
+ def _side(url, **kwargs):
+ if url.endswith("/symbols"):
+ return []
+ seen.update(kwargs.get("params", {}))
+ return _resp(_EURUSD_BARS)
+
+ with patch.object(tl, "throttled_get_json", side_effect=_side):
+ DataLoader().fetch(["EURUSD"], "2024-01-03", "2024-01-04", interval="1D")
+
+ assert seen.get("from") == "2024-01-03T00:00:00Z"
+ assert seen.get("to") == "2024-01-04T23:59:59Z"
+ assert "hours" not in seen # exact range, not the old relative-lookback hack
+
+ def test_truncated_raises_incomplete(self, monkeypatch):
+ """Contract 4: a truncated walk is an error, not a short series."""
+ _set_creds(monkeypatch)
+ resp = _resp(_EURUSD_BARS, truncated=True, stop_reason="deadline")
+ with patch.object(tl, "throttled_get_json", side_effect=_route(candles=resp)):
+ with pytest.raises(IncompleteHistoryError):
+ DataLoader().fetch(["EURUSD"], "2019-01-01", "2024-01-31", interval="1D")
+
+ def test_partial_coverage_raises_incomplete(self, monkeypatch):
+ _set_creds(monkeypatch)
+ resp = _resp(_EURUSD_BARS, coverage="partial", stop_reason="unsupported")
+ with patch.object(tl, "throttled_get_json", side_effect=_route(candles=resp)):
+ with pytest.raises(IncompleteHistoryError):
+ DataLoader().fetch(["EURUSD"], "2024-01-01", "2024-01-31", interval="1D")
+
+ def test_response_without_completeness_signal_raises(self, monkeypatch):
+ """A candles body carrying NO truncated/coverage cannot be verified complete, so
+ it must raise rather than accept a possibly-short series - the case a 2-bar answer
+ to a multi-year request would otherwise slip through as 'complete'."""
+ _set_creds(monkeypatch)
+ monkeypatch.setattr(tl, "cached_loader_fetch", lambda *, fetch, **kw: fetch())
+ body = {"candles": list(_EURUSD_BARS)} # documented-minimal shape: no completeness fields
+ with patch.object(tl, "throttled_get_json", side_effect=_route(candles=body)):
+ with pytest.raises(IncompleteHistoryError):
+ DataLoader().fetch(["EURUSD"], "2019-01-01", "2024-01-31", interval="1D")
+
+ def test_incomplete_propagates_and_is_not_swallowed(self, monkeypatch):
+ """The batch loop swallows transient per-symbol errors, but a partial
+ window must propagate so a backtest fails loudly."""
+ _set_creds(monkeypatch)
+ resp = _resp(_EURUSD_BARS, truncated=True)
+ with patch.object(tl, "throttled_get_json", side_effect=_route(candles=resp)):
+ with pytest.raises(IncompleteHistoryError):
+ DataLoader().fetch(["EURUSD", "XAUUSD"], "2019-01-01", "2024-01-31", interval="1D")
+
+ def test_range_too_large_400_raises_incomplete(self, monkeypatch):
+ """Contract 4, the REAL truncation path (caught live): a window wider than one
+ request is rejected with a 400 `range_too_large`, NOT a 200 `truncated`. It must
+ raise IncompleteHistoryError, not be swallowed as a skipped symbol."""
+ _set_creds(monkeypatch)
+
+ class _Resp:
+ status_code = 400
+
+ def json(self):
+ return {"error": "range_too_large", "maxWindowDays": 1830, "maxBars": 100000}
+
+ err = requests_like_http_error(_Resp())
+
+ def _side(url, **kwargs):
+ if url.endswith("/symbols"):
+ return []
+ raise err
+
+ with patch.object(tl, "throttled_get_json", side_effect=_side):
+ with pytest.raises(IncompleteHistoryError):
+ DataLoader().fetch(["EURUSD"], "2005-01-01", "2024-12-31", interval="1D")
+
+ def test_other_400_stays_a_transient_skip(self, monkeypatch):
+ """A non-range 4xx (e.g. an unknown symbol) is NOT incomplete-history — it stays a
+ transient per-symbol skip so one bad symbol never poisons the batch."""
+ _set_creds(monkeypatch)
+
+ class _Resp:
+ status_code = 400
+
+ def json(self):
+ return {"error": "symbol_not_found"}
+
+ err = requests_like_http_error(_Resp())
+
+ def _side(url, **kwargs):
+ if url.endswith("/symbols"):
+ return []
+ raise err
+
+ with patch.object(tl, "throttled_get_json", side_effect=_side):
+ out = DataLoader().fetch(["EURUSD"], "2024-01-01", "2024-01-31", interval="1D")
+ assert out == {}
+
+ def test_complete_window_returns_frame(self, monkeypatch):
+ _set_creds(monkeypatch)
+ with patch.object(tl, "throttled_get_json", side_effect=_route(candles=_resp(_EURUSD_BARS))):
+ out = DataLoader().fetch(["EURUSD"], "2024-01-01", "2024-01-31", interval="1D")
+ assert "EURUSD" in out
+ assert list(out["EURUSD"].index) == [pd.Timestamp("2024-01-03"), pd.Timestamp("2024-01-04")]
+
+ def test_transient_symbol_error_is_swallowed(self, monkeypatch):
+ """A network blip on one symbol logs+skips (never poisons the batch)."""
+ _set_creds(monkeypatch)
+
+ def _side(url, **kwargs):
+ if url.endswith("/symbols"):
+ return []
+ raise RuntimeError("network blip")
+
+ with patch.object(tl, "throttled_get_json", side_effect=_side):
+ out = DataLoader().fetch(["EURUSD"], "2024-01-01", "2024-01-31", interval="1D")
+ assert out == {}
+
+ def test_unknown_interval_rejected(self, monkeypatch):
+ _set_creds(monkeypatch)
+ with patch.object(tl, "throttled_get_json", side_effect=_route(candles=_resp(_EURUSD_BARS))):
+ assert DataLoader().fetch(["EURUSD"], "2024-01-01", "2024-01-31", interval="3s") == {}
+
+
+# ---------------------------------------------------------------------------
+# Pure parsing (no network)
+# ---------------------------------------------------------------------------
+class TestParseCandles:
+ def test_sorts_ascending_typed_and_named(self):
+ df = _parse_candles(_resp(_EURUSD_BARS), "2024-01-01", "2024-01-31")
+ assert list(df.index) == [pd.Timestamp("2024-01-03"), pd.Timestamp("2024-01-04")]
+ assert list(df.columns) == ["open", "high", "low", "close", "volume"]
+ assert df.index.name == "trade_date"
+ assert df["close"].iloc[0] == 1.10
+ for col in df.columns:
+ assert df[col].dtype == float
+
+ def test_tick_volume_fallback_and_float(self):
+ df = _parse_candles(_resp(_EURUSD_BARS), "2024-01-01", "2024-01-31")
+ assert df["volume"].dtype == float
+ assert df["volume"].iloc[0] == 100.0 # from tickVolume
+
+ def test_explicit_volume_preferred_over_tickvolume(self):
+ bars = [{"timestamp": _TS_JAN3, "open": 1, "high": 2, "low": 0.5, "close": 1.5,
+ "volume": 7, "tickVolume": 999}]
+ df = _parse_candles(_resp(bars), "2024-01-01", "2024-01-31")
+ assert df["volume"].iloc[0] == 7.0
+
+ def test_volume_is_nan_when_bar_has_no_tick_volume(self):
+ """A bar with neither volume nor tickVolume yields NaN volume - honest 'unknown'
+ (e.g. bid-only deep-history bars), never a fabricated number."""
+ bars = [{"timestamp": _TS_JAN3, "open": 1, "high": 2, "low": 0.5, "close": 1.5}]
+ df = _parse_candles(_resp(bars), "2024-01-01", "2024-01-31")
+ assert pd.isna(df["volume"].iloc[0])
+
+ def test_window_trims_out_of_range_bars(self):
+ bars = [{"timestamp": _TS_DEC1, "open": 1, "high": 2, "low": 0.5, "close": 1.5, "tickVolume": 1}] + _EURUSD_BARS
+ df = _parse_candles(_resp(bars), "2024-01-01", "2024-01-31")
+ assert list(df.index) == [pd.Timestamp("2024-01-03"), pd.Timestamp("2024-01-04")]
+
+ def test_empty_body_returns_none(self):
+ assert _parse_candles(_resp([]), "2024-01-01", "2024-01-31") is None
+
+ def test_top_level_array_body_still_parses(self):
+ # Back-compat: a bare list body (no wrapper) still parses.
+ df = _parse_candles(list(_EURUSD_BARS), "2024-01-01", "2024-01-31")
+ assert len(df) == 2