dhanhq

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

DhanHQ — Indian Market Trading Skill

DhanHQ — 印度市场交易技能

Setup

安装配置

Stable install:
python
pip install dhanhq
Use the current SDK branch when you need newer v2 capabilities such as 200-level depth or the latest helper coverage:
python
pip install --upgrade dhanhq
Minimal 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

安全规则 — 必须严格执行

  1. Confirm before placing live orders.
  2. Show a readable order preview before execution.
  3. Default to
    LIMIT
    orders unless the user explicitly wants
    MARKET
    .
  4. Warn when notional exceeds
    Rs. 50,000
    .
  5. For F&O, validate lot size before placement.
  6. Never use
    CNC
    or
    MTF
    for F&O, commodity, or currency segments.
  7. Never hardcode credentials in generated code.
  8. Ask for confirmation before
    modify_order
    ,
    cancel_order
    ,
    kill_switch
    , or any multi-leg live execution.
  1. 下达实盘订单前需确认。
  2. 执行前展示清晰可读的订单预览。
  3. 默认使用
    LIMIT
    限价订单,除非用户明确要求
    MARKET
    市价订单。
  4. 当名义金额超过50,000卢比时发出警告。
  5. 对于期货与期权(F&O),下单前验证手数规模。
  6. 切勿在F&O、商品或货币板块使用
    CNC
    MTF
    产品类型。
  7. 切勿在生成的代码中硬编码凭证。
  8. 在执行
    modify_order
    (修改订单)、
    cancel_order
    (取消订单)、
    kill_switch
    (紧急止损)或任何多腿实盘交易前,需请求确认。

Access Checks Before Live Use

实盘使用前的权限检查

Before using the account for live work, verify:
  1. Access token is valid.
  2. dhan_login.user_profile(...)
    or
    GET /profile
    shows the needed account setup.
  3. dataPlan
    is active for quote/history/feed/option-chain use.
  4. 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
在使用账户进行实盘操作前,需验证:
  1. 访问令牌有效。
  2. dhan_login.user_profile(...)
    GET /profile
    接口显示所需的账户配置已完成。
  3. dataPlan
    数据计划已激活,以便使用报价/历史数据/行情/期权链功能。
  4. 已配置静态IP,用于下单、修改订单、取消订单、超级订单和永久订单操作。
实用的账户信息字段:
  • tokenValidity
    (令牌有效期)
  • activeSegment
    (激活的交易板块)
  • ddpi
  • mtf
  • dataPlan
    (数据计划)
  • dataValidity
    (数据计划有效期)

Current SDK Constants

当前SDK常量

CategoryConstantValue
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
分类常量
交易所
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
交易方向
dhanhq.BUY
BUY
dhanhq.SELL
SELL
订单类型
dhanhq.LIMIT
LIMIT
dhanhq.MARKET
MARKET
dhanhq.SL
STOP_LOSS
dhanhq.SLM
STOP_LOSS_MARKET
产品类型
dhanhq.CNC
CNC
dhanhq.INTRA
INTRADAY
dhanhq.MARGIN
MARGIN
dhanhq.MTF
MTF
订单有效期
dhanhq.DAY
DAY
dhanhq.IOC
IOC

Current SDK Methods To Prefer

推荐使用的当前SDK方法

TaskMethod
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()
任务方法
下单
dhan.place_order()
拆分大额订单
dhan.place_slice_order()
修改订单
dhan.modify_order()
取消订单
dhan.cancel_order()
订单簿
dhan.get_order_list()
通过ID查询订单
dhan.get_order_by_id()
通过关联ID查询订单
dhan.get_order_by_correlationID()
交易簿
dhan.get_trade_book()
交易历史
dhan.get_trade_history()
账户流水
dhan.ledger_report()
超级订单
place_super_order()
,
modify_super_order()
,
cancel_super_order()
,
get_super_order_list()
永久订单
place_forever()
,
modify_forever()
,
cancel_forever()
,
get_forever()
持仓
dhan.get_holdings()
头寸
dhan.get_positions()
转换头寸
dhan.convert_position()
eDIS(电子指令单)
dhan.generate_tpin()
,
dhan.open_browser_for_tpin()
,
dhan.edis_inquiry()
资金限额
dhan.get_fund_limits()
保证金计算器
dhan.margin_calculator()
日线历史数据
dhan.historical_daily_data()
分钟线历史数据
dhan.intraday_minute_data()
过期期权数据
dhan.expired_options_data()
市场报价快照
dhan.ticker_data()
,
dhan.ohlc_data()
,
dhan.quote_data()
到期日列表
dhan.expiry_list()
期权链
dhan.option_chain()
证券主数据
dhanhq.fetch_security_list()
实时市场行情
MarketFeed
实时订单更新
OrderUpdate
完整市场深度
FullDepth
紧急止损开关
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.
  • SDK将HTTP响应封装为
    {"status": "success"|"failure", "remarks": ..., "data": ...}
    格式。不同接口的响应结构不同——成功返回的 payload 差异很大(数组、扁平对象、嵌套字典),具体取决于API。
  • 仓库中的辅助工具添加了一层标准化处理。
    ce_ltp
    ce_oi
    ce_iv
    等字段是仓库定义的名称,并非Dhan的原始字段名。
  • 当前SDK使用
    intraday_minute_data(...)
    方法获取分钟线数据,请勿引用
    historical_minute_data()
  • 历史时间戳为时间戳(epoch)值,需显式转换。
  • 当前SDK使用
    [0, 1, 2, 3]
    验证
    expiry_code
    ,但Dhan的v2附件文档中仅记录了
    0
    1
    2
    。除非Dhan更新API文档,否则优先使用文档中记录的值。
  • 报价API的速率限制为1请求/秒。
  • 期权链的REST数据在
    data["oc"]
    下以行权价字符串作为键。使用仓库辅助工具可获取便于分析的结构化数据行。
  • 当前通过API下达的市价订单会被Dhan转换为带MPP的限价订单。
  • 下单API需要静态IP白名单。
  • Dhan用户可免费使用交易API;数据API需要激活的数据计划。
  • 手数规模和冻结数量会变化,仅将硬编码值作为备用。

