dhanhq
Original:🇺🇸 English
Translated
15 scriptsChecked / no sensitive code detected
Use when the user mentions DhanHQ, Dhan API, or wants to trade on Indian exchanges (NSE, BSE, MCX). Triggers for: place, modify, or cancel stock/F&O/commodity orders on Dhan; fetch portfolio holdings or positions; get live or historical market data; access option chains with Greeks; check fund limits or margin; build any trading automation for Indian markets; resolve NSE/BSE instrument IDs; stream live WebSocket market feeds or order updates. Also trigger for general questions about programmatic trading on Indian exchanges if Dhan is the user's broker.
12installs
Sourcedhan-oss/dhanhq-skills
Added on
NPX Install
npx skill4agent add dhan-oss/dhanhq-skills dhanhqTags
Translated version includes tags in frontmatterSKILL.md Content
View Translation Comparison →DhanHQ — Indian Market Trading Skill
Setup
Stable install:
python
pip install dhanhqUse the current SDK branch when you need newer v2 capabilities such as 200-level depth or the latest helper coverage:
python
pip install --upgrade dhanhqMinimal initialization:
python
from dhanhq import DhanContext, dhanhq
dhan_context = DhanContext("YOUR_CLIENT_ID", "YOUR_ACCESS_TOKEN")
dhan = dhanhq(dhan_context)Environment-variable setup:
python
import os
from dhanhq import DhanContext, dhanhq
dhan_context = DhanContext(
os.environ["DHAN_CLIENT_ID"],
os.environ["DHAN_ACCESS_TOKEN"],
)
dhan = dhanhq(dhan_context)If generating scripts for this repo, prefer:
python
from scripts.dhan_helpers import get_client
dhan, dhan_context = get_client()Safety Rules — Always Enforce
- Confirm before placing live orders.
- Show a readable order preview before execution.
- Default to orders unless the user explicitly wants
LIMIT.MARKET - Warn when notional exceeds .
Rs. 50,000 - For F&O, validate lot size before placement.
- Never use or
CNCfor F&O, commodity, or currency segments.MTF - Never hardcode credentials in generated code.
- Ask for confirmation before ,
modify_order,cancel_order, or any multi-leg live execution.kill_switch
Access Checks Before Live Use
Before using the account for live work, verify:
- Access token is valid.
- or
dhan_login.user_profile(...)shows the needed account setup.GET /profile - is active for quote/history/feed/option-chain use.
dataPlan - Static IP is configured for order placement, order modification, order cancellation, super orders, and forever orders.
Useful profile fields:
tokenValidityactiveSegmentddpimtfdataPlandataValidity
Current SDK Constants
| Category | Constant | Value |
|---|---|---|
| Exchange | | |
| | |
| | |
| | |
| | |
| | |
| | |
| Transaction | | |
| | |
| Order Type | | |
| | |
| | |
| | |
| Product | | |
| | |
| | |
| | |
| Validity | | |
| |
Current SDK Methods To Prefer
| Task | Method |
|---|---|
| Place order | |
| Slice large order | |
| Modify order | |
| Cancel order | |
| Order book | |
| Order by ID | |
| Order by correlation ID | |
| Trade book | |
| Trade history | |
| Ledger | |
| Super orders | |
| Forever orders | |
| Holdings | |
| Positions | |
| Convert position | |
| eDIS | |
| Fund limits | |
| Margin calculator | |
| Daily history | |
| Minute history | |
| Expired options data | |
| Market quote snapshot | |
| Expiry list | |
| Option chain | |
| Security master | |
| Live market feed | |
| Live order updates | |
| Full market depth | |
| Kill switch | |
High-Value Gotchas
- The SDK wraps HTTP responses as . Response shapes vary by endpoint — success payloads differ significantly (arrays, flat objects, nested dicts) depending on the API.
{"status": "success"|"failure", "remarks": ..., "data": ...} - Repo helpers add a normalization layer. Fields like ,
ce_ltp,ce_oiare repo-defined names — not raw Dhan field names.ce_iv - is the current SDK method. Do not reference
intraday_minute_data(...).historical_minute_data() - Historical timestamps are epoch values. Convert them explicitly.
- The SDK currently validates with
expiry_code, but Dhan's v2 annexure documents[0, 1, 2, 3],0,1. Prefer the documented values unless Dhan updates the API docs.2 - Quote APIs are rate-limited to .
1 request/sec - Option-chain REST data is keyed by strike string under . Use repo helpers for analysis-friendly rows.
data["oc"] - Market orders via API are currently converted by Dhan into limit orders with MPP.
- Order placement APIs require static IP whitelisting.
- Trading APIs are free for Dhan users; Data APIs require an active data plan.
- Lot sizes and freeze quantities change. Treat hardcoded values as fallback only.
Product-Type Rules
| Segment | Allowed Product Types |
|---|---|
| |
| |
Instrument Resolution Rules
Use the security master as the primary source for:
security_idlot_sizetick_size- expiry
- strike
- derivative contract lookup
Quick-reference index underlyings:
| Underlying | security_id | Underlying Segment |
|---|---|---|
| NIFTY 50 | | |
| BANK NIFTY | | |
| FINNIFTY | | |
| MIDCPNIFTY | | |
| SENSEX | | |
Preferred Helper Layer
When generating scripts in this repo, prefer:
- for SDK bootstrapping
get_client() - for cash-market lookup
resolve_symbol() - for contract lookup
resolve_derivative() - for option-chain normalization
fetch_chain_df() - for ATM selection
find_atm_row() - for pre-flight margin checks
check_margin() - for readable confirmation
preview_order()
Core Patterns
1. Check account access before data calls
python
from dhanhq import DhanLogin
dhan_login = DhanLogin("YOUR_CLIENT_ID")
profile = dhan_login.user_profile("YOUR_ACCESS_TOKEN")
print(profile["dataPlan"])
print(profile["dataValidity"])2. Fetch historical data with epoch conversion
python
data = dhan.historical_daily_data(
security_id="2885",
exchange_segment=dhanhq.NSE,
instrument_type="EQUITY",
from_date="2024-01-01",
to_date="2024-12-31",
)
if data["status"] == "success":
candles = data["data"]
timestamps = [dhan.convert_to_date_time(ts) for ts in candles["timestamp"]]3. Normalize option-chain data for analysis
python
from scripts.dhan_helpers import fetch_chain_df, find_atm_row
chain_df, spot = fetch_chain_df(dhan, under_security_id=13, expiry="2025-03-27")
atm = find_atm_row(chain_df, spot)
print(spot)
print(atm["strike"])
print(atm["ce_security_id"], atm["ce_ltp"])4. Margin check before live order placement
python
from scripts.dhan_helpers import check_margin
margin = check_margin(
dhan,
security_id="2885",
exchange_segment=dhanhq.NSE,
transaction_type=dhanhq.BUY,
quantity=10,
product_type=dhanhq.CNC,
price=2450.0,
)
print(margin["sufficient"], margin["total_margin"], margin["available_balance"])5. Live market feed
python
from dhanhq import MarketFeed
instruments = [
(MarketFeed.NSE, "2885", MarketFeed.Ticker),
(MarketFeed.NSE_FNO, "49081", MarketFeed.Full),
]
feed = MarketFeed(dhan_context, instruments, "v2")
feed.run_forever()
print(feed.get_data())Rate Limits
| API Category | Per Second | Per Minute | Per Hour | Per Day |
|---|---|---|---|---|
| Order APIs | 10 | 250 | 1000 | 7000 |
| Data APIs | 5 | - | - | 100000 |
| Quote APIs | 1 | Unlimited | Unlimited | Unlimited |
| Non-Trading APIs | 20 | Unlimited | Unlimited | Unlimited |
Reference Files
Dhan APIs cover execution, quotes, OHLC, option chain, and portfolio. For fundamental data (PE, EPS, revenue), technical indicators (RSI, MACD), or shareholding patterns not available via Dhan, use ScanX — see .
references/scanx-data.md| Need | File |
|---|---|
| Orders, super orders, forever orders | references/orders.md |
| Holdings, positions, eDIS | references/portfolio.md |
| Daily/minute history, quotes, expired options | references/market-data.md |
| Option-chain usage and normalization | references/option-chain.md |
| Fund limits and margin checks | references/funds.md |
| Live feeds and depth | references/live-feed.md |
| Error handling and subscription troubleshooting | references/error-codes.md |
| Instrument resolution | references/instruments.md |
| Multi-step execution patterns | references/common-workflows.md |
| Options analytics | references/options-analysis-patterns.md |
| Backtesting patterns | references/backtesting-with-dhan.md |
| PE ratio, RSI, financials, screeners — data Dhan does not provide | references/scanx-data.md |
Data API Subscription Invalid
If the user gets or :
DH-902806- Log in to
web.dhan.co - Open ->
My ProfileAccess DhanHQ APIs - Verify that is active
dataPlan - Activate the Data API plan if needed
- Generate a fresh access token
- Re-test with or
ticker_data()ohlc_data() - If order APIs still fail, check static IP separately