dhan-ts Documentation
Complete TypeScript client for Dhan API v2 - Trading, Market Data, and WebSocket Feeds
dhan-ts
A comprehensive, fully-typed TypeScript/JavaScript client library for Dhan's trading API v2. Build powerful trading applications with type-safe access to orders, market data, portfolio management, and real-time WebSocket feeds.
Why dhan-ts?
Fully Typed
Complete TypeScript support with IntelliSense and compile-time type checking for all API endpoints
Real-time Feeds
WebSocket feeds for live market data, order updates, and market depth with automatic reconnection
Comprehensive API
15+ API modules covering orders, portfolio, funds, market data, options, and more
Production Ready
Battle-tested with automatic reconnection, error handling, and multiple authentication methods
Quick Start
Installation
npm install dhan-tsInitialize Clients
import { DhanHqClient, DhanFeed, DhanEnv } from 'dhan-ts';
const config = {
accessToken: process.env.DHAN_ACCESS_TOKEN!,
clientId: process.env.DHAN_CLIENT_ID!,
env: DhanEnv.PROD,
};
// REST API Client
const client = new DhanHqClient(config);
// WebSocket Feed Client
const feed = new DhanFeed(config);Your First API Call
// Get your fund limits
const funds = await client.funds.getFundLimit();
console.log('Available Balance:', funds.availabelBalance);
// Get your holdings
const holdings = await client.portfolio.getHoldings();
console.log('Holdings:', holdings);
// Place an order
const order = await client.orders.placeOrder({
dhanClientId: config.clientId,
transactionType: 'BUY',
exchangeSegment: 'NSE_EQ',
productType: 'CNC',
orderType: 'LIMIT',
validity: 'DAY',
securityId: '1333',
quantity: 1,
price: 1850.00,
afterMarketOrder: false,
});Your First Live Feed
import { FeedRequestCode, ExchangeSegment } from 'dhan-ts';
const liveFeed = feed.liveFeed;
// Connect
await liveFeed.connect();
// Subscribe to instruments
const instruments = [
[ExchangeSegment.NSE_EQ, "1333"], // Reliance
[ExchangeSegment.NSE_EQ, "13"], // Nifty 50
];
liveFeed.subscribe(instruments, FeedRequestCode.SUBSCRIBE_TICKER);
// Listen for updates
liveFeed.on('data', (data) => {
if (data.type === 'ticker') {
console.log(`${data.securityId}: ₹${data.lastTradedPrice}`);
}
});API Reference
Trading APIs
Orders
Place, modify, cancel orders with full lifecycle management
Portfolio
View holdings, positions, and convert product types
Funds
Check balances and calculate margin requirements
Market Data
Real-time quotes, historical data, and fundamentals
Advanced Order Types
Super Orders
Advanced orders with target, stop loss, and trailing SL
Forever Orders (GTT)
Good Till Triggered orders with OCO support
Options Trading
Option Chain
Option chain with Greeks, IV, and market depth
Expired Option Data
Historical options data for backtesting strategies
Account & Reporting
Authentication
App-based, partner, and static IP authentication
E-DIS
Electronic delivery instruction for selling holdings
Statements
Ledger reports and trade history
Traders Control
Emergency kill switch for risk management
Scanner
Stock screening and market scanner
WebSocket Feeds
Real-time data streaming with automatic reconnection and subscription management.
Live Feed
Real-time market data with ticker, quote, and full subscriptions
Live Order Updates
Instant notifications on order status changes
Market Depth Feed
20 and 200 level market depth for algorithmic trading
Multi Connection Feed
Multiple concurrent connections for 10,000+ instruments
Mock Feeds
Testing feeds without live connections
Complete API Module List
| Module | Description | Documentation |
|---|---|---|
| orders | Place, modify, cancel, and query orders | View → |
| portfolio | Holdings, positions, position conversion | View → |
| funds | Fund limits and margin calculator | View → |
| marketData | LTP, OHLC, historical, fundamentals | View → |
| superOrders | Target + stop loss with trailing | View → |
| foreverOrders | GTT orders with OCO | View → |
| optionChain | Option chain with Greeks | View → |
| expiredOptionData | Historical options data | View → |
| authentication | Auth flows and IP management | View → |
| edis | E-DIS for selling holdings | View → |
| statements | Ledger and trade history | View → |
| tradersControl | Kill switch | View → |
| scanner | Stock screening | View → |
WebSocket Feed List
| Feed | Description | Documentation |
|---|---|---|
| liveFeed | Real-time market data | View → |
| liveOrderUpdate | Order status updates | View → |
| marketDepthFeed20 | 20-level market depth | View → |
| marketDepthFeed200 | 200-level market depth | View → |
| multiConnectionLiveFeed | Multiple connections | View → |
| mockLiveFeed | Testing feed | View → |
Common Use Cases
Algorithmic Trading
// Monitor market data and place orders based on strategy
liveFeed.on('data', async (data) => {
if (data.type === 'ticker') {
const price = data.lastTradedPrice;
// Your trading logic here
if (shouldBuy(price)) {
await client.orders.placeOrder({
// ... order details
});
}
}
});Portfolio Management
// View and manage your portfolio
const holdings = await client.portfolio.getHoldings();
const positions = await client.portfolio.getPositions();
const funds = await client.funds.getFundLimit();
// Calculate total portfolio value
const totalValue = holdings.reduce((sum, h) =>
sum + (h.totalQty * h.avgCostPrice), 0
);Options Trading
// Get option chain with Greeks
const optionChain = await client.optionChain.getOptionChain({
UnderlyingScrip: 13,
UnderlyingSeg: "IDX_I",
Expiry: "2024-01-25",
});
// Analyze strikes
Object.entries(optionChain.data.oc).forEach(([strike, data]) => {
console.log(`${strike} CE IV: ${data.ce?.implied_volatility}`);
console.log(`${strike} PE Delta: ${data.pe?.greeks.delta}`);
});Market Analysis
// Get historical data for backtesting
const historicalData = await client.marketData.getProcessedCandleData({
securityId: '1333',
exchangeSegment: ExchangeSegmentText.NSE_EQ,
instrument: 'EQUITY',
expiryCode: 0,
interval: TimeInterval.DAY_1,
daysAgo: 100,
});
// Analyze candlestick patterns
historicalData.timestamp.forEach((ts, i) => {
const candle = {
open: historicalData.open[i],
high: historicalData.high[i],
low: historicalData.low[i],
close: historicalData.close[i],
volume: historicalData.volume[i],
};
// Your analysis logic
});Key Features
Type Safety
Every API call is fully typed with TypeScript interfaces:
// IntelliSense shows all available fields
const order: OrderResponse = await client.orders.placeOrder({
dhanClientId: string,
transactionType: TransactionType.BUY,
// ... TypeScript guides you through all fields
});Error Handling
Comprehensive error handling with specific error codes:
try {
await client.orders.placeOrder(orderRequest);
} catch (error: any) {
if (error.code === 'DH-906') {
console.error('Order error:', error.message);
} else if (error.code === 'DH-904') {
console.error('Rate limit exceeded');
}
}Automatic Reconnection
WebSocket feeds automatically reconnect with exponential backoff:
liveFeed.on('disconnected', (data) => {
console.log('Disconnected, will auto-reconnect');
});
liveFeed.on('error', (error) => {
console.log('Error, reconnecting...');
});Environment Support
Switch between production and sandbox easily:
// Production
const config = {
accessToken: process.env.DHAN_ACCESS_TOKEN!,
clientId: process.env.DHAN_CLIENT_ID!,
env: DhanEnv.PROD, // Production
};
// Sandbox for testing
const sandboxConfig = {
accessToken: 'sandbox-token',
clientId: 'sandbox-client',
env: DhanEnv.SANDBOX, // Sandbox
};Getting Started
Installation & Setup
Install dhan-ts and make your first API call
Authentication Guide
Learn about different authentication methods
Orders API
Start placing and managing orders
Live Feed
Connect to real-time market data
Support & Resources
- GitHub Repository: anshuopinion/dhan-ts
- Report Issues: GitHub Issues
- npm Package: dhan-ts on npm
- Official Dhan API: Dhan API Documentation
Contributing
Contributions are welcome! Please feel free to submit pull requests or open issues on GitHub.
This is an unofficial TypeScript client for Dhan API. For official support, please contact Dhan directly.