Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(loaders): add read-only Nobitex and Wallex market-data sources

Emad Karimi202b3be22671
diff --git a/agent/SKILL.md b/agent/SKILL.md
index 5e2e4cc60..1632f8f8a 100644
--- a/agent/SKILL.md
+++ b/agent/SKILL.md
@@ -1,7 +1,7 @@
---
name: vibe-trading
version: 0.1.14
-description: Professional finance research toolkit — backtesting (10 engines + benchmark comparison panel), factor analysis, Alpha Zoo (462 pre-built alphas across qlib158/alpha101/gtja191/academic/fundamental), options pricing, 90 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).
+description: Professional finance research toolkit — backtesting (10 engines + benchmark comparison panel), factor analysis, Alpha Zoo (462 pre-built alphas across qlib158/alpha101/gtja191/academic/fundamental), options pricing, 90 finance skills, 30 multi-agent swarm teams, Trade Journal analyzer, and Shadow Account (extract → backtest → render) across 27 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, nobitex, wallex, plus optional-key finnhub/alphavantage/tiingo/fmp).
dependencies:
python: ">=3.11"
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 10 engines (ChinaA, GlobalEquity, IndiaEquity, KoreaEquity, VietnamEquity, Crypto, ChinaFutures, GlobalFutures, Forex + options) with 25 market-data sources (auto-detect + ordered fallback; the hosted forex `tickerall` source is explicit-only):
+Create and run quantitative strategies across 10 engines (ChinaA, GlobalEquity, IndiaEquity, KoreaEquity, VietnamEquity, Crypto, ChinaFutures, GlobalFutures, Forex + options) with 27 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).
@@ -150,7 +150,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 25 sources) | None* |
+| `get_market_data` | Fetch OHLCV data (auto-detect + ordered fallback across 27 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/nobitex.py b/agent/backtest/loaders/nobitex.py
new file mode 100644
index 000000000..77ddeae1d
--- /dev/null
+++ b/agent/backtest/loaders/nobitex.py
@@ -0,0 +1,267 @@
+"""Nobitex spot candle loader (crypto, IRT/Toman-quoted pairs).
+
+Uses the Nobitex public TradingView-UDF REST endpoint (no auth):
+
+ GET https://apiv2.nobitex.ir/market/udf/history
+ ?symbol=BTCIRT&resolution=D&from=<epoch_s>&to=<epoch_s>&page=1
+
+Source facts (verified against apidocs.nobitex.ir + live probes, 2026-08-26):
+
+- ``*IRT`` symbols are quoted in Toman; ``dstCurrency=rls`` stats are in Rial
+ (1 Toman = 10 Rials). This loader only serves ``*IRT`` markets.
+- Max 500 candles per request; ``page`` walks OLDER batches (page 1 = newest
+ in range; a short page or ``{"s": "no_data"}`` ends the walk).
+- Rate limit 60 req/min on this endpoint — a small sleep between pages.
+- Candle timestamps align to Tehran local time (UTC+03:30): daily bars open
+ at Tehran midnight, hourly bars at :30 past the UTC hour.
+- Resolutions: 1/5/15/30 min, 60/180/240/360/720 min, D/2D/3D. There is no
+ weekly resolution — ``1W`` requests reject with an empty result so the
+ fallback chain continues.
+"""
+
+from __future__ import annotations
+
+import logging
+import time
+from typing import Dict, List, Optional
+
+import pandas as pd
+import requests
+
+from backtest.loaders.base import (
+ cached_loader_fetch,
+ check_budget,
+ positive_env_int,
+ retry_with_budget,
+ validate_date_range,
+ validate_ohlc,
+)
+from backtest.loaders.registry import register
+
+logger = logging.getLogger(__name__)
+
+# Project interval tokens -> Nobitex UDF ``resolution`` values. Case aliases
+# accepted; anything else (including weekly) rejects with {} so the fallback
+# chain continues instead of silently substituting daily bars.
+_INTERVAL_MAP = {
+ "1m": "1",
+ "5m": "5",
+ "15m": "15",
+ "30m": "30",
+ "1h": "60",
+ "1H": "60",
+ "3h": "180",
+ "3H": "180",
+ "4h": "240",
+ "4H": "240",
+ "6h": "360",
+ "6H": "360",
+ "12h": "720",
+ "12H": "720",
+ "1d": "D",
+ "1D": "D",
+}
+
+HISTORY_URL = "https://apiv2.nobitex.ir/market/udf/history"
+_MAX_PER_PAGE = 500
+_MAX_PAGES = 40
+_PAGE_SLEEP_S = 0.5 # endpoint allows 60 req/min
+
+_NOBITEX_TIMEOUT_S = positive_env_int("NOBITEX_TIMEOUT_S", 20)
+_NOBITEX_FETCH_BUDGET_S = positive_env_int("NOBITEX_FETCH_BUDGET_S", 90)
+_NOBITEX_PROBE_TIMEOUT_S = positive_env_int("NOBITEX_PROBE_TIMEOUT_S", 8)
+
+_OUTPUT_COLUMNS = ["open", "high", "low", "close", "volume"]
+
+_HEADERS = {"User-Agent": "TraderBot/vibe-trading-loader"}
+
+
+def map_symbol(symbol: str) -> str:
+ """``BTC-IRT`` / ``BTC/IRT`` / ``btcirt`` -> ``BTCIRT``."""
+ return symbol.strip().upper().replace("-", "").replace("/", "")
+
+
+def _session() -> requests.Session:
+ session = requests.Session()
+ session.headers.update(_HEADERS)
+ return session
+
+
+@register
+class DataLoader:
+ """Nobitex crypto OHLCV loader (public UDF endpoint, no auth)."""
+
+ name = "nobitex"
+ markets = {"crypto"}
+ requires_auth = False
+
+ def __init__(self) -> None:
+ """No credentials required for public candles."""
+ pass
+
+ def is_available(self) -> bool:
+ """Probe the public endpoint with a 1-candle request."""
+ try:
+ resp = _session().get(
+ HISTORY_URL,
+ params={
+ "symbol": "BTCIRT",
+ "resolution": "D",
+ "countback": 1,
+ "to": int(time.time()),
+ },
+ timeout=_NOBITEX_PROBE_TIMEOUT_S,
+ )
+ if resp.status_code != 200:
+ logger.warning("Nobitex probe HTTP %s", resp.status_code)
+ return False
+ return resp.json().get("s") == "ok"
+ except Exception as exc: # noqa: BLE001 — availability probe
+ logger.warning("Nobitex probe failed: %s", exc)
+ return False
+
+ 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 IRT-quoted crypto OHLCV (e.g. ``["BTC-IRT", "USDT-IRT"]``).
+
+ Args:
+ codes: Symbols like ``BTC-IRT`` / ``BTCIRT`` (Toman-quoted).
+ start_date: Start date (YYYY-MM-DD, inclusive).
+ end_date: End date (YYYY-MM-DD, exclusive).
+ fields: Ignored (Nobitex has no extra fields).
+ interval: Bar size (1m/5m/15m/30m/1h/3h/4h/6h/12h/1d, case
+ aliases accepted), default ``1D``.
+
+ Returns:
+ Mapping symbol -> DataFrame(trade_date, open, high, low, close, volume).
+ """
+ validate_date_range(start_date, end_date)
+
+ if fields:
+ logger.warning("Nobitex ignores extra fields: %s", fields)
+
+ resolution = _INTERVAL_MAP.get(interval.strip())
+ if resolution is None:
+ logger.warning(
+ "unsupported Nobitex interval %r; rejecting (supported: %s)",
+ interval,
+ sorted(_INTERVAL_MAP),
+ )
+ return {}
+
+ start_ts = int(pd.Timestamp(start_date).timestamp())
+ end_ts = int((pd.Timestamp(end_date) + pd.Timedelta(days=1)).timestamp())
+ session = _session()
+
+ result: Dict[str, pd.DataFrame] = {}
+ for code in codes:
+ symbol = map_symbol(code)
+ try:
+ df = cached_loader_fetch(
+ source=self.name,
+ symbol=symbol,
+ timeframe=interval,
+ start_date=start_date,
+ end_date=end_date,
+ fields=None,
+ fetch=lambda symbol=symbol: self._fetch_one(
+ session, symbol, resolution, start_ts, end_ts
+ ),
+ )
+ if df is not None and not df.empty:
+ result[code] = df
+ except Exception as exc: # noqa: BLE001 — one bad symbol must not abort the batch
+ logger.warning("Nobitex failed for %s: %s", symbol, exc)
+ return result
+
+ def _fetch_one(
+ self,
+ session: requests.Session,
+ symbol: str,
+ resolution: str,
+ start_ts: int,
+ end_ts: int,
+ ) -> Optional[pd.DataFrame]:
+ """Paginated UDF download; pages walk older batches of <=500 bars."""
+ deadline = time.monotonic() + _NOBITEX_FETCH_BUDGET_S
+ label = f"Nobitex fetch for {symbol}"
+ frames: list[pd.DataFrame] = []
+ page = 1
+
+ for _ in range(_MAX_PAGES):
+ check_budget(deadline, label, budget_s=_NOBITEX_FETCH_BUDGET_S)
+
+ def _do_request(page: int = page) -> dict:
+ resp = session.get(
+ HISTORY_URL,
+ params={
+ "symbol": symbol,
+ "resolution": resolution,
+ "from": start_ts,
+ "to": end_ts,
+ "page": page,
+ },
+ timeout=_NOBITEX_TIMEOUT_S,
+ )
+ if resp.status_code in {429, 500, 502, 503, 504}:
+ raise requests.HTTPError(
+ f"Nobitex HTTP {resp.status_code}", response=resp
+ )
+ resp.raise_for_status()
+ return resp.json()
+
+ data = retry_with_budget(
+ _do_request,
+ transient=(requests.RequestException, TimeoutError),
+ deadline=deadline,
+ label=label,
+ )
+ status = data.get("s")
+ if status == "no_data":
+ break
+ if status != "ok":
+ raise requests.RequestException(
+ f"Nobitex UDF error: {data.get('errmsg') or status}"
+ )
+ times = data.get("t") or []
+ if not times:
+ break
+ frame = pd.DataFrame(
+ {
+ "trade_date": pd.to_datetime(times, unit="s"),
+ "open": pd.to_numeric(data["o"], errors="coerce"),
+ "high": pd.to_numeric(data["h"], errors="coerce"),
+ "low": pd.to_numeric(data["l"], errors="coerce"),
+ "close": pd.to_numeric(data["c"], errors="coerce"),
+ "volume": pd.to_numeric(
+ data.get("v") or [0.0] * len(times), errors="coerce"
+ ),
+ }
+ )
+ frame["volume"] = frame["volume"].fillna(0)
+ frames.append(frame)
+ if len(times) < _MAX_PER_PAGE or int(times[0]) <= start_ts:
+ break
+ page += 1
+ time.sleep(_PAGE_SLEEP_S)
+
+ if not frames:
+ return None
+
+ df = pd.concat(frames).set_index("trade_date").sort_index()
+ df = df[~df.index.duplicated(keep="last")]
+ start_dt = pd.Timestamp(start_ts, unit="s")
+ end_dt = pd.Timestamp(end_ts, unit="s")
+ df = df[(df.index >= start_dt) & (df.index < end_dt)]
+ df = df[_OUTPUT_COLUMNS].dropna(subset=["open", "high", "low", "close"])
+ if df.empty:
+ return None
+ df = validate_ohlc(df)
+ return df.astype("float64") if not df.empty else None
diff --git a/agent/backtest/loaders/registry.py b/agent/backtest/loaders/registry.py
index 6e0669537..bcb9c4805 100644
--- a/agent/backtest/loaders/registry.py
+++ b/agent/backtest/loaders/registry.py
@@ -33,6 +33,8 @@ _registered = False
VALID_SOURCES: set[str] = {
"tushare",
"okx",
+ "nobitex",
+ "wallex",
"binance",
"yfinance",
"akshare",
@@ -88,6 +90,8 @@ def _ensure_registered() -> None:
_loader_modules = [
"backtest.loaders.tushare",
"backtest.loaders.okx",
+ "backtest.loaders.nobitex",
+ "backtest.loaders.wallex",
"backtest.loaders.binance_loader",
"backtest.loaders.yfinance_loader",
"backtest.loaders.akshare_loader",
diff --git a/agent/backtest/loaders/wallex.py b/agent/backtest/loaders/wallex.py
new file mode 100644
index 000000000..0d0fc9757
--- /dev/null
+++ b/agent/backtest/loaders/wallex.py
@@ -0,0 +1,265 @@
+"""Wallex spot candle loader (crypto, TMN/Toman-quoted pairs).
+
+Uses the Wallex public TradingView-UDF REST endpoint (no auth):
+
+ GET https://api.wallex.ir/v1/udf/history
+ ?symbol=USDTTMN&resolution=60&from=<epoch_s>&to=<epoch_s>
+
+Source facts (verified against api.wallex.ir live probes, 2026-08-26):
+
+- ``*TMN`` symbols are quoted in Toman; ``*USDT`` pairs are also available.
+- Docs list resolutions 1/15/60/240/480/720/1D/2D/3D, but the backend only
+ produces three real buckets: ``1`` (1m), ``60`` (1h), ``1D`` (daily).
+ ``15`` silently degrades to 1m and ``240/480/720`` to 1h — returning that
+ data under a finer label would be silently wrong, so this loader accepts
+ ONLY 1m/1h/1d and rejects everything else with an empty result.
+- No pagination. Ranges are hard-capped (~25d of 1m, ~3y of 1h per request;
+ over-cap returns HTTP 500, not a truncation) — windows are chunked
+ client-side well under the caps.
+- Response OHLCV values are decimal STRINGS; timestamps are bar-open unix
+ seconds. Volume is base-asset volume.
+- Rate limit headers show ``x-ratelimit-limit: 600``.
+"""
+
+from __future__ import annotations
+
+import logging
+import time
+from typing import Dict, List, Optional
+
+import pandas as pd
+import requests
+
+from backtest.loaders.base import (
+ cached_loader_fetch,
+ check_budget,
+ positive_env_float,
+ positive_env_int,
+ retry_with_budget,
+ validate_date_range,
+ validate_ohlc,
+)
+from backtest.loaders.registry import register
+
+logger = logging.getLogger(__name__)
+
+# Project interval tokens -> Wallex UDF ``resolution`` values. Only the three
+# buckets the backend truly serves are mapped; anything else (including the
+# silently-degrading 15m/4h documented values) rejects with {} so the fallback
+# chain continues instead of receiving mislabeled bars.
+_INTERVAL_MAP = {
+ "1m": "1",
+ "1h": "60",
+ "1H": "60",
+ "1d": "1D",
+ "1D": "1D",
+}
+
+# Client-side chunk spans per resolution (unix seconds), kept well under the
+# observed per-request caps (~25d of 1m, ~3y of 1h, full history of 1D).
+_CHUNK_SPAN_S = {
+ "1": 20 * 86400,
+ "60": 2 * 365 * 86400,
+ "1D": 40 * 365 * 86400,
+}
+
+HISTORY_URL = "https://api.wallex.ir/v1/udf/history"
+_PAGE_SLEEP_S = 0.3
+
+_WALLEX_TIMEOUT_S = positive_env_int("WALLEX_TIMEOUT_S", 20)
+_WALLEX_FETCH_BUDGET_S = positive_env_float("WALLEX_FETCH_BUDGET_S", 90.0)
+_WALLEX_PROBE_TIMEOUT_S = positive_env_int("WALLEX_PROBE_TIMEOUT_S", 8)
+
+_OUTPUT_COLUMNS = ["open", "high", "low", "close", "volume"]
+
+_HEADERS = {"User-Agent": "TraderBot/vibe-trading-loader"}
+
+
+def map_symbol(symbol: str) -> str:
+ """``USDT-TMN`` / ``USDTTMN`` / ``usdttmn`` -> ``USDTTMN``."""
+ return symbol.strip().upper().replace("-", "").replace("/", "")
+
+
+def _session() -> requests.Session:
+ session = requests.Session()
+ session.headers.update(_HEADERS)
+ return session
+
+
+@register
+class DataLoader:
+ """Wallex crypto OHLCV loader (public UDF endpoint, no auth)."""
+
+ name = "wallex"
+ markets = {"crypto"}
+ requires_auth = False
+
+ def __init__(self) -> None:
+ """No credentials required for public candles."""
+ pass
+
+ def is_available(self) -> bool:
+ """Probe the public endpoint with a short 1D request."""
+ try:
+ now = int(time.time())
+ resp = _session().get(
+ HISTORY_URL,
+ params={
+ "symbol": "USDTTMN",
+ "resolution": "1D",
+ "from": now - 2 * 86400,
+ "to": now,
+ },
+ timeout=_WALLEX_PROBE_TIMEOUT_S,
+ )
+ if resp.status_code != 200:
+ logger.warning("Wallex probe HTTP %s", resp.status_code)
+ return False
+ return resp.json().get("s") == "ok"
+ except Exception as exc: # noqa: BLE001 — availability probe
+ logger.warning("Wallex probe failed: %s", exc)
+ return False
+
+ 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 TMN-quoted crypto OHLCV (e.g. ``["USDT-TMN", "BTC-TMN"]``).
+
+ Args:
+ codes: Symbols like ``USDT-TMN`` / ``USDTTMN`` (Toman-quoted).
+ start_date: Start date (YYYY-MM-DD, inclusive).
+ end_date: End date (YYYY-MM-DD, exclusive).
+ fields: Ignored (Wallex has no extra fields).
+ interval: Bar size — only 1m/1h/1d are truly served by Wallex;
+ anything else rejects with an empty result, default ``1D``.
+
+ Returns:
+ Mapping symbol -> DataFrame(trade_date, open, high, low, close, volume).
+ """
+ validate_date_range(start_date, end_date)
+
+ if fields:
+ logger.warning("Wallex ignores extra fields: %s", fields)
+
+ resolution = _INTERVAL_MAP.get(interval.strip())
+ if resolution is None:
+ logger.warning(
+ "unsupported Wallex interval %r; rejecting (Wallex truly serves "
+ "only 1m/1h/1d — other documented values silently degrade)",
+ interval,
+ )
+ return {}
+
+ start_ts = int(pd.Timestamp(start_date).timestamp())
+ end_ts = int((pd.Timestamp(end_date) + pd.Timedelta(days=1)).timestamp())
+ session = _session()
+
+ result: Dict[str, pd.DataFrame] = {}
+ for code in codes:
+ symbol = map_symbol(code)
+ try:
+ df = cached_loader_fetch(
+ source=self.name,
+ symbol=symbol,
+ timeframe=interval,
+ start_date=start_date,
+ end_date=end_date,
+ fields=None,
+ fetch=lambda symbol=symbol: self._fetch_one(
+ session, symbol, resolution, start_ts, end_ts
+ ),
+ )
+ if df is not None and not df.empty:
+ result[code] = df
+ except Exception as exc: # noqa: BLE001 — one bad symbol must not abort the batch
+ logger.warning("Wallex failed for %s: %s", symbol, exc)
+ return result
+
+ def _fetch_one(
+ self,
+ session: requests.Session,
+ symbol: str,
+ resolution: str,
+ start_ts: int,
+ end_ts: int,
+ ) -> Optional[pd.DataFrame]:
+ """Forward time-window chunking (Wallex has no pagination)."""
+ deadline = time.monotonic() + _WALLEX_FETCH_BUDGET_S
+ label = f"Wallex fetch for {symbol}"
+ span = _CHUNK_SPAN_S.get(resolution, 2 * 365 * 86400)
+ frames: list[pd.DataFrame] = []
+ window_start = start_ts
+
+ while window_start < end_ts:
+ check_budget(deadline, label, budget_s=_WALLEX_FETCH_BUDGET_S)
+ window_end = min(window_start + span, end_ts)
+
+ def _do_request(
+ window_start: int = window_start, window_end: int = window_end
+ ) -> dict:
+ resp = session.get(
+ HISTORY_URL,
+ params={
+ "symbol": symbol,
+ "resolution": resolution,
+ "from": window_start,
+ "to": window_end,
+ },
+ timeout=_WALLEX_TIMEOUT_S,
+ )
+ if resp.status_code in {429, 500, 502, 503, 504}:
+ raise requests.HTTPError(
+ f"Wallex HTTP {resp.status_code}", response=resp
+ )
+ resp.raise_for_status()
+ return resp.json()
+
+ data = retry_with_budget(
+ _do_request,
+ transient=(requests.RequestException, TimeoutError),
+ deadline=deadline,
+ label=label,
+ )
+ if data.get("s") == "error":
+ raise requests.RequestException(
+ f"Wallex UDF error: {data.get('errmsg') or 'error'}"
+ )
+ times = data.get("t") or []
+ if times:
+ frames.append(
+ pd.DataFrame(
+ {
+ "trade_date": pd.to_datetime(times, unit="s"),
+ "open": pd.to_numeric(data["o"], errors="coerce"),
+ "high": pd.to_numeric(data["h"], errors="coerce"),
+ "low": pd.to_numeric(data["l"], errors="coerce"),
+ "close": pd.to_numeric(data["c"], errors="coerce"),
+ "volume": pd.to_numeric(
+ data.get("v") or [0.0] * len(times), errors="coerce"
+ ),
+ }
+ )
+ )
+ window_start = window_end
+ if window_start < end_ts:
+ time.sleep(_PAGE_SLEEP_S)
+
+ if not frames:
+ return None
+
+ df = pd.concat(frames).set_index("trade_date").sort_index()
+ df = df[~df.index.duplicated(keep="last")]
+ start_dt = pd.Timestamp(start_ts, unit="s")
+ end_dt = pd.Timestamp(end_ts, unit="s")
+ df = df[(df.index >= start_dt) & (df.index < end_dt)]
+ df = df[_OUTPUT_COLUMNS].dropna(subset=["open", "high", "low", "close"])
+ if df.empty:
+ return None
+ df = validate_ohlc(df)
+ return df.astype("float64") if not df.empty else None
diff --git a/agent/backtest/metrics.py b/agent/backtest/metrics.py
index 602a4a7aa..f38386b5b 100644
--- a/agent/backtest/metrics.py
+++ b/agent/backtest/metrics.py
@@ -29,6 +29,8 @@ _TRADING_DAYS = {
"tickerall": 260,
# crypto
"binance": 365,
+ # Iranian crypto exchanges (24/7 markets, same annualisation as okx/ccxt)
+ "nobitex": 365, "wallex": 365,
# A-share equity
"baostock": 252, "tencent": 252, "eastmoney": 252, "sina": 252,
# US / international equity
@@ -61,6 +63,7 @@ _BARS_PER_DAY = {
"eastmoney": 240, "sina": 240, "mootdx": 240, "futu": 240,
# crypto (24h)
"okx": 1440, "ccxt": 1440, "binance": 1440,
+ "nobitex": 1440, "wallex": 1440,
# forex/CFD (24h intraday)
"mt5": 1440, "tickerall": 1440,
# Indian equity (6.25h session)
@@ -74,6 +77,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,
+ "nobitex": 288, "wallex": 288,
"mt5": 288, "tickerall": 288,
"india_broker": 75,
"pykrx": 78,
@@ -84,6 +88,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,
+ "nobitex": 96, "wallex": 96,
"mt5": 96, "tickerall": 96,
"india_broker": 25,
"pykrx": 26,
@@ -94,6 +99,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,
+ "nobitex": 48, "wallex": 48,
"mt5": 48, "tickerall": 48,
"india_broker": 13,
"pykrx": 13,
@@ -104,6 +110,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,
+ "nobitex": 24, "wallex": 24,
"mt5": 24, "tickerall": 24,
"india_broker": 7,
"pykrx": 7,
@@ -114,6 +121,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,
+ "nobitex": 6, "wallex": 6,
"mt5": 6, "tickerall": 6,
"india_broker": 2,
"pykrx": 2,
@@ -124,6 +132,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,
+ "nobitex": 1, "wallex": 1,
"mt5": 1, "tickerall": 1,
"india_broker": 1,
"pykrx": 1,
diff --git a/agent/src/market_data.py b/agent/src/market_data.py
index f7b867f12..9b0634556 100644
--- a/agent/src/market_data.py
+++ b/agent/src/market_data.py
@@ -39,6 +39,13 @@ _SOURCE_PATTERNS = [
(re.compile(r"^\d{6}\.(KS|KQ)$", re.I), "pykrx"),
(re.compile(r"^[A-Z]+-USDT$", re.I), "okx"),
(re.compile(r"^[A-Z]+/USDT$", re.I), "ccxt"),
+ # Iran: Nobitex IRT-quoted crypto pairs (BTCIRT / BTC-IRT). Toman-
+ # denominated public UDF endpoint, no auth; explicit-source only (not in
+ # the crypto fallback chain — non-IRT pairs would never resolve there).
+ (re.compile(r"^[A-Z]+[-/]?IRT$", re.I), "nobitex"),
+ # Iran: Wallex TMN-quoted crypto pairs (USDTTMN / USDT-TMN). Public UDF
+ # endpoint, no auth; explicit-source only like nobitex.
+ (re.compile(r"^[A-Z]+[-/]?TMN$", re.I), "wallex"),
# Forex pairs and metals (EUR/USD, XAU/USD, EURUSD.FX). mt5 is the head of
# the forex chain and degrades to akshare/yfinance via the registry when no
# local MT5 terminal is attached. The 3-letter quote cannot collide with
diff --git a/agent/src/skills/data-routing/SKILL.md b/agent/src/skills/data-routing/SKILL.md
index 76875ac1a..f1c7b9922 100644
--- a/agent/src/skills/data-routing/SKILL.md
+++ b/agent/src/skills/data-routing/SKILL.md
@@ -23,6 +23,8 @@ per-source skill.
| akshare | A-shares, US, HK, futures, macro, forex | No | Unrestricted | akshare |
| yfinance | US, HK, Canada (TSX/TSXV) stocks, ETFs | No | Needs Yahoo access | yfinance |
| okx | Crypto (OKX exchange) | No | Needs okx.com access | okx-market |
+| nobitex | Crypto, IRT/Toman-quoted pairs (BTC-IRT, USDT-IRT — Iran market premium) | No | Needs apiv2.nobitex.ir access | data-routing (explicit `*IRT` routing only) |
+| wallex | Crypto, TMN/Toman-quoted pairs (USDT-TMN, BTC-TMN — Iran market premium) | No | Needs api.wallex.ir access | data-routing (explicit `*TMN` routing only; truly serves 1m/1h/1d) |
| ccxt | Crypto (100+ exchanges) | No | Needs exchange access | ccxt |
| baostock | A-shares (free daily/min) | No | China network | data-routing |
| tencent | A-shares, HK, US (never-banned) | No | Unrestricted | data-routing |
diff --git a/agent/src/trading/service.py b/agent/src/trading/service.py
index 8d8bbb58e..981daa5c5 100644
--- a/agent/src/trading/service.py
+++ b/agent/src/trading/service.py
@@ -153,10 +153,17 @@ def _local_plugin_call(
from src.trading.connections import ConnectionStore, credential_fields
from src.trading.local_plugins import load_adapter, plugin_by_profile_id
+ store = ConnectionStore()
connection_id = str(overrides.get("connection_id") or "").strip().lower()
+ if not connection_id:
+ # CLI/agent flows do not carry a connection id; when the operator has
+ # installed exactly one connection for this profile, use it. Explicit
+ # ids (Web UI) always win.
+ candidates = [row for row in store.list() if row.profile_id == profile.id]
+ if len(candidates) == 1:
+ connection_id = candidates[0].id
if not connection_id:
raise ValueError("local connector plugins require a connection_id")
- store = ConnectionStore()
connection = store.get(connection_id)
if connection.profile_id != profile.id:
raise ValueError("local connection profile does not match the requested plugin")
diff --git a/agent/tests/test_local_plugin_autoresolve.py b/agent/tests/test_local_plugin_autoresolve.py
new file mode 100644
index 000000000..75cb18044
--- /dev/null
+++ b/agent/tests/test_local_plugin_autoresolve.py
@@ -0,0 +1,79 @@
+"""Regression tests: local connector profiles auto-resolve a single connection.
+
+The CLI and agent trading tools never carry a ``connection_id``; service-level
+local-plugin calls must therefore resolve the operator's single installed
+connection for a profile, and refuse ambiguous setups instead of guessing.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from src.trading.connections import ConnectionStore
+from src.trading.service import check_connection
+
+_ADAPTER = """\
+def check_status(*, credentials, config):
+ return {"status": "ok", "configured": bool(credentials), "readonly": True}
+
+
+def get_account_snapshot(*, credentials, config):
+ return {"status": "ok"}
+
+
+def get_positions(*, credentials, config):
+ return {"status": "ok", "positions": []}
+"""
+
+_MANIFEST: dict[str, Any] = {
+ "schema_version": 1,
+ "profile": {
+ "id": "fake-live-readonly",
+ "connector": "fake",
+ "label": "Fake Live · Local Read-Only",
+ "environment": "live",
+ "readonly": True,
+ "capabilities": ["account.read", "positions.read"],
+ },
+ "entrypoint": "adapter.py",
+ "auth": {
+ "type": "token",
+ "fields": [
+ {"name": "api_token", "label": "Token", "secret": True, "required": True}
+ ],
+ },
+}
+
+
+def runtime_root(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ root = tmp_path / "runtime"
+ root.mkdir()
+ monkeypatch.setattr("src.trading.connections.get_runtime_root", lambda: root)
+ monkeypatch.setattr("src.trading.local_plugins.get_runtime_root", lambda: root)
+ plugin_dir = root / "connectors" / "fake"
+ plugin_dir.mkdir(parents=True)
+ (plugin_dir / "connector.json").write_text(
+ json.dumps(_MANIFEST), encoding="utf-8"
+ )
+ (plugin_dir / "adapter.py").write_text(_ADAPTER, encoding="utf-8")
+ return root
+
+
+def test_auto_resolves_single_connection(runtime_root: Path) -> None:
+ ConnectionStore().create("fake-main", "fake-live-readonly", "Fake")
+ report = check_connection("fake-live-readonly")
+ assert report["status"] == "ok"
+ assert report["configured"] is False
+
+
+def test_ambiguous_connections_require_explicit_id(runtime_root: Path) -> None:
+ store = ConnectionStore()
+ store.create("fake-a", "fake-live-readonly", "A")
+ store.create("fake-b", "fake-live-readonly", "B")
+ with pytest.raises(ValueError, match="connection_id"):
+ check_connection("fake-live-readonly")
diff --git a/agent/tests/test_nobitex_loader.py b/agent/tests/test_nobitex_loader.py
new file mode 100644
index 000000000..9198e1ffb
--- /dev/null
+++ b/agent/tests/test_nobitex_loader.py
@@ -0,0 +1,198 @@
+"""Tests for nobitex loader: contract, symbol mapping, intervals, parsing.
+
+All HTTP is mocked - no test reaches the live Nobitex endpoint. The loader
+talks to the API through ``requests.Session.get``, so tests monkeypatch that
+method on ``nobitex.requests.Session``.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Dict, List
+
+import pandas as pd
+import pytest
+import requests
+
+from backtest.loaders import nobitex
+
+
+def _udf_payload(
+ times: List[int],
+ o: List[Any],
+ h: List[Any],
+ l: List[Any],
+ c: List[Any],
+ v: List[Any],
+ status: str = "ok",
+) -> Dict[str, Any]:
+ return {"s": status, "t": times, "o": o, "h": h, "l": l, "c": c, "v": v}
+
+
+class _FakeResponse:
+ def __init__(self, payload: Dict[str, Any], status_code: int = 200):
+ self._payload = payload
+ self.status_code = status_code
+
+ def json(self) -> Dict[str, Any]:
+ return self._payload
+
+ def raise_for_status(self) -> None:
+ if self.status_code >= 400:
+ raise requests.HTTPError(f"HTTP {self.status_code}")
+
+
+class _CallRecorder:
+ def __init__(self, pages: Dict[int, Dict[str, Any]]):
+ self.pages = pages
+ self.calls: List[Dict[str, Any]] = []
+
+ def __call__(self, url, params=None, timeout=None):
+ self.calls.append({"url": url, "params": dict(params or {})})
+ page = int((params or {}).get("page", 1))
+ payload = self.pages.get(page)
+ if payload is None:
+ return _FakeResponse({"s": "no_data"})
+ return _FakeResponse(payload)
+
+
+def _patch(monkeypatch: pytest.MonkeyPatch, pages: Dict[int, Dict[str, Any]]) -> _CallRecorder:
+ recorder = _CallRecorder(pages)
+ monkeypatch.setattr(nobitex.requests.Session, "get", recorder)
+ return recorder
+
+
+class TestLoaderContract:
+ def test_attributes(self):
+ loader = nobitex.DataLoader()
+ assert loader.name == "nobitex"
+ assert loader.markets == {"crypto"}
+ assert loader.requires_auth is False
+
+
+class TestMapSymbol:
+ @pytest.mark.parametrize(
+ "raw,expected",
+ [
+ ("BTC-IRT", "BTCIRT"),
+ ("BTCIRT", "BTCIRT"),
+ ("btcirt", "BTCIRT"),
+ ("USDT/IRT", "USDTIRT"),
+ (" usdt-irt ", "USDTIRT"),
+ ],
+ )
+ def test_normalizes_aliases(self, raw: str, expected: str):
+ assert nobitex.map_symbol(raw) == expected
+
+
+class TestIntervalMap:
+ def test_resolutions(self):
+ assert nobitex._INTERVAL_MAP["1h"] == "60"
+ assert nobitex._INTERVAL_MAP["1H"] == "60"
+ assert nobitex._INTERVAL_MAP["4h"] == "240"
+ assert nobitex._INTERVAL_MAP["4H"] == "240"
+ assert nobitex._INTERVAL_MAP["1d"] == "D"
+ assert nobitex._INTERVAL_MAP["1D"] == "D"
+ assert nobitex._INTERVAL_MAP["12H"] == "720"
+
+ def test_unsupported_interval_returns_empty_without_http(self, monkeypatch):
+ def _fail(*args: Any, **kwargs: Any) -> None:
+ raise AssertionError("HTTP must not be called for unsupported intervals")
+
+ monkeypatch.setattr(nobitex.requests.Session, "get", _fail)
+ out = nobitex.DataLoader().fetch(
+ ["BTC-IRT"], "2024-01-01", "2024-02-01", interval="1W"
+ )
+ assert out == {}
+
+
+class TestFetch:
+ def test_parses_udf_into_sorted_ohlcv(self, monkeypatch):
+ recorder = _patch(
+ monkeypatch,
+ {
+ 1: _udf_payload(
+ [1704067200, 1704153600],
+ ["1", "2"],
+ ["2", "3"],
+ ["0.5", "1"],
+ ["1.5", "2.5"],
+ ["10", "20"],
+ )
+ },
+ )
+ out = nobitex.DataLoader().fetch(["BTC-IRT"], "2024-01-01", "2024-01-03")
+ assert list(out) == ["BTC-IRT"]
+ df = out["BTC-IRT"]
+ assert df.index.name == "trade_date"
+ assert isinstance(df.index, pd.DatetimeIndex)
+ assert df.index.is_monotonic_increasing
+ assert list(df.columns) == ["open", "high", "low", "close", "volume"]
+ assert len(df) == 2
+ assert df["close"].tolist() == [1.5, 2.5]
+ assert df["volume"].dtype.kind == "f"
+ assert recorder.calls[0]["params"]["symbol"] == "BTCIRT"
+ assert recorder.calls[0]["params"]["resolution"] == "D"
+ assert recorder.calls[0]["params"]["page"] == 1
+
+ def test_no_data_yields_empty_result(self, monkeypatch):
+ _patch(monkeypatch, {1: {"s": "no_data"}})
+ out = nobitex.DataLoader().fetch(["BTC-IRT"], "2024-01-01", "2024-01-03")
+ assert out == {}
+
+ def test_error_status_skips_symbol(self, monkeypatch):
+ _patch(monkeypatch, {1: {"s": "error", "errmsg": "InvalidSymbol"}})
+ out = nobitex.DataLoader().fetch(["BTC-IRT"], "2024-01-01", "2024-01-03")
+ assert out == {}
+
+ def test_one_bad_symbol_does_not_abort_batch(self, monkeypatch):
+ good = _udf_payload([1704067200], ["1"], ["2"], ["0.5"], ["1.5"], ["10"])
+ calls: List[Dict[str, Any]] = []
+
+ def fake_get(session_self, url, params=None, timeout=None):
+ symbol = (params or {}).get("symbol")
+ if symbol == "BADIRT":
+ return _FakeResponse({"s": "error", "errmsg": "InvalidSymbol"})
+ calls.append({"params": dict(params or {})})
+ return _FakeResponse(good)
+
+ monkeypatch.setattr(nobitex.requests.Session, "get", fake_get)
+ out = nobitex.DataLoader().fetch(
+ ["BTC-IRT", "BAD-IRT"], "2024-01-01", "2024-01-03"
+ )
+ assert list(out) == ["BTC-IRT"]
+ assert len(calls) >= 1
+
+ def test_paginates_older_pages_and_dedupes(self, monkeypatch):
+ base = 1700000000
+ t1 = [base + i * 3600 for i in range(nobitex._MAX_PER_PAGE)]
+ t2 = [base - (300 - i) * 3600 for i in range(300)]
+
+ def payload_for(times: List[int]) -> Dict[str, Any]:
+ return _udf_payload(
+ times,
+ ["1"] * len(times),
+ ["2"] * len(times),
+ ["0.5"] * len(times),
+ ["1.5"] * len(times),
+ ["10"] * len(times),
+ )
+
+ recorder = _patch(monkeypatch, {1: payload_for(t1), 2: payload_for(t2)})
+ out = nobitex.DataLoader().fetch(["BTC-IRT"], "2023-11-01", "2024-03-01")
+ assert len(out["BTC-IRT"]) == 800
+ assert [c["params"]["page"] for c in recorder.calls] == [1, 2]
+
+ def test_invalid_date_range_raises(self):
+ with pytest.raises(ValueError):
+ nobitex.DataLoader().fetch(["BTC-IRT"], "2024-02-01", "2024-01-01")
+
+
+class TestRoutingPattern:
+ def test_source_pattern_matches_irt_pairs_only(self):
+ from src.market_data import detect_source
+
+ assert detect_source("BTCIRT") == "nobitex"
+ assert detect_source("BTC-IRT") == "nobitex"
+ assert detect_source("usdtirt") == "nobitex"
+ assert detect_source("BTC-USDT") == "okx"
+ assert detect_source("AAPL.US") == "yahoo"
diff --git a/agent/tests/test_wallex_loader.py b/agent/tests/test_wallex_loader.py
new file mode 100644
index 000000000..8ed768fe6
--- /dev/null
+++ b/agent/tests/test_wallex_loader.py
@@ -0,0 +1,195 @@
+"""Tests for wallex loader: contract, symbol mapping, intervals, chunking.
+
+All HTTP is mocked - no test reaches the live Wallex endpoint. The loader
+talks to the API through ``requests.Session.get``, so tests monkeypatch that
+method on ``wallex.requests.Session``.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Dict, List
+
+import pandas as pd
+import pytest
+import requests
+
+from backtest.loaders import wallex
+
+
+def _udf_payload(
+ times: List[int],
+ o: List[Any],
+ h: List[Any],
+ l: List[Any],
+ c: List[Any],
+ v: List[Any],
+ status: str = "ok",
+) -> Dict[str, Any]:
+ return {"s": status, "t": times, "o": o, "h": h, "l": l, "c": c, "v": v}
+
+
+class _FakeResponse:
+ def __init__(self, payload: Dict[str, Any], status_code: int = 200):
+ self._payload = payload
+ self.status_code = status_code
+
+ def json(self) -> Dict[str, Any]:
+ return self._payload
+
+ def raise_for_status(self) -> None:
+ if self.status_code >= 400:
+ raise requests.HTTPError(f"HTTP {self.status_code}")
+
+
+class _CallRecorder:
+ """Plain callable: when set as a class attribute it receives no self."""
+
+ def __init__(self, handler):
+ self.handler = handler
+ self.calls: List[Dict[str, Any]] = []
+
+ def __call__(self, url, params=None, timeout=None):
+ self.calls.append({"url": url, "params": dict(params or {})})
+ payload = self.handler(dict(params or {}))
+ if isinstance(payload, dict):
+ return _FakeResponse(payload)
+ return payload
+
+
+def _patch(monkeypatch: pytest.MonkeyPatch, handler) -> _CallRecorder:
+ recorder = _CallRecorder(handler)
+ monkeypatch.setattr(wallex.requests.Session, "get", recorder)
+ return recorder
+
+
+class TestLoaderContract:
+ def test_attributes(self):
+ loader = wallex.DataLoader()
+ assert loader.name == "wallex"
+ assert loader.markets == {"crypto"}
+ assert loader.requires_auth is False
+
+
+class TestMapSymbol:
+ @pytest.mark.parametrize(
+ "raw,expected",
+ [
+ ("USDT-TMN", "USDTTMN"),
+ ("USDTTMN", "USDTTMN"),
+ ("usdttmn", "USDTTMN"),
+ ("BTC/TMN", "BTCTMN"),
+ (" btc-tmn ", "BTCTMN"),
+ ],
+ )
+ def test_normalizes_aliases(self, raw: str, expected: str):
+ assert wallex.map_symbol(raw) == expected
+
+
+class TestIntervalMap:
+ def test_only_true_buckets_are_mapped(self):
+ assert wallex._INTERVAL_MAP == {"1m": "1", "1h": "60", "1H": "60", "1d": "1D", "1D": "1D"}
+
+ def test_silently_degrading_intervals_reject_without_http(self, monkeypatch):
+ def _fail(*args: Any, **kwargs: Any) -> None:
+ raise AssertionError("HTTP must not be called for degrading intervals")
+
+ monkeypatch.setattr(wallex.requests.Session, "get", _fail)
+ loader = wallex.DataLoader()
+ for interval in ("15m", "4h", "4H", "720", "1W"):
+ assert loader.fetch(["USDT-TMN"], "2024-01-01", "2024-02-01", interval=interval) == {}
+
+
+class TestFetch:
+ def test_parses_string_ohlcv_into_sorted_floats(self, monkeypatch):
+ def handler(params: Dict[str, Any]):
+ return _udf_payload(
+ [1704067200, 1704153600],
+ ["198216.0", "198148.0"],
+ ["199125.0", "199000.0"],
+ ["198148.0", "197827.0"],
+ ["198174.0", "199000.0"],
+ ["128980.98", "183954.04"],
+ )
+
+ recorder = _patch(monkeypatch, handler)
+ out = wallex.DataLoader().fetch(["USDT-TMN"], "2024-01-01", "2024-01-03")
+ assert list(out) == ["USDT-TMN"]
+ df = out["USDT-TMN"]
+ assert df.index.name == "trade_date"
+ assert isinstance(df.index, pd.DatetimeIndex)
+ assert df.index.is_monotonic_increasing
+ assert list(df.columns) == ["open", "high", "low", "close", "volume"]
+ assert len(df) == 2
+ assert df["close"].tolist() == [198174.0, 199000.0]
+ assert df["volume"].dtype.kind == "f"
+ assert recorder.calls[0]["params"]["symbol"] == "USDTTMN"
+ assert recorder.calls[0]["params"]["resolution"] == "1D"
+
+ def test_error_body_skips_symbol(self, monkeypatch):
+ recorder = _patch(
+ monkeypatch,
+ lambda params: {"errmsg": "Invalid resolution!", "s": "error"},
+ )
+ out = wallex.DataLoader().fetch(["USDT-TMN"], "2024-01-01", "2024-01-03")
+ assert out == {}
+ assert recorder.calls, "handler should have been invoked"
+
+ def test_one_bad_symbol_does_not_abort_batch(self, monkeypatch):
+ good = _udf_payload(
+ [1704067200], ["1"], ["2"], ["0.5"], ["1.5"], ["10"]
+ )
+
+ def handler(params: Dict[str, Any]):
+ if params.get("symbol") == "BADTMN":
+ return {"errmsg": "Invalid symbol", "s": "error"}
+ return good
+
+ _patch(monkeypatch, handler)
+ out = wallex.DataLoader().fetch(
+ ["USDT-TMN", "BAD-TMN"], "2024-01-01", "2024-01-03"
+ )
+ assert list(out) == ["USDT-TMN"]
+
+ def test_forward_chunking_merges_windows(self, monkeypatch):
+ calls: List[Dict[str, Any]] = []
+
+ def handler(params: Dict[str, Any]):
+ calls.append(dict(params))
+ start = int(params["from"])
+ step = 60
+ span = int(params["to"]) - start
+ count = min(span // step, 500)
+ times = [start + i * step for i in range(count)]
+ return _udf_payload(
+ times,
+ ["1"] * count,
+ ["2"] * count,
+ ["0.5"] * count,
+ ["1.5"] * count,
+ ["10"] * count,
+ )
+
+ _patch(monkeypatch, handler)
+ # 74 days of 1m data spans 4 windows of 20 days.
+ out = wallex.DataLoader().fetch(["USDT-TMN"], "2024-01-01", "2024-03-15", interval="1m")
+ df = out["USDT-TMN"]
+ assert df.index.is_monotonic_increasing
+ assert not df.index.duplicated().any()
+ assert len(calls) >= 2
+ froms = [c["from"] for c in calls]
+ assert froms == sorted(froms), "windows must walk forward"
+
+ def test_invalid_date_range_raises(self):
+ with pytest.raises(ValueError):
+ wallex.DataLoader().fetch(["USDT-TMN"], "2024-02-01", "2024-01-01")
+
+
+class TestRoutingPattern:
+ def test_source_pattern_matches_tmn_pairs_only(self):
+ from src.market_data import detect_source
+
+ assert detect_source("USDTTMN") == "wallex"
+ assert detect_source("USDT-TMN") == "wallex"
+ assert detect_source("btc-tmn") == "wallex"
+ assert detect_source("BTCIRT") == "nobitex"
+ assert detect_source("BTC-USDT") == "okx"