Product-Type Rules

产品类型规则

SegmentAllowed Product Types
NSE_EQ
,
BSE_EQ
CNC
,
INTRADAY
,
MARGIN
,
MTF
NSE_FNO
,
BSE_FNO
,
MCX_COMM
,
NSE_CURRENCY
,
BSE_CURRENCY
INTRADAY
,
MARGIN
板块允许的产品类型
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:
Underlyingsecurity_idUnderlying Segment
NIFTY 50
13
IDX_I
BANK NIFTY
25
IDX_I
FINNIFTY
27
IDX_I
MIDCPNIFTY
442
IDX_I
SENSEX
51
IDX_I
将证券主数据作为以下信息的主要来源:
  • security_id
    (证券ID)
  • lot_size
    (手数规模)
  • tick_size
    (最小变动价位)
  • 到期日
  • 行权价
  • 衍生品合约查询
快速参考指数标的:
标的security_id标的板块
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
当为此仓库生成脚本时,优先使用:
  • get_client()
    用于SDK初始化
  • 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 CategoryPer SecondPer MinutePer HourPer Day
Order APIs1025010007000
Data APIs5--100000
Quote APIs1UnlimitedUnlimitedUnlimited
Non-Trading APIs20UnlimitedUnlimitedUnlimited
API分类每秒每分钟每小时每天
订单API1025010007000
数据API5--100000
报价API1无限制无限制无限制
非交易API20无限制无限制无限制

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
.
NeedFile
Orders, super orders, forever ordersreferences/orders.md
Holdings, positions, eDISreferences/portfolio.md
Daily/minute history, quotes, expired optionsreferences/market-data.md
Option-chain usage and normalizationreferences/option-chain.md
Fund limits and margin checksreferences/funds.md
Live feeds and depthreferences/live-feed.md
Error handling and subscription troubleshootingreferences/error-codes.md
Instrument resolutionreferences/instruments.md
Multi-step execution patternsreferences/common-workflows.md
Options analyticsreferences/options-analysis-patterns.md
Backtesting patternsreferences/backtesting-with-dhan.md
PE ratio, RSI, financials, screeners — data Dhan does not providereferences/scanx-data.md
Dhan API涵盖执行、报价、OHLC、期权链和投资组合相关功能。对于基本面数据(PE、EPS、营收)、技术指标(RSI、MACD)或股权结构等Dhan未提供的数据,请使用ScanX——详见
references/scanx-data.md
需求文件
订单、超级订单、永久订单references/orders.md
持仓、头寸、eDISreferences/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
DH-902
or
806
:
  1. Log in to
    web.dhan.co
  2. Open
    My Profile
    ->
    Access DhanHQ APIs
  3. Verify that
    dataPlan
    is active
  4. Activate the Data API plan if needed
  5. Generate a fresh access token
  6. Re-test with
    ticker_data()
    or
    ohlc_data()
  7. If order APIs still fail, check static IP separately
如果用户收到
DH-902
806
错误:
  1. 登录
    web.dhan.co
  2. 打开
    我的资料
    ->
    访问DhanHQ API
  3. 验证
    dataPlan
    数据计划是否已激活
  4. 如有需要,激活数据API计划
  5. 生成新的访问令牌
  6. 使用
    ticker_data()
    ohlc_data()
    重新测试
  7. 如果订单API仍然失败,请单独检查静态IP配置