PaperTrade / fo_dhan.py
Khanna, Videh Rakesh Rakesh
Add provider-independent F&O paper trading for learning
ae7951c
Raw History Blame Contribute Delete
5.75 kB
"""Optional read-only Dhan implementation of the neutral F&O provider interface."""
from datetime import datetime
import math
import os
import time
from dhan_client import get_dhan_client
from fo import FoUnavailable, IST, normalize_quote, number
class DhanFoProvider:
def __init__(self, client=None):
self.client = client if client is not None else get_dhan_client()
def capabilities(self):
available = bool(self.client.enabled and self.client.configured
and os.getenv("DHAN_ALLOW_BROWSER_DATA", "0") == "1"
and not self.client.yahoo_fallback_active)
return {"quotes": available, "option_chain": available, "margin": available}
def _mapping(self, contract):
if not self.capabilities()["quotes"]:
raise FoUnavailable("Optional Dhan derivative data is unavailable")
mapping = contract.get("provider_ids", {}).get("dhan", {})
if not isinstance(mapping, dict) or not str(mapping.get("security_id", "")).isdigit():
raise FoUnavailable("This reference contract has no Dhan mapping")
return mapping
def _invalid_data(self):
from market_calendar import market_status
if market_status().get("status") == "OPEN":
self.client._record_failure("invalid_response")
raise FoUnavailable("Derivative provider returned unusable data")
def quote(self, contract):
mapping = self._mapping(contract)
security_id = str(mapping["security_id"])
result = self.client._request("POST", "/marketfeed/quote", {"NSE_FNO": [int(security_id)]}, timeout=8)
data = result.get("data")
if not isinstance(data, dict) or not isinstance(data.get("NSE_FNO"), dict):
self._invalid_data()
raw = data["NSE_FNO"].get(security_id)
if not isinstance(raw, dict) or not isinstance(raw.get("depth", {}), dict):
self._invalid_data()
try:
traded = datetime.strptime(raw["last_trade_time"], "%d/%m/%Y %H:%M:%S").replace(tzinfo=IST).timestamp()
except (KeyError, TypeError, ValueError):
traded = None
depth = raw.get("depth") or {}
sides = [depth.get(side) or [{}] for side in ("buy", "sell")]
if any(not isinstance(side, list) or not isinstance(side[0], dict) for side in sides):
self._invalid_data()
buy, sell = sides[0][0], sides[1][0]
quote = {"price": raw.get("last_price"), "bid": buy.get("price"), "ask": sell.get("price"),
"bid_quantity": buy.get("quantity"), "ask_quantity": sell.get("quantity"),
"source": "dhan", "observed_at": time.time(), "trade_time": traded}
if not normalize_quote(quote)["stale"]:
self.client._record_success()
else:
from market_calendar import market_status
if market_status().get("status") == "OPEN":
self.client._record_failure("invalid_response")
return quote
def chain(self, contracts):
contract = contracts[0]
mapping = self._mapping(contract)
segment = "IDX_I" if contract["underlying_type"] == "INDEX" else "NSE_EQ"
underlying_id = str(mapping.get("underlying_security_id", ""))
if not underlying_id.isdigit() or mapping.get("underlying_segment") != segment:
raise FoUnavailable("Underlying mapping is unavailable")
result = self.client._request("POST", "/optionchain", {
"UnderlyingScrip": int(underlying_id), "UnderlyingSeg": segment, "Expiry": contract["expiry"]}, timeout=8)
data = result.get("data")
if not isinstance(data, dict) or not isinstance(data.get("oc"), dict):
self._invalid_data()
chain = data["oc"]
rows = []
for reference in contracts:
strike = next((value for key, value in chain.items() if float(key) == reference["strike"]), {})
raw = strike.get(reference["option_type"].lower(), {})
expected = reference.get("provider_ids", {}).get("dhan", {}).get("security_id")
if not raw or str(raw.get("security_id")) != str(expected):
continue
row = {"contract_id": reference["contract_id"], "strike": reference["strike"],
"option_type": reference["option_type"]}
for target, source in (("price", "last_price"), ("bid", "top_bid_price"), ("ask", "top_ask_price"),
("oi", "oi"), ("volume", "volume"), ("iv", "implied_volatility")):
try:
row[target] = float(number(raw.get(source), source, allow_zero=True))
except ValueError:
row[target] = None
row["greeks"] = {key: value for key, value in (raw.get("greeks") or {}).items()
if key in {"delta", "gamma", "theta", "vega"} and isinstance(value, (float, int))
and not isinstance(value, bool) and math.isfinite(value)}
rows.append(row)
if not rows:
self._invalid_data()
self.client._record_success()
return {"contracts": rows, "source": "dhan"}
def margin(self, contract, direction, quantity, price):
mapping = self._mapping(contract)
result = self.client._request("POST", "/margincalculator", {
"dhanClientId": self.client.client_id, "exchangeSegment": "NSE_FNO",
"transactionType": "BUY" if direction == "LONG" else "SELL", "quantity": quantity,
"productType": "MARGIN", "securityId": str(mapping["security_id"]), "price": price}, timeout=8)
return float(number(result.get("totalMargin"), "margin"))