Skip to main content
Broker Guides

Dhan API for Algo Trading: Free API Setup Guide

How to set up DhanHQ's free trading API for algo trading in India — capabilities, token generation, safety, and the path from paper trading to live.

CandleAI Research Team 8 min read

For years, one of the quiet gatekeepers of retail algo trading in India was the broker API fee. If you wanted to place orders programmatically, you paid a monthly charge on top of brokerage — before your strategy had earned a single rupee. Dhan changed that calculus by making its trading API free for individual traders, and that single decision has made it one of the most popular brokers among Indian retail algo traders.

This guide covers what the DhanHQ API actually offers, how its access token works in plain language, and a step-by-step path from enabling the API to running a live strategy — without writing code.

What is the DhanHQ API?

The DhanHQ API is the official programmatic interface to Dhan, the SEBI-registered discount broker. It lets software — whether your own script or a platform like CandleAI — place and manage orders, read your positions and funds, and consume market data on your behalf, using secure credentials instead of your login password.

“Official” matters here. SEBI’s framework for retail algorithmic trading requires automation to flow through registered brokers and their sanctioned APIs. The DhanHQ API is exactly that: a supported, documented channel, not a workaround.

What you can do with the DhanHQ API

The API covers the full trading workflow across segments:

  • Order management — place, modify and cancel orders in equity (NSE/BSE) and derivatives (futures and options), including intraday and delivery product types.
  • Portfolio data — read your open positions, holdings, order book, trade book and available funds in real time.
  • Market data — live price feeds via streaming connections, plus quotes and historical candles for backtesting and signal generation.
  • F&O specifics — option chains and contract details, which matter for the index options strategies many Indian algo traders run.

In practice, this means anything you can do manually on the Dhan app — enter a NIFTY options position, trail a stop on an equity trade, square off before close — can be automated through the API.

Why “free” matters: the cost comparison

API access pricing varies meaningfully across Indian brokers. The exact fees change from time to time, so we will keep this general rather than quoting numbers:

BrokerTrading API accessNotes
Dhan (DhanHQ)FreeFull order + data APIs for individual traders
Zerodha (Kite Connect)Monthly fee appliesHistorical data access is a separate add-on
FyersFreePopular for its data APIs
Angel One (SmartAPI)FreeRegistration and app creation required
UpstoxFreeDeveloper app setup required

Why does this matter more than it looks? Because algo trading is a game of small edges. A recurring monthly platform-plus-API cost is a fixed hurdle your strategy must clear every month before it is genuinely profitable. For a trader running a modest capital base — say a few lakh rupees — removing the API fee lowers the breakeven bar meaningfully. It also removes the psychological pressure to “trade more to justify the fee,” which is exactly the wrong incentive.

None of this makes Dhan automatically the right broker for you — execution quality, margin policies and product support matter too. Our guide on choosing an algo trading platform covers the full evaluation framework. But on pure API economics, free is hard to argue with.

How the Dhan access token works (in plain language)

Every broker API needs a way to prove that requests really come from you. Dhan uses two pieces of information:

  1. Client ID — your Dhan account identifier.
  2. Access token — a long, randomly generated string that acts like a temporary key to your account.

You generate the access token yourself from the Dhan web platform, under the DhanHQ Trading APIs section of your profile. Two things are worth understanding:

  • The token is not your password. You never share your Dhan login password or PIN with any third-party tool. The token is a separate credential with a defined scope and lifespan.
  • Tokens expire — by design. Every token has a validity window, shown to you when you generate it. This is a security feature: even if a token leaked, it would not work forever. Dhan’s tokens are notably long-lived compared to brokers like Zerodha, where the session token expires every trading day and must be refreshed each morning. With Dhan, you generate a token, use it for its validity period, and simply generate a fresh one from the same screen when it lapses.

If your automation suddenly starts failing with authentication errors after weeks of working fine, an expired token is the first thing to check. Regenerating takes under a minute.

Step-by-step: from Dhan account to live algo

