AI trading desk for Indian markets
Broker/API

Dhan API for Algo Trading: Workflow, Checks, and Real Risks

A practical guide to Dhan API for algo trading in India — order workflow, session handling, sandbox testing, and the operational risks retail traders miss.

A
Anadi Algo Research
May 3, 2026  ·  6 min read
Dhan API for Algo Trading: Workflow, Checks, and Real Risks editorial illustration

Dhan has become one of the more popular broker API choices for retail algo traders in India. Free access, decent documentation, an official Python library, and a sandbox for testing make it attractive. But "free API" does not mean "plug and play." If you treat broker APIs like a toy, your strategy will eat losses that have nothing to do with your edge.

This post walks through what a real Dhan API workflow looks like, what to verify before going live, and the failure modes most retail traders learn the hard way.

What Dhan API actually gives you

Dhan exposes the building blocks every algo needs:

  • Order Management API — place, modify, cancel orders across NSE, BSE, NFO, MCX.
  • Market Feeds API — live quotes, depth, and tick data.
  • Portfolio API — open positions, holdings, fund margins.
  • Historical Data API — OHLC and OI for backtests and warmups.
  • Statement API — P&L, contract notes, ledger.

Dhan advertises sub-50ms average order latency and around 20,000 requests per day. For a single-account retail algo running a handful of strategies, that headroom is comfortable. The free tier is genuine — no monthly API fee — which is why many independent developers prototype here first.

What this does not mean: that your algo will execute perfectly. Latency is one slice of the chain. Session expiry, partial fills, exchange rejections, and your own code paths matter more than the broker's median response time.

A realistic Dhan algo workflow

Here is the order of operations for a clean integration. Skip steps and you will pay for them in production.

1. Sandbox first, always

Dhan provides a closed sandbox. Use it. Place full-cycle orders — entry, modify, exit, cancel — and confirm your code handles each broker response. Test rejections too: bad symbol, insufficient margin, frozen quantity. If your algo only knows how to handle "success" responses, it will crash on the first real exchange rejection.

2. Token and session management

Dhan access tokens are time-bound. Build token refresh into your algo as a first-class concern, not an afterthought. A common retail failure: token expires mid-session, the algo silently stops sending orders, exits never trigger, and the position bleeds against you. Log every auth failure loudly and alert yourself.

3. Margin and product type checks

Before placing an order, verify available margin via the Portfolio API. Confirm the product type (CNC, MIS, NRML) matches your intent. An MIS order auto-squares off at the broker's cutoff — usually around 3:15 PM for equity, varying for F&O. If your strategy expects to hold overnight but you accidentally fired an MIS order, the broker will close it for you at market.

4. Order placement with idempotency

Network blips happen. Your algo fires an order, the response times out, you do not know if it was placed. Always tag orders with a client-side reference (order tag) and reconcile against the order book before retrying. Double-firing on a NIFTY options leg can turn a planned 1-lot trade into a 2-lot disaster.

5. Listen to order updates, do not poll

Dhan's APIs are event-driven. Subscribe to order and position update streams instead of hammering REST endpoints in a loop. Polling burns your daily quota and adds latency. Event streams give you fills and rejections in near real time.

6. Reconciliation at session start

Every morning, before placing a single new order, fetch your live positions and open orders from Dhan. Compare against your algo's internal state. If they disagree — and after a crash or restart they often do — pause and reconcile. Never let your algo assume yesterday's in-memory state survived.

Operational risks retail traders underestimate

Frozen quantity limits. Exchanges cap single-order quantity per instrument. A BANKNIFTY 900-lot order will get rejected. Your algo must split into legal slices.

Circuit limits and illiquid strikes. A market order on a far OTM option strike can fill at absurd prices. Use limit orders with sane bands, or skip illiquid contracts entirely. This is part of basic risk management, not an advanced topic.

Slippage between signal and fill. Backtest assumes fills at signal candle close. Live, you face spread, queue position, and exchange latency. Compare your backtest fills against live fills weekly. If slippage exceeds 0.3% on liquid instruments, your strategy logic or order type needs work — see options backtesting for how to model this realistically.

Broker-side rate limits and downtime. Dhan, Zerodha, Upstox, every broker has had outages. Your algo should detect API unavailability, halt new entries, and alert you. Do not let it spiral while the broker recovers.

Partial fills. A 5-lot order might fill 3 lots and stay open. Your stop-loss logic must handle this. Many retail algos place SL only after full entry confirmation — and then sit with no stop on a partially filled position.

Where a platform helps vs writing from scratch

Building a Dhan integration directly is fine if you enjoy plumbing — token refresh, websocket handling, reconnect logic, order reconciliation, slippage logging. Most retail traders do not. They want to define a strategy and have it run.

This is where a managed broker API layer matters. Anadi Algo connects to Dhan and other supported brokers so you spend your time on strategy logic, not on broker quirks. You can build rules in the no-code strategy builder, backtest, paper trade, then route the same logic to Dhan with the operational checks already wired in.

It is the difference between writing your own order reconciliation loop and inheriting one that has already been hardened across thousands of live sessions.

If you want to try this workflow without writing the integration yourself, you can request early access and run a strategy on Dhan through the platform.

Pre-go-live checklist

Before flipping any Dhan algo to live capital, confirm:

  • Sandbox tested for entry, modify, exit, cancel, and rejection responses
  • Token refresh logic verified across an expiry boundary
  • Product type (MIS / NRML / CNC) matches strategy holding period
  • Order idempotency tags and reconciliation logic in place
  • Position and order reconciliation runs at every session start
  • Frozen quantity splits handled for index options and futures
  • Limit orders used on illiquid strikes; no naked market orders OTM
  • Partial fill handling tested — SL placed per filled quantity, not assumed full
  • Outage detection halts new entries and alerts you
  • Live vs backtest slippage compared weekly

The Dhan API is genuinely capable. What kills retail algo accounts is not the broker — it is the missing checks around the broker. Build the checks first, scale the size later.

Related

NSE Algo Trading API

Compare broker API realities, order routing, sessions, and production execution constraints.

Explore →