DhanHQ — Indian Market Trading Skill
Setup
Stable install:
pip install dhanhq
Use the current SDK branch when you need newer v2 capabilities such as 200-level depth or the latest helper coverage:
pip install --upgrade dhanhq
Minimal initialization:
from dhanhq import DhanContext, dhanhq
dhan_context = DhanContext("YOUR_CLIENT_ID", "YOUR_ACCESS_TOKEN")
dhan = dhanhq(dhan_context)
Environment-variable setup:
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:
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
LIMIT orders unless the user explicitly wants MARKET.
- Warn when notional exceeds
Rs. 50,000.
- For F&O, validate lot size before placement.
- Never use
CNC or MTF for F&O, commodity, or currency segments.
- Never hardcode credentials in generated code.
- Ask for confirmation before
modify_order, cancel_order, kill_switch, or any multi-leg live execution.
Access Checks Before Live Use
Before using the account for live work, verify:
- Access token is valid.
dhan_login.user_profile(...) or GET /profile shows the needed account setup.
dataPlan is active for quote/history/feed/option-chain use.
- Static IP is configured for order placement, order modification, order cancellation, super orders, and forever orders.
Useful profile fields:
tokenValidity
activeSegment
ddpi
mtf
dataPlan
dataValidity
Current SDK Constants
| Category |
Constant |
Value |
| Exchange |
dhanhq.NSE |
NSE_EQ |
|
dhanhq.BSE |
BSE_EQ |
|
dhanhq.NSE_FNO |
NSE_FNO |
|
dhanhq.BSE_FNO |
BSE_FNO |
|
dhanhq.MCX |
MCX_COMM |
|
dhanhq.CUR |
NSE_CURRENCY |
|
dhanhq.INDEX |
IDX_I |
| Transaction |
dhanhq.BUY |
BUY |
|
dhanhq.SELL |
SELL |
| Order Type |
dhanhq.LIMIT |
LIMIT |
|
dhanhq.MARKET |
MARKET |
|
dhanhq.SL |
STOP_LOSS |
|
dhanhq.SLM |
STOP_LOSS_MARKET |
| Product |
dhanhq.CNC |
CNC |
|
dhanhq.INTRA |
INTRADAY |
|
dhanhq.MARGIN |
MARGIN |
|
dhanhq.MTF |
MTF |
| Validity |
dhanhq.DAY |
DAY |
|
dhanhq.IOC |
IOC |
Current SDK Methods To Prefer
| Task |
Method |
| Place order |
dhan.place_order() |
| Slice large order |
dhan.place_slice_order() |
| Modify order |
dhan.modify_order() |
| Cancel order |
dhan.cancel_order() |
| Order book |
dhan.get_order_list() |
| Order by ID |
dhan.get_order_by_id() |
| Order by correlation ID |
dhan.get_order_by_correlationID() |
| Trade book |
dhan.get_trade_book() |
| Trade history |
dhan.get_trade_history() |
| Ledger |
dhan.ledger_report() |
| Super orders |
place_super_order(), modify_super_order(), cancel_super_order(), get_super_order_list() |
| Forever orders |
place_forever(), modify_forever(), cancel_forever(), get_forever() |
| Holdings |
dhan.get_holdings() |
| Positions |
dhan.get_positions() |
| Convert position |
dhan.convert_position() |
| eDIS |
dhan.generate_tpin(), dhan.open_browser_for_tpin(), dhan.edis_inquiry() |
| Fund limits |
dhan.get_fund_limits() |
| Margin calculator |
dhan.margin_calculator() |
| Daily history |
dhan.historical_daily_data() |
| Minute history |
dhan.intraday_minute_data() |
| Expired options data |
dhan.expired_options_data() |
| Market quote snapshot |
dhan.ticker_data(), dhan.ohlc_data(), dhan.quote_data() |
| Expiry list |
dhan.expiry_list() |
| Option chain |
dhan.option_chain() |
| Security master |
dhanhq.fetch_security_list() |
| Live market feed |
MarketFeed |
| Live order updates |
OrderUpdate |
| Full market depth |
FullDepth |
| Kill switch |
dhan.kill_switch(), dhan.status_kill_switch() |
High-Value Gotchas
- The SDK wraps HTTP responses as
{"status": "success"|"failure", "remarks": ..., "data": ...}. Response shapes vary by endpoint — success payloads differ significantly (arrays, flat objects, nested dicts) depending on the API.
- Repo helpers add a normalization layer. Fields like
ce_ltp, ce_oi, ce_iv are repo-defined names — not raw Dhan field names.
intraday_minute_data(...) is the current SDK method. Do not reference historical_minute_data().
- Historical timestamps are epoch values. Convert them explicitly.
- The SDK currently validates
expiry_code with [0, 1, 2, 3], but Dhan's v2 annexure documents 0, 1, 2. Prefer the documented values unless Dhan updates the API docs.
- Quote APIs are rate-limited to
1 request/sec.
- Option-chain REST data is keyed by strike string under
data["oc"]. Use repo helpers for analysis-friendly rows.
- 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 |
NSE_EQ, BSE_EQ |
CNC, INTRADAY, MARGIN, MTF |
NSE_FNO, BSE_FNO, MCX_COMM, NSE_CURRENCY, BSE_CURRENCY |
INTRADAY, MARGIN |
Instrument Resolution Rules
Use the security master as the primary source for:
security_id
lot_size
tick_size
- expiry
- strike
- derivative contract lookup
Quick-reference index underlyings:
| Underlying |
security_id |
Underlying Segment |
| NIFTY 50 |
13 |
IDX_I |
| BANK NIFTY |
25 |
IDX_I |
| FINNIFTY |
27 |
IDX_I |
| MIDCPNIFTY |
442 |
IDX_I |
| SENSEX |
51 |
IDX_I |
Preferred Helper Layer
When generating scripts in this repo, prefer:
get_client() for SDK bootstrapping
resolve_symbol() for cash-market lookup
resolve_derivative() for contract lookup
fetch_chain_df() for option-chain normalization
find_atm_row() for ATM selection
check_margin() for pre-flight margin checks
preview_order() for readable confirmation
Core Patterns
1. Check account access before data calls
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
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
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
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
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 DH-902 or 806:
- Log in to
web.dhan.co
- Open
My Profile -> Access DhanHQ APIs
- Verify that
dataPlan is active
- Activate the Data API plan if needed
- Generate a fresh access token
- Re-test with
ticker_data() or ohlc_data()
- If order APIs still fail, check static IP separately
1---2name: dhanhq3description: 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.4---5
6# DhanHQ — Indian Market Trading Skill
7
8## Setup
9
10Stable install:
11
12```python
13pip install dhanhq
14```
15
16Use the current SDK branch when you need newer v2 capabilities such as 200-level depth or the latest helper coverage:
17
18```python
19pip install --upgrade dhanhq
20```
21
22Minimal initialization:
23
24```python
25from dhanhq import DhanContext, dhanhq
26
27dhan_context = DhanContext("YOUR_CLIENT_ID", "YOUR_ACCESS_TOKEN")
28dhan = dhanhq(dhan_context)
29```
30
31Environment-variable setup:
32
33```python
34import os
35from dhanhq import DhanContext, dhanhq
36
37dhan_context = DhanContext(
38 os.environ["DHAN_CLIENT_ID"],
39 os.environ["DHAN_ACCESS_TOKEN"],
40)
41dhan = dhanhq(dhan_context)
42```
43
44If generating scripts for this repo, prefer:
45
46```python
47from scripts.dhan_helpers import get_client
48
49dhan, dhan_context = get_client()
50```
51
52## Safety Rules — Always Enforce
53
541. Confirm before placing live orders.
552. Show a readable order preview before execution.
563. Default to `LIMIT` orders unless the user explicitly wants `MARKET`.
574. Warn when notional exceeds `Rs. 50,000`.
585. For F&O, validate lot size before placement.
596. Never use `CNC` or `MTF` for F&O, commodity, or currency segments.
607. Never hardcode credentials in generated code.
618. Ask for confirmation before `modify_order`, `cancel_order`, `kill_switch`, or any multi-leg live execution.
62
63## Access Checks Before Live Use
64
65Before using the account for live work, verify:
66
671. Access token is valid.
682. `dhan_login.user_profile(...)` or `GET /profile` shows the needed account setup.
693. `dataPlan` is active for quote/history/feed/option-chain use.
704. Static IP is configured for order placement, order modification, order cancellation, super orders, and forever orders.
71
72Useful profile fields:
73- `tokenValidity`
74- `activeSegment`
75- `ddpi`
76- `mtf`
77- `dataPlan`
78- `dataValidity`
79
80## Current SDK Constants
81
82| Category | Constant | Value |
83|----------|----------|-------|
84| Exchange | `dhanhq.NSE` | `NSE_EQ` |
85| | `dhanhq.BSE` | `BSE_EQ` |
86| | `dhanhq.NSE_FNO` | `NSE_FNO` |
87| | `dhanhq.BSE_FNO` | `BSE_FNO` |
88| | `dhanhq.MCX` | `MCX_COMM` |
89| | `dhanhq.CUR` | `NSE_CURRENCY` |
90| | `dhanhq.INDEX` | `IDX_I` |
91| Transaction | `dhanhq.BUY` | `BUY` |
92| | `dhanhq.SELL` | `SELL` |
93| Order Type | `dhanhq.LIMIT` | `LIMIT` |
94| | `dhanhq.MARKET` | `MARKET` |
95| | `dhanhq.SL` | `STOP_LOSS` |
96| | `dhanhq.SLM` | `STOP_LOSS_MARKET` |
97| Product | `dhanhq.CNC` | `CNC` |
98| | `dhanhq.INTRA` | `INTRADAY` |
99| | `dhanhq.MARGIN` | `MARGIN` |
100| | `dhanhq.MTF` | `MTF` |
101| Validity | `dhanhq.DAY` | `DAY` |
102| | `dhanhq.IOC` | `IOC` |
103
104## Current SDK Methods To Prefer
105
106| Task | Method |
107|------|--------|
108| Place order | `dhan.place_order()` |
109| Slice large order | `dhan.place_slice_order()` |
110| Modify order | `dhan.modify_order()` |
111| Cancel order | `dhan.cancel_order()` |
112| Order book | `dhan.get_order_list()` |
113| Order by ID | `dhan.get_order_by_id()` |
114| Order by correlation ID | `dhan.get_order_by_correlationID()` |
115| Trade book | `dhan.get_trade_book()` |
116| Trade history | `dhan.get_trade_history()` |
117| Ledger | `dhan.ledger_report()` |
118| Super orders | `place_super_order()`, `modify_super_order()`, `cancel_super_order()`, `get_super_order_list()` |
119| Forever orders | `place_forever()`, `modify_forever()`, `cancel_forever()`, `get_forever()` |
120| Holdings | `dhan.get_holdings()` |
121| Positions | `dhan.get_positions()` |
122| Convert position | `dhan.convert_position()` |
123| eDIS | `dhan.generate_tpin()`, `dhan.open_browser_for_tpin()`, `dhan.edis_inquiry()` |
124| Fund limits | `dhan.get_fund_limits()` |
125| Margin calculator | `dhan.margin_calculator()` |
126| Daily history | `dhan.historical_daily_data()` |
127| Minute history | `dhan.intraday_minute_data()` |
128| Expired options data | `dhan.expired_options_data()` |
129| Market quote snapshot | `dhan.ticker_data()`, `dhan.ohlc_data()`, `dhan.quote_data()` |
130| Expiry list | `dhan.expiry_list()` |
131| Option chain | `dhan.option_chain()` |
132| Security master | `dhanhq.fetch_security_list()` |
133| Live market feed | `MarketFeed` |
134| Live order updates | `OrderUpdate` |
135| Full market depth | `FullDepth` |
136| Kill switch | `dhan.kill_switch()`, `dhan.status_kill_switch()` |
137
138## High-Value Gotchas
139
140- The SDK wraps HTTP responses as `{"status": "success"|"failure", "remarks": ..., "data": ...}`. Response shapes vary by endpoint — success payloads differ significantly (arrays, flat objects, nested dicts) depending on the API.
141- Repo helpers add a normalization layer. Fields like `ce_ltp`, `ce_oi`, `ce_iv` are repo-defined names — not raw Dhan field names.
142- `intraday_minute_data(...)` is the current SDK method. Do not reference `historical_minute_data()`.
143- Historical timestamps are epoch values. Convert them explicitly.
144- The SDK currently validates `expiry_code` with `[0, 1, 2, 3]`, but Dhan's v2 annexure documents `0`, `1`, `2`. Prefer the documented values unless Dhan updates the API docs.
145- Quote APIs are rate-limited to `1 request/sec`.
146- Option-chain REST data is keyed by strike string under `data["oc"]`. Use repo helpers for analysis-friendly rows.
147- Market orders via API are currently converted by Dhan into limit orders with MPP.
148- Order placement APIs require static IP whitelisting.
149- Trading APIs are free for Dhan users; Data APIs require an active data plan.
150- Lot sizes and freeze quantities change. Treat hardcoded values as fallback only.
151
152## Product-Type Rules
153
154| Segment | Allowed Product Types |
155|---------|-----------------------|
156| `NSE_EQ`, `BSE_EQ` | `CNC`, `INTRADAY`, `MARGIN`, `MTF` |
157| `NSE_FNO`, `BSE_FNO`, `MCX_COMM`, `NSE_CURRENCY`, `BSE_CURRENCY` | `INTRADAY`, `MARGIN` |
158
159## Instrument Resolution Rules
160
161Use the security master as the primary source for:
162- `security_id`
163- `lot_size`
164- `tick_size`
165- expiry
166- strike
167- derivative contract lookup
168
169Quick-reference index underlyings:
170
171| Underlying | security_id | Underlying Segment |
172|------------|-------------|-------------------|
173| NIFTY 50 | `13` | `IDX_I` |
174| BANK NIFTY | `25` | `IDX_I` |
175| FINNIFTY | `27` | `IDX_I` |
176| MIDCPNIFTY | `442` | `IDX_I` |
177| SENSEX | `51` | `IDX_I` |
178
179## Preferred Helper Layer
180
181When generating scripts in this repo, prefer:
182
183- `get_client()` for SDK bootstrapping
184- `resolve_symbol()` for cash-market lookup
185- `resolve_derivative()` for contract lookup
186- `fetch_chain_df()` for option-chain normalization
187- `find_atm_row()` for ATM selection
188- `check_margin()` for pre-flight margin checks
189- `preview_order()` for readable confirmation
190
191## Core Patterns
192
193### 1. Check account access before data calls
194
195```python
196from dhanhq import DhanLogin
197
198dhan_login = DhanLogin("YOUR_CLIENT_ID")
199profile = dhan_login.user_profile("YOUR_ACCESS_TOKEN")
200
201print(profile["dataPlan"])
202print(profile["dataValidity"])
203```
204
205### 2. Fetch historical data with epoch conversion
206
207```python
208data = dhan.historical_daily_data(
209 security_id="2885",
210 exchange_segment=dhanhq.NSE,
211 instrument_type="EQUITY",
212 from_date="2024-01-01",
213 to_date="2024-12-31",
214)
215
216if data["status"] == "success":
217 candles = data["data"]
218 timestamps = [dhan.convert_to_date_time(ts) for ts in candles["timestamp"]]
219```
220
221### 3. Normalize option-chain data for analysis
222
223```python
224from scripts.dhan_helpers import fetch_chain_df, find_atm_row
225
226chain_df, spot = fetch_chain_df(dhan, under_security_id=13, expiry="2025-03-27")
227atm = find_atm_row(chain_df, spot)
228
229print(spot)
230print(atm["strike"])
231print(atm["ce_security_id"], atm["ce_ltp"])
232```
233
234### 4. Margin check before live order placement
235
236```python
237from scripts.dhan_helpers import check_margin
238
239margin = check_margin(
240 dhan,
241 security_id="2885",
242 exchange_segment=dhanhq.NSE,
243 transaction_type=dhanhq.BUY,
244 quantity=10,
245 product_type=dhanhq.CNC,
246 price=2450.0,
247)
248
249print(margin["sufficient"], margin["total_margin"], margin["available_balance"])
250```
251
252### 5. Live market feed
253
254```python
255from dhanhq import MarketFeed
256
257instruments = [
258 (MarketFeed.NSE, "2885", MarketFeed.Ticker),
259 (MarketFeed.NSE_FNO, "49081", MarketFeed.Full),
260]
261
262feed = MarketFeed(dhan_context, instruments, "v2")
263feed.run_forever()
264print(feed.get_data())
265```
266
267## Rate Limits
268
269| API Category | Per Second | Per Minute | Per Hour | Per Day |
270|-------------|-----------:|-----------:|---------:|--------:|
271| Order APIs | 10 | 250 | 1000 | 7000 |
272| Data APIs | 5 | - | - | 100000 |
273| Quote APIs | 1 | Unlimited | Unlimited | Unlimited |
274| Non-Trading APIs | 20 | Unlimited | Unlimited | Unlimited |
275
276## Reference Files
277
278Dhan 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`.
279
280| Need | File |
281|------|------|
282| Orders, super orders, forever orders | [references/orders.md](references/orders.md) |
283| Holdings, positions, eDIS | [references/portfolio.md](references/portfolio.md) |
284| Daily/minute history, quotes, expired options | [references/market-data.md](references/market-data.md) |
285| Option-chain usage and normalization | [references/option-chain.md](references/option-chain.md) |
286| Fund limits and margin checks | [references/funds.md](references/funds.md) |
287| Live feeds and depth | [references/live-feed.md](references/live-feed.md) |
288| Error handling and subscription troubleshooting | [references/error-codes.md](references/error-codes.md) |
289| Instrument resolution | [references/instruments.md](references/instruments.md) |
290| Multi-step execution patterns | [references/common-workflows.md](references/common-workflows.md) |
291| Options analytics | [references/options-analysis-patterns.md](references/options-analysis-patterns.md) |
292| Backtesting patterns | [references/backtesting-with-dhan.md](references/backtesting-with-dhan.md) |
293| PE ratio, RSI, financials, screeners — data Dhan does not provide | [references/scanx-data.md](references/scanx-data.md) |
294
295## Data API Subscription Invalid
296
297If the user gets `DH-902` or `806`:
298
2991. Log in to `web.dhan.co`
3002. Open `My Profile` -> `Access DhanHQ APIs`
3013. Verify that `dataPlan` is active
3024. Activate the Data API plan if needed
3035. Generate a fresh access token
3046. Re-test with `ticker_data()` or `ohlc_data()`
3057. If order APIs still fail, check static IP separately