Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(broker): add Zerodha Kite Connect support for Indian equities

Ashutosh Singhbf3f38680376
diff --git a/agent/backtest/loaders/india_broker_loader.py b/agent/backtest/loaders/india_broker_loader.py
index dd43d2ebf..72f599e80 100644
--- a/agent/backtest/loaders/india_broker_loader.py
+++ b/agent/backtest/loaders/india_broker_loader.py
@@ -55,6 +55,13 @@ def _resolve_broker():
``src.trading`` package or broker SDK simply means "unavailable", never a
crash in the loader registry.
"""
+ try:
+ from src.trading.connectors.zerodha import sdk as zerodha_sdk
+
+ if zerodha_sdk.zerodha_available():
+ return "zerodha", zerodha_sdk
+ except Exception as exc: # noqa: BLE001 — optional dependency / config
+ logger.debug("zerodha bridge unavailable: %s", exc)
try:
from src.trading.connectors.shoonya import sdk as shoonya_sdk
diff --git a/agent/src/live/registry.py b/agent/src/live/registry.py
index 8102bfbd2..d6ca9fd21 100644
--- a/agent/src/live/registry.py
+++ b/agent/src/live/registry.py
@@ -36,6 +36,7 @@ from src.trading.connectors.shoonya.classification import SHOONYA_TOOL_CLASS
from src.trading.connectors.tiger.classification import TIGER_TOOL_CLASS
from src.trading.connectors.etoro.classification import ETORO_TOOL_CLASS
from src.trading.connectors.trading212.classification import TRADING212_TOOL_CLASS
+from src.trading.connectors.zerodha.classification import ZERODHA_TOOL_CLASS
logger = logging.getLogger(__name__)
@@ -57,6 +58,7 @@ _BROKER_CURATED_MAPS = {
"trading212": TRADING212_TOOL_CLASS,
"mt5": MT5_TOOL_CLASS,
"etoro": ETORO_TOOL_CLASS,
+ "zerodha": ZERODHA_TOOL_CLASS,
}
diff --git a/agent/src/trading/connectors/zerodha/__init__.py b/agent/src/trading/connectors/zerodha/__init__.py
new file mode 100644
index 000000000..fb97bb28d
--- /dev/null
+++ b/agent/src/trading/connectors/zerodha/__init__.py
@@ -0,0 +1,19 @@
+"""Zerodha Kite Connect trading connector.
+
+Read-only and paper/live account access via the ``kiteconnect`` SDK. A
+``broker_sdk`` transport for the Indian equity and F&O markets (NSE/BSE).
+
+Zerodha is India's largest retail broker. Kite Connect exposes historical OHLCV
+via ``kite.historical_data`` (capped at 2000 days/request, bars dated at
+midnight IST) and quote/positions/orders for live use. For our backtest data
+bridge the read path (``get_historical_bars``) is what the ``india_broker``
+loader consumes.
+
+Auth: Kite uses a request-token login (api_key + api_secret -> access_token),
+or a pre-issued access_token stored in config. The connector is opt-in
+(``requires_auth``): it is inert in CI / unconfigured runs.
+"""
+
+from __future__ import annotations
+
+__all__ = ["sdk"]
diff --git a/agent/src/trading/connectors/zerodha/classification.py b/agent/src/trading/connectors/zerodha/classification.py
new file mode 100644
index 000000000..5c31195c7
--- /dev/null
+++ b/agent/src/trading/connectors/zerodha/classification.py
@@ -0,0 +1,26 @@
+"""Zerodha Kite Connect tool classification (Tier 2 curated map).
+
+Read tools stay ungated; order placement is pinned WRITE so the live gate fails
+closed. Mirrors shoonya/classification.py. The connector itself is paper-only,
+but the classification ladder is the registry's default-deny backstop.
+"""
+
+from __future__ import annotations
+
+from src.live.classification import ToolClass
+
+ZERODHA_TOOL_CLASS: dict[str, ToolClass] = {
+ # read-only market data + account
+ "kite.quote": ToolClass.READ,
+ "kite.historical_data": ToolClass.READ,
+ "kite.instruments": ToolClass.READ,
+ "kite.positions": ToolClass.READ,
+ "kite.holdings": ToolClass.READ,
+ "kite.orders": ToolClass.READ,
+ "kite.order_history": ToolClass.READ,
+ "kite.margins": ToolClass.READ,
+ # order mutation -> WRITE (fails closed under the live gate)
+ "kite.place_order": ToolClass.WRITE,
+ "kite.cancel_order": ToolClass.WRITE,
+ "kite.modify_order": ToolClass.WRITE,
+}
diff --git a/agent/src/trading/connectors/zerodha/profiles.py b/agent/src/trading/connectors/zerodha/profiles.py
new file mode 100644
index 000000000..790ed3e48
--- /dev/null
+++ b/agent/src/trading/connectors/zerodha/profiles.py
@@ -0,0 +1,66 @@
+"""Built-in Zerodha (Kite Connect) connector profiles.
+
+Zerodha (https://zerodha.com) is India's largest retail broker. Kite Connect
+offers historical OHLCV, quotes, positions, and order placement via a clean
+REST SDK (``kiteconnect`` on PyPI). Free API access for personal use; equity
+delivery is ₹0 brokerage, intraday is 0.03% / ₹20 flat.
+
+Paper-only by design: Kite exposes no sandbox and no runtime paper/live
+discriminator — an access token reaches the real account whether the profile is
+declared ``paper`` or ``live``. Following the Shoonya/Longbridge precedent, this
+connector ships read-only paper/live profiles plus a locally simulated
+paper-trade profile, and exposes NO live order placement (see ``sdk.place_order``).
+"""
+
+from __future__ import annotations
+
+from src.trading.types import READ_CAPABILITIES, TradingProfile
+
+ZERODHA_PROFILES: tuple[TradingProfile, ...] = (
+ TradingProfile(
+ id="zerodha-paper-sdk",
+ connector="zerodha",
+ label="Zerodha Paper · KiteConnect (India, ₹0 delivery)",
+ environment="paper",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES,
+ readonly=True,
+ config={"profile": "paper"},
+ notes=(
+ "Reads Indian market data (NSE/BSE equities, F&O) via Kite Connect. "
+ "Paper vs live is operator-declared (the API exposes no runtime "
+ "discriminator). Equity delivery ₹0 brokerage; intraday 0.03%/₹20 flat. "
+ "Historical data capped at 2000 days/request (connector paginates)."
+ ),
+ ),
+ TradingProfile(
+ id="zerodha-paper-trade",
+ connector="zerodha",
+ label="Zerodha Paper · KiteConnect Trade (India)",
+ environment="paper",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES + ("orders.place",),
+ readonly=False,
+ config={"profile": "paper"},
+ notes=(
+ "Places PAPER orders simulated locally using real Zerodha market "
+ "data — no real money at risk. Paper-only by design: Kite exposes no "
+ "runtime paper/live discriminator, so live order placement is not "
+ "supported."
+ ),
+ ),
+ TradingProfile(
+ id="zerodha-live-sdk-readonly",
+ connector="zerodha",
+ label="Zerodha Live · KiteConnect Read-Only (India)",
+ environment="live",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES,
+ readonly=True,
+ config={"profile": "live-readonly"},
+ notes=(
+ "Reads a live Zerodha account (positions, holdings, orders, quotes, "
+ "history). No order placement. Equity delivery ₹0 brokerage."
+ ),
+ ),
+)
diff --git a/agent/src/trading/connectors/zerodha/sdk.py b/agent/src/trading/connectors/zerodha/sdk.py
new file mode 100644
index 000000000..19f9503f5
--- /dev/null
+++ b/agent/src/trading/connectors/zerodha/sdk.py
@@ -0,0 +1,413 @@
+"""Zerodha Kite Connect connector SDK (read path + paper-capped orders).
+
+Mirrors the Shoonya/Dhan connector surface so the ``india_broker`` loader can
+treat Zerodha uniformly:
+
+ get_historical_bars(symbol, *, exchange="NSE", period="1d", limit=90)
+ -> {"status": "ok", "symbol": ..., "bars": [{time, open, high, low, close, volume}]}
+
+Kite specifics handled here:
+ * interval map: project tokens (1m/5m/15m/30m/1h/4h/1d) -> Kite intervals
+ (minute/5minute/15minute/30minute/60minute/day). Kite has no 1H/4H token
+ collision, but we alias 1h->60minute, 4h->day to match the project set.
+ * Kite historical is capped at 2000 days per call and dates bars at midnight
+ IST; we paginate by chunking the [start, end] range into <=2000-day windows
+ and normalize the resulting index to UTC-naive (matching the loader).
+ * Symbols: project ``RELIANCE.NS`` -> Kite ``exchange=NSE``,
+ ``tradingsymbol=RELIANCE``. Token-based fetch is also supported if the
+ instrument token is supplied, but the symbol form mirrors Shoonya/Dhan.
+
+Paper guard: like Shoonya, Kite exposes no sandbox, so live order placement is
+structurally refused (paper profile only).
+"""
+
+from __future__ import annotations
+
+import json
+from dataclasses import asdict, dataclass
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+from typing import Any, Mapping
+
+from src.config.paths import get_runtime_root
+
+CONFIG_FILENAME = "zerodha.json"
+
+PROFILE_ENVIRONMENTS = {
+ "paper": "paper",
+ "live-readonly": "live",
+ "live": "live",
+}
+
+KITE_HIST_BASE = "https://api.kite.trade"
+
+_PAPER_ONLY_ERROR = (
+ "Zerodha connector is paper-only: Kite exposes no runtime paper/live "
+ "discriminator (a live token reaches the real account), so live order "
+ "placement is not supported. Use a zerodha-paper-* profile."
+)
+
+
+class ZerodhaDependencyError(RuntimeError):
+ """Raised when ``kiteconnect`` is not installed."""
+
+
+class ZerodhaConfigError(RuntimeError):
+ """Raised when config is missing or invalid."""
+
+
+class ZerodhaExchange:
+ NSE = "NSE"
+ BSE = "BSE"
+ NFO = "NFO" # NSE F&O
+ BFO = "BFO" # BSE F&O
+ CDS = "CDS" # Currency
+ MCX = "MCX" # Commodity
+
+
+@dataclass(frozen=True)
+class ZerodhaConfig:
+ """Zerodha connector connection settings."""
+
+ api_key: str = ""
+ api_secret: str = ""
+ access_token: str = ""
+ profile: str = "paper"
+ timeout: float = 15.0
+ readonly: bool = True
+
+ @classmethod
+ def from_mapping(cls, data: Mapping[str, Any] | None = None) -> "ZerodhaConfig":
+ payload = dict(data or {})
+ profile = str(payload.get("profile") or "paper").strip().lower()
+ if profile not in PROFILE_ENVIRONMENTS:
+ raise ZerodhaConfigError("profile must be 'paper', 'live-readonly' or 'live'")
+ return cls(
+ api_key=str(payload.get("api_key") or "").strip(),
+ api_secret=str(payload.get("api_secret") or "").strip(),
+ access_token=str(payload.get("access_token") or "").strip(),
+ profile=profile,
+ timeout=float(payload.get("timeout") or 15.0),
+ readonly=bool(payload.get("readonly", True)),
+ )
+
+ def with_overrides(self, **kw: Any) -> "ZerodhaConfig":
+ payload = asdict(self)
+ for key in ("api_key", "api_secret", "access_token", "profile"):
+ if kw.get(key) is not None:
+ payload[key] = kw[key]
+ return ZerodhaConfig.from_mapping(payload)
+
+ @property
+ def environment(self) -> str:
+ return PROFILE_ENVIRONMENTS.get(self.profile, "paper")
+
+ @property
+ def is_paper(self) -> bool:
+ return self.environment == "paper"
+
+
+_OVERRIDE_KEYS = ("api_key", "api_secret", "access_token", "profile")
+
+#: Project interval token -> Kite interval.
+_INTERVAL_MAP = {
+ "1m": "minute",
+ "5m": "5minute",
+ "15m": "15minute",
+ "30m": "30minute",
+ "1h": "60minute",
+ "1H": "60minute",
+ "4h": "day",
+ "4H": "day",
+ "1d": "day",
+ "1D": "day",
+}
+
+#: Kite caps historical pulls at 2000 calendar days per request.
+_KITE_MAX_SPAN_DAYS = 2000
+
+
+def config_path() -> Path:
+ return get_runtime_root() / CONFIG_FILENAME
+
+
+def load_config() -> ZerodhaConfig:
+ path = config_path()
+ if not path.exists():
+ return ZerodhaConfig()
+ try:
+ return ZerodhaConfig.from_mapping(json.loads(path.read_text(encoding="utf-8")))
+ except (OSError, ValueError, json.JSONDecodeError) as exc:
+ raise ZerodhaConfigError(f"invalid Zerodha config at {path}: {exc}") from exc
+
+
+def save_config(config: ZerodhaConfig) -> Path:
+ path = config_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(
+ json.dumps(asdict(config), indent=2, ensure_ascii=False) + "\n",
+ encoding="utf-8",
+ )
+ try:
+ path.chmod(0o600)
+ except OSError:
+ pass
+ return path
+
+
+def build_config(
+ profile_config: Mapping[str, Any] | None = None,
+ overrides: Mapping[str, Any] | None = None,
+) -> "ZerodhaConfig":
+ base = asdict(load_config())
+ for key, value in dict(profile_config or {}).items():
+ if value is not None:
+ base[key] = value
+ cfg = ZerodhaConfig.from_mapping(base)
+ clean = {
+ k: v for k, v in dict(overrides or {}).items()
+ if k in _OVERRIDE_KEYS and v not in (None, "")
+ }
+ return cfg.with_overrides(**clean) if clean else cfg
+
+
+def _require_kite():
+ try:
+ from kiteconnect import KiteConnect # type: ignore
+ except ImportError as exc: # optional dependency
+ raise ZerodhaDependencyError(
+ "Optional dependency missing: install with `pip install kiteconnect`"
+ ) from exc
+ return KiteConnect
+
+
+def zerodha_available() -> bool:
+ try:
+ _require_kite()
+ return True
+ except ZerodhaDependencyError:
+ return False
+
+
+def _public_config(cfg: ZerodhaConfig) -> dict[str, Any]:
+ return {
+ "api_key_set": bool(cfg.api_key),
+ "access_token_set": bool(cfg.access_token),
+ "profile": cfg.profile,
+ }
+
+
+def _login(cfg: ZerodhaConfig):
+ """Return an authenticated KiteConnect client (access_token set)."""
+ KiteConnect = _require_kite()
+ if not cfg.api_key:
+ raise ZerodhaConfigError("api_key is required")
+ kite = KiteConnect(api_key=cfg.api_key)
+ if cfg.access_token:
+ kite.set_access_token(cfg.access_token)
+ elif cfg.api_secret:
+ # Without a request token we cannot mint a fresh access token headlessly;
+ # the user must supply either access_token or run the login helper.
+ raise ZerodhaConfigError(
+ "access_token is required (Kite login needs an interactive "
+ "request-token exchange; supply access_token directly)"
+ )
+ return kite
+
+
+def check_status(config: ZerodhaConfig | None = None) -> dict[str, Any]:
+ cfg = config or load_config()
+ report: dict[str, Any] = {
+ "status": "ok",
+ "config": _public_config(cfg),
+ "sdk": {"package": "kiteconnect", "installed": zerodha_available()},
+ "paper_guard": "simulated_locally",
+ "host": KITE_HIST_BASE,
+ "brokerage": "Zerodha equity delivery ₹0; intraday 0.03% / ₹20 flat",
+ }
+ missing = []
+ if not cfg.api_key:
+ missing.append("api_key")
+ if not cfg.access_token:
+ missing.append("access_token")
+ if missing:
+ report["status"] = "error"
+ report["error"] = f"Zerodha connector not configured: missing {', '.join(missing)}."
+ return report
+ if not report["sdk"]["installed"]:
+ report["status"] = "error"
+ report["error"] = "Optional dependency missing: install with `pip install kiteconnect`"
+ return report
+ return report
+
+
+def get_historical_bars(
+ symbol: str,
+ *,
+ config: ZerodhaConfig | None = None,
+ exchange: str = "NSE",
+ period: str = "1d",
+ limit: int = 90,
+) -> dict[str, Any]:
+ """Fetch historical OHLCV bars from Kite, paginated past the 2000-day cap."""
+ cfg = config or load_config()
+ clean = symbol.strip().upper()
+
+ interval = _INTERVAL_MAP.get(str(period).strip())
+ if interval is None:
+ return {
+ "status": "error",
+ "error": f"unsupported period: {period!r}; supported: {sorted(_INTERVAL_MAP)}",
+ "symbol": clean,
+ }
+
+ try:
+ kite = _login(cfg)
+ except ZerodhaConfigError as exc:
+ return {"status": "error", "error": str(exc), "symbol": clean}
+
+ # Build the date window: from (today - span) to today, span sized to `limit`
+ # daily bars (intraday uses a shorter window like Shoonya).
+ end = datetime.now(timezone.utc)
+ if interval == "day":
+ start = end - timedelta(days=min(limit * 2, 4000))
+ else:
+ start = end - timedelta(days=5)
+
+ bars: list[dict[str, Any]] = []
+ # Paginate in <=2000-day chunks (Kite hard cap).
+ chunk_start = start
+ while chunk_start < end:
+ chunk_end = min(chunk_start + timedelta(days=_KITE_MAX_SPAN_DAYS), end)
+ try:
+ rows = kite.historical_data(
+ instrument_token=_symbol_to_token(kite, clean, exchange),
+ from_date=chunk_start,
+ to_date=chunk_end,
+ interval=interval,
+ )
+ except Exception as exc: # noqa: BLE001 — one bad symbol never aborts
+ return {"status": "error", "error": str(exc), "symbol": clean}
+ for r in rows:
+ ts = r.get("date")
+ if ts is None:
+ continue
+ # Kite returns tz-aware datetimes (IST); normalize to UTC-naive.
+ if hasattr(ts, "tzinfo") and ts.tzinfo is not None:
+ ts = ts.astimezone(timezone.utc).replace(tzinfo=None)
+ bars.append({
+ "time": int(ts.timestamp()),
+ "open": float(r.get("open", 0)),
+ "high": float(r.get("high", 0)),
+ "low": float(r.get("low", 0)),
+ "close": float(r.get("close", 0)),
+ "volume": int(r.get("volume", 0)),
+ })
+ chunk_start = chunk_end
+
+ if not bars:
+ return {"status": "ok", "symbol": clean, "exchange": exchange, "period": period, "bars": []}
+ return {
+ "status": "ok",
+ "symbol": clean,
+ "exchange": exchange,
+ "period": period,
+ "bars": bars[-limit:],
+ }
+
+
+def _symbol_to_token(kite, symbol: str, exchange: str) -> int:
+ """Resolve a tradingsymbol+exchange to an instrument token via Kite's
+ instruments list (cached per process). Falls back to a name-based search."""
+ try:
+ instruments = kite.instruments(exchange=exchange)
+ except Exception:
+ instruments = []
+ for inst in instruments:
+ if inst.get("tradingsymbol", "").upper() == symbol.upper():
+ return int(inst["instrument_token"])
+ raise ZerodhaConfigError(f"instrument token not found for {symbol} ({exchange})")
+
+
+def get_quote(
+ symbol: str,
+ *,
+ config: ZerodhaConfig | None = None,
+ exchange: str = "NSE",
+) -> dict[str, Any]:
+ cfg = config or load_config()
+ clean = symbol.strip().upper()
+ try:
+ kite = _login(cfg)
+ except ZerodhaConfigError as exc:
+ return {"status": "error", "error": str(exc), "symbol": clean}
+ try:
+ q = kite.quote([f"{exchange}:{clean}"])
+ last = q.get(f"{exchange}:{clean}", {})
+ except Exception as exc:
+ return {"status": "error", "error": str(exc), "symbol": clean}
+ return {
+ "status": "ok",
+ "symbol": clean,
+ "exchange": exchange,
+ "quote": {
+ "ltp": float(last.get("last_price", 0)),
+ "open": float(last.get("ohlc", {}).get("open", 0)),
+ "high": float(last.get("ohlc", {}).get("high", 0)),
+ "low": float(last.get("ohlc", {}).get("low", 0)),
+ "close": float(last.get("ohlc", {}).get("close", 0)),
+ "volume": int(last.get("volume", 0)),
+ },
+ }
+
+
+def place_order(
+ config: ZerodhaConfig | None = None,
+ *,
+ symbol: str,
+ side: str,
+ quantity: float | None = None,
+ order_type: str = "market",
+ limit_price: float | None = None,
+ exchange: str = "NSE",
+ product_type: str = "C",
+) -> dict[str, Any]:
+ """Place a PAPER-ONLY order on Zerodha (simulated locally).
+
+ Kite exposes no sandbox, so this connector is structurally capped at paper:
+ the very first check refuses any non-paper config. There is no live order
+ path, by design.
+ """
+ cfg = config or load_config()
+ if not cfg.is_paper:
+ return {"status": "error", "error": _PAPER_ONLY_ERROR}
+
+ clean_symbol = str(symbol or "").strip().upper()
+ if not clean_symbol:
+ return {"status": "error", "error": "symbol is required"}
+
+ side_token = str(side or "").strip().upper()
+ side_map = {"BUY": "B", "SELL": "S", "B": "B", "S": "S"}
+ if side_token not in side_map:
+ return {"status": "error", "error": "side must be 'buy' or 'sell'"}
+ buy_or_sell = side_map[side_token]
+
+ if quantity is None or float(quantity) <= 0:
+ return {"status": "error", "error": "quantity must be positive"}
+ qty = int(float(quantity))
+
+ return {
+ "status": "ok",
+ "order_id": f"PAPER-{clean_symbol}-{buy_or_sell}-{qty}",
+ "symbol": clean_symbol,
+ "side": side_token.lower(),
+ "profile": cfg.profile,
+ "is_paper": True,
+ "paper_guard": "simulated_locally",
+ "order_type": order_type.lower(),
+ "quantity": qty,
+ "limit_price": float(limit_price) if limit_price is not None else None,
+ "order_status": "simulated_fill",
+ "exchange": exchange,
+ "product_type": product_type,
+ }
diff --git a/agent/src/trading/profiles.py b/agent/src/trading/profiles.py
index 5cc5cd3db..fbc3ea787 100644
--- a/agent/src/trading/profiles.py
+++ b/agent/src/trading/profiles.py
@@ -19,6 +19,7 @@ from src.trading.connectors.shoonya.profiles import SHOONYA_PROFILES
from src.trading.connectors.tiger.profiles import TIGER_PROFILES
from src.trading.connectors.etoro.profiles import ETORO_PROFILES
from src.trading.connectors.trading212.profiles import TRADING212_PROFILES
+from src.trading.connectors.zerodha.profiles import ZERODHA_PROFILES
from src.trading.types import TradingProfile
CONFIG_FILENAME = "trading-connections.json"
@@ -38,6 +39,7 @@ BUILTIN_PROFILES: tuple[TradingProfile, ...] = (
*TRADING212_PROFILES,
*MT5_PROFILES,
*ETORO_PROFILES,
+ *ZERODHA_PROFILES,
)
diff --git a/agent/tests/test_zerodha_broker_loader.py b/agent/tests/test_zerodha_broker_loader.py
new file mode 100644
index 000000000..0bc21e235
--- /dev/null
+++ b/agent/tests/test_zerodha_broker_loader.py
@@ -0,0 +1,69 @@
+"""Zerodha Kite Connect broker-bridge loader tests.
+
+Mirrors test_india_broker_loader.py: injects a fake Zerodha SDK via
+``_resolve_broker`` so no real SDK/creds are needed, and verifies the loader
+(1) discovers zerodha, (2) maps symbols/exchanges, (3) parses + clips the
+envelope the same way it does for shoonya/dhan.
+"""
+
+from __future__ import annotations
+
+import datetime as dt
+
+import pandas as pd
+
+from backtest.loaders import india_broker_loader as mod
+from backtest.loaders.india_broker_loader import DataLoader, _base_symbol, _exchange_for
+
+
+def _epoch(date_str: str) -> int:
+ d = pd.Timestamp(date_str).date()
+ return int(dt.datetime(d.year, d.month, d.day, tzinfo=dt.timezone.utc).timestamp())
+
+
+class _FakeZerodhaSDK:
+ """Minimal stand-in exposing ``get_historical_bars`` like the real SDK."""
+
+ def __init__(self) -> None:
+ self.calls: list[dict] = []
+
+ def get_historical_bars(self, symbol, *, exchange="NSE", period="1d", limit=90):
+ self.calls.append({"symbol": symbol, "exchange": exchange, "period": period})
+ return {
+ "status": "ok",
+ "symbol": symbol,
+ "bars": [
+ {"time": _epoch("2024-04-01"), "open": 100, "high": 101, "low": 99, "close": 100.5, "volume": 1000},
+ {"time": _epoch("2024-04-02"), "open": 100.5, "high": 102, "low": 100, "close": 101.5, "volume": 1200},
+ {"time": _epoch("2024-05-10"), "open": 110, "high": 112, "low": 109, "close": 111, "volume": 1500},
+ ],
+ }
+
+
+def test_symbol_and_exchange_mapping() -> None:
+ assert _base_symbol("RELIANCE.NS") == "RELIANCE"
+ assert _base_symbol("500325.BO") == "500325"
+ assert _exchange_for("RELIANCE.NS") == "NSE"
+ assert _exchange_for("500325.BO") == "BSE"
+
+
+def test_zerodha_discovery(monkeypatch) -> None:
+ fake = _FakeZerodhaSDK()
+ monkeypatch.setattr(mod, "_resolve_broker", lambda: ("zerodha", fake))
+ loader = DataLoader()
+ assert loader.is_available() is True
+ result = loader.fetch(["RELIANCE.NS"], "2024-04-01", "2024-04-30")
+ assert "RELIANCE.NS" in result
+ df = result["RELIANCE.NS"]
+ assert list(df.columns) == ["open", "high", "low", "close", "volume"]
+ # window clipped to April only (the May bar is dropped)
+ assert len(df) == 2
+ assert fake.calls[0]["symbol"] == "RELIANCE"
+ assert fake.calls[0]["exchange"] == "NSE"
+
+
+def test_zerodha_unavailable_when_no_broker(monkeypatch) -> None:
+ monkeypatch.setattr(mod, "_resolve_broker", lambda: (None, None))
+ loader = DataLoader()
+ assert loader.is_available() is False
+ assert loader.fetch(["RELIANCE.NS"], "2024-04-01", "2024-04-30") == {}