Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(trading): add Dhan + Shoonya Indian broker connectors (paper-capped)

Panditvirchandra77-lgtmdda7a5739bed
diff --git a/agent/src/live/registry.py b/agent/src/live/registry.py
index ff1723b7f..75c6d02a6 100644
--- a/agent/src/live/registry.py
+++ b/agent/src/live/registry.py
@@ -25,11 +25,13 @@ from src.live.order_guard import LiveOrderGuardTool
from src.tools.mcp import MCPRemoteTool
from src.trading.connectors.alpaca.classification import ALPACA_TOOL_CLASS
from src.trading.connectors.binance.classification import BINANCE_TOOL_CLASS
+from src.trading.connectors.dhan.classification import DHAN_TOOL_CLASS
from src.trading.connectors.futu.classification import FUTU_TOOL_CLASS
from src.trading.connectors.ibkr.classification import IBKR_TOOL_CLASS
from src.trading.connectors.longbridge.classification import LONGBRIDGE_TOOL_CLASS
from src.trading.connectors.okx.classification import OKX_TOOL_CLASS
from src.trading.connectors.robinhood.classification import ROBINHOOD_TOOL_CLASS
+from src.trading.connectors.shoonya.classification import SHOONYA_TOOL_CLASS
from src.trading.connectors.tiger.classification import TIGER_TOOL_CLASS
logger = logging.getLogger(__name__)
@@ -47,6 +49,8 @@ _BROKER_CURATED_MAPS = {
"okx": OKX_TOOL_CLASS,
"binance": BINANCE_TOOL_CLASS,
"futu": FUTU_TOOL_CLASS,
+ "dhan": DHAN_TOOL_CLASS,
+ "shoonya": SHOONYA_TOOL_CLASS,
}
diff --git a/agent/src/trading/connectors/dhan/__init__.py b/agent/src/trading/connectors/dhan/__init__.py
new file mode 100644
index 000000000..8cab33850
--- /dev/null
+++ b/agent/src/trading/connectors/dhan/__init__.py
@@ -0,0 +1,8 @@
+"""Dhan trading connector.
+
+Read-only and paper/live account access via the official ``dhanhq`` SDK.
+A ``broker_sdk`` transport for the Indian equity and F&O markets (NSE/BSE).
+
+Dhan provides free API access with a trading account. Paper trading uses the
+Dhan sandbox environment; live uses production endpoints.
+"""
diff --git a/agent/src/trading/connectors/dhan/classification.py b/agent/src/trading/connectors/dhan/classification.py
new file mode 100644
index 000000000..b816cc766
--- /dev/null
+++ b/agent/src/trading/connectors/dhan/classification.py
@@ -0,0 +1,32 @@
+"""Curated read/write classification for Dhan SDK operations.
+
+Keys are the connector's own operation names. Order-mutating SDK calls are
+pinned WRITE so the live gate never treats them as plain reads; anything
+unlisted and not a known read is treated as WRITE (fail-closed) by the gate.
+"""
+
+from __future__ import annotations
+
+from src.live.classification import ToolClass
+
+#: Dhan SDK operation read/write catalog.
+DHAN_TOOL_CLASS: dict[str, ToolClass] = {
+ # READ
+ "get_fund_limits": ToolClass.READ,
+ "get_holdings": ToolClass.READ,
+ "get_positions": ToolClass.READ,
+ "get_order_list": ToolClass.READ,
+ "get_order_by_id": ToolClass.READ,
+ "get_trade_book": ToolClass.READ,
+ "intraday_daily_candle_data": ToolClass.READ,
+ "historical_daily_candle_data": ToolClass.READ,
+ "ltp": ToolClass.READ,
+ "ohlc": ToolClass.READ,
+ "quote": ToolClass.READ,
+ "market_depth": ToolClass.READ,
+ # WRITE
+ "place_order": ToolClass.WRITE,
+ "modify_order": ToolClass.WRITE,
+ "cancel_order": ToolClass.WRITE,
+ "place_slice_order": ToolClass.WRITE,
+}
diff --git a/agent/src/trading/connectors/dhan/profiles.py b/agent/src/trading/connectors/dhan/profiles.py
new file mode 100644
index 000000000..ab236765b
--- /dev/null
+++ b/agent/src/trading/connectors/dhan/profiles.py
@@ -0,0 +1,67 @@
+"""Built-in Dhan connector profiles.
+
+Dhan (https://dhan.co) is an Indian discount broker with free API access.
+Supports NSE/BSE equities, F&O (NIFTY/BANKNIFTY options), currency, and
+commodity segments.
+
+Paper-only by design: Dhan exposes no sandbox and no runtime paper/live
+discriminator — a single Access Token reads the same account whether the
+profile is declared ``paper`` or ``live``. Following the Longbridge precedent,
+this connector therefore ships read-only paper/live profiles plus a locally
+simulated paper-trade profile, and exposes NO live order placement. Paper vs
+live is operator-declared (config-trust); the connector's order path is
+structurally capped at paper (see ``sdk.place_order``).
+"""
+
+from __future__ import annotations
+
+from src.trading.types import READ_CAPABILITIES, TradingProfile
+
+DHAN_PROFILES: tuple[TradingProfile, ...] = (
+ TradingProfile(
+ id="dhan-paper-sdk",
+ connector="dhan",
+ label="Dhan Paper · dhanhq (India)",
+ environment="paper",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES,
+ readonly=True,
+ config={"profile": "paper"},
+ notes=(
+ "Reads real-time Indian market data (NSE/BSE) via Dhan's free API. "
+ "Paper vs live is operator-declared (the API exposes no runtime "
+ "discriminator). Supports equities, F&O (NIFTY/BANKNIFTY options), "
+ "currency, commodity."
+ ),
+ ),
+ TradingProfile(
+ id="dhan-paper-trade",
+ connector="dhan",
+ label="Dhan Paper · dhanhq 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 Dhan market data "
+ "— no real money at risk. Paper-only by design: Dhan exposes no "
+ "runtime paper/live discriminator, so live order placement is not "
+ "supported. Supports NSE equities and F&O (NIFTY/BANKNIFTY options)."
+ ),
+ ),
+ TradingProfile(
+ id="dhan-live-sdk-readonly",
+ connector="dhan",
+ label="Dhan Live · dhanhq Read-Only (India)",
+ environment="live",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES,
+ readonly=True,
+ config={"profile": "live-readonly"},
+ notes=(
+ "Reads a live Dhan account (account, positions, orders, quotes, "
+ "history). Order placement is not exposed in this profile."
+ ),
+ ),
+)
diff --git a/agent/src/trading/connectors/dhan/sdk.py b/agent/src/trading/connectors/dhan/sdk.py
new file mode 100644
index 000000000..eb395bbee
--- /dev/null
+++ b/agent/src/trading/connectors/dhan/sdk.py
@@ -0,0 +1,600 @@
+"""Read-only + order Dhan connector via the official ``dhanhq`` SDK.
+
+Wraps ``DhanHQ`` client for account, positions, orders, quotes, and historical
+data. Supports NSE/BSE equities and F&O (NIFTY/BANKNIFTY options).
+
+Paper-vs-live: Dhan has no sandbox environment. Paper mode uses the same API
+for market data reads but simulates orders locally. Live mode places real orders
+through Dhan's production API.
+"""
+
+from __future__ import annotations
+
+import json
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from types import ModuleType
+from typing import Any, Mapping
+
+from src.config.paths import get_runtime_root
+
+CONFIG_FILENAME = "dhan.json"
+
+PROFILE_ENVIRONMENTS = {
+ "paper": "paper",
+ "live-readonly": "live",
+ "live": "live",
+}
+
+DHAN_API_URL = "https://api.dhan.co"
+
+#: Returned by order methods when a non-paper config reaches them. Dhan exposes
+#: no runtime paper/live discriminator (same token reads the same account), so —
+#: following the Longbridge precedent — the connector is structurally capped at
+#: paper and never opens a live order path.
+_PAPER_ONLY_ERROR = (
+ "Dhan connector is paper-only: it exposes no runtime paper/live "
+ "discriminator, so live order placement is not supported. Use a "
+ "dhan-paper-* profile."
+)
+
+
+class DhanDependencyError(RuntimeError):
+ """Raised when the optional ``dhanhq`` package is not installed."""
+
+
+class DhanConfigError(RuntimeError):
+ """Raised when the connector configuration is missing or invalid."""
+
+
+# ---------------------------------------------------------------------------
+# NSE instrument constants for F&O
+# ---------------------------------------------------------------------------
+
+#: NSE exchange segment codes used by Dhan API.
+class DhanSegment:
+ NSE_EQ = "NSE_EQ"
+ NSE_FNO = "NSE_FNO"
+ BSE_EQ = "BSE_EQ"
+ BSE_FNO = "BSE_FNO"
+ MCX_COMM = "MCX_COMM"
+ CUR = "CUR"
+
+
+#: Common NIFTY/BANKNIFTY security IDs (Dhan uses numeric security IDs).
+NIFTY_SECURITY_ID = "13" # NIFTY 50 index
+BANKNIFTY_SECURITY_ID = "25" # BANK NIFTY index
+
+
+@dataclass(frozen=True)
+class DhanConfig:
+ """Dhan connector connection settings.
+
+ Args:
+ client_id: Dhan client ID (visible on dhan.co dashboard).
+ access_token: Dhan API access token (generated from dhan.co).
+ profile: ``paper``, ``live-readonly`` or ``live``.
+ timeout: Network timeout in seconds.
+ readonly: Whether order placement is disabled.
+ """
+
+ client_id: 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) -> "DhanConfig":
+ """Build a config from a JSON-like mapping."""
+ payload = dict(data or {})
+ profile = str(payload.get("profile") or "paper").strip().lower()
+ if profile not in PROFILE_ENVIRONMENTS:
+ raise DhanConfigError("profile must be 'paper', 'live-readonly' or 'live'")
+ return cls(
+ client_id=str(payload.get("client_id") 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,
+ *,
+ client_id: str | None = None,
+ access_token: str | None = None,
+ profile: str | None = None,
+ ) -> "DhanConfig":
+ """Return a copy with CLI/tool overrides applied."""
+ payload = asdict(self)
+ if client_id is not None:
+ payload["client_id"] = client_id
+ if access_token is not None:
+ payload["access_token"] = access_token
+ if profile is not None:
+ payload["profile"] = profile
+ return DhanConfig.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 = ("client_id", "access_token", "profile")
+
+
+def build_config(
+ profile_config: Mapping[str, Any] | None = None,
+ overrides: Mapping[str, Any] | None = None,
+) -> "DhanConfig":
+ """Resolve config: saved file ← profile defaults ← CLI overrides."""
+ base = asdict(load_config())
+ for key, value in dict(profile_config or {}).items():
+ if value is not None:
+ base[key] = value
+ cfg = DhanConfig.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 config_path() -> Path:
+ return get_runtime_root() / CONFIG_FILENAME
+
+
+def load_config() -> DhanConfig:
+ path = config_path()
+ if not path.exists():
+ return DhanConfig()
+ try:
+ return DhanConfig.from_mapping(json.loads(path.read_text(encoding="utf-8")))
+ except (OSError, ValueError, json.JSONDecodeError) as exc:
+ raise DhanConfigError(f"invalid Dhan config at {path}: {exc}") from exc
+
+
+def save_config(config: DhanConfig) -> 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 dhan_available() -> bool:
+ try:
+ _require_dhan()
+ return True
+ except DhanDependencyError:
+ return False
+
+
+# ---------------------------------------------------------------------------
+# Five read operations + order placement
+# ---------------------------------------------------------------------------
+
+
+def check_status(config: DhanConfig | None = None) -> dict[str, Any]:
+ """Check SDK readiness and config completeness."""
+ cfg = config or load_config()
+ report: dict[str, Any] = {
+ "status": "ok",
+ "config": _public_config(cfg),
+ "sdk": {"package": "dhanhq", "installed": dhan_available()},
+ "paper_guard": "simulated_locally",
+ "host": DHAN_API_URL,
+ }
+
+ missing = _missing_fields(cfg)
+ if missing:
+ report["status"] = "error"
+ report["error"] = f"Dhan 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 dhanhq`."
+ return report
+
+ try:
+ get_account_snapshot(cfg) # connectivity probe; result unused
+ except Exception as exc:
+ report["status"] = "error"
+ report["error"] = str(exc)
+ return report
+
+ report["account"] = {
+ "profile": cfg.profile,
+ "is_paper": cfg.is_paper,
+ }
+ return report
+
+
+def get_account_snapshot(config: DhanConfig | None = None) -> dict[str, Any]:
+ """Fetch fund limits (account summary) for the configured account."""
+ cfg = config or load_config()
+ client = _dhan_client(cfg)
+ funds = client.get_fund_limits()
+
+ return {
+ "status": "ok",
+ "profile": cfg.profile,
+ "is_paper": cfg.is_paper,
+ "host": DHAN_API_URL,
+ "account": {
+ "currency": "INR",
+ "available_margin": _safe_get(funds, "data", "availabelBalance"),
+ "used_margin": _safe_get(funds, "data", "utilizedAmount"),
+ "collateral": _safe_get(funds, "data", "collateralAmount"),
+ },
+ }
+
+
+def get_positions(config: DhanConfig | None = None) -> dict[str, Any]:
+ """Fetch current positions."""
+ cfg = config or load_config()
+ client = _dhan_client(cfg)
+ positions = client.get_positions()
+
+ rows = []
+ for item in _as_list(positions.get("data")):
+ rows.append({
+ "symbol": item.get("tradingSymbol", ""),
+ "security_id": item.get("securityId", ""),
+ "exchange_segment": item.get("exchangeSegment", ""),
+ "product_type": item.get("productType", ""),
+ "quantity": item.get("netQty", 0),
+ "average_cost": item.get("costPrice", 0),
+ "current_price": item.get("currentPrice", 0),
+ "unrealized_pnl": item.get("realizedProfit", 0),
+ "day_buy_qty": item.get("dayBuyQty", 0),
+ "day_sell_qty": item.get("daySellQty", 0),
+ })
+
+ return {
+ "status": "ok",
+ "profile": cfg.profile,
+ "is_paper": cfg.is_paper,
+ "positions": rows,
+ }
+
+
+def get_open_orders(
+ config: DhanConfig | None = None,
+ *,
+ include_executions: bool = False,
+) -> dict[str, Any]:
+ """Fetch open orders and optionally executed trades."""
+ cfg = config or load_config()
+ client = _dhan_client(cfg)
+ orders = client.get_order_list()
+
+ open_orders = []
+ executions = []
+ for item in _as_list(orders.get("data")):
+ order_dict = _order_to_dict(item)
+ status = str(item.get("orderStatus", "")).upper()
+ if status in ("PENDING", "TRANSIT", "OPEN"):
+ open_orders.append(order_dict)
+ elif include_executions and status in ("TRADED", "FILLED"):
+ executions.append(order_dict)
+
+ 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 get_quote(
+ symbol: str,
+ *,
+ config: DhanConfig | None = None,
+ security_id: str | None = None,
+ exchange_segment: str = "NSE_EQ",
+) -> dict[str, Any]:
+ """Fetch LTP + OHLC for a symbol.
+
+ Dhan requires numeric ``security_id`` + ``exchange_segment`` for quotes.
+ If ``security_id`` is not provided, attempt to use ``symbol`` as the ID.
+ """
+ cfg = config or load_config()
+ client = _dhan_client(cfg)
+
+ sec_id = str(security_id or symbol).strip()
+ segment = exchange_segment.strip().upper()
+
+ try:
+ ltp_data = client.ltp(security_id=sec_id, exchange_segment=segment)
+ ohlc_data = client.ohlc(security_id=sec_id, exchange_segment=segment)
+ except Exception as exc:
+ return {"status": "error", "error": str(exc), "symbol": symbol}
+
+ return {
+ "status": "ok",
+ "symbol": symbol,
+ "security_id": sec_id,
+ "exchange_segment": segment,
+ "quote": {
+ "ltp": _safe_get(ltp_data, "data", "lastPrice"),
+ "open": _safe_get(ohlc_data, "data", "open"),
+ "high": _safe_get(ohlc_data, "data", "high"),
+ "low": _safe_get(ohlc_data, "data", "low"),
+ "close": _safe_get(ohlc_data, "data", "close"),
+ "volume": _safe_get(ohlc_data, "data", "volume"),
+ },
+ }
+
+
+def get_historical_bars(
+ symbol: str,
+ *,
+ config: DhanConfig | None = None,
+ security_id: str | None = None,
+ exchange_segment: str = "NSE_EQ",
+ instrument_type: str = "EQUITY",
+ period: str = "1d",
+ limit: int = 90,
+) -> dict[str, Any]:
+ """Fetch historical OHLCV bars.
+
+ ``period`` tokens: ``1m``, ``5m``, ``15m``, ``30m`` → intraday candles.
+ ``1d`` → daily candles. Dhan's intraday data is limited to last 5 trading
+ days; daily goes back much further.
+ """
+ cfg = config or load_config()
+ client = _dhan_client(cfg)
+
+ sec_id = str(security_id or symbol).strip()
+ segment = exchange_segment.strip().upper()
+
+ from datetime import datetime, timedelta
+
+ to_date = datetime.now()
+ # Intraday: max 5 days back; daily: use limit
+ if period in ("1m", "5m", "15m", "30m"):
+ from_date = to_date - timedelta(days=5)
+ else:
+ from_date = to_date - timedelta(days=min(limit * 2, 365))
+
+ try:
+ if period in ("1m", "5m", "15m", "30m"):
+ data = client.intraday_daily_candle_data(
+ security_id=sec_id,
+ exchange_segment=segment,
+ instrument_type=instrument_type,
+ )
+ else:
+ data = client.historical_daily_candle_data(
+ security_id=sec_id,
+ exchange_segment=segment,
+ instrument_type=instrument_type,
+ from_date=from_date.strftime("%Y-%m-%d"),
+ to_date=to_date.strftime("%Y-%m-%d"),
+ )
+ except Exception as exc:
+ return {"status": "error", "error": str(exc), "symbol": symbol}
+
+ bars = []
+ for candle in _as_list(data.get("data", {}).get("candles")):
+ if len(candle) >= 6:
+ bars.append({
+ "time": candle[0],
+ "open": candle[1],
+ "high": candle[2],
+ "low": candle[3],
+ "close": candle[4],
+ "volume": candle[5],
+ })
+
+ return {
+ "status": "ok",
+ "symbol": symbol,
+ "security_id": sec_id,
+ "period": period,
+ "bars": bars[-limit:],
+ }
+
+
+def place_order(
+ config: DhanConfig | 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",
+ security_id: str | None = None,
+ exchange_segment: str = "NSE_EQ",
+ product_type: str = "INTRADAY",
+) -> dict[str, Any]:
+ """Place a PAPER-ONLY order on Dhan (simulated locally).
+
+ Dhan exposes no runtime paper/live discriminator, so this connector is
+ structurally capped at paper: the very first check refuses any config whose
+ ``environment`` is not ``paper``. There is therefore no live order path
+ here, by design. Paper orders are simulated locally — Dhan has no sandbox.
+
+ Args:
+ symbol: Trading symbol or security ID.
+ side: ``buy`` or ``sell``.
+ quantity: Number of shares/lots.
+ order_type: ``market`` or ``limit``.
+ limit_price: Required for limit orders.
+ security_id: Dhan numeric security ID.
+ exchange_segment: NSE_EQ, NSE_FNO, BSE_EQ, etc.
+ product_type: INTRADAY, CNC (delivery), MARGIN.
+ """
+ cfg = config or load_config()
+
+ # ---- HARD GUARD: structurally paper-only (must run before anything) ----
+ 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()
+ if side_token not in ("BUY", "SELL"):
+ return {"status": "error", "error": "side must be 'buy' or 'sell'"}
+
+ type_token = str(order_type or "").strip().upper()
+ if type_token not in ("MARKET", "LIMIT"):
+ return {"status": "error", "error": "order_type must be 'market' or 'limit'"}
+
+ if quantity is None or float(quantity) <= 0:
+ return {"status": "error", "error": "quantity must be positive"}
+
+ qty = int(float(quantity))
+ sec_id = str(security_id or symbol).strip()
+
+ if type_token == "LIMIT" and limit_price is None:
+ return {"status": "error", "error": "limit order requires limit_price"}
+
+ price = float(limit_price) if limit_price is not None else 0
+
+ # Paper-only: simulate locally (Dhan has no sandbox).
+ return {
+ "status": "ok",
+ "order_id": f"PAPER-{sec_id}-{side_token}-{qty}",
+ "symbol": clean_symbol,
+ "security_id": sec_id,
+ "side": side_token.lower(),
+ "profile": cfg.profile,
+ "is_paper": True,
+ "paper_guard": "simulated_locally",
+ "order_type": type_token.lower(),
+ "quantity": qty,
+ "limit_price": price if type_token == "LIMIT" else None,
+ "order_status": "simulated_fill",
+ "exchange_segment": exchange_segment,
+ "product_type": product_type,
+ }
+
+
+def cancel_order(
+ config: DhanConfig | None = None,
+ order_id: str = "",
+ *,
+ symbol: str | None = None,
+) -> dict[str, Any]:
+ """Cancel a PAPER-ONLY order on Dhan (simulated locally).
+
+ Like :func:`place_order`, the first check refuses any non-paper config —
+ this connector never reaches a live order, so it never cancels one.
+ """
+ cfg = config or load_config()
+
+ # ---- HARD GUARD: structurally paper-only (must run before anything) ----
+ 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,
+ }
+
+
+# ---------------------------------------------------------------------------
+# SDK plumbing
+# ---------------------------------------------------------------------------
+
+
+def _require_dhan() -> ModuleType:
+ try:
+ import dhanhq # type: ignore
+ except ModuleNotFoundError as exc:
+ raise DhanDependencyError(
+ "dhanhq is not installed; run `pip install dhanhq`."
+ ) from exc
+ return dhanhq
+
+
+def _dhan_client(cfg: DhanConfig):
+ _require_dhan()
+ from dhanhq import dhanhq as DhanHQ # type: ignore
+
+ if not cfg.client_id or not cfg.access_token:
+ raise DhanConfigError(
+ "Dhan connector not configured: set client_id and access_token "
+ "in ~/.vibe-trading/dhan.json or via environment."
+ )
+ return DhanHQ(cfg.client_id, cfg.access_token)
+
+
+def _missing_fields(cfg: DhanConfig) -> list[str]:
+ missing = []
+ if not cfg.client_id:
+ missing.append("client_id")
+ if not cfg.access_token:
+ missing.append("access_token")
+ return missing
+
+
+def _public_config(cfg: DhanConfig) -> dict[str, Any]:
+ data = asdict(cfg)
+ if data.get("access_token"):
+ data["access_token"] = data["access_token"][:8] + "***"
+ return data
+
+
+def _as_list(value: Any) -> list[Any]:
+ if value is None:
+ return []
+ if isinstance(value, (list, tuple)):
+ return list(value)
+ return [value]
+
+
+def _safe_get(data: Any, *keys: str) -> Any:
+ """Safely traverse nested dicts."""
+ for key in keys:
+ if isinstance(data, Mapping):
+ data = data.get(key)
+ else:
+ return None
+ return data
+
+
+def _order_to_dict(item: Any) -> dict[str, Any]:
+ return {
+ "order_id": str(item.get("orderId", "")),
+ "symbol": item.get("tradingSymbol", ""),
+ "security_id": item.get("securityId", ""),
+ "side": item.get("transactionType", "").lower(),
+ "order_type": item.get("orderType", "").lower(),
+ "quantity": item.get("quantity", 0),
+ "filled_qty": item.get("filledQty", 0),
+ "price": item.get("price", 0),
+ "status": item.get("orderStatus", ""),
+ "exchange_segment": item.get("exchangeSegment", ""),
+ "product_type": item.get("productType", ""),
+ }
diff --git a/agent/src/trading/connectors/shoonya/__init__.py b/agent/src/trading/connectors/shoonya/__init__.py
new file mode 100644
index 000000000..8bc2a4f2d
--- /dev/null
+++ b/agent/src/trading/connectors/shoonya/__init__.py
@@ -0,0 +1,8 @@
+"""Shoonya (Finvasia) trading connector.
+
+Read-only and paper/live account access via the ``NorenRestApiPy`` SDK.
+A ``broker_sdk`` transport for the Indian equity and F&O markets (NSE/BSE).
+
+Shoonya offers ZERO brokerage and free API access — the cheapest Indian broker
+for algo trading. Supports NSE/BSE equities, F&O, currency, and commodity.
+"""
diff --git a/agent/src/trading/connectors/shoonya/classification.py b/agent/src/trading/connectors/shoonya/classification.py
new file mode 100644
index 000000000..b6883c31e
--- /dev/null
+++ b/agent/src/trading/connectors/shoonya/classification.py
@@ -0,0 +1,29 @@
+"""Curated read/write classification for Shoonya (Finvasia) SDK operations.
+
+Keys are the connector's own operation names. Order-mutating SDK calls are
+pinned WRITE so the live gate never treats them as plain reads; anything
+unlisted and not a known read is treated as WRITE (fail-closed) by the gate.
+"""
+
+from __future__ import annotations
+
+from src.live.classification import ToolClass
+
+#: Shoonya SDK operation read/write catalog.
+SHOONYA_TOOL_CLASS: dict[str, ToolClass] = {
+ # READ
+ "get_limits": ToolClass.READ,
+ "get_holdings": ToolClass.READ,
+ "get_positions": ToolClass.READ,
+ "get_order_book": ToolClass.READ,
+ "get_trade_book": ToolClass.READ,
+ "get_quotes": ToolClass.READ,
+ "get_time_price_series": ToolClass.READ,
+ "get_daily_price_series": ToolClass.READ,
+ "searchscrip": ToolClass.READ,
+ "get_security_info": ToolClass.READ,
+ # WRITE
+ "place_order": ToolClass.WRITE,
+ "modify_order": ToolClass.WRITE,
+ "cancel_order": ToolClass.WRITE,
+}
diff --git a/agent/src/trading/connectors/shoonya/profiles.py b/agent/src/trading/connectors/shoonya/profiles.py
new file mode 100644
index 000000000..29ef483b3
--- /dev/null
+++ b/agent/src/trading/connectors/shoonya/profiles.py
@@ -0,0 +1,70 @@
+"""Built-in Shoonya (Finvasia) connector profiles.
+
+Shoonya (https://shoonya.com) by Finvasia offers ZERO brokerage on all
+segments — the cheapest Indian broker for algorithmic trading.
+
+Supports NSE/BSE equities, F&O (NIFTY/BANKNIFTY options), currency, and
+commodity. The API uses a TOTP-based login flow (vendor code + TOTP secret
+required alongside user/password).
+
+Paper-only by design: Shoonya exposes no sandbox and no runtime paper/live
+discriminator — the TOTP login reaches the same real account whether the
+profile is declared ``paper`` or ``live``. Following the Longbridge precedent,
+this connector ships read-only paper/live profiles plus a locally simulated
+paper-trade profile, and exposes NO live order placement. The connector's
+order path is structurally capped at paper (see ``sdk.place_order``).
+"""
+
+from __future__ import annotations
+
+from src.trading.types import READ_CAPABILITIES, TradingProfile
+
+SHOONYA_PROFILES: tuple[TradingProfile, ...] = (
+ TradingProfile(
+ id="shoonya-paper-sdk",
+ connector="shoonya",
+ label="Shoonya Paper · NorenApi (India, ₹0 brokerage)",
+ environment="paper",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES,
+ readonly=True,
+ config={"profile": "paper"},
+ notes=(
+ "Reads real-time Indian market data (NSE/BSE) via Shoonya's free API. "
+ "Paper vs live is operator-declared (the API exposes no runtime "
+ "discriminator). Zero brokerage on all segments. Supports equities, "
+ "F&O (NIFTY/BANKNIFTY options), currency, commodity."
+ ),
+ ),
+ TradingProfile(
+ id="shoonya-paper-trade",
+ connector="shoonya",
+ label="Shoonya Paper · NorenApi Trade (India, ₹0 brokerage)",
+ environment="paper",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES + ("orders.place",),
+ readonly=False,
+ config={"profile": "paper"},
+ notes=(
+ "Places PAPER orders simulated locally using real Shoonya market "
+ "data — no real money at risk. Paper-only by design: Shoonya "
+ "exposes no runtime paper/live discriminator, so live order "
+ "placement is not supported. Zero brokerage. Supports NIFTY/"
+ "BANKNIFTY options."
+ ),
+ ),
+ TradingProfile(
+ id="shoonya-live-sdk-readonly",
+ connector="shoonya",
+ label="Shoonya Live · NorenApi Read-Only (India, ₹0 brokerage)",
+ environment="live",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES,
+ readonly=True,
+ config={"profile": "live-readonly"},
+ notes=(
+ "Reads a live Shoonya account (fund limits, positions, orders, "
+ "quotes, history). No order placement. Zero brokerage."
+ ),
+ ),
+)
diff --git a/agent/src/trading/connectors/shoonya/sdk.py b/agent/src/trading/connectors/shoonya/sdk.py
new file mode 100644
index 000000000..bc6e831b4
--- /dev/null
+++ b/agent/src/trading/connectors/shoonya/sdk.py
@@ -0,0 +1,609 @@
+"""Read-only + order Shoonya (Finvasia) connector via ``NorenRestApiPy`` SDK.
+
+Wraps the Shoonya/NorenApi client for account, positions, orders, quotes, and
+historical data. Supports NSE/BSE equities and F&O (NIFTY/BANKNIFTY options).
+
+Zero brokerage on ALL segments — the cheapest Indian broker for algo trading.
+
+Authentication: Shoonya uses a TOTP-based login flow. The user must provide:
+- user_id: Shoonya login ID
+- password: Login password
+- vendor_code: API vendor code (from Shoonya dashboard)
+- api_secret: API secret key
+- totp_secret: TOTP secret for 2FA (base32 encoded)
+
+Paper-vs-live: Shoonya has no sandbox. Paper mode uses the same API for market
+data reads but simulates orders locally.
+"""
+
+from __future__ import annotations
+
+import json
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from types import ModuleType
+from typing import Any, Mapping
+
+from src.config.paths import get_runtime_root
+
+CONFIG_FILENAME = "shoonya.json"
+
+PROFILE_ENVIRONMENTS = {
+ "paper": "paper",
+ "live-readonly": "live",
+ "live": "live",
+}
+
+SHOONYA_API_URL = "https://api.shoonya.com/NorenWClientTP"
+
+#: Returned by order methods when a non-paper config reaches them. Shoonya
+#: exposes no runtime paper/live discriminator (TOTP login reaches the same real
+#: account), so — following the Longbridge precedent — the connector is
+#: structurally capped at paper and never opens a live order path.
+_PAPER_ONLY_ERROR = (
+ "Shoonya connector is paper-only: it exposes no runtime paper/live "
+ "discriminator, so live order placement is not supported. Use a "
+ "shoonya-paper-* profile."
+)
+
+
+class ShoonyaDependencyError(RuntimeError):
+ """Raised when ``NorenRestApiPy`` is not installed."""
+
+
+class ShoonyaConfigError(RuntimeError):
+ """Raised when config is missing or invalid."""
+
+
+# ---------------------------------------------------------------------------
+# NSE exchange codes for Shoonya
+# ---------------------------------------------------------------------------
+
+class ShoonyaExchange:
+ NSE = "NSE"
+ NFO = "NFO" # NSE F&O
+ BSE = "BSE"
+ BFO = "BFO" # BSE F&O
+ CDS = "CDS" # Currency
+ MCX = "MCX" # Commodity
+
+
+@dataclass(frozen=True)
+class ShoonyaConfig:
+ """Shoonya connector connection settings."""
+
+ user_id: str = ""
+ password: str = ""
+ vendor_code: str = ""
+ api_secret: str = ""
+ totp_secret: str = ""
+ profile: str = "paper"
+ timeout: float = 15.0
+ readonly: bool = True
+
+ @classmethod
+ def from_mapping(cls, data: Mapping[str, Any] | None = None) -> "ShoonyaConfig":
+ payload = dict(data or {})
+ profile = str(payload.get("profile") or "paper").strip().lower()
+ if profile not in PROFILE_ENVIRONMENTS:
+ raise ShoonyaConfigError("profile must be 'paper', 'live-readonly' or 'live'")
+ return cls(
+ user_id=str(payload.get("user_id") or "").strip(),
+ password=str(payload.get("password") or "").strip(),
+ vendor_code=str(payload.get("vendor_code") or "").strip(),
+ api_secret=str(payload.get("api_secret") or "").strip(),
+ totp_secret=str(payload.get("totp_secret") or "").strip(),
+ profile=profile,
+ timeout=float(payload.get("timeout") or 15.0),
+ readonly=bool(payload.get("readonly", True)),
+ )
+
+ def with_overrides(self, **kw: Any) -> "ShoonyaConfig":
+ payload = asdict(self)
+ for key in ("user_id", "password", "vendor_code", "api_secret", "totp_secret", "profile"):
+ if kw.get(key) is not None:
+ payload[key] = kw[key]
+ return ShoonyaConfig.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 = ("user_id", "password", "vendor_code", "api_secret", "totp_secret", "profile")
+
+
+def build_config(
+ profile_config: Mapping[str, Any] | None = None,
+ overrides: Mapping[str, Any] | None = None,
+) -> "ShoonyaConfig":
+ base = asdict(load_config())
+ for key, value in dict(profile_config or {}).items():
+ if value is not None:
+ base[key] = value
+ cfg = ShoonyaConfig.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 config_path() -> Path:
+ return get_runtime_root() / CONFIG_FILENAME
+
+
+def load_config() -> ShoonyaConfig:
+ path = config_path()
+ if not path.exists():
+ return ShoonyaConfig()
+ try:
+ return ShoonyaConfig.from_mapping(json.loads(path.read_text(encoding="utf-8")))
+ except (OSError, ValueError, json.JSONDecodeError) as exc:
+ raise ShoonyaConfigError(f"invalid Shoonya config at {path}: {exc}") from exc
+
+
+def save_config(config: ShoonyaConfig) -> 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 shoonya_available() -> bool:
+ try:
+ _require_shoonya()
+ return True
+ except ShoonyaDependencyError:
+ return False
+
+
+# ---------------------------------------------------------------------------
+# Five read operations + order placement
+# ---------------------------------------------------------------------------
+
+
+def check_status(config: ShoonyaConfig | None = None) -> dict[str, Any]:
+ cfg = config or load_config()
+ report: dict[str, Any] = {
+ "status": "ok",
+ "config": _public_config(cfg),
+ "sdk": {"package": "NorenRestApiPy", "installed": shoonya_available()},
+ "paper_guard": "simulated_locally",
+ "host": SHOONYA_API_URL,
+ "brokerage": "₹0 (zero) on all segments",
+ }
+
+ missing = _missing_fields(cfg)
+ if missing:
+ report["status"] = "error"
+ report["error"] = f"Shoonya 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 NorenRestApiPy` or from "
+ "https://github.com/Shoonya-Dev/ShoonyaApi-py"
+ )
+ return report
+
+ return report
+
+
+def get_account_snapshot(config: ShoonyaConfig | None = None) -> dict[str, Any]:
+ cfg = config or load_config()
+ api = _login(cfg)
+ limits = api.get_limits()
+
+ if limits is None:
+ return {"status": "error", "error": "Failed to fetch fund limits"}
+
+ return {
+ "status": "ok",
+ "profile": cfg.profile,
+ "is_paper": cfg.is_paper,
+ "host": SHOONYA_API_URL,
+ "brokerage": "₹0",
+ "account": {
+ "currency": "INR",
+ "cash": limits.get("cash", "0"),
+ "margin_available": limits.get("marginavailable", "0"),
+ "margin_used": limits.get("marginused", "0"),
+ "collateral": limits.get("collateral", "0"),
+ "payin": limits.get("payin", "0"),
+ },
+ }
+
+
+def get_positions(config: ShoonyaConfig | None = None) -> dict[str, Any]:
+ cfg = config or load_config()
+ api = _login(cfg)
+ positions = api.get_positions()
+
+ rows = []
+ for item in _as_list(positions):
+ rows.append({
+ "symbol": item.get("tsym", ""),
+ "exchange": item.get("exch", ""),
+ "product_type": item.get("prd", ""),
+ "quantity": int(item.get("netqty", 0)),
+ "average_cost": float(item.get("netavgprc", 0)),
+ "ltp": float(item.get("lp", 0)),
+ "unrealized_pnl": float(item.get("urmtom", 0)),
+ "realized_pnl": float(item.get("rpnl", 0)),
+ "day_buy_qty": int(item.get("daybuyqty", 0)),
+ "day_sell_qty": int(item.get("daysellqty", 0)),
+ })
+
+ return {
+ "status": "ok",
+ "profile": cfg.profile,
+ "is_paper": cfg.is_paper,
+ "positions": rows,
+ }
+
+
+def get_open_orders(
+ config: ShoonyaConfig | None = None,
+ *,
+ include_executions: bool = False,
+) -> dict[str, Any]:
+ cfg = config or load_config()
+ api = _login(cfg)
+ orders = api.get_order_book()
+
+ open_orders = []
+ executions = []
+ for item in _as_list(orders):
+ order_dict = _order_to_dict(item)
+ status = str(item.get("status", "")).upper()
+ if status in ("PENDING", "OPEN", "TRIGGER_PENDING"):
+ open_orders.append(order_dict)
+ elif include_executions and status in ("COMPLETE", "FILLED"):
+ executions.append(order_dict)
+
+ 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 get_quote(
+ symbol: str,
+ *,
+ config: ShoonyaConfig | None = None,
+ exchange: str = "NSE",
+) -> dict[str, Any]:
+ """Fetch quote for a symbol.
+
+ Shoonya uses ``exchange:tradingsymbol`` format for quotes.
+ """
+ cfg = config or load_config()
+ api = _login(cfg)
+
+ clean = symbol.strip().upper()
+ try:
+ quote = api.get_quotes(exchange=exchange, token=clean)
+ except Exception as exc:
+ return {"status": "error", "error": str(exc), "symbol": clean}
+
+ if quote is None:
+ return {"status": "error", "error": "quote not found", "symbol": clean}
+
+ return {
+ "status": "ok",
+ "symbol": clean,
+ "exchange": exchange,
+ "quote": {
+ "ltp": float(quote.get("lp", 0)),
+ "open": float(quote.get("o", 0)),
+ "high": float(quote.get("h", 0)),
+ "low": float(quote.get("l", 0)),
+ "close": float(quote.get("c", 0)),
+ "volume": int(quote.get("v", 0)),
+ "bid": float(quote.get("bp1", 0)),
+ "ask": float(quote.get("sp1", 0)),
+ },
+ }
+
+
+def get_historical_bars(
+ symbol: str,
+ *,
+ config: ShoonyaConfig | None = None,
+ exchange: str = "NSE",
+ period: str = "1d",
+ limit: int = 90,
+) -> dict[str, Any]:
+ """Fetch historical OHLCV bars."""
+ cfg = config or load_config()
+ api = _login(cfg)
+
+ clean = symbol.strip().upper()
+ from datetime import datetime, timedelta
+
+ end = datetime.now()
+ if period in ("1m", "5m", "15m", "30m"):
+ start = end - timedelta(days=5)
+ else:
+ start = end - timedelta(days=min(limit * 2, 365))
+
+ interval_map = {"1m": "1", "5m": "5", "15m": "15", "30m": "30", "1h": "60", "1d": "D"}
+ interval = interval_map.get(period, "D")
+
+ try:
+ if interval == "D":
+ data = api.get_daily_price_series(
+ exchange=exchange,
+ tradingsymbol=clean,
+ startdate=start.timestamp(),
+ enddate=end.timestamp(),
+ )
+ else:
+ data = api.get_time_price_series(
+ exchange=exchange,
+ token=clean,
+ starttime=start.timestamp(),
+ endtime=end.timestamp(),
+ interval=interval,
+ )
+ except Exception as exc:
+ return {"status": "error", "error": str(exc), "symbol": clean}
+
+ bars = []
+ for item in _as_list(data):
+ bars.append({
+ "time": item.get("time", item.get("ssboe", "")),
+ "open": float(item.get("into", item.get("o", 0))),
+ "high": float(item.get("inth", item.get("h", 0))),
+ "low": float(item.get("intl", item.get("l", 0))),
+ "close": float(item.get("intc", item.get("c", 0))),
+ "volume": int(item.get("intv", item.get("v", 0))),
+ })
+
+ return {
+ "status": "ok",
+ "symbol": clean,
+ "exchange": exchange,
+ "period": period,
+ "bars": bars[-limit:],
+ }
+
+
+def place_order(
+ config: ShoonyaConfig | 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 = "I",
+) -> dict[str, Any]:
+ """Place a PAPER-ONLY order on Shoonya (simulated locally).
+
+ Shoonya exposes no runtime paper/live discriminator, so this connector is
+ structurally capped at paper: the very first check refuses any config whose
+ ``environment`` is not ``paper``. There is therefore no live order path
+ here, by design. Paper orders are simulated locally — Shoonya has no sandbox.
+
+ Args:
+ symbol: Trading symbol.
+ side: ``buy`` or ``sell``.
+ quantity: Number of shares/lots.
+ order_type: ``market`` or ``limit``.
+ exchange: NSE, NFO, BSE, BFO, MCX, CDS.
+ product_type: I (intraday), C (delivery/CNC), M (margin).
+ """
+ cfg = config or load_config()
+
+ # ---- HARD GUARD: structurally paper-only (must run before anything) ----
+ 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]
+
+ type_map = {"MARKET": "MKT", "LIMIT": "LMT", "MKT": "MKT", "LMT": "LMT"}
+ type_token = str(order_type or "").strip().upper()
+ if type_token not in type_map:
+ return {"status": "error", "error": "order_type must be 'market' or 'limit'"}
+ price_type = type_map[type_token]
+
+ if quantity is None or float(quantity) <= 0:
+ return {"status": "error", "error": "quantity must be positive"}
+
+ qty = int(float(quantity))
+ price = float(limit_price) if limit_price is not None else 0.0
+
+ if price_type == "LMT" and limit_price is None:
+ return {"status": "error", "error": "limit order requires limit_price"}
+
+ # Paper-only: simulate locally (Shoonya has no sandbox).
+ 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": price if price_type == "LMT" else None,
+ "order_status": "simulated_fill",
+ "exchange": exchange,
+ "product_type": product_type,
+ "brokerage": "₹0",
+ }
+
+
+def cancel_order(
+ config: ShoonyaConfig | None = None,
+ order_id: str = "",
+ *,
+ symbol: str | None = None,
+) -> dict[str, Any]:
+ cfg = config or load_config()
+
+ # ---- HARD GUARD: structurally paper-only (must run before anything) ----
+ 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,
+ }
+
+
+# ---------------------------------------------------------------------------
+# SDK plumbing
+# ---------------------------------------------------------------------------
+
+#: Authenticated NorenApi sessions keyed by login identity (``user_id``), so a
+#: second account's reads never reuse the first account's session.
+_api_cache: dict[str, Any] = {}
+
+
+def _require_shoonya() -> ModuleType:
+ try:
+ import NorenRestApiPy.NorenApi as NorenApi # type: ignore
+ except ModuleNotFoundError as exc:
+ raise ShoonyaDependencyError(
+ "NorenRestApiPy is not installed; run "
+ "`pip install NorenRestApiPy` or install from "
+ "https://github.com/Shoonya-Dev/ShoonyaApi-py"
+ ) from exc
+ return NorenApi
+
+
+def _login(cfg: ShoonyaConfig):
+ """Login to Shoonya API with TOTP authentication.
+
+ Sessions are cached per ``user_id`` so distinct accounts never share an
+ authenticated client.
+ """
+ missing = _missing_fields(cfg)
+ if missing:
+ raise ShoonyaConfigError(
+ f"Shoonya connector not configured: missing {', '.join(missing)}. "
+ "Set them in ~/.vibe-trading/shoonya.json"
+ )
+
+ cached = _api_cache.get(cfg.user_id)
+ if cached is not None:
+ return cached
+
+ NorenApi = _require_shoonya()
+
+ try:
+ import pyotp
+ except ModuleNotFoundError as exc:
+ raise ShoonyaDependencyError(
+ "pyotp is not installed (required for Shoonya TOTP login); run "
+ "`pip install pyotp`."
+ ) from exc
+
+ class ShoonyaApi(NorenApi.NorenApi):
+ def __init__(self):
+ super().__init__(
+ host=SHOONYA_API_URL,
+ websocket="wss://api.shoonya.com/NorenWSTP/",
+ )
+
+ api = ShoonyaApi()
+
+ totp = pyotp.TOTP(cfg.totp_secret).now()
+
+ ret = api.login(
+ userid=cfg.user_id,
+ password=cfg.password,
+ twoFA=totp,
+ vendor_code=cfg.vendor_code,
+ api_secret=cfg.api_secret,
+ imei="vibe-trading",
+ )
+
+ if ret is None or ret.get("stat") != "Ok":
+ error_msg = ret.get("emsg", "Login failed") if ret else "Login returned None"
+ raise ShoonyaConfigError(f"Shoonya login failed: {error_msg}")
+
+ _api_cache[cfg.user_id] = api
+ return api
+
+
+def _missing_fields(cfg: ShoonyaConfig) -> list[str]:
+ missing = []
+ for field in ("user_id", "password", "vendor_code", "api_secret", "totp_secret"):
+ if not getattr(cfg, field):
+ missing.append(field)
+ return missing
+
+
+def _public_config(cfg: ShoonyaConfig) -> dict[str, Any]:
+ data = asdict(cfg)
+ for secret in ("password", "api_secret", "totp_secret"):
+ if data.get(secret):
+ data[secret] = "***redacted***"
+ if data.get("user_id"):
+ data["user_id"] = data["user_id"][:2] + "***"
+ return data
+
+
+def _as_list(value: Any) -> list[Any]:
+ if value is None:
+ return []
+ if isinstance(value, (list, tuple)):
+ return list(value)
+ return [value]
+
+
+def _order_to_dict(item: Any) -> dict[str, Any]:
+ return {
+ "order_id": str(item.get("norenordno", "")),
+ "symbol": item.get("tsym", ""),
+ "exchange": item.get("exch", ""),
+ "side": "buy" if item.get("trantype") == "B" else "sell",
+ "order_type": item.get("prctyp", "").lower(),
+ "quantity": int(item.get("qty", 0)),
+ "filled_qty": int(item.get("fillshares", 0)),
+ "price": float(item.get("prc", 0)),
+ "status": item.get("status", ""),
+ "product_type": item.get("prd", ""),
+ }
diff --git a/agent/src/trading/profiles.py b/agent/src/trading/profiles.py
index bbc3c3508..6723ce46e 100644
--- a/agent/src/trading/profiles.py
+++ b/agent/src/trading/profiles.py
@@ -8,11 +8,13 @@ from pathlib import Path
from src.config.paths import get_runtime_root
from src.trading.connectors.alpaca.profiles import ALPACA_PROFILES
from src.trading.connectors.binance.profiles import BINANCE_PROFILES
+from src.trading.connectors.dhan.profiles import DHAN_PROFILES
from src.trading.connectors.futu.profiles import FUTU_PROFILES
from src.trading.connectors.ibkr.profiles import IBKR_PROFILES
from src.trading.connectors.longbridge.profiles import LONGBRIDGE_PROFILES
from src.trading.connectors.okx.profiles import OKX_PROFILES
from src.trading.connectors.robinhood.profiles import ROBINHOOD_PROFILES
+from src.trading.connectors.shoonya.profiles import SHOONYA_PROFILES
from src.trading.connectors.tiger.profiles import TIGER_PROFILES
from src.trading.types import TradingProfile
@@ -28,6 +30,8 @@ BUILTIN_PROFILES: tuple[TradingProfile, ...] = (
*OKX_PROFILES,
*BINANCE_PROFILES,
*FUTU_PROFILES,
+ *DHAN_PROFILES,
+ *SHOONYA_PROFILES,
)
diff --git a/agent/src/trading/service.py b/agent/src/trading/service.py
index 90c7f9907..a8ae9f7c2 100644
--- a/agent/src/trading/service.py
+++ b/agent/src/trading/service.py
@@ -20,6 +20,8 @@ _SDK_CONNECTOR_MODULES = {
"okx": "src.trading.connectors.okx.sdk",
"binance": "src.trading.connectors.binance.sdk",
"futu": "src.trading.connectors.futu.sdk",
+ "dhan": "src.trading.connectors.dhan.sdk",
+ "shoonya": "src.trading.connectors.shoonya.sdk",
}
diff --git a/agent/tests/test_sdk_connectors.py b/agent/tests/test_sdk_connectors.py
index 462c43ce9..a41e450b8 100644
--- a/agent/tests/test_sdk_connectors.py
+++ b/agent/tests/test_sdk_connectors.py
@@ -16,12 +16,16 @@ from src.trading.connectors.alpaca import sdk as al
from src.trading.connectors.alpaca.classification import ALPACA_TOOL_CLASS
from src.trading.connectors.binance import sdk as bn
from src.trading.connectors.binance.classification import BINANCE_TOOL_CLASS
+from src.trading.connectors.dhan import sdk as dh
+from src.trading.connectors.dhan.classification import DHAN_TOOL_CLASS
from src.trading.connectors.futu import sdk as ft
from src.trading.connectors.futu.classification import FUTU_TOOL_CLASS
from src.trading.connectors.longbridge import sdk as lb
from src.trading.connectors.longbridge.classification import LONGBRIDGE_TOOL_CLASS
from src.trading.connectors.okx import sdk as ox
from src.trading.connectors.okx.classification import OKX_TOOL_CLASS
+from src.trading.connectors.shoonya import sdk as sh
+from src.trading.connectors.shoonya.classification import SHOONYA_TOOL_CLASS
from src.trading.connectors.tiger import sdk as tg
from src.trading.connectors.tiger.classification import TIGER_TOOL_CLASS
@@ -34,7 +38,7 @@ pytestmark = pytest.mark.unit
def test_sdk_profiles_registered() -> None:
- """All six broker connectors register paper and read-only live profiles."""
+ """All broker connectors register paper and read-only live profiles."""
ids = {p.id for p in profiles.list_profiles()}
assert {
"tiger-paper-sdk", "tiger-live-sdk-readonly",
@@ -43,9 +47,24 @@ def test_sdk_profiles_registered() -> None:
"okx-paper-sdk", "okx-live-sdk-readonly",
"binance-paper-sdk", "binance-live-sdk-readonly",
"futu-paper-sdk", "futu-live-sdk-readonly",
+ "dhan-paper-sdk", "dhan-live-sdk-readonly",
+ "shoonya-paper-sdk", "shoonya-live-sdk-readonly",
} <= ids
+def test_no_discriminator_brokers_expose_no_live_trade_profile() -> None:
+ """Brokers without a runtime paper/live discriminator (Longbridge, Dhan,
+ Shoonya) must NOT register any live order-placing profile — the Longbridge
+ precedent. A ``*-live-trade`` profile here would be a red-line regression."""
+ ids = {p.id for p in profiles.list_profiles()}
+ for broker in ("longbridge", "dhan", "shoonya"):
+ assert f"{broker}-live-trade" not in ids
+ # No live profile for these brokers may advertise an order capability.
+ for p in profiles.list_profiles():
+ if p.connector == broker and p.environment == "live":
+ assert not any(".place" in cap or "requires_mandate" in cap for cap in p.capabilities)
+
+
@pytest.mark.parametrize(
"profile_id, connector, environment",
[
@@ -61,6 +80,10 @@ def test_sdk_profiles_registered() -> None:
("binance-live-sdk-readonly", "binance", "live"),
("futu-paper-sdk", "futu", "paper"),
("futu-live-sdk-readonly", "futu", "live"),
+ ("dhan-paper-sdk", "dhan", "paper"),
+ ("dhan-live-sdk-readonly", "dhan", "live"),
+ ("shoonya-paper-sdk", "shoonya", "paper"),
+ ("shoonya-live-sdk-readonly", "shoonya", "live"),
],
)
def test_sdk_profiles_are_readonly_broker_sdk(profile_id, connector, environment) -> None:
@@ -358,6 +381,8 @@ def test_okx_invalid_profile_rejected() -> None:
("okx", "place_order"),
("binance", "create_order"),
("futu", "place_order"),
+ ("dhan", "place_order"),
+ ("shoonya", "place_order"),
],
)
def test_order_ops_write_pinned_via_registry(broker, order_op) -> None:
@@ -461,3 +486,101 @@ def test_okx_history_maps_candles_and_period(monkeypatch) -> None:
assert len(out["bars"]) == 1
bar = out["bars"][0]
assert bar["open"] == "100" and bar["close"] == "105" and bar["confirm"] == "1"
+
+
+# --------------------------------------------------------------------------- #
+# Dhan + Shoonya: structural paper-only cap (no runtime discriminator)
+#
+# Like Longbridge, these brokers expose no sandbox / no runtime paper/live
+# discriminator (same token/login reaches the same real account). The order
+# path is therefore structurally capped at paper: any non-paper config is
+# refused at the first line, so a flipped ``profile`` override can never reach a
+# live order. Paper orders are simulated locally (neither broker has a sandbox).
+# --------------------------------------------------------------------------- #
+
+
[email protected]("mod, Config", [(dh, dh.DhanConfig), (sh, sh.ShoonyaConfig)])
[email protected]("profile", ["live", "live-readonly"])
+def test_in_broker_place_order_refuses_non_paper(mod, Config, profile) -> None:
+ """A non-paper config is refused before any SDK call (fail-closed)."""
+ result = mod.place_order(Config(profile=profile), symbol="RELIANCE", side="buy", quantity=1)
+ assert result["status"] == "error"
+ assert "paper-only" in result["error"]
+
+
[email protected]("mod, Config", [(dh, dh.DhanConfig), (sh, sh.ShoonyaConfig)])
+def test_in_broker_cancel_order_refuses_non_paper(mod, Config) -> None:
+ result = mod.cancel_order(Config(profile="live"), "ORD1")
+ assert result["status"] == "error"
+ assert "paper-only" in result["error"]
+
+
[email protected]("mod, Config", [(dh, dh.DhanConfig), (sh, sh.ShoonyaConfig)])
+def test_in_broker_paper_place_order_simulated_locally(mod, Config) -> None:
+ """Paper config simulates locally — no real money, no SDK call."""
+ result = mod.place_order(Config(profile="paper"), symbol="RELIANCE", side="buy", quantity=10)
+ assert result["status"] == "ok"
+ assert result["is_paper"] is True
+ assert result["order_status"] == "simulated_fill"
+ assert result["paper_guard"] == "simulated_locally"
+
+
[email protected]("mod, Config", [(dh, dh.DhanConfig), (sh, sh.ShoonyaConfig)])
+def test_in_broker_paper_cancel_order_simulated(mod, Config) -> None:
+ result = mod.cancel_order(Config(profile="paper"), "ORD1")
+ assert result["status"] == "ok"
+ assert result["cancelled"] is True
+ assert result["is_paper"] is True
+
+
+def test_in_broker_order_ops_classified_write() -> None:
+ for name in ("place_order", "modify_order", "cancel_order"):
+ assert DHAN_TOOL_CLASS[name] is ToolClass.WRITE
+ assert SHOONYA_TOOL_CLASS[name] is ToolClass.WRITE
+ for name in ("get_positions", "get_holdings"):
+ assert DHAN_TOOL_CLASS[name] is ToolClass.READ
+ assert SHOONYA_TOOL_CLASS[name] is ToolClass.READ
+
+
+def test_dhan_redacts_access_token() -> None:
+ cfg = dh.DhanConfig(client_id="C1", access_token="tok-abcdefgh-secret")
+ pub = dh._public_config(cfg)
+ assert "secret" not in str(pub)
+ assert pub["access_token"].endswith("***")
+
+
+def test_shoonya_redacts_secrets() -> None:
+ cfg = sh.ShoonyaConfig(
+ user_id="USER1", password="pw", vendor_code="V", api_secret="sec", totp_secret="totp"
+ )
+ pub = sh._public_config(cfg)
+ for secret in ("password", "api_secret", "totp_secret"):
+ assert pub[secret] == "***redacted***"
+ assert "sec" not in str(pub) or pub["api_secret"] == "***redacted***"
+ assert pub["user_id"].endswith("***")
+
+
+def test_dhan_invalid_profile_rejected() -> None:
+ with pytest.raises(dh.DhanConfigError):
+ dh.DhanConfig.from_mapping({"profile": "go-live"})
+
+
+def test_shoonya_invalid_profile_rejected() -> None:
+ with pytest.raises(sh.ShoonyaConfigError):
+ sh.ShoonyaConfig.from_mapping({"profile": "go-live"})
+
+
+def test_dhan_service_unconfigured(monkeypatch, tmp_path) -> None:
+ monkeypatch.setattr(dh, "get_runtime_root", lambda: tmp_path)
+ result = service.check_connection("dhan-paper-sdk")
+ assert result["status"] == "error"
+ assert result["connector"] == "dhan"
+ assert result["transport"] == "broker_sdk"
+
+
+def test_shoonya_service_unconfigured(monkeypatch, tmp_path) -> None:
+ monkeypatch.setattr(sh, "get_runtime_root", lambda: tmp_path)
+ result = service.check_connection("shoonya-paper-sdk")
+ assert result["status"] == "error"
+ assert result["connector"] == "shoonya"
+ assert result["transport"] == "broker_sdk"