dhan-ts logodhan-ts

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?

Quick Start

Installation

npm install dhan-ts

Initialize 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

Advanced Order Types

Options Trading

Account & Reporting

WebSocket Feeds

Real-time data streaming with automatic reconnection and subscription management.

Complete API Module List

ModuleDescriptionDocumentation
ordersPlace, modify, cancel, and query ordersView →
portfolioHoldings, positions, position conversionView →
fundsFund limits and margin calculatorView →
marketDataLTP, OHLC, historical, fundamentalsView →
superOrdersTarget + stop loss with trailingView →
foreverOrdersGTT orders with OCOView →
optionChainOption chain with GreeksView →
expiredOptionDataHistorical options dataView →
authenticationAuth flows and IP managementView →
edisE-DIS for selling holdingsView →
statementsLedger and trade historyView →
tradersControlKill switchView →
scannerStock screeningView →

WebSocket Feed List

FeedDescriptionDocumentation
liveFeedReal-time market dataView →
liveOrderUpdateOrder status updatesView →
marketDepthFeed2020-level market depthView →
marketDepthFeed200200-level market depthView →
multiConnectionLiveFeedMultiple connectionsView →
mockLiveFeedTesting feedView →

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

Support & Resources

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.