dhanhq
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDhanHQ — Indian Market Trading Skill
DhanHQ — 印度市场交易技能
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()稳定版本安装:
python
pip install dhanhq当你需要v2版本的新功能(如200档深度或最新辅助工具支持)时,请使用当前SDK分支:
python
pip install --upgrade dhanhq最小化初始化:
python
from dhanhq import DhanContext, dhanhq
dhan_context = DhanContext("YOUR_CLIENT_ID", "YOUR_ACCESS_TOKEN")
dhan = dhanhq(dhan_context)环境变量配置:
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)如果为此仓库生成脚本,优先使用:
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
- 下达实盘订单前需确认。
- 执行前展示清晰可读的订单预览。
- 默认使用限价订单,除非用户明确要求
LIMIT市价订单。MARKET - 当名义金额超过50,000卢比时发出警告。
- 对于期货与期权(F&O),下单前验证手数规模。
- 切勿在F&O、商品或货币板块使用或
CNC产品类型。MTF - 切勿在生成的代码中硬编码凭证。
- 在执行(修改订单)、
modify_order(取消订单)、cancel_order(紧急止损)或任何多腿实盘交易前,需请求确认。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
在使用账户进行实盘操作前,需验证:
- 访问令牌有效。
- 或
dhan_login.user_profile(...)接口显示所需的账户配置已完成。GET /profile - 数据计划已激活,以便使用报价/历史数据/行情/期权链功能。
dataPlan - 已配置静态IP,用于下单、修改订单、取消订单、超级订单和永久订单操作。
实用的账户信息字段:
- (令牌有效期)
tokenValidity - (激活的交易板块)
activeSegment ddpimtf- (数据计划)
dataPlan - (数据计划有效期)
dataValidity
Current SDK Constants
当前SDK常量
| Category | Constant | Value |
|---|---|---|
| Exchange | | |
| | |
| | |
| | |
| | |
| | |
| | |
| Transaction | | |
| | |
| Order Type | | |
| | |
| | |
| | |
| Product | | |
| | |
| | |
| | |
| Validity | | |
| |
| 分类 | 常量 | 值 |
|---|---|---|
| 交易所 | | |
| | |
| | |
| | |
| | |
| | |
| | |
| 交易方向 | | |
| | |
| 订单类型 | | |
| | |
| | |
| | |
| 产品类型 | | |
| | |
| | |
| | |
| 订单有效期 | | |
| |
Current SDK Methods To Prefer
推荐使用的当前SDK方法
| 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 | |
| 任务 | 方法 |
|---|---|
| 下单 | |
| 拆分大额订单 | |
| 修改订单 | |
| 取消订单 | |
| 订单簿 | |
| 通过ID查询订单 | |
| 通过关联ID查询订单 | |
| 交易簿 | |
| 交易历史 | |
| 账户流水 | |
| 超级订单 | |
| 永久订单 | |
| 持仓 | |
| 头寸 | |
| 转换头寸 | |
| eDIS(电子指令单) | |
| 资金限额 | |
| 保证金计算器 | |
| 日线历史数据 | |
| 分钟线历史数据 | |
| 过期期权数据 | |
| 市场报价快照 | |
| 到期日列表 | |
| 期权链 | |
| 证券主数据 | |
| 实时市场行情 | |
| 实时订单更新 | |
| 完整市场深度 | |
| 紧急止损开关 | |
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.
- SDK将HTTP响应封装为格式。不同接口的响应结构不同——成功返回的 payload 差异很大(数组、扁平对象、嵌套字典),具体取决于API。
{"status": "success"|"failure", "remarks": ..., "data": ...} - 仓库中的辅助工具添加了一层标准化处理。、
ce_ltp、ce_oi等字段是仓库定义的名称,并非Dhan的原始字段名。ce_iv - 当前SDK使用方法获取分钟线数据,请勿引用
intraday_minute_data(...)。historical_minute_data() - 历史时间戳为时间戳(epoch)值,需显式转换。
- 当前SDK使用验证
[0, 1, 2, 3],但Dhan的v2附件文档中仅记录了expiry_code、0、1。除非Dhan更新API文档,否则优先使用文档中记录的值。2 - 报价API的速率限制为1请求/秒。
- 期权链的REST数据在下以行权价字符串作为键。使用仓库辅助工具可获取便于分析的结构化数据行。
data["oc"] - 当前通过API下达的市价订单会被Dhan转换为带MPP的限价订单。
- 下单API需要静态IP白名单。
- Dhan用户可免费使用交易API;数据API需要激活的数据计划。
- 手数规模和冻结数量会变化,仅将硬编码值作为备用。
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 | | |
将证券主数据作为以下信息的主要来源:
- (证券ID)
security_id - (手数规模)
lot_size - (最小变动价位)
tick_size - 到期日
- 行权价
- 衍生品合约查询
快速参考指数标的:
| 标的 | security_id | 标的板块 |
|---|---|---|
| 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()
当为此仓库生成脚本时,优先使用:
- 用于SDK初始化
get_client() - 用于现货市场查询
resolve_symbol() - 用于合约查询
resolve_derivative() - 用于期权链标准化
fetch_chain_df() - 用于平值期权选择
find_atm_row() - 用于下单前保证金检查
check_margin() - 用于清晰的订单确认预览
preview_order()
Core Patterns
核心模式
1. Check account access before data calls
1. 数据调用前检查账户权限
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"])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
2. 获取历史数据并转换时间戳
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"]]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
3. 标准化期权链数据用于分析
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"])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
4. 实盘下单前检查保证金
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"])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
5. 实时市场行情
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())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 |
| API分类 | 每秒 | 每分钟 | 每小时 | 每天 |
|---|---|---|---|---|
| 订单API | 10 | 250 | 1000 | 7000 |
| 数据API | 5 | - | - | 100000 |
| 报价API | 1 | 无限制 | 无限制 | 无限制 |
| 非交易API | 20 | 无限制 | 无限制 | 无限制 |
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 |
Dhan API涵盖执行、报价、OHLC、期权链和投资组合相关功能。对于基本面数据(PE、EPS、营收)、技术指标(RSI、MACD)或股权结构等Dhan未提供的数据,请使用ScanX——详见。
references/scanx-data.md| 需求 | 文件 |
|---|---|
| 订单、超级订单、永久订单 | references/orders.md |
| 持仓、头寸、eDIS | references/portfolio.md |
| 日线/分钟线历史数据、报价、过期期权 | references/market-data.md |
| 期权链使用与标准化 | references/option-chain.md |
| 资金限额与保证金检查 | references/funds.md |
| 实时行情与深度 | references/live-feed.md |
| 错误处理与订阅故障排查 | references/error-codes.md |
| 工具解析 | references/instruments.md |
| 多步骤执行模式 | references/common-workflows.md |
| 期权分析 | references/options-analysis-patterns.md |
| 回测模式 | references/backtesting-with-dhan.md |
| PE比率、RSI、财务数据、筛选器——Dhan未提供的数据 | references/scanx-data.md |
Data API Subscription Invalid
数据API订阅无效
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
如果用户收到或错误:
DH-902806- 登录
web.dhan.co - 打开->
我的资料访问DhanHQ API - 验证数据计划是否已激活
dataPlan - 如有需要,激活数据API计划
- 生成新的访问令牌
- 使用或
ticker_data()重新测试ohlc_data() - 如果订单API仍然失败,请单独检查静态IP配置