Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(broker): zerodha review hardening — tz-correct day bars, 4h fail-closed, interval-aware pagination, cred-gated availability, cached instruments, service-layer surface

Ashutosh Singh5c41f59cbb60
diff --git a/README.md b/README.md
index 3aa58dfde..2fb68d191 100644
--- a/README.md
+++ b/README.md
@@ -359,7 +359,7 @@ One `get_market_data` call, **23 free market-data sources** (plus the optional *
| `futu` | HK / A | OpenD | optional local FutuOpenD |
| `mt5` | forex / metals | MT5 terminal | MetaTrader 5 (Exness-style) forex / metal bars, 1m–1D |
| `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) |
+| `india_broker` | India (NSE/BSE) | broker login | read-only Zerodha / Shoonya / Dhan bars for `.NS` / `.BO` (fallback-chain tail) |
| `local` | any | none | your own CSV / Parquet / DuckDB via `local:` prefix |
**Fallback chains (by IP-ban risk):**
@@ -502,7 +502,7 @@ Connector-first profiles. Most do read + paper-account order placement — IBKR
| **Futu** | HK / US / A | read + paper + bounded live |
| **eToro** | global | read + paper + bounded live (Public API; demo keys reach only `/demo` paths, plus copy-trading workflows) |
| **MetaTrader 5** | forex / CFD | read + paper + bounded live (Exness-style; demo ⇔ paper identity guard) |
-| **Longbridge** · **Dhan** · **Shoonya** | US / HK · India (NSE/BSE) | read + paper only — no runtime paper/live discriminator, so live order placement is hard-refused |
+| **Longbridge** · **Dhan** · **Shoonya** · **Zerodha** | US / HK · India (NSE/BSE) | read + paper only — no runtime paper/live discriminator, so live order placement is hard-refused |
| **Trading 212** | UK / EU | fully read-only — `place_order` / `cancel_order` hard-refuse even paper |
Paper-vs-live is a **structural per-broker runtime guard** (account-id format, host separation, demo flag, or trade environment), never a config flag the agent can flip. A broker exposing no such discriminator is capped at paper + read-only.
diff --git a/agent/backtest/loaders/india_broker_loader.py b/agent/backtest/loaders/india_broker_loader.py
index 72f599e80..51d968ff4 100644
--- a/agent/backtest/loaders/india_broker_loader.py
+++ b/agent/backtest/loaders/india_broker_loader.py
@@ -1,7 +1,8 @@
-"""India broker data bridge: feed Shoonya / Dhan history into the backtest layer.
+"""India broker data bridge: feed Zerodha / Shoonya / Dhan history into the backtest layer.
-The Shoonya (Finvasia) and Dhan connectors already expose live-account market
-data via ``get_historical_bars`` (read path). This loader adapts that envelope
+The Zerodha (Kite Connect), Shoonya (Finvasia) and Dhan connectors already
+expose live-account market data via ``get_historical_bars`` (read path). This
+loader adapts that envelope
into the standard OHLCV frame so a user's *broker* history can back the same
backtests as the public Yahoo feed — useful when matching a live account exactly
or pulling symbols Yahoo lacks.
@@ -23,7 +24,7 @@ come back short. For deep history prefer Yahoo.
from __future__ import annotations
import logging
-from typing import Any, Dict, List, Optional
+from typing import Dict, List, Optional
import pandas as pd
@@ -50,8 +51,10 @@ _PERIOD_MAP = {
def _resolve_broker():
"""Return ``(broker_key, sdk_module)`` for the first available India broker.
- Prefers Shoonya, then Dhan. Returns ``(None, None)`` when neither the SDK
- nor a config is present. Import is deferred and defensive so a missing
+ Prefers Zerodha, then Shoonya, then Dhan. Returns ``(None, None)`` when
+ neither the SDK nor a config is present (a connector is "available" only
+ when its SDK is importable AND its credentials are configured — see
+ ``zerodha_available``). Import is deferred and defensive so a missing
``src.trading`` package or broker SDK simply means "unavailable", never a
crash in the loader registry.
"""
@@ -124,7 +127,7 @@ def _bars_to_frame(bars: list[dict], start_date: str, end_date: str) -> Optional
@register
class DataLoader:
- """Shoonya / Dhan history adapter for the ``india_equity`` market."""
+ """Zerodha / Shoonya / Dhan history adapter for the ``india_equity`` market."""
name = "india_broker"
markets = {"india_equity"}
diff --git a/agent/src/trading/connectors/zerodha/sdk.py b/agent/src/trading/connectors/zerodha/sdk.py
index 19f9503f5..347acfa48 100644
--- a/agent/src/trading/connectors/zerodha/sdk.py
+++ b/agent/src/trading/connectors/zerodha/sdk.py
@@ -5,14 +5,18 @@ treat Zerodha uniformly:
get_historical_bars(symbol, *, exchange="NSE", period="1d", limit=90)
-> {"status": "ok", "symbol": ..., "bars": [{time, open, high, low, close, volume}]}
+ get_account_snapshot() / get_positions() / get_open_orders() / get_quote(symbol)
+ -> Shoonya-shaped read envelopes (the ``service.py`` broker_sdk surface)
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).
+ * interval map: project tokens (1m/5m/15m/30m/1h/1d) -> Kite intervals
+ (minute/5minute/15minute/30minute/60minute/day). ``4h`` is rejected, not
+ aliased: Kite has no 4h interval, and returning daily candles under a 4h
+ period would silently mislabel data (fail closed, like Dhan).
+ * Kite caps each historical request at a per-interval number of days
+ (1m: 60, 5m: 100, 15m/30m: 200, 60m: 400, day: 2000); we paginate the
+ [start, end] range into cap-sized 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.
@@ -41,6 +45,9 @@ PROFILE_ENVIRONMENTS = {
KITE_HIST_BASE = "https://api.kite.trade"
+#: India Standard Time (Kite timestamps are IST).
+_IST = timezone(timedelta(hours=5, minutes=30))
+
_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 "
@@ -109,7 +116,9 @@ class ZerodhaConfig:
_OVERRIDE_KEYS = ("api_key", "api_secret", "access_token", "profile")
-#: Project interval token -> Kite interval.
+#: Project interval token -> Kite interval. ``4h`` is deliberately absent:
+#: Kite has no 4h interval and aliasing it to daily would return mislabeled
+#: daily candles (fail closed instead).
_INTERVAL_MAP = {
"1m": "minute",
"5m": "5minute",
@@ -117,14 +126,20 @@ _INTERVAL_MAP = {
"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
+#: Kite caps each historical request at this many calendar days per interval
+#: (documented API limits; a wider span raises "interval exceeds max limit").
+_KITE_MAX_SPAN_DAYS: dict[str, int] = {
+ "minute": 60,
+ "5minute": 100,
+ "15minute": 200,
+ "30minute": 200,
+ "60minute": 400,
+ "day": 2000,
+}
def config_path() -> Path:
@@ -182,11 +197,21 @@ def _require_kite():
def zerodha_available() -> bool:
+ """True only when ``kiteconnect`` is importable AND credentials exist.
+
+ The ``india_broker`` loader treats the first available connector as *the*
+ broker (``_resolve_broker`` never falls through to the next one after a
+ runtime error), so an import-only check would let an unconfigured install
+ shadow a configured Shoonya/Dhan account. Mirrors the loader's documented
+ contract: available only when the SDK is importable AND a broker is
+ configured.
+ """
try:
_require_kite()
- return True
except ZerodhaDependencyError:
return False
+ cfg = load_config()
+ return bool(cfg.api_key and cfg.access_token)
def _public_config(cfg: ZerodhaConfig) -> dict[str, Any]:
@@ -241,6 +266,25 @@ def check_status(config: ZerodhaConfig | None = None) -> dict[str, Any]:
return report
+def _bar_epoch(ts: Any, *, day_bar: bool) -> int | None:
+ """Epoch (UTC-naive seconds) for a Kite candle timestamp.
+
+ Kite timestamps are IST. Intraday candles are real instants, so the UTC
+ epoch is exact. Day candles are dated at midnight IST; shifting that
+ instant to UTC (18:30 the *previous* day) would relabel every daily bar
+ one calendar day early and make the loader's date-range clip drop the
+ first day of each window — so day bars keep their IST calendar date at
+ midnight UTC instead.
+ """
+ if not isinstance(ts, datetime):
+ return None
+ if ts.tzinfo is None: # kiteconnect is tz-aware; defensive fallback
+ ts = ts.replace(tzinfo=_IST)
+ if day_bar:
+ return int(datetime(ts.year, ts.month, ts.day, tzinfo=timezone.utc).timestamp())
+ return int(ts.astimezone(timezone.utc).timestamp())
+
+
def get_historical_bars(
symbol: str,
*,
@@ -249,7 +293,7 @@ def get_historical_bars(
period: str = "1d",
limit: int = 90,
) -> dict[str, Any]:
- """Fetch historical OHLCV bars from Kite, paginated past the 2000-day cap."""
+ """Fetch historical OHLCV bars from Kite, paginated past the per-interval cap."""
cfg = config or load_config()
clean = symbol.strip().upper()
@@ -266,22 +310,32 @@ def get_historical_bars(
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).
+ # Size the window to `limit` bars with 2x trading-day headroom, like the
+ # day path. Dense intervals (1m/5m/15m/30m) stay within their per-request
+ # cap: 60 days of 1m candles is already ~22k rows, and Kite's own
+ # retention for these is bounded anyway. 60minute/day paginate past their
+ # caps, so a 1h request is no longer truncated to 5 days.
end = datetime.now(timezone.utc)
- if interval == "day":
- start = end - timedelta(days=min(limit * 2, 4000))
- else:
- start = end - timedelta(days=5)
+ cap = _KITE_MAX_SPAN_DAYS[interval]
+ window = min(limit * 2, 4000)
+ if interval in ("minute", "5minute", "15minute", "30minute"):
+ window = min(window, cap)
+ start = end - timedelta(days=window)
+
+ # Resolve the instrument token once (the exchange dump is cached).
+ try:
+ token = _symbol_to_token(kite, clean, exchange)
+ except ZerodhaConfigError as exc:
+ return {"status": "error", "error": str(exc), "symbol": clean}
bars: list[dict[str, Any]] = []
- # Paginate in <=2000-day chunks (Kite hard cap).
+ # Paginate in per-interval chunks (Kite hard cap per request).
chunk_start = start
while chunk_start < end:
- chunk_end = min(chunk_start + timedelta(days=_KITE_MAX_SPAN_DAYS), end)
+ chunk_end = min(chunk_start + timedelta(days=cap), end)
try:
rows = kite.historical_data(
- instrument_token=_symbol_to_token(kite, clean, exchange),
+ instrument_token=token,
from_date=chunk_start,
to_date=chunk_end,
interval=interval,
@@ -289,21 +343,20 @@ def get_historical_bars(
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:
+ ts_epoch = _bar_epoch(r.get("date"), day_bar=(interval == "day"))
+ if ts_epoch 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()),
+ "time": ts_epoch,
"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
+ # Kite's from/to dates are inclusive; advance a full day so the
+ # boundary candle is not fetched twice by the next chunk.
+ chunk_start = chunk_end + timedelta(days=1)
if not bars:
return {"status": "ok", "symbol": clean, "exchange": exchange, "period": period, "bars": []}
@@ -316,13 +369,28 @@ def get_historical_bars(
}
+#: Kite's full instrument list per exchange, cached per process. The dump is
+#: large (tens of MB) and static within a session; re-downloading it on every
+#: bar fetch would dominate the read path.
+_INSTRUMENT_CACHE: dict[str, tuple[dict[str, Any], ...]] = {}
+
+
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 = []
+ """Resolve a tradingsymbol+exchange to an instrument token.
+
+ The instrument list is fetched once per exchange and cached for the
+ process. A cache miss surfaces the real API error instead of masquerading
+ as "token not found".
+ """
+ instruments = _INSTRUMENT_CACHE.get(exchange)
+ if instruments is None:
+ try:
+ instruments = tuple(kite.instruments(exchange=exchange) or ())
+ except Exception as exc:
+ raise ZerodhaConfigError(
+ f"failed to fetch {exchange} instrument list: {exc}"
+ ) from exc
+ _INSTRUMENT_CACHE[exchange] = instruments
for inst in instruments:
if inst.get("tradingsymbol", "").upper() == symbol.upper():
return int(inst["instrument_token"])
@@ -361,14 +429,137 @@ def get_quote(
}
+def _num(value: Any, default: float = 0.0) -> float:
+ """Coerce a Kite API field to float, tolerating None/empty strings."""
+ if value is None or value == "":
+ return default
+ try:
+ return float(value)
+ except (TypeError, ValueError):
+ return default
+
+
+def _as_list(value: Any) -> list[Any]:
+ if value is None:
+ return []
+ if isinstance(value, (list, tuple)):
+ return list(value)
+ return [value]
+
+
+def get_account_snapshot(config: ZerodhaConfig | None = None) -> dict[str, Any]:
+ """Read fund/margin summary from Kite (equity segment)."""
+ cfg = config or load_config()
+ try:
+ kite = _login(cfg)
+ margins = kite.margins()
+ except ZerodhaConfigError as exc:
+ return {"status": "error", "error": str(exc)}
+ except Exception as exc: # noqa: BLE001 — one bad read never aborts
+ return {"status": "error", "error": str(exc)}
+ equity = margins.get("equity", {}) if isinstance(margins, dict) else {}
+ available = equity.get("available", {}) or {}
+ utilised = equity.get("utilised", {}) or {}
+ return {
+ "status": "ok",
+ "profile": cfg.profile,
+ "is_paper": cfg.is_paper,
+ "host": KITE_HIST_BASE,
+ "brokerage": "Zerodha equity delivery ₹0; intraday 0.03% / ₹20 flat",
+ "account": {
+ "currency": "INR",
+ "cash": _num(available.get("cash")),
+ "margin_available": _num(equity.get("net")),
+ "margin_used": _num(utilised.get("margins")),
+ "collateral": _num(available.get("collateral")),
+ "payin": _num(available.get("intraday_payin")),
+ },
+ }
+
+
+def get_positions(config: ZerodhaConfig | None = None) -> dict[str, Any]:
+ """Read open (net) positions from Kite."""
+ cfg = config or load_config()
+ try:
+ kite = _login(cfg)
+ positions = kite.positions()
+ except ZerodhaConfigError as exc:
+ return {"status": "error", "error": str(exc)}
+ except Exception as exc: # noqa: BLE001 — one bad read never aborts
+ return {"status": "error", "error": str(exc)}
+ raw = positions.get("net", []) if isinstance(positions, dict) else positions
+ rows = []
+ for item in _as_list(raw):
+ rows.append({
+ "symbol": item.get("tradingsymbol", ""),
+ "exchange": item.get("exchange", ""),
+ "product_type": item.get("product", ""),
+ "quantity": int(_num(item.get("quantity", 0))),
+ "average_cost": _num(item.get("average_price", 0)),
+ "ltp": _num(item.get("last_price", 0)),
+ "unrealized_pnl": _num(item.get("unrealised", 0)),
+ "realized_pnl": _num(item.get("realised", 0)),
+ "overnight_quantity": int(_num(item.get("overnight_quantity", 0))),
+ "multiplier": _num(item.get("multiplier", 1)),
+ })
+ return {"status": "ok", "profile": cfg.profile, "is_paper": cfg.is_paper, "positions": rows}
+
+
+def get_open_orders(
+ config: ZerodhaConfig | None = None,
+ *,
+ include_executions: bool = False,
+) -> dict[str, Any]:
+ """Read the Kite order book; open orders, optionally executions."""
+ cfg = config or load_config()
+ try:
+ kite = _login(cfg)
+ orders = kite.orders()
+ except ZerodhaConfigError as exc:
+ return {"status": "error", "error": str(exc)}
+ except Exception as exc: # noqa: BLE001 — one bad read never aborts
+ return {"status": "error", "error": str(exc)}
+ open_orders: list[dict[str, Any]] = []
+ executions: list[dict[str, Any]] = []
+ for item in _as_list(orders):
+ status = str(item.get("status", "")).upper()
+ order = {
+ "order_id": item.get("order_id", ""),
+ "symbol": item.get("tradingsymbol", ""),
+ "exchange": item.get("exchange", ""),
+ "side": "buy" if str(item.get("transaction_type", "")).upper() == "BUY" else "sell",
+ "order_type": str(item.get("order_type", "")).lower(),
+ "quantity": int(_num(item.get("quantity", 0))),
+ "filled_qty": int(_num(item.get("filled_quantity", 0))),
+ "price": _num(item.get("price", 0)),
+ "status": item.get("status", ""),
+ "product_type": item.get("product", ""),
+ }
+ if status in ("OPEN", "PENDING", "TRIGGER_PENDING"):
+ open_orders.append(order)
+ elif include_executions and status in ("COMPLETE", "FILLED"):
+ executions.append(order)
+ result: dict[str, Any] = {
+ "status": "ok",
+ "profile": cfg.profile,
+ "is_paper": cfg.is_paper,
+ "open_orders": open_orders,
+ }
+ if include_executions:
+ result["executions"] = executions
+ return result
+
+
def place_order(
config: ZerodhaConfig | None = None,
*,
symbol: str,
side: str,
quantity: float | None = None,
+ notional: float | None = None,
order_type: str = "market",
limit_price: float | None = None,
+ time_in_force: str = "day",
exchange: str = "NSE",
product_type: str = "C",
) -> dict[str, Any]:
@@ -382,6 +573,10 @@ def place_order(
if not cfg.is_paper:
return {"status": "error", "error": _PAPER_ONLY_ERROR}
+ # ``notional`` and ``time_in_force`` are part of the uniform service.py
+ # surface but meaningless for a locally simulated paper fill.
+ del notional, time_in_force
+
clean_symbol = str(symbol or "").strip().upper()
if not clean_symbol:
return {"status": "error", "error": "symbol is required"}
@@ -411,3 +606,33 @@ def place_order(
"exchange": exchange,
"product_type": product_type,
}
+
+
+def cancel_order(
+ config: ZerodhaConfig | None = None,
+ order_id: str = "",
+ *,
+ symbol: str | None = None,
+) -> dict[str, Any]:
+ """Cancel a PAPER-ONLY order (simulated locally).
+
+ Kite exposes no sandbox, so like ``place_order`` this is structurally
+ capped at paper: the very first check refuses any non-paper config, and a
+ cancel is a local simulation, never a live API call.
+ """
+ cfg = config or load_config()
+ if not cfg.is_paper:
+ return {"status": "error", "error": _PAPER_ONLY_ERROR}
+
+ clean_id = str(order_id or "").strip()
+ if not clean_id:
+ return {"status": "error", "error": "order_id is required"}
+
+ return {
+ "status": "ok",
+ "order_id": clean_id,
+ "symbol": symbol.strip().upper() if isinstance(symbol, str) and symbol.strip() else None,
+ "profile": cfg.profile,
+ "is_paper": True,
+ "cancelled": True,
+ }
diff --git a/agent/src/trading/service.py b/agent/src/trading/service.py
index ce21bb04d..355353523 100644
--- a/agent/src/trading/service.py
+++ b/agent/src/trading/service.py
@@ -23,6 +23,7 @@ _SDK_CONNECTOR_MODULES = {
"futu": "src.trading.connectors.futu.sdk",
"dhan": "src.trading.connectors.dhan.sdk",
"shoonya": "src.trading.connectors.shoonya.sdk",
+ "zerodha": "src.trading.connectors.zerodha.sdk",
"trading212": "src.trading.connectors.trading212.sdk",
"mt5": "src.trading.connectors.mt5.sdk",
"etoro": "src.trading.connectors.etoro.sdk",
diff --git a/agent/tests/test_zerodha_sdk.py b/agent/tests/test_zerodha_sdk.py
new file mode 100644
index 000000000..6e20f1a67
--- /dev/null
+++ b/agent/tests/test_zerodha_sdk.py
@@ -0,0 +1,314 @@
+"""Zerodha Kite Connect SDK unit tests (no network, no real SDK).
+
+Covers the behaviors that regressed in review: IST day-bar dating (no -1 day
+shift), 4h fail-closed, interval-aware windows/pagination (no duplicate
+boundary bars), cred-gated availability, and the per-exchange instrument
+cache. Mirrors the loader-test style: fake SDK injected, no real creds.
+"""
+
+from __future__ import annotations
+
+import datetime as dt
+from datetime import datetime, timedelta, timezone
+from typing import Any
+
+from src.trading.connectors.zerodha import sdk as zsdk
+
+
+def _ist(y: int, m: int, d: int, hh: int = 0, mm: int = 0) -> datetime:
+ return datetime(y, m, d, hh, mm, tzinfo=zsdk._IST)
+
+
+class _FakeKite:
+ """Minimal kiteconnect stand-in recording calls."""
+
+ def __init__(self) -> None:
+ self._instruments = [
+ {"tradingsymbol": "RELIANCE", "instrument_token": "12345"},
+ {"tradingsymbol": "500325", "instrument_token": "67890"},
+ ]
+ self.instruments_calls = 0
+ self.historical_calls: list[dict] = []
+
+ def instruments(self, exchange: str = "NSE"):
+ self.instruments_calls += 1
+ return self._instruments
+
+ def margins(self):
+ return {
+ "equity": {
+ "net": 123456.0,
+ "available": {"cash": 50000.0, "collateral": 70000.0, "intraday_payin": 1000.0},
+ "utilised": {"margins": 6543.0, "debits": 0.0},
+ },
+ "commodity": {},
+ }
+
+ def positions(self):
+ return {
+ "day": [
+ {"tradingsymbol": "RELIANCE", "exchange": "NSE", "product": "CNC",
+ "quantity": 5, "average_price": 1500.0, "last_price": 1600.0,
+ "unrealised": 500.0, "realised": 0.0, "overnight_quantity": 0, "multiplier": 1},
+ ],
+ "net": [
+ {"tradingsymbol": "RELIANCE", "exchange": "NSE", "product": "CNC",
+ "quantity": 5, "average_price": 1500.0, "last_price": 1600.0,
+ "unrealised": 500.0, "realised": 0.0, "overnight_quantity": 0, "multiplier": 1},
+ ],
+ }
+
+ def orders(self):
+ return [
+ {"order_id": "1001", "tradingsymbol": "RELIANCE", "exchange": "NSE",
+ "transaction_type": "BUY", "status": "OPEN", "order_type": "LIMIT",
+ "quantity": 10, "filled_quantity": 0, "price": 1550.0, "product": "CNC"},
+ {"order_id": "1002", "tradingsymbol": "TCS", "exchange": "NSE",
+ "transaction_type": "SELL", "status": "COMPLETE", "order_type": "MARKET",
+ "quantity": 5, "filled_quantity": 5, "price": 4200.0, "product": "CNC"},
+ ]
+
+ def historical_data(self, instrument_token, from_date, to_date, interval):
+ self.historical_calls.append({
+ "instrument_token": instrument_token,
+ "from_date": from_date,
+ "to_date": to_date,
+ "interval": interval,
+ })
+ # One candle at the chunk start, IST-dated, so any chunk overlap
+ # surfaces as a duplicated epoch in the merged output.
+ return [{
+ "date": _ist(from_date.year, from_date.month, from_date.day),
+ "open": 1.0, "high": 2.0, "low": 0.5, "close": 1.5, "volume": 10,
+ }]
+
+
+def _patch_kite(monkeypatch, fake: Any) -> None:
+ monkeypatch.setattr(zsdk, "_login", lambda cfg: fake)
+ # Fresh cache per test so instruments_calls is deterministic.
+ monkeypatch.setattr(zsdk, "_INSTRUMENT_CACHE", {})
+
+
+def _cfg() -> zsdk.ZerodhaConfig:
+ return zsdk.ZerodhaConfig(api_key="k", access_token="t")
+
+
+# ---------------------------------------------------------------------------
+# Timezone: day bars keep their IST calendar date
+# ---------------------------------------------------------------------------
+
+def test_day_bar_keeps_ist_calendar_date() -> None:
+ # 2024-04-01 00:00 IST == 2024-03-31 18:30 UTC. The bar must be dated
+ # 2024-04-01 (midnight UTC), never shifted back a day.
+ epoch = zsdk._bar_epoch(_ist(2024, 4, 1), day_bar=True)
+ assert epoch == int(datetime(2024, 4, 1, tzinfo=timezone.utc).timestamp())
+
+
+def test_intraday_bar_keeps_exact_instant() -> None:
+ # 09:15 IST == 03:45 UTC the same day (real instant, no date shift).
+ epoch = zsdk._bar_epoch(_ist(2024, 4, 1, 9, 15), day_bar=False)
+ assert epoch == int(datetime(2024, 4, 1, 3, 45, tzinfo=timezone.utc).timestamp())
+
+
+def test_bar_epoch_tolerates_naive_and_missing_input() -> None:
+ naive = datetime(2024, 4, 1) # defensive: assume IST, like kiteconnect
+ assert zsdk._bar_epoch(naive, day_bar=True) == int(
+ datetime(2024, 4, 1, tzinfo=timezone.utc).timestamp()
+ )
+ assert zsdk._bar_epoch(None, day_bar=True) is None
+
+
+def test_loader_alignment_no_first_day_loss(monkeypatch) -> None:
+ """End-to-end: a window starting on a trading day keeps that day's bar."""
+ from backtest.loaders.india_broker_loader import _bars_to_frame
+ # One daily bar dated 2024-04-01 midnight IST (the Kite convention).
+ bars = [{"time": zsdk._bar_epoch(_ist(2024, 4, 1), day_bar=True),
+ "open": 1.0, "high": 2.0, "low": 0.5, "close": 1.5, "volume": 10}]
+ frame = _bars_to_frame(bars, "2024-04-01", "2024-04-30")
+ assert frame is not None
+ assert len(frame) == 1 # the 04-01 bar survives the clip (previously dropped)
+ assert frame.index[0] == dt.datetime(2024, 4, 1)
+
+
+# ---------------------------------------------------------------------------
+# Interval handling
+# ---------------------------------------------------------------------------
+
+def test_4h_rejected_not_aliased_to_daily() -> None:
+ out = zsdk.get_historical_bars("RELIANCE", config=_cfg(), period="4h")
+ assert out["status"] == "error"
+ assert "unsupported period" in out["error"]
+ out2 = zsdk.get_historical_bars("RELIANCE", config=_cfg(), period="4H")
+ assert out2["status"] == "error"
+
+
+def test_1h_window_no_longer_truncated_to_5_days(monkeypatch) -> None:
+ fake = _FakeKite()
+ _patch_kite(monkeypatch, fake)
+ out = zsdk.get_historical_bars("RELIANCE", config=_cfg(), period="1h", limit=90)
+ assert out["status"] == "ok"
+ span = fake.historical_calls[0]["to_date"] - fake.historical_calls[0]["from_date"]
+ # 90 bars * 2x trading-day headroom = 180 days (previously a hardcoded 5).
+ assert 170 <= span.days <= 190
+
+
+def test_minute_window_bounded_by_kite_cap(monkeypatch) -> None:
+ fake = _FakeKite()
+ _patch_kite(monkeypatch, fake)
+ zsdk.get_historical_bars("RELIANCE", config=_cfg(), period="1m", limit=2000)
+ span = fake.historical_calls[0]["to_date"] - fake.historical_calls[0]["from_date"]
+ assert span.days == 60 # Kite's 1-minute per-request cap
+
+
+def test_pagination_advances_past_boundary_no_duplicates(monkeypatch) -> None:
+ fake = _FakeKite()
+ _patch_kite(monkeypatch, fake)
+ # limit=2000 daily -> 4000-day window -> two 2000-day chunks.
+ out = zsdk.get_historical_bars("RELIANCE", config=_cfg(), period="1d", limit=2000)
+ assert out["status"] == "ok"
+ assert len(fake.historical_calls) == 2
+ # Second chunk must start the day AFTER the first chunk's end (Kite ranges
+ # are inclusive), so the boundary candle is fetched exactly once.
+ assert fake.historical_calls[1]["from_date"] == (
+ fake.historical_calls[0]["to_date"] + timedelta(days=1)
+ )
+ times = [b["time"] for b in out["bars"]]
+ assert len(times) == len(set(times))
+
+
+def test_instrument_dump_cached_per_exchange(monkeypatch) -> None:
+ fake = _FakeKite()
+ _patch_kite(monkeypatch, fake)
+ zsdk.get_historical_bars("RELIANCE", config=_cfg(), period="1d", limit=90)
+ zsdk.get_historical_bars("RELIANCE", config=_cfg(), period="1d", limit=90)
+ assert fake.instruments_calls == 1
+
+
+def test_token_resolved_once_before_pagination(monkeypatch) -> None:
+ fake = _FakeKite()
+ _patch_kite(monkeypatch, fake)
+ zsdk.get_historical_bars("RELIANCE", config=_cfg(), period="1d", limit=2000)
+ assert fake.instruments_calls == 1 # not once per chunk
+
+
+# ---------------------------------------------------------------------------
+# Availability gating
+# ---------------------------------------------------------------------------
+
+def test_available_requires_import_and_creds(monkeypatch) -> None:
+ class _DummyKite:
+ pass
+
+ def _raise_dep():
+ raise zsdk.ZerodhaDependencyError("not installed")
+
+ monkeypatch.setattr(zsdk, "_require_kite", lambda: _DummyKite)
+ monkeypatch.setattr(zsdk, "load_config", lambda: _cfg())
+ assert zsdk.zerodha_available() is True
+
+ monkeypatch.setattr(zsdk, "load_config", lambda: zsdk.ZerodhaConfig(api_key="k"))
+ assert zsdk.zerodha_available() is False # import alone is not enough
+
+ monkeypatch.setattr(zsdk, "load_config", lambda: _cfg())
+ monkeypatch.setattr(zsdk, "_require_kite", _raise_dep)
+ assert zsdk.zerodha_available() is False # missing package is not enough
+
+
+# ---------------------------------------------------------------------------
+# Service-layer surface (service.py broker_sdk dispatch)
+# ---------------------------------------------------------------------------
+
+def test_get_account_snapshot_maps_kite_margins(monkeypatch) -> None:
+ fake = _FakeKite()
+ _patch_kite(monkeypatch, fake)
+ out = zsdk.get_account_snapshot(_cfg())
+ assert out["status"] == "ok"
+ assert out["account"]["currency"] == "INR"
+ assert out["account"]["cash"] == 50000.0
+ assert out["account"]["margin_available"] == 123456.0
+ assert out["account"]["margin_used"] == 6543.0
+ assert out["account"]["collateral"] == 70000.0
+
+
+def test_get_positions_maps_net_rows(monkeypatch) -> None:
+ fake = _FakeKite()
+ _patch_kite(monkeypatch, fake)
+ out = zsdk.get_positions(_cfg())
+ assert out["status"] == "ok"
+ assert len(out["positions"]) == 1
+ row = out["positions"][0]
+ assert row["symbol"] == "RELIANCE"
+ assert row["quantity"] == 5
+ assert row["average_cost"] == 1500.0
+ assert row["unrealized_pnl"] == 500.0
+ assert row["multiplier"] == 1
+
+
+def test_get_open_orders_filters_and_optional_executions(monkeypatch) -> None:
+ fake = _FakeKite()
+ _patch_kite(monkeypatch, fake)
+ out = zsdk.get_open_orders(_cfg())
+ assert out["status"] == "ok"
+ assert [o["order_id"] for o in out["open_orders"]] == ["1001"]
+ assert "executions" not in out
+
+ out2 = zsdk.get_open_orders(_cfg(), include_executions=True)
+ assert [o["order_id"] for o in out2["executions"]] == ["1002"]
+ assert out2["executions"][0]["side"] == "sell"
+
+
+def test_read_ops_error_envelope_on_broker_failure(monkeypatch) -> None:
+ class _FailingKite:
+ def margins(self):
+ raise RuntimeError("kite down")
+
+ def positions(self):
+ raise RuntimeError("kite down")
+
+ def orders(self):
+ raise RuntimeError("kite down")
+
+ _patch_kite(monkeypatch, _FailingKite())
+ for out in (zsdk.get_account_snapshot(_cfg()),
+ zsdk.get_positions(_cfg()),
+ zsdk.get_open_orders(_cfg())):
+ assert out["status"] == "error"
+ assert out["error"] == "kite down"
+
+
+def test_place_order_accepts_service_surface_kwargs() -> None:
+ # service.py passes notional/time_in_force for every broker_sdk connector.
+ out = zsdk.place_order(
+ _cfg(), symbol="RELIANCE", side="buy", quantity=10,
+ notional=15000.0, time_in_force="day",
+ )
+ assert out["status"] == "ok"
+ assert out["is_paper"] is True
+
+
+def test_cancel_order_paper_only_and_validation() -> None:
+ out = zsdk.cancel_order(_cfg(), "PAPER-RELIANCE-B-10")
+ assert out["status"] == "ok"
+ assert out["cancelled"] is True
+
+ out2 = zsdk.cancel_order(_cfg(), "")
+ assert out2["status"] == "error"
+
+ live = zsdk.ZerodhaConfig(api_key="k", access_token="t", profile="live")
+ out3 = zsdk.cancel_order(live, "PAPER-RELIANCE-B-10")
+ assert out3["status"] == "error"
+ assert "paper" in out3["error"]
+
+
+def test_service_dispatch_reaches_zerodha_sdk(monkeypatch) -> None:
+ """check_connection('zerodha-paper-sdk') must route to the zerodha SDK
+ (previously ValueError), returning the SDK's missing-config error."""
+ # Deterministic: empty config regardless of any real zerodha.json on disk.
+ monkeypatch.setattr(zsdk, "load_config", lambda: zsdk.ZerodhaConfig())
+ from src.trading.service import check_connection
+
+ out = check_connection("zerodha-paper-sdk")
+ assert out["status"] == "error"
+ assert "not configured" in out["error"]
+ assert out["connector"] == "zerodha"
+ assert out["profile_id"] == "zerodha-paper-sdk"