Here is the complete path, assuming you already have an active Dhan trading account.

  1. Enable API access on Dhan. Log in to the Dhan web platform, open your profile, and find the DhanHQ Trading APIs section. Accept the terms to activate API access for your account. Note your Client ID.
  2. Generate an access token. In the same section, create a new token. Give it a recognizable name (e.g. the platform it is for), note the validity period shown, and copy the token immediately — treat it like a key, because it is one.
  3. Connect the broker inside CandleAI. In the dashboard, go to broker connections, choose Dhan, and paste your Client ID and access token. The platform verifies the connection by fetching your funds and positions — a read-only handshake — and stores the credentials encrypted.
  4. Build and backtest a strategy first. Before any order goes anywhere, your rules should survive a proper backtest on historical NSE data. If you are starting from scratch, describe your idea in plain English in the AI strategy builder or assemble it visually — our guide on building trading strategies with AI walks through this.
  5. Paper trade on live data. Run the strategy in paper mode for at least a few weeks. It uses live market prices and the same execution engine as real deployment, but with virtual money. This is where you catch the gap between backtest assumptions and live market behaviour — see Backtesting vs Paper Trading for why both stages matter.
  6. Deploy live with risk limits set. Once paper results track your backtest, deploy to your Dhan account with one click — but only after configuring a max daily loss, position limits and auto square-off. Automation without risk limits is just a faster way to lose money.

You can start free and complete steps 3–5 without any capital at risk — paper trading needs no funded account.

Safety: what to check before handing over any token

A broker token grants real power over your account, so hold any platform — including ours — to these standards:

  • Encrypted storage. Tokens should be encrypted at rest, never stored in plain text or logged — and the platform should never ask for your Dhan password or PIN.
  • No password sharing, ever. Any tool that asks for your actual broker login password is an immediate red flag. The token-based flow exists precisely so you never have to do this.
  • Revocability. You can revoke a Dhan access token at any time from the DhanHQ Trading APIs section. The moment you revoke it, every system using that token loses access. If you ever suspect a leak, revoke first and investigate second.
  • Audit trail. The platform should log every order it placed and why, so you can reconcile against your Dhan order book.

Troubleshooting common issues

Authentication errors after the setup worked earlier. Almost always an expired or revoked token. Generate a fresh token on Dhan and update it in your platform’s broker connection settings.

Orders rejected by the broker. Read the rejection reason in the order book — common causes are insufficient margin, trading in a segment you have not activated on your Dhan account (F&O requires separate activation), circuit limits, or an instrument in a ban period. These are account or exchange issues, not API issues.

Order placed but no position visible. Check whether the order is still pending (a limit order away from market price) or was partially filled. The positions endpoint reflects executed quantity only.

Strategy behaves differently live than in backtest. Expected to a degree — slippage, latency and partial fills exist in the real world. If the gap is large, revisit your fill assumptions and read our risk management guide before scaling up.

Market data feed disconnects. Streaming connections drop occasionally on any broker. A well-built platform reconnects automatically; if you self-host, you own that reconnection logic — one more reason managed execution is worth considering.

FAQ

Is the Dhan API really free, or are there hidden charges? API access itself is free for individual traders. You still pay normal trading costs — brokerage where applicable, STT, exchange charges, GST and stamp duty — exactly as you would trading manually. There is no separate monthly API subscription, which is the fee that applies at some other brokers.

Do I need to know how to code to use the DhanHQ API? Not if you use a platform that integrates it. CandleAI connects to Dhan with your Client ID and token, and you build strategies through the AI or visual builder — no Python, no servers, no token-refresh scripts. Coding is only necessary if you want to build your own stack from scratch.

How often do I need to refresh the Dhan access token? Only when it expires. Dhan shows the validity period when you generate a token, and unlike daily-expiry brokers, you are not forced to re-authenticate every morning. Set a reminder around the expiry date so live strategies are never interrupted.

Can I revoke access if I stop using a platform? Yes, instantly. Delete the token from the DhanHQ Trading APIs section on Dhan’s web platform and it stops working everywhere. This is the correct off-boarding step whenever you stop using any third-party tool.


Trading in securities involves risk of loss. Nothing in this article is investment advice; it is educational content. Always test strategies thoroughly before deploying real capital.

Put this into practice

Build and backtest your own strategy free — no coding, no card.

Start free