DhanHQ API v2
Get a Dhan access token, read funds and portfolio, pull quotes, option chains and candles, and test orders in the Dhan sandbox.
Finance & bankingGuided#trading#stock-broking#india#market-data#orders#sandbox
Fork copies the collection into your workspace, without the publisher's secrets, so you can add your own key and send requests. Star saves it to your starred APIs (Account › Marketplace) and helps others find it.
Overview
DhanHQ is the API platform of Dhan, an Indian stock broker. Its v2 REST API covers authentication (PIN + TOTP, API key consent flow or a token from Dhan Web), profile and funds, static IP management, live quotes, option chains and historical candles, margin calculation, orders (regular, AMO, super, slicing), trades, holdings and positions, plus WebSocket market and order feeds. This guided collection covers the core of it and sends order calls to the Dhan sandbox by default.
> Orders can be real. Order requests use orderBaseUrl and orderToken. Left at the sandbox defaults they never reach the exchange. Point them at https://api.dhan.co/v2 with a live token only when you mean to trade, and start with a LIMIT price away from the market and quantity 1 (or an AMO you cancel before the next open).
Get credentials
- Open a Dhan account and log in to Dhan Web. Trading APIs are free for all Dhan users; Data APIs (quotes, option chain, candles) need a paid subscription shown on the platform.
- Quickest token: My Profile > Access DhanHQ APIs > generate an access token (24 hours). Paste it into
accessTokenand your client ID intoclientId. - PIN + TOTP: set up TOTP under DhanHQ Trading APIs, then fill
pinandtotpSecret(or type a code intototp) and send Generate an access token. - API key flow: create an API key and secret (valid 12 months) with a redirect URL; fill
appIdandappSecretand run steps 1 to 3 in folder 1. - Sandbox: sign in at Dhan Cloud to get a sandbox token and paste it into
orderToken. - Static IP: live order placement, modification and cancellation require a whitelisted static IP (primary and secondary, changeable once every 7 days).
Authentication
Every API call sends access-token: <JWT> (set on the collection). Data APIs (market feed, option chain) also send client-id: <your client ID>. Tokens last 24 hours.
Base URLs
| Purpose | URL |
|---|---|
| Live API | https://api.dhan.co/v2 (baseUrl) |
| Sandbox | https://sandbox.dhan.co/v2 (orderBaseUrl default) |
| Auth service | https://auth.dhan.co |
| Scrip master | https://images.dhan.co/api-data/api-scrip-master.csv |
Run order
Folder 1 (get a token, profile, funds, static IPs) → folder 2 (scrip master, then quotes, option chain, candles; security ID 1333 and index 13 are the IDs Dhan's own examples use) → folder 3 (margin, then place, modify, read and cancel in the sandbox) → folder 4 (holdings and positions).
Limits
Order APIs allow about 10 requests per second with per-minute, per-hour and daily caps; Data APIs 5 per second; market quotes 1 per second for up to 1000 instruments; the option chain about one request every 3 seconds. An order can be modified 25 times. Current figures: Rate limits.
Common errors
Errors look like {"errorType": "...", "errorCode": "DH-9xx", "errorMessage": "..."}; Data APIs use numeric codes.
| Code | Meaning | What to do |
|---|---|---|
| DH-901 | Token or client ID invalid or expired | Generate a new token |
| DH-902 / 806 | Data APIs not subscribed or no API access | Subscribe on Dhan Web |
| DH-904 / 805 | Rate limit | Slow down |
| DH-905 | Missing or bad parameters | Check field names and enums |
| DH-906 | Order cannot be processed | Check segment, product, price and IP whitelist |
| 807 / 809 | Token expired or invalid (data) | Renew or regenerate |
| 813 | Invalid securityId | Look it up in the scrip master |
Links
Endpoints 26
1. Start here: access token and account
- POSTGenerate an access token with PIN and TOTP
https://auth.dhan.co/app/generateAccessTokenCreates a 24-hour access token directly, for accounts with TOTP enabled (Dhan Web > DhanHQ Trading APIs > Setup TOTP). Everything goes in the query string:… - POSTAPI key login, step 1: generate consent
https://auth.dhan.co/app/generate-consentFirst step of the API key and secret login (create the key on Dhan Web > My Profile > Access DhanHQ APIs > API key; keys last 12 months). Sends app_id and… - GETAPI key login, step 2: browser login (browser step)
https://auth.dhan.co/login/consentApp-loginOpen this URL in a browser. The user signs in to Dhan with 2FA and is redirected to the redirect URL set on the API key with ?tokenId=.... Copy that value… - POSTAPI key login, step 3: consume consent
https://auth.dhan.co/app/consumeApp-consentExchanges the tokenId from the browser redirect for an access token, authenticated with the same app_id and app_secret headers. The token (24 hours) is saved… - GETGet the user profile
/profileThe simplest first call: confirms the token works and shows the client ID, token validity, active segments, DDPI, MTF and Data API plan status. If dataPlan is… - GETGet fund limits
/fundlimitReturns the trading balance: availabelBalance (note Dhan's spelling; the main usable balance), start-of-day limit, collateral from pledges, receivable amount,… - GETGet whitelisted static IPs
/ip/getIPLists the primary and secondary static IPs registered for API orders and the dates from which each can be changed (once every 7 days). Live order placement,… - GETRenew a Dhan Web token
/RenewTokenExtends a still-valid token generated on Dhan Web by another 24 hours; the old token stops working and the new one is saved into accessToken. Send your client…
2. Market data (Data API plan)
- GETDownload the scrip master CSV (public)
https://images.dhan.co/api-data/api-scrip-master.csvDownloads the compact instrument list as CSV; no token needed. Columns include SEM_EXM_EXCH_ID, SEM_SEGMENT, SEM_SMST_SECURITY_ID (the securityId to use in… - POSTGet last traded prices
/marketfeed/ltpReturns the LTP for many instruments at once: the body maps exchange segment to a list of integer security IDs (up to 1000 instruments per call, about 1 call… - POSTGet OHLC quotes
/marketfeed/ohlcSame body as LTP; returns the last price plus the day's open, high, low and close for each security ID. Useful for watchlists and for picking a limit price. - POSTGet a full quote with depth
/marketfeed/quoteFull snapshot per instrument: LTP, OHLC, volume, open interest, average price, circuit limits and five levels of market depth. Same segment-to-IDs body.… - POSTGet option expiry dates
/optionchain/expirylistLists the active expiry dates (YYYY-MM-DD) for an underlying's options. UnderlyingScrip is the underlying's security ID (13 is the Nifty 50 index in Dhan's… - POSTGet an option chain
/optionchainReturns every strike for one underlying and expiry with call and put LTP, OI, volume, best bid/ask, IV and Greeks. Use an expiry from the previous request… - POSTGet daily historical candles
/charts/historicalDaily OHLCV candles for one instrument back to its listing. Body: securityId, exchangeSegment, instrument (EQUITY, INDEX, FUTIDX, OPTSTK...), expiryCode for… - POSTGet intraday candles
/charts/intradayMinute candles (interval 1, 5, 15, 25 or 60) for up to 90 days per request and about 5 years back. Dates take a time as well (YYYY-MM-DD HH:MM:SS). Same…
3. Orders (sandbox first)
- POSTCalculate margin for an order (no trade)
{{orderBaseUrl}}/margincalculatorReturns the margin an order would need: total, SPAN, exposure and variable margin, brokerage, leverage, your available balance and any shortfall… - POSTPlace an order
{{orderBaseUrl}}/ordersPlaces an order; orderId is saved into orderId. The response gives orderStatus (TRANSIT, PENDING, REJECTED...); fetch the order to see the final state.… - PUTModify a pending order
{{orderBaseUrl}}/orders/{{orderId}}Changes a pending order (orderId in the path and body): send dhanClientId, orderType and validity (required) plus the new price, quantity, triggerPrice or… - DELETECancel a pending order
{{orderBaseUrl}}/orders/{{orderId}}Cancels a pending order by ID. Run it after the test placement. The response returns the order ID with orderStatus CANCELLED once accepted. Traded orders… - GETGet the order book
{{orderBaseUrl}}/ordersLists today's orders with status (TRANSIT, PENDING, PART_TRADED, TRADED, REJECTED, CANCELLED), quantities filled and remaining, average traded price, AMO… - GETGet an order by ID
{{orderBaseUrl}}/orders/{{orderId}}Returns one order (orderId) with its latest status, prices, quantities and timestamps. Use it right after placing to see whether the order reached the… - GETGet the trade book
{{orderBaseUrl}}/tradesLists today's executed trades: order and exchange IDs, trade ID, side, segment, product, symbol, traded quantity and price, and timestamps. Empty until… - GETGet trades for an order
{{orderBaseUrl}}/trades/{{orderId}}Lists the fills of one order (orderId). A partially filled order shows several entries with their own traded quantity and price.
4. Portfolio
- GETGet holdings
{{orderBaseUrl}}/holdingsLists demat holdings: exchange, trading symbol, securityId, ISIN, total, DP, T1 and available quantities, collateral quantity, MTF quantities, average cost… - GETGet positions
{{orderBaseUrl}}/positionsLists open and today's positions: position type (LONG, SHORT, CLOSED), segment, product, buy/sell averages and quantities, net quantity, realised and…
API details
- Base URL
https://api.dhan.co/v2https://sandbox.dhan.co/v2https://auth.dhan.co- Authentication
- An API key in the access-token header
- Operations
- 26 operations on 26 pathsGET 12POST 12PUT 1DELETE 1
- Main resources
- 1. Start here: access token and account 82. Market data (Data API plan) 83. Orders (sandbox first) 84. Portfolio 2
- Description format
- Swastik Codes guided collection, API version
checked against the docs on 2026-11-18 - Links
- Documentation
How to test the DhanHQ API v2 in Swastik Codes
- Open the APISelect “Fork & run in Swastik Codes” on this page. Sign in or create a free account if asked.
- Fork it into your workspaceChoose a workspace. You get your own copy of the DhanHQ API v2 collection, without the publisher's secrets.
- Add your credentialsThis API uses an API key in the access-token header. Add yours in the collection's variables or an environment; the requests already reference it.
- Send a requestPick an endpoint, for example “Generate an access token with PIN and TOTP” (POST https://auth.dhan.co/app/generateAccessToken), and press Send. Check the response, add tests and run the whole collection with the runner.
Frequently asked questions
What is the DhanHQ API v2?
Get a Dhan access token, read funds and portfolio, pull quotes, option chains and candles, and test orders in the Dhan sandbox. It is listed under Finance & banking and has 26 endpoints.
Who publishes the DhanHQ API v2?
It is listed from Dhan's public API description (an OpenAPI document), not published by Dhan on Swastik Codes. Anyone who controls dhan.co can claim the profile by adding a DNS TXT record.
What is the base URL of the DhanHQ API v2?
Its description lists 3 base URLs: https://api.dhan.co/v2, https://sandbox.dhan.co/v2, https://auth.dhan.co. The first is the usual one; the others are typically sandbox or regional servers.
How do I authenticate with the DhanHQ API v2?
With an API key in the access-token header.
How many endpoints does the DhanHQ API v2 have?
26 operations on 26 paths (12 GET, 12 POST, 1 PUT, 1 DELETE). The largest groups are 1. Start here: access token and account, 2. Market data (Data API plan), 3. Orders (sandbox first), 4. Portfolio.
Is forking the DhanHQ API v2 free?
Yes. Forking copies the collection into your workspace for free. It has been starred 0 times and forked 0 times.