# DhanHQ API Documentation — Full Export

> Generated on 2026-05-26T05:22:25.840Z
> Total documents: 104

---

---

## Calculate Margin

`POST` https://api.dhan.co/v2/margincalculator

Fetch span, exposure, var, brokerage, leverage, and available margin values for any type of order and instrument that you want to place.




### Request Body Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| dhanClientId | string | Yes | User specific identification generated by Dhan |
| exchangeSegment | enum | Yes | Exchange Segment (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`, `IDX_I`. |
| transactionType | enum | Yes | The trading side of transaction Values: `BUY`, `SELL`. Default: `BUY`. |
| quantity | int | Yes | Number of shares for the order |
| productType | enum | Yes | Product type of trade Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`, `CO`, `BO`. Default: `CNC`. |
| securityId | string | Yes | Exchange standard ID for each scrip. refer here |
| price | float | No | Price at which order is placed |
| triggerPrice | float | No | Price at which order is triggered |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| totalMargin | float | No | Overall combined Margin required |
| spanMargin | float | No | Maximum possible loss that property might face |
| exposureMargin | float | No | Value represents in excess of the SPAN margin |
| availableBalance | float | No | Represents overall usable balance in the account |
| variableMargin | float | No | Variable margin |
| insufficientBalance | float | No | Insufficient balance |
| brokerage | float | No | Brokerage |
| leverage | string | No | Leverage |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | Margin calculation |


### Example Request

```bash
curl -X POST https://api.dhan.co/v2/margincalculator \
  -H "access-token: <your-access-token>" \
  -H "Content-Type: application/json" \
  -d '{
    "dhanClientId": "your-client-id",
    "exchangeSegment": "NSE_EQ",
    "transactionType": "BUY",
    "quantity": 1,
    "productType": "CNC",
    "securityId": "1333",
    "price": 500.00
  }'
```

---

## Calculate Multi-Order Margin

`POST` https://api.dhan.co/v2/margincalculator/multi

Calculate combined margin for multiple orders with hedge benefits.

The Multi Order Margin Calculator API allows users to calculate margin requirements for multiple scripts in a single request, including span, exposure, equity, F&O, and commodity margins.

Note: Margin values returned are indicative and valid only for the current trading session.


### Request Body Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| dhanClientId | string | Yes | User specific identification generated by Dhan |
| includePosition | enum | No | Include existing positions while calculating margin Values: `true`, `false`. Default: `false`. |
| includeOrder | enum | No | Include existing orders while calculating margin Values: `true`, `false`. Default: `false`. |
| scripList[0].exchangeSegment | enum | Yes | Exchange Segment (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`, `IDX_I`. |
| scripList[0].transactionType | enum | Yes | The trading side of transaction Values: `BUY`, `SELL`. Default: `BUY`. |
| scripList[0].quantity | int | Yes | Number of shares for the order |
| scripList[0].productType | enum | Yes | Product type of trade Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`, `CO`, `BO`. Default: `CNC`. |
| scripList[0].securityId | string | Yes | Exchange standard ID for each scrip. refer here |
| scripList[0].price | float | No | Price at which order is placed |
| scripList[0].triggerPrice | float | No | Price at which order is triggered |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| clientId | string | No | User specific identification generated by Dhan |
| totalMargin | float | No | Overall combined Margin required |
| spanMargin | float | No | Span margin |
| exposure | float | No | Exposure |
| equityMargin | float | No | Equity margin |
| foMargin | float | No | F&O margin |
| commodity | float | No | Commodity margin |
| currency | float | No | Currency margin |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | Multi-order margin calculation |


### Example Request

```bash
curl -X POST https://api.dhan.co/v2/margincalculator/multi \
  -H "access-token: <your-access-token>" \
  -H "Content-Type: application/json"
```

---

## Cancel Order

`DELETE` https://api.dhan.co/v2/orders/{order-id}

Cancel a pending order.

> **NOTICE:** Order Placement, Modification and Cancellation APIs requires Static IP whitelisting - [refer here](/api/v2/guides/authentication#setup-static-ip)


### Path Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| order-id | string | Yes | Order ID of the Order being cancelled |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| orderId | string | No | Order specific identification generated by Dhan |
| orderStatus | enum string | No | Last updated status of the order Values: `TRANSIT`, `PENDING`, `REJECTED`, `CANCELLED`, `TRADED`. |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | Order cancelled |


### Example Request

```bash
curl -X DELETE https://api.dhan.co/v2/orders/{order-id} \
  -H "access-token: <your-access-token>"
```

---

## Cancel Super Order Leg

`DELETE` https://api.dhan.co/v2/super/orders/{order-id}/{order-leg}

Cancel a specific leg of a super order.

Users can cancel a pending/active super order using the order ID. There is no body for request and response for this call. On successful completion of request ‘202 Accepted’ response status code will appear.

> **NOTICE:** Order Placement, Modification and Cancellation APIs requires Static IP whitelisting - [refer here](/api/v2/guides/authentication#setup-static-ip)


### Path Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| order-id | string | Yes | Order ID of the Order being cancelled |
| order-leg | string | Yes | Order Leg to be cancelled Values: `ENTRY_LEG`, `TARGET_LEG`, `STOP_LOSS_LEG`. |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| order-id | string | No | Order specific identification generated by Dhan |
| orderStatus | enum string | No | Last updated status Values: `TRANSIT`, `PENDING`, `REJECTED`, `CANCELLED`. |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | Leg cancelled |


### Example Request

```bash
curl -X DELETE https://api.dhan.co/v2/super/orders/{order-id}/{order-leg} \
  -H "access-token: <your-access-token>"
```

---

## Conditional Trigger

Conditional Trigger

When the conditional order is triggered, you will receive a postback update if set up [here](/api/v2/guides/postback).

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/alerts/orders` | Place Conditional Trigger |
| PUT | `/alerts/orders/{alertId}` | Modify Conditional Trigger |
| DELETE | `/alerts/orders/{alertId}` | Delete Conditional Trigger |
| GET | `/alerts/orders/{alertId}` | Get Conditional Trigger by ID |
| GET | `/alerts/orders` | Get All Conditional Triggers |

> **note:** - Conditional Triggers are currently supported only for Equities and Indices.
> - You can receive a postback update by providing a Webhook URL ([here](/api/v2/guides/postback)) while generating the Access Token.

---

## Configure P&L Based Exit

`POST` https://api.dhan.co/v2/pnlExit

Configure automatic exit rules based on cumulative profit or loss thresholds.

:::note Note
The configured P&L based exit remains active for the current day and is reset at the end of the trading session.
:::


> **NOTICE:** Order Placement, Modification and Cancellation APIs requires Static IP whitelisting - [refer here](/api/v2/guides/authentication#setup-static-ip)


| Parameter | Data Type | Description |
|-----------|-----------|-------------|
| pnlExitStatus | string | P&L based exit status: `ACTIVE` `INACTIVE` |
| message | string | Status of Conditional Trigger |


### Request Body Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| dhanClientId | string | No | User specific identification generated by Dhan |
| profitValue | float | No | Maximum portfolio-level profit to trigger exit |
| lossValue | float | No | Maximum portfolio-level loss to trigger exit |
| productType[0] | enum | No | Product types applicable (array): INTRADAY or DELIVERY Values: `INTRADAY`, `DELIVERY`. Default: `INTRADAY`. |
| enableKillSwitch | string | No | Indicates if kill switch is enabled: true or false |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | P&L exit configured |
| 401 | Unauthorized |


### Example Request

```bash
curl -X POST https://api.dhan.co/v2/pnlExit \
  -H "access-token: <your-access-token>" \
  -H "Content-Type: application/json"
```

---

## Convert Position

`POST` https://api.dhan.co/v2/positions/convert

Convert position between product types (e.g., INTRADAY to CNC).

Users can convert their open position from intraday to delivery or delivery to intraday.


> **NOTICE:** Order Placement, Modification and Cancellation APIs requires Static IP whitelisting - [refer here](/api/v2/guides/authentication#setup-static-ip)


No response body. On successful completion of request, `202 Accepted` response status code will appear.


### Request Body Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| dhanClientId | string | No | User specific identification generated by Dhan |
| fromProductType | enum | No | From Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`, `CO`, `BO`. Default: `INTRADAY`. |
| exchangeSegment | enum | No | Exchange Segment (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`, `IDX_I`. |
| positionType | enum | No | Position to convert Values: `LONG`, `SHORT`, `CLOSED`. Default: `LONG`. |
| securityId | string | No | Exchange standard ID for each scrip. refer here |
| convertQty | int | No | Quantity to convert |
| toProductType | enum | No | To Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`, `CO`, `BO`. Default: `CNC`. |


### Status Codes

| Code | Description |
|------|-------------|
| 202 | Conversion accepted |


### Example Request

```bash
curl -X POST https://api.dhan.co/v2/positions/convert \
  -H "access-token: <your-access-token>" \
  -H "Content-Type: application/json"
```

---

## Data APIs

All endpoints for market data, historical charts, option chains, and account statements.

---

## Market Quote

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | [Get LTP](/api/v2/market-quote/get-ltp) | Get last traded price for instruments |
| POST | [Get OHLC](/api/v2/market-quote/get-ohlc) | Get open, high, low, close data |
| POST | [Get Full Quote](/api/v2/market-quote/get-quote) | Get complete market quote with depth |

## Historical Data

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | [Daily Historical Data](/api/v2/historical-data/get-daily-historical) | Get daily OHLC candles |
| POST | [Intraday Historical Data](/api/v2/historical-data/get-intraday-historical) | Get intraday candles (1min, 5min, etc.) |

## Option Chain

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | [Get Expiry List](/api/v2/option-chain/get-expiry-list) | Get available expiry dates |
| POST | [Get Option Chain](/api/v2/option-chain/get-option-chain) | Get full option chain data |

## Expired Options Data

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | [Historical Rolling Options Data](/api/v2/expired-options-data/get-expired-options-data) | Fetch expired options data with OHLC, IV, OI |

## Statements

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | [Trade History](/api/v2/statements/get-trade-history) | Get detailed trade history |
| GET | [Ledger Report](/api/v2/statements/get-ledger-report) | Get ledger/fund statement |

---

## Delete Conditional Trigger

`DELETE` https://api.dhan.co/v2/alerts/orders/{alertId}

Delete an existing conditional trigger.

> **NOTICE:** Order Placement, Modification and Cancellation APIs requires Static IP whitelisting - [refer here](/api/v2/guides/authentication#setup-static-ip)


### Path Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| alertId | string | Yes | Alert specific identification generated by Dhan |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| alertId | string | No | Alert specific identification generated by Dhan |
| alertStatus | enum string | No | Last updated status of the order Values: `ACTIVE`, `TRIGGERED`, `EXPIRED`, `CANCELLED`. |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | Conditional trigger deleted |
| 401 | Unauthorized |


### Example Request

```bash
curl -X DELETE https://api.dhan.co/v2/alerts/orders/{alertId} \
  -H "access-token: <your-access-token>"
```

---

## DhanHQ API

Introduction to DhanHQ Trading & Investment API

# Getting Started


DhanHQ API is a state-of-the-art platform for you to build trading and investment services & strategies.

It is a set of REST-like APIs that provide integration with our trading platform. Execute & modify orders in real time, manage portfolio, access live market data and more, with lightning fast API collection.

We offer resource-based URLs that accept JSON or form-encoded requests. The response is returned as JSON-encoded responses by using Standard HTTP response codes, verbs, and authentication.


  
  [
    <span className="intro-card__icon">![Python]()</span>
    
  ](https://github.com/dhan-oss/DhanHQ-py)


## Structure


## Errors

Error responses come with the error code and message generated internally by the system. The sample structure of error response is shown below.

```json
{
    "errorType": "",
    "errorCode": "",
    "errorMessage": ""
}
```

You can find detailed error code and message under [Annexure](/api/v2/guides/annexure).


## Rate Limit

| Rate Limit | Order APIs | Data APIs | Quote APIs | Non Trading APIs |
|------------|------------|-----------|------------|------------------|
| **per second** | 10 | 5 | 1 | 20 |
| **per minute** | 250 | - | Unlimited | Unlimited |
| **per hour** | 1000 | - | Unlimited | Unlimited |
| **per day** | 7000 | 100000 | Unlimited | Unlimited |

> **info:** Order Modifications are capped at **25 modifications/order**.

---

## EDIS Status Inquiry

`GET` https://api.dhan.co/v2/edis/inquire/{isin}

Check eDIS approval status for a stock by ISIN. Pass ALL to check all holdings.

You can check the status of stock whether it is approved and marked for sell action. User have to enter ISIN of the stock. An International Securities Identification Number (ISIN) is a 12-digit alphanumeric code that uniquely identifies a specific security. You can get ISIN of portfolio stocks, in response of holdings API.

Alternatively, you can pass "ALL" instead of ISIN to get eDIS status of all holdings in your portfolio.


### Path Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| isin | string | Yes | ISIN of portfolio stocks, derived from holdings API |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| clientId | string | No | User specific identification generated by Dhan |
| isin | string | No | ISIN of portfolio stocks, derived from holdings API |
| totalQty | int | No | T1 qty + Delivered qty |
| aprvdQty | int | No | Approved Quantity for eDIS |
| status | enum string | No | Status of EDIS request Values: `SUCCESS`, `FAILURE`. |
| remarks | string | No | Any relevant remarks regarding the eDIS approval status |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | eDIS status |
| 401 | Unauthorized |


### Example Request

```bash
curl -X GET https://api.dhan.co/v2/edis/inquire/{isin} \
  -H "access-token: <your-access-token>"
```

---

## EDIS

EDIS

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/edis/tpin` | Generate T-PIN |
| POST | `/edis/from` | Retrieve escaped html form & enter T-PIN |
| GET | `/edis/inquire/{isin}` | Inquire the status of stock for edis approval. |

---

## Exit All Positions

`DELETE` https://api.dhan.co/v2/positions

Exit all open positions at market price.

Exit all active positions and cancel all open orders for the current trading day.


> **NOTICE:** Order Placement, Modification and Cancellation APIs requires Static IP whitelisting - [refer here](/api/v2/guides/authentication#setup-static-ip)


No response body. On successful completion of request, `202 Accepted` response status code will appear.


### Status Codes

| Code | Description |
|------|-------------|
| 200 | All positions exited |


### Example Request

```bash
curl -X DELETE https://api.dhan.co/v2/positions \
  -H "access-token: <your-access-token>"
```

---

## Expired Options Data

Expired Options Data

This API gives you expired options contract data. We have pre processed data for you to get it on rolling basis i.e. you can fetch last 5 years of strike wise data based on ATM and upto 10 strikes above and below. In addition to that, the data values are open, high, low, close, implied volatility, volume, open interest and spot information as well.

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/charts/rollingoption` | Get Continuous Expired Options Contract data |

---

## Funds

Funds

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/margincalculator` | Margin requirement for any order |
| GET | `/fundlimit` | Retrieve Available Fund Limits |
| POST | `/margincalculator/multi` | Calculate Margin for Multiple Orders |

---

## Generate eDIS Form

`POST` https://api.dhan.co/v2/edis/bulkform

Generate an eDIS bulk authorisation form for one or more ISINs.

Generate a bulk eDIS authorisation form. Pass one or more ISINs to get the CDSL HTML form that allows users to approve multiple stocks for selling in a single submission.


### Request Body Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| isin | array | Yes | List of ISINs to approve for selling (from holdings API) |
| exchange | enum | Yes | Exchange Values: `NSE`, `BSE`. Default: `NSE`. |
| segment | enum | Yes | Trading segment Values: `EQ`, `COMM`. Default: `EQ`. |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| dhanClientId | string | No | User specific identification generated by Dhan |
| edisFormHtml | string | No | Escaped HTML form to be rendered on the client side |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | eDIS form HTML returned |
| 401 | Unauthorized |


### Example Request

```bash
curl -X POST https://api.dhan.co/v2/edis/bulkform \
  -H "access-token: <your-access-token>" \
  -H "Content-Type: application/json"
```

---

## Generate T-PIN

`GET` https://api.dhan.co/v2/edis/tpin

Request a T-PIN on your registered mobile number for eDIS authorization.

Get T-Pin on your registered mobile number using this API.


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| dhanClientId | string | No | User specific identification generated by Dhan |
| edisStatus | enum string | No | Status of EDIS request Values: `SUCCESS`, `FAILURE`. |
| remarks | string | No | Any relevant remarks regarding the generated T-PIN request |


### Status Codes

| Code | Description |
|------|-------------|
| 202 | T-PIN request accepted |
| 401 | Unauthorized |


### Example Request

```bash
curl -X GET https://api.dhan.co/v2/edis/tpin \
  -H "access-token: <your-access-token>"
```

---

## Get All Conditional Triggers

`GET` https://api.dhan.co/v2/alerts/orders

Retrieve all conditional triggers for the authenticated account.

Retrieve a list of all conditional triggers for the authenticated account, along with their current status and configuration details.


### Status Codes

| Code | Description |
|------|-------------|
| 200 | List of conditional triggers |
| 401 | Unauthorized |


### Example Request

```bash
curl -X GET https://api.dhan.co/v2/alerts/orders \
  -H "access-token: <your-access-token>"
```

---

## Get Conditional Trigger by ID

`GET` https://api.dhan.co/v2/alerts/orders/{alertId}

Retrieve status and details for a specific conditional trigger.

Retrieve the status and detailed conditional triggers for a specific trigger by its unique identification (alertId).


### Path Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| alertId | string | Yes | Alert specific identification generated by Dhan |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | Conditional trigger details |
| 401 | Unauthorized |


### Example Request

```bash
curl -X GET https://api.dhan.co/v2/alerts/orders/{alertId} \
  -H "access-token: <your-access-token>"
```

---

## Get Daily Historical Data

`POST` https://api.dhan.co/v2/charts/historical

Get daily OHLC candle data for backtesting and analysis.

Retrieve OHLC & Volume of daily candle for desired instrument. The data for any scrip is available back upto the date of its inception.


### Request Body Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| securityId | string | No | Exchange standard ID for each scrip. refer here |
| exchangeSegment | enum | No | Exchange & segment (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`, `IDX_I`. |
| instrument | string | No | Instrument type of the scrip (see Annexure) |
| expiryCode | int | No | Expiry of the instrument (for derivatives) |
| oi | string | No | Open Interest data for F&O: true or false |
| fromDate | string | No | Start date (YYYY-MM-DD) |
| toDate | string | No | End date (YYYY-MM-DD, non-inclusive) |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| open | float | No | Open price of the timeframe |
| high | float | No | High price in the timeframe |
| low | float | No | Low price in the timeframe |
| close | float | No | Close price of the timeframe |
| volume | int | No | Volume traded in the timeframe |
| open_interest | int | No | Open interest (for F&O instruments) |
| timestamp | int | No | Epoch timestamp |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | Historical OHLC data |


### Example Request

```bash
curl -X POST https://api.dhan.co/v2/charts/historical \
  -H "access-token: <your-access-token>" \
  -H "Content-Type: application/json"
```

---

## Historical Rolling Options Data

`POST` https://api.dhan.co/v2/charts/rollingoption

Fetch expired options contract data on a rolling basis with OHLC, IV, OI and spot information. Up to 30 days per call. Last 5 years available.

Fetch expired options data on a rolling basis, along with the Open Interest, Implied Volatility, OHLC, Volume as well as information about the spot. You can fetch for upto 30 days of data in a single API call. Expired options data is stored on a minute level, based on strike price relative to spot (example ATM, ATM+1, ATM-1, etc.).

You can fetch data upto last 5 years. We have added both Index Options and Stock Options data on this.


### Request Body Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| exchangeSegment | enum | No | Exchange & Segment Values: `NSE_FNO`, `BSE_FNO`. Default: `NSE_FNO`. |
| interval | enum | No | Minute intervals Values: `1`, `5`, `15`, `25`, `60`. Default: `5`. |
| securityId | string | No | Underlying security ID |
| instrument | enum | No | Instrument type Values: `OPTIDX`, `OPTSTK`. Default: `OPTIDX`. |
| expiryFlag | enum | No | Expiry Flag Values: `WEEK`, `MONTH`. Default: `WEEK`. |
| expiryCode | enum | No | 0=Current, 1=Next, 2=Far Values: `0`, `1`, `2`. Default: `0`. |
| strike | string | No | ATM, ATM+1 to ATM+10, ATM-1 to ATM-10 |
| drvOptionType | enum | No | Option Type Values: `CALL`, `PUT`. Default: `CALL`. |
| requiredData | array | No | Array of data fields: open, high, low, close, iv, volume, strike, oi, spot Values: `open`, `high`, `low`, `close`, `iv`, `volume`, `strike`, `oi`, `spot`. |
| fromDate | string | No | Start Date (YYYY-MM-DD) |
| toDate | string | No | End Date (YYYY-MM-DD) |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| data.ce.open | array | No | Array of open prices for CE |
| data.ce.high | array | No | Array of high prices for CE |
| data.ce.low | array | No | Array of low prices for CE |
| data.ce.close | array | No | Array of close prices for CE |
| data.ce.volume | array | No | Array of volumes for CE |
| data.ce.iv | array | No | Array of implied volatilities for CE |
| data.ce.oi | array | No | Array of open interest for CE |
| data.ce.spot | array | No | Array of underlying spot prices for CE |
| data.ce.strike | array | No | Array of strike prices for CE |
| data.ce.timestamp | array | No | Array of epoch timestamps for CE |
| data.pe | object | No | Object containing PE data points analogous to CE |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | Expired options data |
| 401 | Unauthorized |


### Example Request

```bash
curl -X POST https://api.dhan.co/v2/charts/rollingoption \
  -H "access-token: <your-access-token>" \
  -H "Content-Type: application/json"
```

---

## Get Expiry List

`POST` https://api.dhan.co/v2/optionchain/expirylist

Get available expiry dates for an underlying.

Retrieve dates of all expiries of any underlying, for which Options Instruments are active.


### Request Body Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| UnderlyingScrip | int | Yes | Security ID of underlying instrument (see Annexure) |
| UnderlyingSeg | string | No | Exchange and segment of underlying (see Annexure) |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| data[] | array | No | All expiry dates of underlying in YYYY-MM-DD |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | List of expiry dates |


### Example Request

```bash
curl -X POST https://api.dhan.co/v2/optionchain/expirylist \
  -H "access-token: <your-access-token>" \
  -H "client-id: <your-client-id>" \
  -H "Content-Type: application/json"
```

---

## Get Fund Limits

`GET` https://api.dhan.co/v2/fundlimit

Retrieve available balance and fund limits.

Get all information of your trading account like balance, margin utilised, collateral, etc.


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| dhanClientId | string | No | User specific identification generated by Dhan |
| availabelBalance | float | No | Primary field to check the overall usable balance |
| sodLimit | float | No | Start of day limit |
| collateralAmount | float | No | Amount received against pledged shares |
| receiveableAmount | float | No | Any newly added funds or updated profit |
| utilizedAmount | float | No | Funds used for executing any trades |
| blockedPayoutAmount | float | No | Funds blocked for withdrawal |
| withdrawableBalance | float | No | Amount available to withdraw |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | Fund limit details |


### Example Request

```bash
curl -X GET https://api.dhan.co/v2/fundlimit \
  -H "access-token: <your-access-token>"
```

---

## Get Holdings

`GET` https://api.dhan.co/v2/holdings

Retrieve all holdings in demat account.

Users can retrieve all holdings bought/sold in previous trading sessions. All T1 and delivered quantities can be fetched.


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| exchange | enum string | No | Exchange Values: `NSE`, `BSE`, `MCX`, `ALL`. |
| tradingSymbol | string | No | Refer Trading Symbol in Tables |
| securityId | string | No | Exchange standard ID for each scrip. refer here |
| isin | string | No | ISIN of the stock |
| totalQty | int | No | T1 qty + Delivered qty |
| dpQty | int | No | Delivered Quantity |
| t1Qty | int | No | T1 Qty |
| mtf_t1_qty | int | No | MTF T1 quantities |
| mtf_qty | int | No | MTF delivered quantities |
| availableQty | int | No | Total quantity - Pledged quantity |
| collateralQty | int | No | Pledged quantity |
| avgCostPrice | float | No | Average buying price of the stock |
| lastTradedPrice | float | No | Last traded price (LTP) for the scrip |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | List of holdings |


### Example Request

```bash
curl -X GET https://api.dhan.co/v2/holdings \
  -H "access-token: <your-access-token>"
```

---

## Get Intraday Historical Data

`POST` https://api.dhan.co/v2/charts/intraday

Get intraday OHLC candle data (1, 5, 15, 25, 60 minute intervals).

Retrieve Open, High, Low, Close, OI & Volume of 1, 5, 15, 25 and 60 min candle for desired instrument for last 5 years. This data available for all exchanges and segments for all active instruments.


### Request Body Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| securityId | string | No | Exchange standard ID for each scrip. refer here |
| exchangeSegment | enum | No | Exchange & segment (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`, `IDX_I`. |
| instrument | string | No | Instrument type of the scrip (see Annexure) |
| interval | enum | No | Minute intervals Values: `1`, `5`, `15`, `25`, `60`. Default: `5`. |
| oi | string | No | Open Interest data for F&O: true or false |
| fromDate | string | No | Start date (YYYY-MM-DD) |
| toDate | string | No | End date (YYYY-MM-DD) |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| open | float | No | Open price of the timeframe |
| high | float | No | High price in the timeframe |
| low | float | No | Low price in the timeframe |
| close | float | No | Close price of the timeframe |
| volume | int | No | Volume traded in the timeframe |
| open_interest | int | No | Open interest (for F&O instruments) |
| timestamp | int | No | Epoch timestamp |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | Intraday OHLC data |


### Example Request

```bash
curl -X POST https://api.dhan.co/v2/charts/intraday \
  -H "access-token: <your-access-token>" \
  -H "Content-Type: application/json"
```

---

## Kill Switch Status

`GET` https://api.dhan.co/v2/killswitch

Check whether kill switch is active for the current trading day.

The API allows you to check kill switch status for your account - whether it is active for the current trade or not.


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| dhanClientId | string | No | User specific identification generated by Dhan |
| killSwitchStatus | string | No | Status of Kill Switch Values: `ACTIVATE`, `DEACTIVATE`. |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | Current kill switch status |
| 401 | Unauthorized |


### Example Request

```bash
curl -X GET https://api.dhan.co/v2/killswitch \
  -H "access-token: <your-access-token>"
```

---

## Ledger Report

`GET` https://api.dhan.co/v2/ledger

Retrieve Trading Account Ledger Report with all credit and debit transaction details.




### Query Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| from-date | string (date) | No | Start date in YYYY-MM-DD format |
| to-date | string (date) | No | End date in YYYY-MM-DD format |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| dhanClientId | string | No | User specific identification generated by Dhan |
| narration | string | No | Description of transaction |
| voucherdate | string | No | Date of ledger entry |
| exchange | string | No | Exchange for the transaction |
| voucherdesc | string | No | Nature of transaction |
| vouchernumber | string | No | Voucher number for the transaction |
| debit | string | No | Debit amount for the entry |
| credit | string | No | Credit amount for the entry |
| runbal | string | No | Running balance after the entry |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | Ledger entries |
| 401 | Unauthorized |


### Example Request

```bash
curl -X GET https://api.dhan.co/v2/ledger \
  -H "access-token: <your-access-token>"
```

---

## Get LTP

`POST` https://api.dhan.co/v2/marketfeed/ltp

Get last traded price for multiple instruments.

Retrieve LTP for list of instruments with single API request


### Request Body Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| NSE_EQ | int-array | No | List of NSE Equity security IDs as integers (comma-separated, e.g. 1333, 11536) |
| NSE_FNO | int-array | No | List of NSE F&O security IDs as integers (comma-separated, e.g. 49081, 49082) |
| BSE_EQ | int-array | No | List of BSE Equity security IDs as integers (comma-separated) |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | LTP data |


### Example Request

```bash
curl --request POST \
  --url https://api.dhan.co/v2/marketfeed/ltp \
  --header 'Accept: application/json' \
  --header 'Content-Type: application/json' \
  --header 'access-token: <your-access-token>' \
  --header 'client-id: <your-client-id>' \
  --data '{
    "NSE_EQ": [11536],
    "NSE_FNO": [49081, 49082]
  }'
```

---

## Get OHLC

`POST` https://api.dhan.co/v2/marketfeed/ohlc

Get OHLC (Open, High, Low, Close) data for instruments.

Retrieve the Open, High, Low and Close price along with LTP for specified list of instruments.


### Request Body Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| NSE_EQ | int-array | No | List of NSE Equity security IDs as integers (comma-separated, e.g. 1333, 11536) |
| NSE_FNO | int-array | No | List of NSE F&O security IDs as integers (comma-separated, e.g. 49081, 49082) |
| BSE_EQ | int-array | No | List of BSE Equity security IDs as integers (comma-separated) |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | OHLC data |


### Example Request

```bash
curl --request POST \
  --url https://api.dhan.co/v2/marketfeed/ohlc \
  --header 'Accept: application/json' \
  --header 'Content-Type: application/json' \
  --header 'access-token: <your-access-token>' \
  --header 'client-id: <your-client-id>' \
  --data '{
    "NSE_EQ": [11536]
  }'
```

---

## Get Option Chain

`POST` https://api.dhan.co/v2/optionchain

Retrieve real-time Option Chain across exchanges for all underlying. You can fetch OI, Greeks, Volume, LTP, best bid/ask and IV across all strikes.

Retrieve real-time Option Chain across exchanges for all underlying. You can fetch Open Interest (OI), Greeks, Volume, Last Traded Price, Best Bid/Ask and Implied Volatility (IV) across all strikes for any underlying.


### Request Body Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| UnderlyingScrip | int | Yes | Security ID of underlying instrument (see Annexure) |
| UnderlyingSeg | string | No | Exchange and segment of underlying (see Annexure) |
| Expiry | string | No | Expiry date of option in YYYY-MM-DD (active expiries can be fetched from Expiry List API) |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | Option chain data |


### Example Request

```bash
curl -X POST https://api.dhan.co/v2/optionchain \
  -H "access-token: <your-access-token>" \
  -H "client-id: <your-client-id>" \
  -H "Content-Type: application/json"
```

---

## Get Order by Correlation ID

`GET` https://api.dhan.co/v2/orders/external/{correlation-id}

Retrieve order details using your custom correlation ID.

In case the user has missed order id due to unforeseen reason, this API retrieves the order status using a tag called correlation id specified by users themselve.


### Path Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| correlation-id | string | Yes | The user/partner generated id for tracking back. |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| dhanClientId | string | No | User specific identification generated by Dhan |
| orderId | string | No | Order specific identification generated by Dhan |
| correlation-id | string | No | The user/partner generated id for tracking back. Values: `Max 30 chars`, `Allowed: [^a-zA-Z0-9 _-]`. |
| orderStatus | enum string | No | Last updated status of the order Values: `TRANSIT`, `PENDING`, `REJECTED`, `CANCELLED`, `TRADED`. |
| transactionType | enum string | No | The trading side of transaction Values: `BUY`, `SELL`. |
| exchangeSegment | enum string | No | Exchange Segment (see [Annexure](/api/v2/guides/annexure#exchange-segment)) |
| productType | enum string | No | Product type of trade Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`, `CO`, `BO`. |
| orderType | enum string | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| validity | enum string | No | Validity of Order Values: `DAY`, `IOC`. |
| tradingSymbol | string | No | Refer Trading Symbol in Tables |
| securityId | string | No | Exchange standard ID for each scrip. refer here |
| quantity | int | No | Number of shares for the order |
| disclosedQuantity | int | No | Number of shares visible |
| price | float | No | Price at which order is placed |
| triggerPrice | float | No | Price at which order is triggered, for SL-M, SL-L, CO & BO |
| afterMarketOrder | boolean | No | The order placed is AMO? |
| boProfitValue | float | No | Bracket Order Target Price change |
| boStopLossValue | float | No | Bracket Order Stop Loss Price change |
| legName | enum string | No | Leg identification in case of BO Values: `ENTRY_LEG`, `TARGET_LEG`, `STOP_LOSS_LEG`. |
| createTime | string | No | Time at which the order is created |
| updateTime | string | No | Time at which the last activity happened |
| exchangeTime | string | No | Time at which order reached at exchange |
| drvExpiryDate | string | No | For F&O, expiry date of contract |
| drvOptionType | enum string | No | Type of Option Values: `CALL`, `PUT`. |
| drvStrikePrice | float | No | For Options, Strike Price |
| omsErrorCode | string | No | Error code in case the order is rejected or failed |
| omsErrorDescription | string | No | Description of error in case the order is rejected or failed |
| algoId | string | No | Exchange Algo ID for Dhan |
| remainingQuantity | integer | No | Quantity pending at the exchange to be traded (quantity - filledQty) |
| averageTradedPrice | integer | No | Average price at which order is traded |
| filledQty | integer | No | Quantity of order traded on Exchange |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | Order details |


### Example Request

```bash
curl -X GET https://api.dhan.co/v2/orders/external/{correlation-id} \
  -H "access-token: <your-access-token>"
```

---

## Get Order by ID

`GET` https://api.dhan.co/v2/orders/{order-id}

Retrieve details of a specific order by its ID.

Users can retrieve the details and status of an order from the orderbook placed during the day.


### Path Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| order-id | string | Yes | Order specific identification generated by Dhan |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| dhanClientId | string | No | User specific identification generated by Dhan |
| order-id | string | No | Order specific identification generated by Dhan |
| exchangeOrderId | string | No | Order specific identification generated by exchange |
| correlationId | string | No | The user/partner generated id for tracking back. Values: `Max 30 chars`, `Allowed: [^a-zA-Z0-9 _-]`. |
| orderStatus | enum string | No | Last updated status of the order Values: `TRANSIT`, `PENDING`, `REJECTED`, `CANCELLED`, `TRADED`. |
| transactionType | enum string | No | The trading side of transaction Values: `BUY`, `SELL`. |
| exchangeSegment | enum string | No | Exchange Segment (see [Annexure](/api/v2/guides/annexure#exchange-segment)) |
| productType | enum string | No | Product type of trade Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`, `CO`, `BO`. |
| orderType | enum string | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| validity | enum string | No | Validity of Order Values: `DAY`, `IOC`. |
| tradingSymbol | string | No | Refer Trading Symbol in Tables |
| securityId | string | No | Exchange standard ID for each scrip. refer here |
| quantity | int | No | Number of shares for the order |
| disclosedQuantity | int | No | Number of shares visible |
| price | float | No | Price at which order is placed |
| triggerPrice | float | No | Price at which order is triggered, for SL-M, SL-L, CO & BO |
| afterMarketOrder | boolean | No | The order placed is AMO? |
| boProfitValue | float | No | Bracket Order Target Price change |
| boStopLossValue | float | No | Bracket Order Stop Loss Price change |
| legName | enum string | No | Leg identification in case of BO Values: `ENTRY_LEG`, `TARGET_LEG`, `STOP_LOSS_LEG`. |
| createTime | string | No | Time at which the order is created |
| updateTime | string | No | Time at which the last activity happened |
| exchangeTime | string | No | Time at which order reached at exchange |
| drvExpiryDate | string | No | For F&O, expiry date of contract |
| drvOptionType | enum string | No | Type of Option Values: `CALL`, `PUT`. |
| drvStrikePrice | float | No | For Options, Strike Price |
| omsErrorCode | string | No | Error code in case the order is rejected or failed |
| omsErrorDescription | string | No | Description of error in case the order is rejected or failed |
| algoId | string | No | Exchange Algo ID for Dhan |
| remainingQuantity | integer | No | Quantity pending at the exchange to be traded (quantity - filledQty) |
| averageTradedPrice | integer | No | Average price at which order is traded |
| filledQty | integer | No | Quantity of order traded on Exchange |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | Order details |


### Example Request

```bash
curl -X GET https://api.dhan.co/v2/orders/{order-id} \
  -H "access-token: <your-access-token>"
```

---

## Get Order Book

`GET` https://api.dhan.co/v2/orders

Retrieve all orders for the current trading day.

This API lets you retrieve an array of all orders requested in a day with their last updated status.


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| dhanClientId | string | No | User specific identification generated by Dhan |
| orderId | string | No | Order specific identification generated by Dhan |
| exchangeOrderId | string | No | Order specific identification generated by exchange |
| correlationId | string | No | The user/partner generated id for tracking back. Values: `Max 30 chars`, `Allowed: [^a-zA-Z0-9 _-]`. |
| orderStatus | enum string | No | Last updated status of the order Values: `TRANSIT`, `PENDING`, `REJECTED`, `CANCELLED`, `TRADED`. |
| transactionType | enum string | No | The trading side of transaction Values: `BUY`, `SELL`. |
| exchangeSegment | enum string | No | Exchange Segment (see [Annexure](/api/v2/guides/annexure#exchange-segment)) |
| productType | enum string | No | Product type of trade Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`, `CO`, `BO`. |
| orderType | enum string | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| validity | enum string | No | Validity of Order Values: `DAY`, `IOC`. |
| tradingSymbol | string | No | Refer Trading Symbol in Tables |
| securityId | string | No | Exchange standard ID for each scrip. refer here |
| quantity | int | No | Number of shares for the order |
| disclosedQuantity | int | No | Number of shares visible |
| price | float | No | Price at which order is placed |
| triggerPrice | float | No | Price at which order is triggered, for SL-M, SL-L, CO & BO |
| afterMarketOrder | boolean | No | The order placed is AMO? |
| boProfitValue | float | No | Bracket Order Target Price change |
| boStopLossValue | float | No | Bracket Order Stop Loss Price change |
| legName | enum string | No | Leg identification in case of BO Values: `ENTRY_LEG`, `TARGET_LEG`, `STOP_LOSS_LEG`. |
| createTime | string | No | Time at which the order is created |
| updateTime | string | No | Time at which the last activity happened |
| exchangeTime | string | No | Time at which order reached at exchange |
| drvExpiryDate | string | No | For F&O, expiry date of contract |
| drvOptionType | enum string | No | Type of Option Values: `CALL`, `PUT`. |
| drvStrikePrice | float | No | For Options, Strike Price |
| omsErrorCode | string | No | Error code in case the order is rejected or failed |
| omsErrorDescription | string | No | Description of error in case the order is rejected or failed |
| algoId | string | No | Exchange Algo ID for Dhan |
| remainingQuantity | integer | No | Quantity pending at the exchange to be traded (quantity - filledQty) |
| averageTradedPrice | integer | No | Average price at which order is traded |
| filledQty | integer | No | Quantity of order traded on Exchange |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | List of orders |


### Example Request

```bash
curl -X GET https://api.dhan.co/v2/orders \
  -H "access-token: <your-access-token>"
```

---

## Get P&L Based Exit

`GET` https://api.dhan.co/v2/pnlExit

Fetch the currently active P&L based exit configuration.

| Parameter | Data Type | Description |
|-----------|-----------|-------------|
| pnlExitStatus | string | Current status of the P&L exit operation: `ACTIVE` `INACTIVE` |
| profit | float | User-defined target profit amount for the P&L exit |
| loss | float | User-defined target loss amount for the P&L exit |
| enableKillSwitch | boolean | Indicates if the kill switch is enabled for this P&L exit |
| productType | string | Product types applicable: `INTRADAY` `DELIVERY` |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | Current P&L exit config |
| 401 | Unauthorized |


### Example Request

```bash
curl -X GET https://api.dhan.co/v2/pnlExit \
  -H "access-token: <your-access-token>"
```

---

## Get Positions

`GET` https://api.dhan.co/v2/positions

Retrieve all open positions for the current trading day.

Users can retrieve a list of all open positions for the day. This includes all F&O carryforward positions as well.


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| dhanClientId | string | No | User specific identification generated by Dhan |
| tradingSymbol | string | No | Refer Trading Symbol in Tables |
| securityId | string | No | Exchange standard ID for each scrip. refer here |
| positionType | enum string | No | Type of Position Values: `LONG`, `SHORT`, `CLOSED`. |
| exchangeSegment | enum string | No | Exchange Segment (see [Annexure](/api/v2/guides/annexure#exchange-segment)) |
| productType | enum string | No | Product type of trade Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`, `CO`, `BO`. |
| buyAvg | float | No | Buying average of all quantities |
| buyQty | int | No | Total bought quantities |
| costPrice | float | No | Cost price field |
| sellAvg | float | No | Selling average of all quantities |
| sellQty | int | No | Total sold quantities |
| netQty | int | No | Current quantity calculated as (buy quantity - sell quantity) |
| realizedProfit | float | No | Booked Profit and Loss |
| unrealizedProfit | float | No | Unbooked Profit and Loss |
| rbiReferenceRate | float | No | Reference rate in case of Currency |
| multiplier | int | No | Value for each point change, equal to lot size |
| carryForwardBuyQty | int | No | Bought Carry forwarded quantities |
| carryForwardSellQty | int | No | Sold Carry forwarded quantities |
| carryForwardBuyValue | float | No | Total buy value of carry forwarded quantities |
| carryForwardSellValue | float | No | Total sell value of carry forwarded quantities |
| dayBuyQty | int | No | Bought day quantities |
| daySellQty | int | No | Sold day quantities |
| dayBuyValue | float | No | Total buy value of day quantities |
| daySellValue | float | No | Total sell value of day quantities |
| drvExpiryDate | string | No | Expiry date of the contract |
| drvOptionType | enum string | No | Option type Values: `CALL`, `PUT`. |
| drvStrikePrice | float | No | Strike price |
| crossCurrency | boolean | No | Is cross currency? True/False |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | List of positions |


### Example Request

```bash
curl -X GET https://api.dhan.co/v2/positions \
  -H "access-token: <your-access-token>"
```

---

## Get Full Quote

`POST` https://api.dhan.co/v2/marketfeed/quote

Get full market quote including market depth (5 levels).

Retrieve full details including market depth, OHLC data, Open Interest and Volume along with LTP for specified instruments.


### Request Body Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| NSE_EQ | int-array | No | List of NSE Equity security IDs as integers (comma-separated, e.g. 1333, 11536) |
| NSE_FNO | int-array | No | List of NSE F&O security IDs as integers (comma-separated, e.g. 49081, 49082) |
| BSE_EQ | int-array | No | List of BSE Equity security IDs as integers (comma-separated) |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | Full quote with depth |


### Example Request

```bash
curl --request POST \
  --url https://api.dhan.co/v2/marketfeed/quote \
  --header 'Accept: application/json' \
  --header 'Content-Type: application/json' \
  --header 'access-token: <your-access-token>' \
  --header 'client-id: <your-client-id>' \
  --data '{
    "NSE_EQ": [11536]
  }'
```

---

## Get Super Orders

`GET` https://api.dhan.co/v2/super/orders

Retrieve all super orders for the current trading day.

This API lets you retrieve an array of all super orders placed in a day with their last updated status. This is a special order book which only consists of Super Orders, where the target and stop loss orders are nested under the main entry order leg. Individual legs of each super order can also be found in the main order book with their Order ID.


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| dhanClientId | string | No | User specific identification generated by Dhan |
| algoId | string | No | Algo ID |
| orderId | string | No | Order specific identification generated by Dhan |
| correlationId | string | No | The user/partner generated id for tracking back. Values: `Max 30 chars`. |
| orderStatus | enum string | No | Last updated status Values: `TRANSIT`, `PENDING`, `CLOSED`, `REJECTED`, `CANCELLED`, `PART_TRADED`, `TRADED`, `EXPIRED`. |
| transactionType | enum string | No | Trading side Values: `BUY`, `SELL`. |
| exchangeSegment | enum string | No | Exchange Segment (see [Annexure](/api/v2/guides/annexure#exchange-segment)) |
| productType | enum string | No | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. |
| orderType | enum string | No | Order Type Values: `LIMIT`, `MARKET`. |
| validity | enum string | No | Validity of Order Values: `DAY`, `IOC`. |
| tradingSymbol | string | No | Refer Trading Symbol in Tables |
| securityId | string | No | Exchange standard ID for each scrip. refer here |
| quantity | int | No | Number of shares for the order |
| remainingQuantity | int | No | Quantity pending execution |
| ltp | float | No | Last Traded Price of the instrument |
| price | float | No | Price at which order is placed |
| afterMarketOrder | boolean | No | If the order is placed after market |
| legName | enum string | No | Leg identification Values: `ENTRY_LEG`. |
| trailingJump | float | No | Price Jump by which Stop Loss should be trailed |
| exchangeOrderId | string | No | Exchange generated ID for the order |
| createTime | string | No | Time at which the order is created |
| updateTime | string | No | Last updated time of the order |
| exchangeTime | string | No | Time at which order was sent to the exchange |
| omsErrorDescription | string | No | Description of error in case the order is rejected or failed |
| averageTradedPrice | integer | No | Average price at which order is traded |
| filledQty | integer | No | Quantity of order traded on Exchange |
| legDetails | []array | No | Array of Leg Details |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | List of super orders |


### Example Request

```bash
curl -X GET https://api.dhan.co/v2/super/orders \
  -H "access-token: <your-access-token>"
```

---

## Trade History

`GET` https://api.dhan.co/v2/trades/{from-date}/{to-date}/{page-number}

Retrieve detailed trade history for all orders for a given time frame. Response is paginated.

Users can retrieve their detailed trade history for all orders for a particular time frame. User needs to add header parameters along with page number as the response is paginated.


### Path Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| from-date | string | Yes | Start date in YYYY-MM-DD format |
| to-date | string | Yes | End date in YYYY-MM-DD format |
| page-number | integer | Yes | Page number (pass 0 as default) |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| dhanClientId | string | No | User specific identification generated by Dhan |
| orderId | string | No | Order specific identification generated by Dhan |
| exchangeOrderId | string | No | Order specific identification generated by exchange |
| exchangeTradeId | string | No | Trade specific identification generated by exchange |
| transactionType | enum string | No | The trading side of transaction Values: `BUY`, `SELL`. |
| exchangeSegment | enum string | No | Exchange Segment (see [Annexure](/api/v2/guides/annexure#exchange-segment)) |
| productType | enum string | No | Product type of trade Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`, `CO`, `BO`. |
| orderType | enum string | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| customSymbol | string | No | Custom trading symbol |
| securityId | string | No | Exchange standard ID for each scrip. refer here |
| tradedQuantity | int | No | Number of shares executed |
| tradedPrice | float | No | Price at which trade is executed |
| isin | string | No | ISIN of the security |
| instrument | string | No | Instrument type |
| sebiTax | float | No | SEBI Tax |
| stt | float | No | Securities Transaction Tax (STT) |
| brokerageCharges | float | No | Brokerage charges |
| serviceTax | float | No | Service tax |
| exchangeTransactionCharges | float | No | Exchange transaction charges |
| stampDuty | float | No | Stamp duty |
| createTime | string | No | Time at which the order is created |
| updateTime | string | No | Time at which the last activity happened |
| exchangeTime | string | No | Time at which order reached at exchange |
| drvExpiryDate | string | No | For F&O, expiry date of contract |
| drvOptionType | enum string | No | Type of Option Values: `CALL`, `PUT`. |
| drvStrikePrice | float | No | For Options, Strike Price |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | Paginated trade history |
| 401 | Unauthorized |


### Example Request

```bash
curl -X GET https://api.dhan.co/v2/trades/{from-date}/{to-date}/{page-number} \
  -H "access-token: <your-access-token>"
```

---

## Get Trades for Order

`GET` https://api.dhan.co/v2/trades/{order-id}

Retrieve all trades executed for a specific order.

Users can retrieve the trade details using an order id. Often during partial trades or Bracket/ Cover Orders, traders get confused in reading trade from tradebook.The response of this API will include all the trades generated for a particular order id.


### Path Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| order-id | string | Yes | Order specific identification generated by Dhan |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| dhanClientId | string | No | User specific identification generated by Dhan |
| order-id | string | No | Order specific identification generated by Dhan |
| exchangeOrderId | string | No | Order specific identification generated by exchange |
| exchangeTradeId | string | No | Trade specific identification generated by exchange |
| transactionType | enum string | No | The trading side of transaction Values: `BUY`, `SELL`. |
| exchangeSegment | enum string | No | Exchange Segment (see [Annexure](/api/v2/guides/annexure#exchange-segment)) |
| productType | enum string | No | Product type of trade Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`, `CO`, `BO`. |
| orderType | enum string | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| tradingSymbol | string | No | Refer Trading Symbol in Tables |
| securityId | string | No | Exchange standard ID for each scrip. refer here |
| tradedQuantity | int | No | Number of shares executed |
| tradedPrice | float | No | Price at which trade is executed |
| createTime | string | No | Time at which the order is created |
| updateTime | string | No | Time at which the last activity happened |
| exchangeTime | string | No | Time at which order reached at exchange |
| drvExpiryDate | string | No | For F&O, expiry date of contract |
| drvOptionType | enum string | No | Type of Option Values: `CALL`, `PUT`. |
| drvStrikePrice | float | No | For Options, Strike Price |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | Trades for order |


### Example Request

```bash
curl -X GET https://api.dhan.co/v2/trades/{order-id} \
  -H "access-token: <your-access-token>"
```

---

## Get Trade Book

`GET` https://api.dhan.co/v2/trades

Retrieve all trades for the current trading day.




### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| dhanClientId | string | No | User specific identification generated by Dhan |
| orderId | string | No | Order specific identification generated by Dhan |
| exchangeOrderId | string | No | Order specific identification generated by exchange |
| exchangeTradeId | string | No | Trade specific identification generated by exchange |
| transactionType | enum string | No | The trading side of transaction Values: `BUY`, `SELL`. |
| exchangeSegment | enum string | No | Exchange Segment (see [Annexure](/api/v2/guides/annexure#exchange-segment)) |
| productType | enum string | No | Product type of trade Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`, `CO`, `BO`. |
| orderType | enum string | No | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| tradingSymbol | string | No | Refer Trading Symbol in Tables |
| customSymbol | string | No | Custom trading symbol |
| securityId | string | No | Exchange standard ID for each scrip. refer here |
| tradedQuantity | int | No | Number of shares executed |
| tradedPrice | float | No | Price at which trade is executed |
| createTime | string | No | Time at which the order is created |
| updateTime | string | No | Time at which the last activity happened |
| exchangeTime | string | No | Time at which order reached at exchange |
| drvExpiryDate | string | No | For F&O, expiry date of contract |
| drvOptionType | enum string | No | Type of Option Values: `CALL`, `PUT`. |
| drvStrikePrice | float | No | For Options, Strike Price |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | List of trades |


### Example Request

```bash
curl -X GET https://api.dhan.co/v2/trades \
  -H "access-token: <your-access-token>"
```

---

## Historical Data

Historical Data

This API gives you historical candle data for the desired scrip across segments & exchange. This data is presented in the form of a candle and gives you timestamp, open, high, low, close & volume.

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/charts/historical` | Get OHLC for daily timeframe |
| POST | `/charts/intraday` | Get OHLC for minute timeframe |

---

## Manage Kill Switch

`POST` https://api.dhan.co/v2/killswitch

Activate or deactivate the kill switch for your account. Disables trading for the current day.

This API lets you activate the kill switch for your account, which will disable trading for current trading day. Pass `killSwitchStatus` as a query parameter.

:::note Note
You need to ensure that all your positions are closed and there are no pending orders in your account to be able to activate Kill Switch.
:::


> **NOTICE:** Order Placement, Modification and Cancellation APIs requires Static IP whitelisting - [refer here](/api/v2/guides/authentication#setup-static-ip)


### Query Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| killSwitchStatus | string | No | ACTIVATE or DEACTIVATE the kill switch Values: `ACTIVATE`, `DEACTIVATE`. |


### Request Body Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| dhanClientId | string | No | User specific identification generated by Dhan |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| dhanClientId | string | No | User specific identification generated by Dhan |
| killSwitchStatus | string | No | Status of Kill Switch - activated or not |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | Kill switch status updated |
| 401 | Unauthorized |


### Example Request

```bash
curl -X POST https://api.dhan.co/v2/killswitch \
  -H "access-token: <your-access-token>" \
  -H "Content-Type: application/json"
```

---

## Market Quote

Market Quote

This API gives you snapshots of multiple instruments at once. You can fetch LTP, Quote or Market Depth of instruments via API which sends real time data at the time of API request.

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/marketfeed/ltp` | Get ticker data of instruments |
| POST | `/marketfeed/ohlc` | Get OHLC data of instruments |
| POST | `/marketfeed/quote` | Get market depth data of instruments |

:::info Info
You can fetch upto 1000 instruments in single API request with rate limit of 1 request per second.
:::

---

## Modify Conditional Trigger

`PUT` https://api.dhan.co/v2/alerts/orders/{alertId}

Modify a conditional trigger

> **NOTICE:** Order Placement, Modification and Cancellation APIs requires Static IP whitelisting - [refer here](/api/v2/guides/authentication#setup-static-ip)


### Path Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| alertId | string | Yes | Alert specific identification generated by Dhan |


### Request Body Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| dhanClientId | string | No | User specific identification generated by Dhan |
| alertId | string | No | Alert specific identification generated by Dhan |
| condition.comparisonType | enum | Yes | Type of comparison for the condition Values: `TECHNICAL_WITH_VALUE`, `TECHNICAL_WITH_TECHNICAL`. Default: `TECHNICAL_WITH_VALUE`. |
| condition.exchangeSegment | enum | Yes | Exchange Segment for the condition (see Annexure) Values: `NSE_EQ`, `BSE_EQ`, `IDX_I`. |
| condition.securityId | string | Yes | Exchange standard ID for each scrip. refer here |
| condition.indicatorName | string | No | Name of the technical indicator (e.g. SMA_5, EMA_10, RSI, MACD) |
| condition.timeFrame | enum | Yes | Timeframe for the indicator Values: `DAY`, `ONE_MIN`, `FIVE_MIN`, `FIFTEEN_MIN`. Default: `DAY`. |
| condition.operator | enum | Yes | Operator for the condition Values: `CROSSING_UP`, `CROSSING_DOWN`, `CROSSING_ANY_SIDE`, `GREATER_THAN`, `LESS_THAN`, `GREATER_THAN_EQUAL`, `LESS_THAN_EQUAL`, `EQUAL`, `NOT_EQUAL`. Default: `CROSSING_UP`. |
| condition.comparingValue | float | No | Value to compare against (for TECHNICAL_WITH_VALUE) |
| condition.comparingIndicatorName | string | No | Second indicator name to compare (for TECHNICAL_WITH_TECHNICAL) |
| condition.expDate | string | Yes | Expiry date of the conditional trigger (YYYY-MM-DD) |
| condition.frequency | enum | Yes | Trigger frequency: ONCE or ALWAYS Values: `ONCE`, `ALWAYS`. Default: `ONCE`. |
| condition.userNote | string | No | Custom note for the condition |
| orders[0].transactionType | enum | Yes | The trading side of transaction Values: `BUY`, `SELL`. Default: `BUY`. |
| orders[0].exchangeSegment | enum | Yes | Exchange Segment for the order (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`, `IDX_I`. |
| orders[0].productType | enum | Yes | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`, `CO`, `BO`. Default: `CNC`. |
| orders[0].orderType | enum | Yes | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. Default: `LIMIT`. |
| orders[0].securityId | string | Yes | Exchange standard ID for each scrip. refer here |
| orders[0].quantity | int | Yes | Number of shares for the order |
| orders[0].validity | enum | Yes | Validity of order Values: `DAY`, `IOC`. Default: `DAY`. |
| orders[0].price | string | Yes | Price at which order is placed (e.g. "250.5") |
| orders[0].discQuantity | string | No | Disclosed quantity (e.g. "100") |
| orders[0].triggerPrice | string | No | Price at which order is triggered (e.g. "2500.0") |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| alertId | string | No | Alert specific identification generated by Dhan |
| alertStatus | enum string | No | Last updated status of the order Values: `ACTIVE`, `TRIGGERED`, `EXPIRED`, `CANCELLED`. |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | Conditional trigger modified |
| 400 | Bad Request |
| 401 | Unauthorized |


### Example Request

```bash
curl -X PUT https://api.dhan.co/v2/alerts/orders/{alertId} \
  -H "access-token: <your-access-token>" \
  -H "Content-Type: application/json"
```

---

## Modify Order

`PUT` https://api.dhan.co/v2/orders/{orderId}

Modify a pending order.

Using this API one can modify pending order in orderbook. The variables that can be modified are price, quantity, order type & validity. The user has to mention the desired value in fields.

> **NOTICE:** Order Placement, Modification and Cancellation APIs requires Static IP whitelisting - [refer here](/api/v2/guides/authentication#setup-static-ip)


### Path Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| order-id | string | Yes | Order specific identification generated by Dhan |


### Request Body Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| dhanClientId | string | Yes | User specific identification generated by Dhan |
| orderId | string | Yes | Order specific identification generated by Dhan |
| orderType | enum | Yes | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. Default: `LIMIT`. |
| legName | enum | No | In case of BO & CO, which leg is modified Values: `ENTRY_LEG`, `TARGET_LEG`, `STOP_LOSS_LEG`. Default: `ENTRY_LEG`. |
| quantity | int | No | Quantity to be modified |
| price | float | No | Price to be modified |
| disclosedQuantity | int | No | Number of shares visible (keep >30% of quantity) |
| triggerPrice | float | No | Price at which order is triggered (for SL-M & SL-L) |
| validity | enum | Yes | Validity of Order Values: `DAY`, `IOC`. Default: `DAY`. |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| orderId | string | No | Order specific identification generated by Dhan |
| orderStatus | enum string | No | Last updated status of the order Values: `TRANSIT`, `PENDING`, `REJECTED`, `CANCELLED`, `TRADED`, `EXPIRED`. |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | Order modified |


### Example Request

```bash
curl -X PUT https://api.dhan.co/v2/orders/{orderId} \
  -H "access-token: <your-access-token>" \
  -H "Content-Type: application/json"
```

---

## Modify Super Order

`PUT` https://api.dhan.co/v2/super/orders/{order-id}

Modify a pending super order leg.

This API can be used to modify any leg of a Super Order till it is in `PENDING` or `PART_TRADED` state.

> **Note:** Order Entry Leg `ENTRY_LEG` can help modify the entire super order and can only be modified when the order status is `PENDING` or `PART_TRADED`. Once the entry order status is `TRADED`, only `TARGET_LEG` and `STOP_LOSS_LEG` price and trail jump can be modified.

> **NOTICE:** Order Placement, Modification and Cancellation APIs requires Static IP whitelisting - [refer here](/api/v2/guides/authentication#setup-static-ip)


### Path Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| order-id | string | Yes | Order specific identification generated by Dhan |


### Request Body Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| dhanClientId | string | Yes | User specific identification generated by Dhan |
| orderId | string | Yes | Order specific identification generated by Dhan |
| orderType | enum | Yes | Order Type (conditionally required) Values: `LIMIT`, `MARKET`. Default: `LIMIT`. |
| legName | enum | Yes | ENTRY_LEG: entire super order (only when PENDING/PART_TRADED); TARGET_LEG or STOP_LOSS_LEG once traded Values: `ENTRY_LEG`, `TARGET_LEG`, `STOP_LOSS_LEG`. Default: `ENTRY_LEG`. |
| quantity | int | Yes | Quantity to be modified — only for ENTRY_LEG |
| price | float | Yes | Price to be modified — only for ENTRY_LEG |
| targetPrice | float | Yes | Target Price — for ENTRY_LEG or TARGET_LEG |
| stopLossPrice | float | Yes | Stop Loss Price — for ENTRY_LEG or STOP_LOSS_LEG |
| trailingJump | float | Yes | Stop Loss price jump — for ENTRY_LEG or STOP_LOSS_LEG. Set to 0 to cancel trailing |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| order-id | string | No | Order specific identification generated by Dhan |
| orderStatus | enum string | No | Last updated status Values: `TRANSIT`, `PENDING`, `REJECTED`, `TRADED`. |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | Super order modified |


### Example Request

```bash
curl -X PUT https://api.dhan.co/v2/super/orders/{order-id} \
  -H "access-token: <your-access-token>" \
  -H "Content-Type: application/json"
```

---

## Option Chain

Option Chain

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/optionchain` | Get Option Chain of any instrument |
| POST | `/optionchain/expirylist` | Expiry List for Options of Underlying |

:::info Info
Rate limit for Option Chain API is set to one unique request every 3 seconds. This means you can fetch entire option chain for multiple different underlying instrument or multiple expiries of same instrument concurrently every 3 seconds.
:::

---

## Orders

Orders

The order management API lets you place a new order, cancel or modify the pending order, retrieve the order status, trade status, order book & tradebook.

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/orders` | Place a new order |
| PUT | `/orders/{order-id}` | Modify a pending order |
| DELETE | `/orders/{order-id}` | Cancel a pending order |
| POST | `/orders/slicing` | Slice order into multiple legs over freeze limit |
| GET | `/orders` | Retrieve the list of all orders for the day |
| GET | `/orders/{order-id}` | Retrieve the status of an order |
| GET | `/orders/external/{correlation-id}` | Retrieve the status of an order by correlation id |
| GET | `/trades` | Retrieve the list of all trades for the day |
| GET | `/trades/{order-id}` | Retrieve the details of trade by an order id |

> **note:** Order Placement, Modification and Cancellation APIs requires Static IP whitelisting - [here](/api/v2/guides/authentication#setup-static-ip)

---

## Place Conditional Trigger

`POST` https://api.dhan.co/v2/alerts/orders

Create a new conditional trigger with conditions (price or technical indicators) that, when met, place one or multiple orders automatically.

Using this API, you can create a new conditional trigger wherein you define conditions (price or technical indicators) that, when met, place one or multiple orders automatically on the user's Dhan account. It supports multiple combinations of indicators and operators.


> **NOTICE:** Order Placement, Modification and Cancellation APIs requires Static IP whitelisting - [refer here](/api/v2/guides/authentication#setup-static-ip)


### Request Body Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| dhanClientId | string | No | User specific identification generated by Dhan |
| condition.comparisonType | enum | Yes | Type of comparison for the condition Values: `TECHNICAL_WITH_VALUE`, `TECHNICAL_WITH_TECHNICAL`. Default: `TECHNICAL_WITH_VALUE`. |
| condition.exchangeSegment | enum | Yes | Exchange Segment for the condition (see Annexure) Values: `NSE_EQ`, `BSE_EQ`, `IDX_I`. |
| condition.securityId | string | Yes | Exchange standard ID for each scrip. refer here |
| condition.indicatorName | string | No | Name of the technical indicator (e.g. SMA_5, EMA_10, RSI, MACD) |
| condition.timeFrame | enum | Yes | Timeframe for the indicator Values: `DAY`, `ONE_MIN`, `FIVE_MIN`, `FIFTEEN_MIN`. Default: `DAY`. |
| condition.operator | enum | Yes | Operator for the condition Values: `CROSSING_UP`, `CROSSING_DOWN`, `CROSSING_ANY_SIDE`, `GREATER_THAN`, `LESS_THAN`, `GREATER_THAN_EQUAL`, `LESS_THAN_EQUAL`, `EQUAL`, `NOT_EQUAL`. Default: `CROSSING_UP`. |
| condition.comparingValue | float | No | Value to compare against (for TECHNICAL_WITH_VALUE) |
| condition.comparingIndicatorName | string | No | Second indicator name to compare (for TECHNICAL_WITH_TECHNICAL) |
| condition.expDate | string | Yes | Expiry date of the conditional trigger (YYYY-MM-DD) |
| condition.frequency | enum | Yes | Trigger frequency: ONCE or ALWAYS Values: `ONCE`, `ALWAYS`. Default: `ONCE`. |
| condition.userNote | string | No | Custom note for the condition |
| orders[0].transactionType | enum | Yes | The trading side of transaction Values: `BUY`, `SELL`. Default: `BUY`. |
| orders[0].exchangeSegment | enum | Yes | Exchange Segment for the order (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`, `IDX_I`. |
| orders[0].productType | enum | Yes | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`, `CO`, `BO`. Default: `CNC`. |
| orders[0].orderType | enum | Yes | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. Default: `LIMIT`. |
| orders[0].securityId | string | Yes | Exchange standard ID for each scrip. refer here |
| orders[0].quantity | int | Yes | Number of shares for the order |
| orders[0].validity | enum | Yes | Validity of order Values: `DAY`, `IOC`. Default: `DAY`. |
| orders[0].price | string | Yes | Price at which order is placed (e.g. "250.5") |
| orders[0].discQuantity | string | No | Disclosed quantity (e.g. "100") |
| orders[0].triggerPrice | string | No | Price at which order is triggered (e.g. "2500.0") |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | Conditional trigger created |
| 400 | Bad Request |
| 401 | Unauthorized |


### Example Request

```bash
curl -X POST https://api.dhan.co/v2/alerts/orders \
  -H "access-token: <your-access-token>" \
  -H "Content-Type: application/json"
```

---

## Place Order

`POST` https://api.dhan.co/v2/orders

Place a new order on the exchange.

The order request API lets you place new orders.


> **NOTICE:** Order Placement, Modification and Cancellation APIs requires Static IP whitelisting - [refer here](/api/v2/guides/authentication#setup-static-ip)


### Request Body Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| dhanClientId | string | No | User specific identification generated by Dhan |
| correlationId | string | No | User/partner generated id for tracking back Constraints: Max 30 chars, Allowed: a-zA-Z0-9-_. |
| transactionType | enum | Yes | The trading side of transaction Values: `BUY`, `SELL`. Default: `BUY`. |
| exchangeSegment | enum | Yes | Exchange Segment (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`, `IDX_I`. |
| productType | enum | Yes | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`, `CO`, `BO`. Default: `CNC`. |
| orderType | enum | Yes | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. Default: `LIMIT`. |
| validity | enum | Yes | Validity of Order Values: `DAY`, `IOC`. Default: `DAY`. |
| securityId | string | Yes | Exchange standard ID for each scrip. refer here |
| quantity | int | Yes | Number of shares for the order |
| disclosedQuantity | int | No | Number of shares visible (keep >30% of quantity) |
| price | float | No | Price at which order is placed |
| triggerPrice | float | No | Price at which order is triggered (for SL-M & SL-L) |
| afterMarketOrder | boolean | No | Flag for orders placed after market hours |
| amoTime | enum | No | Timing for after market order Values: `PRE_OPEN`, `OPEN`, `OPEN_30`, `OPEN_60`. |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| orderId | string | No | Order specific identification generated by Dhan |
| orderStatus | enum string | No | Last updated status of the order Values: `TRANSIT`, `PENDING`, `REJECTED`, `CANCELLED`, `TRADED`. |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | Order placed successfully |
| 400 | Bad Request |
| 401 | Unauthorized |


### Example Request

```bash
curl -X POST https://api.dhan.co/v2/orders \
  -H "access-token: <your-access-token>" \
  -H "Content-Type: application/json"
```

---

## Place Super Order

`POST` https://api.dhan.co/v2/super/orders

Place a bracket order with entry, target, and stop-loss levels.

The super order request API lets you place new super orders. You can place a combination of orders using this API, wether that be entry leg, target leg and stop loss leg.

This order type is available across segments and exchanges. You can place intraday, carry forward or even MTF orders via this order type.

> **NOTICE:** Order Placement, Modification and Cancellation APIs requires Static IP whitelisting - [refer here](/api/v2/guides/authentication#setup-static-ip)


### Request Body Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| dhanClientId | string | Yes | User specific identification generated by Dhan |
| correlationId | string | No | User/partner generated id for tracking back. Constraints: Max 30 chars, Allowed: a-zA-Z0-9-_. |
| transactionType | enum | Yes | The trading side of transaction Values: `BUY`, `SELL`. Default: `BUY`. |
| exchangeSegment | enum | Yes | Exchange Segment (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`, `IDX_I`. |
| productType | enum | Yes | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`. Default: `CNC`. |
| orderType | enum | Yes | Order Type Values: `LIMIT`, `MARKET`. Default: `LIMIT`. |
| securityId | string | Yes | Exchange standard ID for each scrip. refer here |
| quantity | int | Yes | Number of shares for the order |
| price | float | Yes | Price at which order is placed |
| targetPrice | float | Yes | Target Price for the Super Order |
| stopLossPrice | float | Yes | Stop Loss Price for the Super Order |
| trailingJump | float | Yes | Price Jump by which Stop Loss should be trailed |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| orderId | string | No | Order specific identification generated by Dhan |
| orderStatus | enum string | No | Last updated status Values: `TRANSIT`, `PENDING`, `REJECTED`. |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | Super order placed |


### Example Request

```bash
curl -X POST https://api.dhan.co/v2/super/orders \
  -H "access-token: <your-access-token>" \
  -H "Content-Type: application/json"
```

---

## Portfolio

Portfolio

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/holdings` | Retrieve list of holdings in demat account |
| GET | `/positions` | Retrieve open positions |
| POST | `/positions/convert` | Convert intraday position to delivery or delivery to intraday |
| DELETE | `/positions` | Exit All Positions |

---

## Slice Order

`POST` https://api.dhan.co/v2/orders/slicing

Place order with slicing for quantities exceeding freeze limit.

This API helps you slice your order request into multiple orders to allow you to place over freeze limit quantity for F&O instruments.


> **NOTICE:** Order Placement, Modification and Cancellation APIs requires Static IP whitelisting - [refer here](/api/v2/guides/authentication#setup-static-ip)


### Request Body Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| dhanClientId | string | Yes | User specific identification generated by Dhan |
| correlationId | string | No | User/partner generated id for tracking back Constraints: Max 30 chars, Allowed: a-zA-Z0-9-_. |
| transactionType | enum | Yes | The trading side of transaction Values: `BUY`, `SELL`. Default: `BUY`. |
| exchangeSegment | enum | Yes | Exchange Segment (see Annexure) Values: `NSE_EQ`, `NSE_FNO`, `BSE_EQ`, `BSE_FNO`, `MCX_COMM`, `IDX_I`. |
| productType | enum | Yes | Product type Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`, `CO`, `BO`. Default: `CNC`. |
| orderType | enum | Yes | Order Type Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. Default: `LIMIT`. |
| validity | enum | Yes | Validity of Order Values: `DAY`, `IOC`. Default: `DAY`. |
| securityId | string | No | Exchange standard ID for each scrip. refer here |
| quantity | int | Yes | Number of shares for the order |
| disclosedQuantity | int | No | Number of shares visible (keep >30% of quantity) |
| price | float | Yes | Price at which order is placed |
| triggerPrice | float | No | Price at which order is triggered (for SL-M & SL-L) |
| afterMarketOrder | boolean | No | Flag for orders placed after market hours |
| amoTime | enum | No | Timing for after market order Values: `PRE_OPEN`, `OPEN`, `OPEN_30`, `OPEN_60`. |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| orderId | string | No | Order specific identification generated by Dhan |
| orderStatus | enum string | No | Last updated status of the order Values: `TRANSIT`, `PENDING`, `REJECTED`, `CANCELLED`, `TRADED`. |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | Sliced orders placed |


### Example Request

```bash
curl -X POST https://api.dhan.co/v2/orders/slicing \
  -H "access-token: <your-access-token>" \
  -H "Content-Type: application/json"
```

---

## Statement

Statement

This set of APIs retreives all your trade and ledger details to help you summarise and analyse your trades.

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/ledger` | Retrieve Trading Account debit and credit details |
| GET | `/trades/` | Retrieve historical trade data |

---

## Stop P&L Based Exit

`DELETE` https://api.dhan.co/v2/pnlExit

Disable the active P&L based exit configuration.

> **NOTICE:** Order Placement, Modification and Cancellation APIs requires Static IP whitelisting - [refer here](/api/v2/guides/authentication#setup-static-ip)


| Parameter | Data Type | Description |
|-----------|-----------|-------------|
| pnlExitStatus | string | P&L based exit status: `ACTIVE` `INACTIVE` |
| message | string | Status of Conditional Trigger |


### Status Codes

| Code | Description |
|------|-------------|
| 200 | P&L exit stopped |
| 401 | Unauthorized |


### Example Request

```bash
curl -X DELETE https://api.dhan.co/v2/pnlExit \
  -H "access-token: <your-access-token>"
```

---

## Super Order

Super Order

This particular set of APIs can be used to create, modify and cancel super orders. You can place super orders across all exchanges and segments.

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/super/orders` | Create a new super order |
| PUT | `/super/orders/{order-id}` | Modify a pending super order |
| DELETE | `/super/orders/{order-id}/{order-leg}` | Cancel a pending super order leg |
| GET | `/super/orders` | Retrieve the list of all super orders |

---

## Trader's Control

Trader's Control

These set of APIs are built for traders to manage their risks and preferences using advanced tools built in right into Dhan. You can set and manage Kill Switch for your account along with having P&L based auto-exit feature.

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/killswitch` | Manage Kill Switch |
| GET | `/killswitch` | Kill Switch Status |
| POST | `/pnlExit` | Configure P&L Based Exit |
| DELETE | `/pnlExit` | Stop P&L Based Exit |
| GET | `/pnlExit` | Get P&L Based Exit |

---

## Trading APIs

All endpoints for order placement, modification, portfolio management, and trading controls.

---

## Orders

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | [Place Order](/api/v2/orders/place-order) | Place a new order on the exchange |
| PUT | [Modify Order](/api/v2/orders/modify-order) | Modify a pending order |
| DELETE | [Cancel Order](/api/v2/orders/cancel-order) | Cancel a pending order |
| GET | [Get Order Book](/api/v2/orders/get-orders) | Retrieve all orders for the day |
| GET | [Get Order by ID](/api/v2/orders/get-order-by-id) | Get a specific order by order ID |
| GET | [Get Order by Correlation ID](/api/v2/orders/get-order-by-correlation-id) | Get order by partner correlation ID |
| POST | [Slice Order](/api/v2/orders/slice-order) | Place order with slicing for freeze limit |
| GET | [Get Trade Book](/api/v2/orders/get-trades) | Retrieve all trades for the day |
| GET | [Get Trades for Order](/api/v2/orders/get-trades-by-order-id) | Get trades for a specific order |

## Super Orders

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | [Place Super Order](/api/v2/super-orders/place-super-order) | Place a bracket order with entry, target, and stop-loss |
| PUT | [Modify Super Order](/api/v2/super-orders/modify-super-order) | Modify a pending super order leg |
| DELETE | [Cancel Super Order Leg](/api/v2/super-orders/cancel-super-order-leg) | Cancel a specific leg of a super order |
| GET | [Get Super Orders](/api/v2/super-orders/get-super-orders) | Retrieve all super orders |

## Conditional Triggers

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | [Place Conditional Trigger](/api/v2/conditional-triggers/place-conditional-trigger) | Create a new conditional trigger |
| PUT | [Modify Conditional Trigger](/api/v2/conditional-triggers/modify-conditional-trigger) | Modify an existing trigger |
| DELETE | [Delete Conditional Trigger](/api/v2/conditional-triggers/delete-conditional-trigger) | Delete a trigger |
| GET | [Get Conditional Trigger by ID](/api/v2/conditional-triggers/get-conditional-trigger-by-id) | Get a specific trigger |
| GET | [Get All Conditional Triggers](/api/v2/conditional-triggers/get-all-conditional-triggers) | Retrieve all triggers |

## Portfolio

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | [Get Holdings](/api/v2/portfolio/get-holdings) | Retrieve current holdings |
| GET | [Get Positions](/api/v2/portfolio/get-positions) | Retrieve current positions |
| POST | [Convert Position](/api/v2/portfolio/convert-position) | Convert position between product types |
| DELETE | [Exit All Positions](/api/v2/portfolio/exit-all-positions) | Exit all open positions |

## Trader's Control

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | [Manage Kill Switch](/api/v2/traders-control/manage-kill-switch) | Enable or disable kill switch |
| GET | [Kill Switch Status](/api/v2/traders-control/get-kill-switch-status) | Get current kill switch status |
| POST | [Configure P&L Exit](/api/v2/traders-control/configure-pnl-exit) | Set up P&L based exit |
| GET | [Get P&L Exit](/api/v2/traders-control/get-pnl-exit) | Get current P&L exit config |
| DELETE | [Stop P&L Exit](/api/v2/traders-control/stop-pnl-exit) | Stop P&L based exit |

## EDIS

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | [Generate T-PIN](/api/v2/edis/generate-tpin) | Generate T-PIN for EDIS |
| POST | [Generate eDIS Form](/api/v2/edis/generate-edis-form) | Generate eDIS authorization form |
| GET | [EDIS Status Inquiry](/api/v2/edis/edis-inquiry) | Check EDIS authorization status |

## Funds

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | [Get Fund Limits](/api/v2/funds/get-fund-limits) | Retrieve available fund limits |
| POST | [Calculate Margin](/api/v2/funds/calculate-margin) | Calculate margin for an order |
| POST | [Calculate Multi-Order Margin](/api/v2/funds/calculate-multi-margin) | Calculate margin for multiple orders |

---

## Annexure

Complete reference for all enum values, exchange segments, product types, error codes and more

Reference tables for all enum values used across DhanHQ APIs.

---

## Exchange Segment

| Attribute | Exchange | Segment | Enum |
|-----------|----------|---------|------|
| `IDX_I` | Index | Index Value | `0` |
| `NSE_EQ` | NSE | Equity Cash | `1` |
| `NSE_FNO` | NSE | Futures & Options | `2` |
| `BSE_EQ` | BSE | Equity Cash | `4` |
| `MCX_COMM` | MCX | Commodity | `5` |
| `BSE_FNO` | BSE | Futures & Options | `8` |

---

## Product Type

CO & BO product types will be valid only for Intraday.

| Attribute | Detail |
|-----------|--------|
| `CNC` | Cash & Carry for equity deliveries |
| `INTRADAY` | Intraday for Equity, Futures & Options |
| `MARGIN` | Carry Forward in Futures & Options |
| `CO` | Cover Order |
| `BO` | Bracket Order |

---

## Order Status

| Attribute | Detail |
|-----------|--------|
| `TRANSIT` | Did not reach the exchange server |
| `PENDING` | Awaiting execution |
| `CLOSED` | Used for Super Order, once both entry and exit orders are placed |
| `TRIGGERED` | Used for Super Order, if Target or Stop Loss leg is triggered |
| `REJECTED` | Rejected by broker/exchange |
| `CANCELLED` | Cancelled by user |
| `PART_TRADED` | Partial Quantity traded successfully |
| `TRADED` | Executed successfully |

---

## After Market Order Time

| Attribute | Detail |
|-----------|--------|
| `PRE_OPEN` | AMO pumped at pre-market session |
| `OPEN` | AMO pumped at market open |
| `OPEN_30` | AMO pumped 30 minutes after market open |
| `OPEN_60` | AMO pumped 60 minutes after market open |

---

## Expiry Code

| Attribute | Detail |
|-----------|--------|
| `0` | Current Expiry / Near Expiry |
| `1` | Next Expiry |
| `2` | Far Expiry |

---

## Instrument

| Attribute | Detail |
|-----------|--------|
| `INDEX` | Index |
| `FUTIDX` | Futures of Index |
| `OPTIDX` | Options of Index |
| `EQUITY` | Equity |
| `FUTSTK` | Futures of Stock |
| `OPTSTK` | Options of Stock |
| `FUTCOM` | Futures of Commodity |
| `OPTFUT` | Options of Commodity Futures |

---

## Feed Request Code

| Code | Action |
|------|--------|
| `11` | Connect Feed |
| `12` | Disconnect Feed |
| `15` | Subscribe — Ticker Packet |
| `16` | Unsubscribe — Ticker Packet |
| `17` | Subscribe — Quote Packet |
| `18` | Unsubscribe — Quote Packet |
| `21` | Subscribe — Full Packet |
| `22` | Unsubscribe — Full Packet |
| `23` | Subscribe — Full Market Depth |
| `25` | Unsubscribe — Full Market Depth |

---

## Feed Response Code

| Code | Packet |
|------|--------|
| `1` | Index Packet |
| `2` | Ticker Packet |
| `4` | Quote Packet |
| `5` | OI Packet |
| `6` | Prev Close Packet |
| `7` | Market Status Packet |
| `8` | Full Packet |
| `50` | Feed Disconnect |

---

## Trading API Error

| Type | Code | Message |
|------|------|---------|
| Invalid Authentication | `DH-901` | Client ID or user generated access token is invalid or expired |
| Invalid Access | `DH-902` | User has not subscribed to Data APIs or does not have access to Trading APIs |
| User Account | `DH-903` | Errors related to User's Account — check if required segments are activated |
| Rate Limit | `DH-904` | Too many requests — try throttling API calls |
| Input Exception | `DH-905` | Missing required fields, bad values for parameters etc. |
| Order Error | `DH-906` | Incorrect request for order — cannot be processed |
| Data Error | `DH-907` | Unable to fetch data due to incorrect parameters or no data present |
| Internal Server Error | `DH-908` | Server was not able to process request — occurs rarely |
| Network Error | `DH-909` | API was unable to communicate with backend system |
| Others | `DH-910` | Error originating from other reasons |

---

## Data API Error

| Code | Description |
|------|-------------|
| `800` | Internal Server Error |
| `804` | Requested number of instruments exceeds limit |
| `805` | Too many requests or connections — further requests may result in blocking |
| `806` | Data APIs not subscribed |
| `807` | Access token is expired |
| `808` | Authentication Failed — Client ID or Access Token invalid |
| `809` | Access token is invalid |
| `810` | Client ID is invalid |
| `811` | Invalid Expiry Date |
| `812` | Invalid Date Format |
| `813` | Invalid SecurityId |
| `814` | Invalid Request |

---

## Conditional Triggers

### Comparison Type

| Type | Description | Mandatory Fields |
|------|-------------|------------------|
| `TECHNICAL_WITH_VALUE` | Compare technical indicator against a fixed numeric value | `indicatorName` `operator` `timeFrame` `comparingValue` |
| `TECHNICAL_WITH_INDICATOR` | Compare technical indicator against another indicator | `indicatorName` `operator` `timeFrame` `comparingIndicatorName` |
| `TECHNICAL_WITH_CLOSE` | Compare a technical indicator with closing price | `indicatorName` `operator` `timeFrame` |
| `PRICE_WITH_VALUE` | Compare market price against fixed value | `operator` `comparingValue` |

### Indicator Name

| Indicator | Description |
|-----------|-------------|
| `SMA_5` | Simple Moving Average (5 periods) |
| `SMA_10` | Simple Moving Average (10 periods) |
| `SMA_20` | Simple Moving Average (20 periods) |
| `SMA_50` | Simple Moving Average (50 periods) |
| `SMA_100` | Simple Moving Average (100 periods) |
| `SMA_200` | Simple Moving Average (200 periods) |
| `EMA_5` | Exponential Moving Average (5 periods) |
| `EMA_10` | Exponential Moving Average (10 periods) |
| `EMA_20` | Exponential Moving Average (20 periods) |
| `EMA_50` | Exponential Moving Average (50 periods) |
| `EMA_100` | Exponential Moving Average (100 periods) |
| `EMA_200` | Exponential Moving Average (200 periods) |
| `BB_UPPER` | Upper Bollinger Band |
| `BB_LOWER` | Lower Bollinger Band |
| `RSI_14` | Relative Strength Index |
| `ATR_14` | Average True Range |
| `STOCHASTIC` | Stochastic Oscillator |
| `STOCHRSI_14` | Stochastic RSI |
| `MACD_26` | MACD long-term component |
| `MACD_12` | MACD short-term component |
| `MACD_HIST` | MACD histogram |

### Operator

| Operator | Description |
|----------|-------------|
| `CROSSING_UP` | Crosses above |
| `CROSSING_DOWN` | Crosses below |
| `CROSSING_ANY_SIDE` | Crosses either side |
| `GREATER_THAN` | Greater than |
| `LESS_THAN` | Less than |
| `GREATER_THAN_EQUAL` | Greater than or equal |
| `LESS_THAN_EQUAL` | Less than or equal |
| `EQUAL` | Equal |
| `NOT_EQUAL` | Not equal |

### Status

| Status | Description |
|--------|-------------|
| `ACTIVE` | Alert is currently active |
| `TRIGGERED` | Alert condition met |
| `EXPIRED` | Alert expired |
| `CANCELLED` | Alert cancelled |

---

## Consume Consent

`POST` https://auth.dhan.co/app/consumeApp-consent

Consume tokenId and generate an access token for API Key & Secret based login.

Use this after the browser-login redirect step. Pass the `tokenId` received from the redirect along with the API key and secret to generate the final access token.


### Query Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| tokenId | string | Yes | User specific token ID obtained from the browser login step |


### Header Parameters

| Header | Type | Required | Description |
|--------|------|----------|-------------|
| app_id | string | Yes | API key generated from Dhan |
| app_secret | string | Yes | API secret generated from Dhan |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| dhanClientId | string | No | User specific identification generated by Dhan |
| dhanClientName | string | No | Name of the user |
| dhanClientUcc | string | No | Unique Client Code (UCC) |
| givenPowerOfAttorney | boolean | No | Whether the user has activated DDPI |
| accessToken | string | No | JWT access token to be used for API authentication |
| expiryTime | string | No | ISO timestamp when the access token expires |


### Example Request

```bash
curl --location 'https://auth.dhan.co/app/consumeApp-consent?tokenId={Token ID}' \
  --header 'app_id: {API Key}' \
  --header 'app_secret: {API Secret}'
```

---

## Generate Consent

`POST` https://auth.dhan.co/app/generate-consent

Generate a consent session for API Key & Secret based login.

This validates the app credentials and creates a consent session that is used in the browser-login step.

> **note:** Users can generate up to 25 `consentAppId` values per day. Each one stays active until `tokenId` is generated, but only one token stays active at a time.


### Query Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| client_id | string | Yes | Dhan client ID |


### Header Parameters

| Header | Type | Required | Description |
|--------|------|----------|-------------|
| app_id | string | Yes | API key generated from Dhan |
| app_secret | string | Yes | API secret generated from Dhan |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| consentAppId | string | No | Temporary session ID to be used in the browser login step |
| consentAppStatus | string | No | Status of the consent creation request |
| status | string | No | API response status |


### Example Request

```bash
curl --location --request POST \
  'https://auth.dhan.co/app/generate-consent?client_id={dhanClientId}' \
  --header 'app_id: {API key}' \
  --header 'app_secret: {API secret}'
```

---

## Generate Token

`POST` https://auth.dhan.co/app/generateAccessToken

Generate an access token using dhanClientId, PIN, and TOTP.

Use this endpoint when TOTP is enabled for the account and you want to generate a fresh access token directly through the auth service.


### Query Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| dhanClientId | string | Yes | Client ID of the user |
| pin | string | Yes | Dhan Pin of the user, numeric code |
| totp | string | Yes | TOTP code from the authenticator app |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| dhanClientId | string | No | User specific identification generated by Dhan |
| dhanClientName | string | No | Name registered on Dhan |
| dhanClientUcc | string | No | Unique Client Code registered with Dhan |
| givenPowerOfAttorney | boolean | No | DDPI status |
| accessToken | string | No | Generated access token |
| expiryTime | string | No | Token expiry time, usually 24 hours from generation |


### Example Request

```bash
curl --location --request POST \
  'https://auth.dhan.co/app/generateAccessToken?dhanClientId={CLIENT_ID}&pin={PIN}&totp={TOTP}'
```

---

## Get IP

`GET` https://api.dhan.co/v2/ip/getIP

Get the currently configured primary and secondary IPs and their next modification dates.

Use this endpoint to fetch the currently configured primary and secondary IPs along with the dates on which each can next be modified.


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| modifyDateSecondary | string | No | Date from which the secondary IP can be modified |
| secondaryIP | string | No | Currently set secondary static IP |
| modifyDatePrimary | string | No | Date from which the primary IP can be modified |
| primaryIP | string | No | Currently set primary static IP |


### Example Request

```bash
curl --request GET \
  --url https://api.dhan.co/v2/ip/getIP \
  --header 'access-token: {Access Token}'
```

---

## Modify IP

`PUT` https://api.dhan.co/v2/ip/modifyIP

Modify a primary or secondary static IP when the modification window is available.

Use this endpoint to modify the configured primary or secondary static IP. This can only be used when the account is within the allowed modification period.


### Request Body Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| dhanClientId | string | Yes | User specific identification |
| ip | string | Yes | Static IP address in IPv4 or IPv6 format |
| ipFlag | enum | Yes | Flag to set the IP as primary or secondary Values: `PRIMARY`, `SECONDARY`. Default: `PRIMARY`. |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| message | string | No | API response message |
| status | string | No | API response status |


### Example Request

```bash
curl --request PUT \
  --url https://api.dhan.co/v2/ip/modifyIP \
  --header 'Content-Type: application/json' \
  --header 'access-token: {Access Token}' \
  --data '{
  "dhanClientId": "1000000001",
  "ip": "10.200.10.10",
  "ipFlag": "PRIMARY"
  }'
```

---

## Consume Consent

`POST` https://auth.dhan.co/partner/consume-consent

Consume partner tokenId and generate an access token for the end user.

Use this after the browser-login redirect step. Pass the `tokenId` from the redirect along with partner credentials to generate the end-user access token.


### Query Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| tokenId | string | Yes | User specific token ID obtained from the browser login step |


### Header Parameters

| Header | Type | Required | Description |
|--------|------|----------|-------------|
| partner_id | string | Yes | Partner ID provided by Dhan |
| partner_secret | string | Yes | Partner secret provided by Dhan |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| dhanClientId | string | No | User specific identification generated by Dhan |
| dhanClientName | string | No | Name of the user |
| dhanClientUcc | string | No | Unique Client Code (UCC) |
| givenPowerOfAttorney | boolean | No | Whether the user has activated DDPI |
| accessToken | string | No | JWT access token to be used for API authentication |
| expiryTime | string | No | ISO timestamp when the access token expires |


### Example Request

```bash
curl --location 'https://auth.dhan.co/partner/consume-consent?tokenId={Token ID}' \
  --header 'partner_id: {Partner ID}' \
  --header 'partner_secret: {Partner Secret}'
```

---

## Generate Consent

`POST` https://auth.dhan.co/partner/generate-consent

Generate a partner consent session for user login.

This validates the partner credentials and creates the consent session required for the browser-login step.


### Header Parameters

| Header | Type | Required | Description |
|--------|------|----------|-------------|
| partner_id | string | Yes | Partner ID provided by Dhan |
| partner_secret | string | Yes | Partner secret provided by Dhan |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| consentId | string | No | Temporary session ID on partner level, used in the browser login step |
| consentStatus | string | No | Status of the partner consent request |


### Example Request

```bash
curl --location 'https://auth.dhan.co/partner/generate-consent' \
  --header 'partner_id: {Partner ID}' \
  --header 'partner_secret: {Partner Secret}'
```

---

## Renew Token

`GET` https://api.dhan.co/v2/RenewToken

Renew an active Dhan Web access token for another 24 hours.

This renews a currently active token generated from Dhan Web and returns a new token with another 24 hours of validity.

> **note:** This only renews tokens which are active. Renewing an expired token returns an error.


### Header Parameters

| Header | Type | Required | Description |
|--------|------|----------|-------------|
| dhanClientId | string | Yes | Client ID of the user |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| dhanClientId | string | No | User specific identification generated by Dhan |
| dhanClientName | string | No | Name registered on Dhan |
| dhanClientUcc | string | No | Unique Client Code registered with Dhan |
| givenPowerOfAttorney | boolean | No | DDPI status |
| accessToken | string | No | Newly generated access token |
| expiryTime | string | No | New token expiry timestamp |


### Example Request

```bash
curl --location 'https://api.dhan.co/v2/RenewToken' \
  --header 'access-token: {JWT Token}' \
  --header 'dhanClientId: {Client ID}'
```

---

## Set IP

`POST` https://api.dhan.co/v2/ip/setIP

Set a primary or secondary static IP for the account.

Use this endpoint to setup the primary or secondary static IP for the account. Once an IP is setup, it cannot be modified for the next 7 days.


### Request Body Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| dhanClientId | string | Yes | User specific identification |
| ip | string | Yes | Static IP address in IPv4 or IPv6 format |
| ipFlag | enum | Yes | Flag to set the IP as primary or secondary Values: `PRIMARY`, `SECONDARY`. Default: `PRIMARY`. |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| message | string | No | API response message |
| status | string | No | API response status |


### Example Request

```bash
curl --request POST \
  --url https://api.dhan.co/v2/ip/setIP \
  --header 'Content-Type: application/json' \
  --header 'access-token: {Access Token}' \
  --data '{
  "dhanClientId": "1000000001",
  "ip": "10.200.10.10",
  "ipFlag": "PRIMARY"
  }'
```

---

## Authentication

Authentication methods for DhanHQ API — access tokens, API keys, partner login, TOTP, Static IP and more

DhanHQ APIs require authentication based on an access token which needs to be passed with every request. There are various methods to generate this access token depending on user type and the purpose of usage.

**Two categories of users:**

- **Individual** — Users who have a Dhan account and want to build their own algorithm or trading system on top of DhanHQ APIs.
- **Partners** — Platforms that want to build on top of DhanHQ APIs and serve it to their users. This can be algo platforms, fintechs, banks, PMS, and others.

## Eligibility

All Dhan users get access to **Trading APIs for free**. This means you can place and manage orders, positions, funds and all other transactions without paying any extra charges. For Data APIs, there are additional charges mentioned on the platform.

If you are a partner who wants to get integrated and build on top of DhanHQ APIs, you can reach out by filling the form on the [DhanHQ website](https://dhanhq.co/trading-apis).

---

## Authentication APIs

Use the child pages under this section for the endpoint-style pages with request forms and interactive API explorer.

### Access Token

- [Generate Token](/api/v2/authentication/generate-token)
- [Renew Token](/api/v2/authentication/renew-token)

### API Key & Secret

- [Generate Consent](/api/v2/authentication/api-key-generate-consent)
- [Consume Consent](/api/v2/authentication/api-key-consume-consent)

### Partners

- [Generate Consent](/api/v2/authentication/partner-generate-consent)
- [Consume Consent](/api/v2/authentication/partner-consume-consent)

### Setup Static IP

- [Set IP](/api/v2/authentication/set-ip)
- [Modify IP](/api/v2/authentication/modify-ip)
- [Get IP](/api/v2/authentication/get-ip)

---

## Access for Individual Traders

As an individual trader, there are two methods to generate an access token:

- Directly generate access token from Dhan Web
- Use API key based authentication method

### Access Token

Individual traders can directly get their Access Token from [web.dhan.co](https://web.dhan.co). Here's how:

1. Login to [web.dhan.co](https://web.dhan.co)
2. Click on **My Profile** and navigate to **Access DhanHQ APIs**
3. Generate **Access Token** for a validity of 24 hours
4. Optionally enter a Postback URL while generating the token, to get order updates as [Postback](/api/v2/guides/postback)

For API-based token flows, use:

- [Generate Token](/api/v2/authentication/generate-token)
- [Renew Token](/api/v2/authentication/renew-token)

### API Key & Secret

Individuals can also login with an OAuth-based flow. All Dhan users can generate an individual API key and secret.

**To generate API key and secret:**

1. Login to [web.dhan.co](https://web.dhan.co)
2. Click on **My Profile** and navigate to **Access DhanHQ APIs**
3. Toggle to **API key** and enter your app name
4. Enter **App name**, **Redirect URL** and **Postback URL** as needed

> **note:** API Key & Secret are valid for 12 months from the date of generation.

After getting the API key and secret, the full flow is:

1. [Generate Consent](/api/v2/authentication/api-key-generate-consent)
2. Browser login
3. [Consume Consent](/api/v2/authentication/api-key-consume-consent)

#### Step 2: Browser Based Login

This endpoint needs to be opened directly on a browser. On this step, the user needs to enter their Dhan credentials, validate with 2FA like OTP, pin, or password. If the login is successful, the user is redirected to the URL provided while generating the API key. Along with the redirect, Dhan sends a `tokenId` which is used in the consume-consent step.

> **note:** This ends with a `302` redirect on the browser. You can consume the `tokenId` from the path parameter directly.

**Request URL**

```text
https://auth.dhan.co/login/consentApp-login?consentAppId={consentAppId}
```

**Path Parameter**

- `consentAppId` — Temporary session ID created in the generate-consent stage

**Response**

```text
{redirect_URL}/?tokenId={Token ID for user}
```

---

## For Partners

Once a partner receives `partner_id` and `partner_secret`, they can use this authentication mechanism for their users.

This login method is a three-step flow for platforms where the user logs into their Dhan account from the third-party product itself.

1. [Generate Consent](/api/v2/authentication/partner-generate-consent)
2. Browser login for user
3. [Consume Consent](/api/v2/authentication/partner-consume-consent)

#### Step 2: Dhan Login on Browser for User

This endpoint needs to be opened directly on a browser tab for browser-based applications or on a webview for mobile apps. On this step, the end user enters their Dhan credentials, validates with 2FA, and is redirected with a `tokenId` for the final consume-consent step.

![Partner Browser Login Flow]()

> **note:** This ends with a `302` redirect on the browser. You can consume the `tokenId` from the path parameter directly.

**Request URL**

```text
https://auth.dhan.co/consent-login?consentId={consentId}
```

**Path Parameter**

- `consentId` — Temporary session ID created in the partner generate-consent stage

**Response**

```text
{redirect_URL}/?tokenId={Token ID for user}
```

---

## Setup Static IP

Static IP whitelisting is mandatory as per the new SEBI and exchange guidelines.

In line with this, you can use the API pages below to set Static IP for your account, or use Dhan Web to set it up manually.

- [Set IP](/api/v2/authentication/set-ip)
- [Modify IP](/api/v2/authentication/modify-ip)
- [Get IP](/api/v2/authentication/get-ip)

Do note that each individual needs to have a unique static IP. Once an IP is whitelisted, it cannot be edited for the next 7 days or as recommended by the exchange.

Do note that Static IP is only required while using Order Placement APIs including Orders and Super Order. While fetching order details or trade details, no such IP whitelisting is required.

> **info:** A static IP is a fixed, permanent internet address for your device or server. Unlike the default IP on home Wi-Fi, a static IP does not change. To use one, you need to request and purchase it separately from your Internet Service Provider (ISP).

---

## Setup TOTP

As an API user, you can setup TOTP to simplify authentication for API-only flows, as an alternative to OTP received on email or mobile number.

### What is TOTP?

Time-based One-Time Password (TOTP) is a 6-digit code generated from a shared secret and current time (RFC 6238). Once you enable TOTP for your account, you’ll receive a secret (via QR/code) that your server can use to generate a fresh code every 30 seconds.

### How to Set Up TOTP

1. Go to Dhan Web → DhanHQ Trading APIs section
2. Select **Setup TOTP**
3. Confirm with OTP on mobile/email
4. Scan the QR via an Authenticator app or enter the code shown
5. Confirm by entering the first TOTP

Once this is setup, you will by default see TOTP as an option while logging into partner platforms or inside the API key based authentication mode.

---

## User Profile

User Profile API can be used to check validity of access token and account setup. It is a simple `GET` request and can be a good first validation call during integration.

```bash
curl --location 'https://api.dhan.co/v2/profile' \
  --header 'access-token: {JWT}'
```

---

## Conditional Trigger

Place, modify, delete and retrieve conditional trigger orders based on price or technical indicators

The Conditional Trigger API lets you place orders based on set conditions. These conditions can be based on price or technical indicators or a combination of both. You can set one or multiple orders to be triggered when the condition is met.

When a conditional order is triggered, you will receive a postback update if [configured](/api/v2/guides/postback).

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/alerts/orders` | Place Conditional Trigger |
| PUT | `/alerts/orders/{alertId}` | Modify Conditional Trigger |
| DELETE | `/alerts/orders/{alertId}` | Delete Conditional Trigger |
| GET | `/alerts/orders/{alertId}` | Get Conditional Trigger by ID |
| GET | `/alerts/orders` | Get All Conditional Triggers |

> **note:** - Conditional Triggers are currently supported only for Equities and Indices.
> - You can receive postback updates by providing a Webhook URL while generating the Access Token.

---

## Place Conditional Trigger

Create a new conditional trigger with conditions (price or technical indicators) that, when met, place one or multiple orders automatically.

```bash
curl --request POST \
  --url https://api.dhan.co/v2/alerts/orders \
  --header 'Accept: application/json' \
  --header 'Content-Type: application/json' \
  --header 'access-token: {JWT}' \
  --data '{Request Body}'
```

**Request Structure**

```json
{
  "dhanClientId": "123456789",
  "condition": {
    "comparisonType": "TECHNICAL_WITH_VALUE",
    "exchangeSegment": "NSE_EQ",
    "securityId": "12345",
    "indicatorName": "SMA_5",
    "timeFrame": "DAY",
    "operator": "CROSSING_UP",
    "comparingValue": 250,
    "expDate": "2019-08-24",
    "frequency": "ONCE",
    "userNote": "Price crossing SMA"
  },
  "orders": [
    {
      "transactionType": "BUY",
      "exchangeSegment": "NSE_EQ",
      "productType": "CNC",
      "orderType": "LIMIT",
      "securityId": "12345",
      "quantity": 10,
      "validity": "DAY",
      "price": "250.00",
      "discQuantity": "0",
      "triggerPrice": "0"
    }
  ]
}
```


| Parameter | Data Type | Description | Sample Value |
|-----------|-----------|-------------|--------------|
| `condition`* | object | Alert condition configuration | — |
| `condition.comparisonType`* | string | Type of comparison ([see Annexure](/api/v2/guides/annexure#comparison-type)) | `TECHNICAL_WITH_VALUE` |
| `condition.timeframe`* | string | Timeframe for indicator evaluation — `DATE` `ONE_MIN` `FIVE_MIN` `FIFTEEN_MIN` | `DAY` |
| `condition.exchangeSegment`* | enum | Exchange — `NSE_EQ` `BSE_EQ` `IDX_I` | `NSE_EQ` |
| `condition.securityId`* | string | Exchange standard ID for scrip ([Instruments](/api/v2/guides/instruments)) | `12345` |
| `condition.indicatorName`** | string | Technical indicator ([see Annexure](/api/v2/guides/annexure#indicator-name)) | `SMA_5` |
| `condition.operator`* | string | Condition operator ([see Annexure](/api/v2/guides/annexure#operator)) | `CROSSING_UP` |
| `condition.comparingValue`** | number | Value for comparison | `250` |
| `condition.comparingIndicatorName`** | string | Technical indicator ([see Annexure](/api/v2/guides/annexure#indicator-name)) | `SMA_10` |
| `condition.expDate`* | string (date) | Expiry date of alert (default: 1 year) | `2019-08-24` |
| `condition.frequency`* | string | Trigger frequency | `ONCE` |
| `condition.userNote` | string | User-provided note | `Price crossing SMA` |
| `orders` | array[obj] | List of orders to execute when triggered | — |
| `orders.transactionType`* | enum | `BUY` or `SELL` | `BUY` |
| `orders.exchangeSegment`* | enum | Exchange Segment ([see Annexure](/api/v2/guides/annexure#exchange-segment)) | `NSE_EQ` |
| `orders.productType`* | enum | `CNC` `INTRADAY` `MARGIN` `MTF` | `CNC` |
| `orders.orderType`* | enum | `LIMIT` `MARKET` `STOP_LOSS` `STOP_LOSS_MARKET` | `LIMIT` |
| `orders.securityId`* | string | Exchange standard ID ([Instruments](/api/v2/guides/instruments)) | `12345` |
| `orders.quantity`* | integer | Number of shares | `10` |
| `orders.validity`* | enum | `DAY` or `IOC` | `DAY` |
| `orders.price`* | string | Price at which order is placed | `250` |
| `orders.discQuantity` | string | Disclosed quantity (≥30% of quantity) | `0` |
| `orders.triggerPrice`** | string | Trigger price for SL-M & SL-L | `0` |

**Response**

```json
{
  "alertId": "12345",
  "alertStatus": "ACTIVE"
}
```

---

## Modify Conditional Trigger

Modify a conditional trigger logic and/or the associated order execution parameters.

```bash
curl --request PUT \
  --url https://api.dhan.co/v2/alerts/orders/{alertId} \
  --header 'Accept: application/json' \
  --header 'Content-Type: application/json' \
  --header 'access-token: {JWT}' \
  --data '{Request Body}'
```

The request structure and parameters are the same as [Place Conditional Trigger](#place-conditional-trigger), with the addition of `alertId` as a path parameter.

**Response**

```json
{
  "alertId": "12345",
  "alertStatus": "ACTIVE"
}
```

---

## Delete Conditional Trigger

Delete an existing conditional trigger using its `alertId`.

```bash
curl --request DELETE \
  --url https://api.dhan.co/v2/alerts/orders/{alertId} \
  --header 'Accept: application/json' \
  --header 'access-token: {JWT}'
```

**Response**

```json
{
  "alertId": "12345",
  "alertStatus": "CANCELLED"
}
```

---

## Get Conditional Trigger by ID

Retrieve status and details for a specific trigger by its `alertId`.

```bash
curl --request GET \
  --url https://api.dhan.co/v2/alerts/orders/{alertId} \
  --header 'Accept: application/json' \
  --header 'access-token: {JWT}'
```

**Response**

```json
{
  "alertId": "12345",
  "alertStatus": "ACTIVE",
  "createdTime": "2019-08-24T14:15:22Z",
  "triggeredTime": null,
  "lastPrice": "245.50",
  "condition": {
    "comparisonType": "TECHNICAL_WITH_VALUE",
    "exchangeSegment": "NSE_EQ",
    "securityId": "12345",
    "indicatorName": "SMA_5",
    "timeFrame": "DAY",
    "operator": "CROSSING_UP",
    "comparingValue": "250.00",
    "expDate": "2019-08-24",
    "frequency": "ONCE",
    "userNote": "Price crossing SMA"
  },
  "orders": [
    {
      "transactionType": "BUY",
      "exchangeSegment": "NSE_EQ",
      "productType": "CNC",
      "orderType": "LIMIT",
      "securityId": "12345",
      "quantity": 10,
      "validity": "DAY",
      "price": "250.00",
      "discQuantity": "0",
      "triggerPrice": "0"
    }
  ]
}
```

**Additional Response Fields**

| Parameter | Data Type | Description |
|-----------|-----------|-------------|
| `alertId` | string | Unique identifier of the alert |
| `alertStatus` | string | Status ([see Annexure](/api/v2/guides/annexure#status)) |
| `createdTime` | string | Timestamp when alert was created |
| `triggeredTime` | string | Timestamp when alert was triggered |
| `lastPrice` | string | Last price of the instrument |

---

## Get All Conditional Triggers

Retrieve all conditional triggers for the authenticated account.

```bash
curl --request GET \
  --url https://api.dhan.co/v2/alerts/orders \
  --header 'Accept: application/json' \
  --header 'access-token: {JWT}'
```

**Response** — Returns an array of trigger objects with the same structure as [Get by ID](#get-conditional-trigger-by-id).

For description of enum values, refer to the [Annexure](/api/v2/guides/annexure).

---

## EDIS

Generate T-PIN, eDIS form and inquire stock approval status for selling holdings

To sell holding stocks, one needs to complete the CDSL eDIS flow — generate T-PIN & mark stock to complete the sell action.

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/edis/tpin` | Generate T-PIN |
| POST | `/edis/form` | Retrieve escaped HTML form & enter T-PIN |
| GET | `/edis/inquire/{isin}` | Inquire the status of stock for eDIS approval |

---

## Generate T-PIN

Get T-Pin on your registered mobile number using this API.

```bash
curl --request GET \
  --url https://api.dhan.co/v2/edis/tpin \
  --header 'Content-Type: application/json' \
  --header 'access-token: {JWT}'
```

**Request** — No Body

**Response** — `202 Accepted`

---

## Generate eDIS Form

Retrieve escaped HTML form of CDSL and enter T-PIN to mark the stock for EDIS approval. User has to render this form at their end to unescape. You can get ISIN of portfolio stocks in the response of Holdings API.

```bash
curl --request POST \
  --url https://api.dhan.co/v2/edis/form \
  --header 'Content-Type: application/json' \
  --header 'access-token: {JWT}' \
  --data '{}'
```

**Request Structure**

```json
{
    "isin": "INE733E01010",
    "qty": 1,
    "exchange": "NSE",
    "segment": "EQ",
    "bulk": true
}
```


**Response Structure**

```json
{
    "dhanClientId": "1000000401",
    "edisFormHtml": "<!DOCTYPE html> <html>...</html>"
}
```


---

## EDIS Status & Inquiry

Check the status of a stock — whether it is approved and marked for sell action. Pass the ISIN of the stock (12-digit alphanumeric code). You can get ISIN from the Holdings API response.

Alternatively, pass `ALL` instead of ISIN to get eDIS status of all holdings in your portfolio.

```bash
curl --request GET \
  --url https://api.dhan.co/v2/edis/inquire/{isin} \
  --header 'Content-Type: application/json' \
  --header 'access-token: {JWT}'
```

**Request** — No Body

**Response**

```json
{
    "clientId": "1000000401",
    "isin": "INE00IN01015",
    "totalQty": 10,
    "aprvdQty": 4,
    "status": "SUCCESS",
    "remarks": "eDIS transaction done successfully"
}
```


For description of enum values, refer to the [Annexure](/api/v2/guides/annexure).


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| isin | string | No | International Securities Identification Number |
| qty | int | No | Number of shares to mark for eDIS transaction |
| exchange | string | No | or Values: `NSE`, `BSE`. |
| segment | string | No | Values: `EQ`. |
| bulk | boolean | No | To mark eDIS for all stocks in portfolio |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| dhanClientId | string | No | User specific identification |
| edisFormHtml | string | No | Escaped HTML Form — render at your end to unescape |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| clientId | string | No | User specific identification |
| isin | string | No | International Securities Identification Number |
| totalQty | string | No | Total number of shares |
| aprvdQty | string | No | Number of approved stocks |
| status | string | No | Status of the eDIS order |
| remarks | string | No | Remarks of the order status |

---

## Error Handling

DhanHQ API error types and response format

All DhanHQ API error responses follow a consistent structure.

## Error Response Format

```json
{
  "status": "failure",
  "errorType": "VALIDATION_ERROR",
  "errorCode": "E001",
  "errorMessage": "Invalid security ID"
}
```

## Error Types

| Error Type | HTTP Code | Description |
|------------|-----------|-------------|
| `VALIDATION_ERROR` | 400 | Invalid request parameters |
| `AUTHENTICATION_ERROR` | 401 | Invalid or expired access token |
| `AUTHORIZATION_ERROR` | 403 | Insufficient permissions |
| `RATE_LIMIT_ERROR` | 429 | Too many requests |
| `INTERNAL_ERROR` | 500 | Server-side error |

## Handling in Python

```python
from dhanhq import DhanContext, dhanhq

context = DhanContext("client_id", "access_token")
dhan = dhanhq(context)

response = dhan.place_order(
    security_id="1333",
    exchange_segment="NSE_EQ",
    transaction_type="BUY",
    quantity=10,
    order_type="MARKET",
    product_type="INTRADAY"
)

if response.get("status") == "failure":
    error_type = response.get("errorType")
    error_msg = response.get("errorMessage")
    print(f"Error [{error_type}]: {error_msg}")
```

## Common Error Scenarios

### Invalid Security ID
```json
{
  "status": "failure",
  "errorType": "VALIDATION_ERROR",
  "errorCode": "E001",
  "errorMessage": "Invalid security ID"
}
```

### Expired Token
```json
{
  "status": "failure",
  "errorType": "AUTHENTICATION_ERROR",
  "errorCode": "AUTH001",
  "errorMessage": "Invalid or expired access token"
}
```

### Rate Limit Exceeded
```json
{
  "status": "failure",
  "errorType": "RATE_LIMIT_ERROR",
  "errorCode": "RL001",
  "errorMessage": "Too many requests. Please retry after 1 second."
}
```

:::tip Retry Strategy
For `RATE_LIMIT_ERROR`, implement exponential backoff with a minimum delay of 1 second between retries.
:::

---

## Expired Options Data

Fetch expired options contract data on a rolling basis with OHLC, IV, OI and spot data

This API gives you expired options contract data. Pre-processed data is available on a rolling basis — fetch the last 5 years of strike-wise data based on ATM and up to 10 strikes above and below.

Data values include: **open, high, low, close, implied volatility, volume, open interest** and **spot** information.

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/charts/rollingoption` | Get Continuous Expired Options Contract data |

---

## Historical Rolling Data

Fetch expired options data on a rolling basis, along with OI, IV, OHLC, Volume and spot information. You can fetch up to **30 days** of data per API call. Data is stored on a minute level, based on strike price relative to spot (e.g., ATM, ATM+1, ATM-1).

Both **Index Options** and **Stock Options** data are available for the last 5 years.

```bash
curl --request POST \
  --url https://api.dhan.co/v2/charts/rollingoption \
  --header 'Accept: application/json' \
  --header 'Content-Type: application/json' \
  --header 'access-token: {JWT}' \
  --data '{}'
```

**Request Structure**

```json
{
    "exchangeSegment": "NSE_FNO",
    "interval": "1",
    "securityId": 13,
    "instrument": "OPTIDX",
    "expiryFlag": "MONTH",
    "expiryCode": 1,
    "strike": "ATM",
    "drvOptionType": "CALL",
    "requiredData": ["open", "high", "low", "close", "volume"],
    "fromDate": "2021-08-01",
    "toDate": "2021-09-01"
}
```


**Response Structure**

```json
{
    "data": {
        "ce": {
            "iv": [],
            "oi": [],
            "strike": [],
            "spot": [],
            "open": [354, 360.3],
            "high": [],
            "low": [],
            "close": [],
            "volume": [],
            "timestamp": [1756698300, 1756699200]
        },
        "pe": null
    }
}
```


For description of enum values, refer to the [Annexure](/api/v2/guides/annexure).


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| exchangeSegment | enum | Yes | Exchange & segment ([Annexure](/api/v2/guides/annexure#exchange-segment)) |
| interval | enum int | Yes | Minute intervals — , , , , Values: `1`, `5`, `15`, `25`, `60`. |
| securityId | string | Yes | Underlying exchange standard ID ([Instruments](/api/v2/guides/instruments)) |
| instrument | enum | Yes | Instrument type ([Annexure](/api/v2/guides/annexure#instrument)) |
| expiryCode | enum int | Yes | Expiry ([Annexure](/api/v2/guides/annexure#expiry-code)) |
| expiryFlag | enum | Yes | or Values: `WEEK`, `MONTH`. |
| strike | enum | Yes | for At the Money, up to / for Index Options near expiry, up to / for other contracts Values: `ATM`, `ATM+10`, `ATM-10`, `ATM+3`, `ATM-3`. |
| drvOptionType | enum | Yes | or Values: `CALL`, `PUT`. |
| requiredData | array | Yes | Requested fields — Values: `open`, `high`, `low`, `close`, `iv`, `volume`, `strike`, `oi`, `spot`. |
| fromDate | string | Yes | Start date (YYYY-MM-DD) |
| toDate | string | Yes | End date (non-inclusive) |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| open | float | No | Open price of the timeframe |
| high | float | No | High price |
| low | float | No | Low price |
| close | float | No | Close price |
| volume | int | No | Volume traded |
| timestamp | int | No | Epoch timestamp |

---

## Full Market Depth

20 and 200 level market depth via WebSocket for NSE Equity and Derivatives

Level 3 data includes market depth upto 20 levels. We are extending beyond and adding **200 level data**. This shows complete picture of the market movements and it is streamed real-time via websockets.

This data can be used to detect demand supply zones, outside of 5 level market depth and build trading systems to detect market movements.


  Only NSE Equity and Derivatives segments are enabled for Full Market Depth.


Similar to [Live Market Feed](/api/v2/guides/live-market-feed), all request messages over WebSocket are in JSON whereas all response messages over WebSocket are in Binary.

## Establishing Connection

### 20 Level

To establish connection with DhanHQ WebSocket for 20 Level Market Depth, you can connect to the below endpoint using WebSocket library.

```
wss://depth-api-feed.dhan.co/twentydepth?token=eyxxxxx&clientId=100xxxxxxx&authType=2
```

### 200 Level

To establish connection with DhanHQ WebSocket for 200 Level Market Depth, you can connect to the below endpoint using WebSocket library.

```
wss://full-depth-api.dhan.co/twohundreddepth?token=eyxxxxx&clientId=100xxxxxxx&authType=2
```

**Query Parameters**

| Field | Description |
|-------|-------------|
| token* | Access Token generated via Dhan |
| clientId* | User specific identification generated by Dhan |
| authType* | 2 by Default |

## Adding Instruments

### 20 Level

For 20 Level Market Depth, you can subscribe upto 50 instruments in a single connection and receive market data packets.

For subscribing, this can be done using JSON message which needs to be sent over WebSocket connection.

:::note Note
You can send all 50 instruments in a single JSON message for 20 Depth. You can send multiple messages over a single connection as well to subscribe to all instruments in parts and receive data.
:::

**Request Structure**

```json
{
    "RequestCode" : 23,
    "InstrumentCount" : 1,
    "InstrumentList" : [
        {
            "ExchangeSegment" : "NSE_EQ",
            "SecurityId" : "1333"
        }
    ]
}
```

### 200 Level

In 200 level market depth, only 1 instrument per connection can be subscribed. The JSON payload needs to be sent similar to 20 level depth subscription, while the socket connection has been established.

**Request Structure**

```json
{
    "RequestCode" : 23,
    "ExchangeSegment" : "NSE_EQ",
    "SecurityId" : "1333"
}
```

## Keeping Connection Alive

To keep the WebSocket connection alive and prevent it from closing, the server side uses **Ping-Pong** module. Server side sends ping every 10 seconds to the client server (in this case, your system) to maintain WebSocket status as open.

An automated pong is sent by websocket library. You can use the same as response to the ping.


In case the client server does not respond for more than 40 seconds, the connection is closed from server side and you will have to reestablish connection.


## Response Structure

The market depth data is sent as structured binary packet. It will require parsing to readable format to extract the relevant information.

All responses from Dhan Market Feed consists of [Response Header](#response-header) and Payload. Header for every response message remains the same with different [feed response code](/api/v2/guides/annexure#feed-response-code), while the payload can be different.

### 20 Level

#### Response Header

The response header message is of 12 bytes which will remain as part of the response message. The message structure is given as below.

| Bytes | Type | Size | Description |
|-------|------|------|-------------|
| 1-2 | int16 | 2 | Message Length of the entire payload packet |
| 3 | [ ] byte | 1 | Feed Response Code can be referred in [Annexure](/api/v2/guides/annexure#feed-response-code) |
| 4 | [ ] byte | 1 | Exchange Segment can be referred in [Annexure](/api/v2/guides/annexure#exchange-segment) |
| 5-8 | int32 | 4 | Security ID - can be found [here](/api/v2/guides/instruments) |
| 9-12 | uint32 | 4 | Message Sequence (to be ignored) |

**Depth Packet**
Depth Data Packet for 20 level market depth is structured differently from 5 level depth. Over here, you will receive the bid (sell) and ask (buy) data packets separately, each containing 20 packets of 16 bytes each.

| Bytes | Type | Size | Description |
|-------|------|------|-------------|
| 0-12 | [ ] array | 12 | [Response Header](#response-header)
`41` for Bid Data (Buy)
`51` for Ask Data (Sell) (see Annexure) |
| 13-332 | Bid/Ask Depth Structure | 320 | 20 packets of 16 bytes each for each instrument in below provided structure |

Each of these 20 packets will be received in the following packet structure:

| Bytes | Type | Size | Description |
|-------|------|------|-------------|
| 1-8 | float64 | 8 | Price |
| 9-12 | uint32 | 4 | Quantity |
| 13-16 | uint32 | 4 | No. of Orders |

### 200 Level

#### Response Header

The response header message is of 12 bytes which will remain as part of the response message. The message structure is given as below.

| Bytes | Type | Size | Description |
|-------|------|------|-------------|
| 1-2 | int16 | 2 | Message Length of the entire payload packet |
| 3 | [ ] byte | 1 | Feed Response Code can be referred in [Annexure](/api/v2/guides/annexure#feed-response-code) |
| 4 | [ ] byte | 1 | Exchange Segment can be referred in [Annexure](/api/v2/guides/annexure#exchange-segment) |
| 5-8 | int32 | 4 | Security ID - can be found [here](/api/v2/guides/instruments) |
| 9-12 | uint32 | 4 | No of Rows - gives number of rows to be read for response |

**Depth Packet**
200 level market depth is structured similar to 20 level depth. Over here, you will receive the bid (sell) and ask (buy) data packets separately, each containing multiple packets of 16 bytes each.

| Bytes | Type | Size | Description |
|-------|------|------|-------------|
| 0-12 | [ ] array | 12 | [Response Header](#response-header-1)
`41` for Bid Data (Buy)
`51` for Ask Data (Sell) (see Annexure) |
| 13-3212 | Bid/Ask Depth Structure | 3200 | 200 packets of 16 bytes each for each instrument in below provided structure |

Each of these 200 packets will be received in the following packet structure:

| Bytes | Type | Size | Description |
|-------|------|------|-------------|
| 1-8 | float64 | 8 | Price |
| 9-12 | uint32 | 4 | Quantity |
| 13-16 | uint32 | 4 | No. of Orders |

:::note Note
Whenever 20 or 200 level depth packets are sent on the connection, they are stacked one after another in a single message. For 20 level depth, if two instruments are subscribed, then the first instrument's Bid packet followed by Ask packet of that instrument is added and then the second instrument's bid and ask packets in same sequence. To handle this, you can break down the packet on the basis of length.
:::

## Feed Disconnect

If you want to disconnect WebSocket, you can send below JSON request message via the connection.

```json
{
    "RequestCode" : 12
}
```

In case of WebSocket disconnection from server side, you will receive disconnection packet, which will have disconnection reason code.

- If more than 5 websockets are established, then the first socket will be disconnected with `805` with every additional connection.

| Bytes | Type | Size | Description |
|-------|------|------|-------------|
| 0-12 | [ ] array | 8 | [Response Header](#response-header-1) with code `50` (see Annexure) |
| 13-14 | int16 | 2 | Disconnection message code - [here](/api/v2/guides/annexure#data-api-error) |

You can find detailed Disconnection message code description [here](/api/v2/guides/annexure#data-api-error).


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| RequestCode | int | Yes | Code for subscribing to particular data mode for Full Market Depth (see [Annexure](/api/v2/guides/annexure#feed-request-code)) Values: `23`. |
| InstrumentCount | int | Yes | No. of instruments to subscribe from this request |
| InstrumentList.ExchangeSegment | enum string | Yes | Exchange Segment of instrument to be subscribed (see [Annexure](/api/v2/guides/annexure#exchange-segment)) |
| InstrumentList.SecurityId | string | Yes | Exchange standard ID for each scrip. refer here |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| RequestCode | int | Yes | Code for subscribing to particular data mode for Full Market Depth (see [Annexure](/api/v2/guides/annexure#feed-request-code)) Values: `23`. |
| ExchangeSegment | enum string | Yes | Exchange Segment of instrument to be subscribed (see [Annexure](/api/v2/guides/annexure#exchange-segment)) |
| SecurityId | string | Yes | Exchange standard ID for each scrip. refer here |

---

## Getting Started

Get started with DhanHQ API for algorithmic trading

with DhanHQ API


DhanHQ API Ver 2.0 is a state-of-the-art platform for building trading and investment services & strategies. It provides REST APIs supported in all languages, allowing seamless integration with your applications.

## 1. Create an Account

Sign up at [dhan.co](https://dhan.co) and complete KYC verification.

## 2. Generate API Credentials

Navigate to your account settings to generate:
- **Client ID**: Your unique identifier
- **Access Token**: JWT authentication token for API requests

## 3. Install the SDK

```bash
pip install dhanhq
```

## 4. Initialize the Client

```python
from dhanhq import DhanContext, dhanhq

context = DhanContext("YOUR_CLIENT_ID", "YOUR_ACCESS_TOKEN")
dhan = dhanhq(context)
```

## 5. Place Your First Order

```python
response = dhan.place_order(
    security_id="1333",
    exchange_segment="NSE_EQ",
    transaction_type="BUY",
    quantity=10,
    order_type="MARKET",
    product_type="INTRADAY"
)
print(response)
```

## API Structure

All API requests follow REST conventions with JSON request/response bodies.

### Base URLs

| Environment | URL | Description |
|-------------|-----|-------------|
| **Production** | `https://api.dhan.co/v2` | Live trading environment |
| **Sandbox** | `https://sandbox.dhan.co/v2` | Testing environment |

### Request Headers

| Header | Required | Description |
|--------|----------|-------------|
| `access-token` | Yes | JWT access token from DhanHQ |
| `Content-Type` | Yes | `application/json` |

## What's Next?

- **[Authentication](/api/v2/guides/authentication)** — Learn about access tokens and security
- **[API Reference](/api/v2/)** — Browse all 31+ API endpoints
- **[Python SDK](/api/v2/guides/sdks/python)** — Full Python SDK reference
- **[Rate Limits](/api/v2/guides/rate-limits)** — Understand API rate limits

---

## Instrument List

Fetch tradable instrument lists with Security IDs and column descriptions

You can fetch instrument lists for all instruments tradable via Dhan using these URLs:

**Compact:**

```
https://images.dhan.co/api-data/api-scrip-master.csv
```

**Detailed:**

```
https://images.dhan.co/api-data/api-scrip-master-detailed.csv
```

This fetches a CSV with Security IDs and other important details for building with DhanHQ APIs.

---

## Segmentwise List

Fetch a detailed instrument list for a particular exchange and segment:

```bash
curl --location 'https://api.dhan.co/v2/instrument/{exchangeSegment}'
```

> **note:** This fetches instruments for one `exchangeSegment` at a time. The mapping can be found in [Annexure](/api/v2/guides/annexure#exchange-segment).

---

## Column Description

| Detailed Tag | Compact Tag | Description |
|---|---|---|
| `EXCH_ID` | `SEM_EXM_EXCH_ID` | Exchange — `NSE` `BSE` `MCX` |
| `SEGMENT` | `SEM_SEGMENT` | `C` (Currency), `D` (Derivatives), `E` (Equity), `M` (Commodity) |
| `ISIN` | — | ISIN — 12-digit alphanumeric code |
| `INSTRUMENT` | `SEM_INSTRUMENT_NAME` | Instrument defined by Exchange ([Annexure](/api/v2/guides/annexure#instrument)) |
| — | `SEM_EXPIRY_CODE` | Expiry Code for Futures ([Annexure](/api/v2/guides/annexure#expiry-code)) |
| `UNDERLYING_SECURITY_ID` | — | Security ID of underlying (Derivatives) |
| `UNDERLYING_SYMBOL` | — | Symbol of underlying (Derivatives) |
| `SYMBOL_NAME` | `SM_SYMBOL_NAME` | Symbol name |
| — | `SEM_TRADING_SYMBOL` | Exchange trading symbol |
| `DISPLAY_NAME` | `SEM_CUSTOM_SYMBOL` | Dhan display symbol name |
| `INSTRUMENT_TYPE` | `SEM_EXCH_INSTRUMENT_TYPE` | Exchange-defined instrument type |
| `SERIES` | `SEM_SERIES` | Exchange-defined series |
| `LOT_SIZE` | `SEM_LOT_UNITS` | Lot Size |
| `SM_EXPIRY_DATE` | `SEM_EXPIRY_DATE` | Expiry date (Derivatives) |
| `STRIKE_PRICE` | `SEM_STRIKE_PRICE` | Options Strike Price |
| `OPTION_TYPE` | `SEM_OPTION_TYPE` | `CE` (Call) or `PE` (Put) |
| `TICK_SIZE` | `SEM_TICK_SIZE` | Minimum price increment |
| `EXPIRY_FLAG` | `SEM_EXPIRY_FLAG` | `M` (Monthly) or `W` (Weekly) |
| `BRACKET_FLAG` | — | Bracket order — `N` (Not available), `Y` (Allowed) |
| `COVER_FLAG` | — | Cover order — `N` (Not available), `Y` (Allowed) |
| `ASM_GSM_FLAG` | — | ASM/GSM — `N` (No), `R` (Removed), `Y` (Yes) |
| `ASM_GSM_CATEGORY` | — | ASM/GSM category (`NA` if none) |
| `BUY_SELL_INDICATOR` | — | `A` if both Buy/Sell allowed |
| `BUY_CO_MIN_MARGIN_PER` | — | Buy cover order min margin (%) |
| `SELL_CO_MIN_MARGIN_PER` | — | Sell cover order min margin (%) |
| `BUY_CO_SL_RANGE_MAX_PERC` | — | Buy CO max SL range (%) |
| `SELL_CO_SL_RANGE_MAX_PERC` | — | Sell CO max SL range (%) |
| `BUY_CO_SL_RANGE_MIN_PERC` | — | Buy CO min SL range (%) |
| `SELL_CO_SL_RANGE_MIN_PERC` | — | Sell CO min SL range (%) |
| `BUY_BO_MIN_MARGIN_PER` | — | Buy bracket order min margin (%) |
| `SELL_BO_MIN_MARGIN_PER` | — | Sell bracket order min margin (%) |
| `BUY_BO_SL_RANGE_MAX_PERC` | — | Buy BO max SL range (%) |
| `SELL_BO_SL_RANGE_MAX_PERC` | — | Sell BO max SL range (%) |
| `BUY_BO_SL_RANGE_MIN_PERC` | — | Buy BO min SL range (%) |
| `SELL_BO_SL_MIN_RANGE` | — | Sell BO min SL range (%) |
| `BUY_BO_PROFIT_RANGE_MAX_PERC` | — | Buy BO max target range (%) |
| `SELL_BO_PROFIT_RANGE_MAX_PERC` | — | Sell BO max target range (%) |
| `BUY_BO_PROFIT_RANGE_MIN_PERC` | — | Buy BO min target range (%) |
| `SELL_BO_PROFIT_RANGE_MIN_PERC` | — | Sell BO min target range (%) |
| `MTF_LEVERAGE` | — | MTF leverage available (x multiple) for eligible Equity instruments |

---

## Live Market Feed

Real-time market data streaming via WebSocket — ticker, quote, and full packets

Real-time Market Data across exchanges and segments can now be availed on your system via WebSocket. WebSocket provides an efficient means to receive live market data. WebSocket keeps a persistent connection open, allowing the server to push real-time data to your systems.

All Dhan platforms work on these same market feed WebSocket connections that deliver lightning fast market data to you. Do note that this is **tick-by-tick event based data** that is sent over the websocket.

You can establish upto five WebSocket connections per user with 5000 instruments on each connection.

All request messages over WebSocket are in JSON whereas all response messages over WebSocket are in Binary. You will require WebSocket library in any programming language to be able to use Live Market Feed along with Binary converter.


**Using DhanHQ Libraries for WebSockets**


- You can use [DhanHQ Python Library](https://github.com/dhan-hq/dhanhq-py) to quick start with Live Market Feed.


## Establishing Connection

To establish connection with DhanHQ WebSocket for Market Feed, you can connect to the below endpoint using WebSocket library.

```
wss://api-feed.dhan.co?version=2&token=eyxxxxx&clientId=100xxxxxxx&authType=2
```

**Query Parameters**

| Field | Description |
|-------|-------------|
| version* | 2 for DhanHQ v2 |
| token* | Access Token generated via Dhan |
| clientId* | User specific identification generated by Dhan |
| authType* | 2 by Default |

## Adding Instruments

You can subscribe upto 5000 instruments in a single connection and receive market data packets. For subscribing, this can be done using JSON message which needs to be send over WebSocket connection.

:::note Note
You can only send upto 100 instruments in a single JSON message. You can send multiple messages over a single connection to subscribe to all instruments and receive data.
:::

**Request Structure**

```json
{
    "RequestCode" : 15,
    "InstrumentCount" : 2,
    "InstrumentList" : [
        {
            "ExchangeSegment" : "NSE_EQ",
            "SecurityId" : "1333"
        },
        {
            "ExchangeSegment" : "BSE_EQ",
            "SecurityId" : "532540"
        }
    ]
}
```

## Keeping Connection Alive

To keep the WebSocket connection alive and prevent it from closing, the server side uses **Ping-Pong** module. Server side sends ping every 10 seconds to the client server (in this case, your system) to maintain WebSocket status as open.

An automated pong is sent by websocket library. You can use the same as response to the ping.

> **warning:** In case the client server does not respond for more than 40 seconds, the connection is closed from server side and you will have to reestablish connection.

## Market Data

The market feed data is sent as structured binary packet which is shared at super fast speed.

DhanHQ Live Market Feed is real-time data and there are three modes in which you can receive the data, depending on your use case:

- Ticker Data
- Quote Data
- Full Data

### Binary Response

Binary messages consist of sequences of bytes that represent the data. This contrasts with text messages, which use character encoding (e.g., UTF-8) to represent data in a readable format. Binary messages require parsing to extract the relevant information.

The reason for us to choose binary messages over text or JSON is to have compactness, speed and flexibility on data to be shared at lightning fast speed.

All responses from Dhan Market Feed consists of [Response Header](#response-header) and Payload. Header for every response message remains the same with different [feed response code](/api/v2/guides/annexure#feed-response-code), while the payload can be different.

**Endianness**
Endianness determines the order in which bytes are arranged for multi-byte data (like integers and floats).

**Types:**
- **Little Endian:** Least significant byte first (0x78, 0x56, 0x34, 0x12)
- **Big Endian:** Most significant byte first (0x12, 0x34, 0x56, 0x78)

The data on DhanHQ Websockets are sent in Little Endian. In case your system is Big Endian, you will have to define endianness while reading the websocket.

### Response Header

The response header message is of 8 bytes which will remain same as part of all the response messages. The message structure is given as below.

| Bytes | Type | Size | Description |
|-------|------|------|-------------|
| 1 | [ ] byte | 1 | Feed Response Code can be referred in [Annexure](/api/v2/guides/annexure#feed-response-code) |
| 2-3 | int16 | 2 | Message Length of the entire payload packet |
| 4 | [ ] byte | 1 | Exchange Segment can be referred in [Annexure](/api/v2/guides/annexure#exchange-segment) |
| 5-8 | int32 | 4 | Security ID - can be found [here](/api/v2/guides/instruments) |

### Ticker Packet

This packet consists of Last Traded Price (LTP) and Last Traded Time (LTT) data across segments.

| Bytes | Type | Size | Description |
|-------|------|------|-------------|
| 0-8 | [ ] array | 8 | [Response Header](#response-header) with code `2` (see Annexure) |
| 9-12 | float32 | 4 | Last Traded Price of the subscribed instrument |
| 13-16 | int32 | 4 | Last Trade Time (EPOCH) |

**Prev Close**
Whenever any instrument is subscribed for any data packet, we also send this packet which has Previous Day data to make it easier for day on day comparison.

| Bytes | Type | Size | Description |
|-------|------|------|-------------|
| 0-8 | [ ] array | 8 | [Response Header](#response-header) with code `6` (see Annexure) |
| 9-12 | float32 | 4 | Previous day closing price |
| 13-16 | int32 | 4 | Open Interest - previous day |

### Quote Packet

This data packet is for all instruments across segments and exchanges which consists of complete trade data, along with Last Trade Price (LTP) and other information like update time and quantity.

| Bytes | Type | Size | Description |
|-------|------|------|-------------|
| 0-8 | [ ] array | 8 | [Response Header](#response-header) with code `4` (see Annexure) |
| 9-12 | float32 | 4 | Latest Traded Price of the subscribed instrument |
| 13-14 | int16 | 2 | Last Traded Quantity |
| 15-18 | int32 | 4 | Last Trade Time (LTT) - EPOCH |
| 19-22 | float32 | 4 | Average Trade Price (ATP) |
| 23-26 | int32 | 4 | Volume |
| 27-30 | int32 | 4 | Total Sell Quantity |
| 31-34 | int32 | 4 | Total Buy Quantity |
| 35-38 | float32 | 4 | Day Open Value |
| 39-42 | float32 | 4 | Day Close Value - only sent post market close |
| 43-46 | float32 | 4 | Day High Value |
| 47-50 | float32 | 4 | Day Low Value |

**OI Data**
Whenever you subscribe to Quote Data, you also receive Open Interest (OI) data packets which is important for Derivative Contracts.

| Bytes | Type | Size | Description |
|-------|------|------|-------------|
| 0-8 | [ ] array | 8 | [Response Header](#response-header) with code `5` (see Annexure) |
| 9-12 | int32 | 4 | Open Interest of the contract |

### Full Packet

This data packet is for all instruments across segments and exchanges which consists of complete trade data along with Market Depth and OI data in a single packet.

| Bytes | Type | Size | Description |
|-------|------|------|-------------|
| 0-8 | [ ] array | 8 | [Response Header](#response-header) with code `8` (see Annexure) |
| 9-12 | float32 | 4 | Latest Traded Price of the subscribed instrument |
| 13-14 | int16 | 2 | Last Traded Quantity |
| 15-18 | int32 | 4 | Last Trade Time (LTT) - EPOCH |
| 19-22 | float32 | 4 | Average Trade Price (ATP) |
| 23-26 | int32 | 4 | Volume |
| 27-30 | int32 | 4 | Total Sell Quantity |
| 31-34 | int32 | 4 | Total Buy Quantity |
| 35-38 | int32 | 4 | Open Interest in the contract (for Derivatives) |
| 39-42 | int32 | 4 | Highest Open Interest for the da (only for NSE_FNO) |
| 43-46 | int32 | 4 | Lowest Open Interest for the day (only for NSE_FNO) |
| 47-50 | float32 | 4 | Day Open Value |
| 51-54 | float32 | 4 | Day Close Value - only sent post market close |
| 55-58 | float32 | 4 | Day High Value |
| 59-62 | float32 | 4 | Day Low Value |
| 63-162 | Market Depth Structure | 100 | 5 packets of 20 bytes each for each instrument in below provided structure |

Each of these 5 packets will be received in the following packet structure:

| Bytes | Type | Size | Description |
|-------|------|------|-------------|
| 1-4 | int32 | 4 | Bid Quantity |
| 5-8 | int32 | 4 | Ask Quantity |
| 9-10 | int16 | 2 | No. of Bid Orders |
| 11-12 | int16 | 2 | No. of Ask Orders |
| 13-16 | float32 | 4 | Bid Price |
| 17-20 | float32 | 4 | Ask Price |

## Feed Disconnect

If you want to disconnect WebSocket, you can send below JSON request message via the connection.

```json
{
    "RequestCode" : 12
}
```

In case of WebSocket disconnection from server side, you will receive disconnection packet, which will have disconnection reason code.

- If more than 5 websockets are established, then the first socket will be disconnected with `805` with every additional connection.

| Bytes | Type | Size | Description |
|-------|------|------|-------------|
| 0-8 | [ ] array | 8 | [Response Header](#response-header) with code `50` (see Annexure) |
| 9-10 | int16 | 2 | Disconnection message code - [here](/api/v2/guides/annexure#data-api-error) |

You can find detailed Disconnection message code description [here](/api/v2/guides/annexure#data-api-error).


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| RequestCode | int | Yes | Code for subscribing to particular data mode (see [Annexure](/api/v2/guides/annexure#feed-request-code)) |
| InstrumentCount | int | Yes | No. of instruments to subscribe from this request |
| InstrumentList.ExchangeSegment | enum string | Yes | Exchange Segment of instrument to be subscribed (see [Annexure](/api/v2/guides/annexure#exchange-segment)) |
| InstrumentList.SecurityId | string | Yes | Exchange standard ID for each scrip. refer here |

---

## Live Order Update

Real-time order updates via WebSocket for individuals and partners

Realtime order updates of all your orders can be received directly via WebSocket. Once you connect and authorise, all order updates in your account will get reflected in real time via the stream.

With this update stream, you can know about status, traded price, quantity and other details about your orders.

All messages are sent in **JSON** format over WebSocket.

---

## Establishing Connection

Connect to the DhanHQ Live Order Update WebSocket endpoint:

```
wss://api-order-update.dhan.co
```

After connecting, send an authorisation message.

### For Individual

Receive order updates for all orders placed via your account, irrespective of the platform.

**Authorisation Message**

```json
{
    "LoginReq": {
        "MsgCode": 42,
        "ClientId": "1000000001",
        "Token": "JWT"
    },
    "UserType": "SELF"
}
```


### For Partners

Platforms can receive order updates for all users connected to their platform via [Partner Login](/api/v2/guides/authentication#for-partners).

**Authorisation Message**

```json
{
    "LoginReq": {
        "MsgCode": 42,
        "ClientId": "partner_id"
    },
    "UserType": "PARTNER",
    "Secret": "partner_secret"
}
```


---

## Order Update

Order Update messages are sent via WebSocket in the following structure:

```json
{
    "Data": {
        "Exchange": "NSE",
        "Segment": "E",
        "Source": "N",
        "SecurityId": "14366",
        "ClientId": "1000000001",
        "ExchOrderNo": "1400000000404591",
        "OrderNo": "1124091136546",
        "Product": "C",
        "TxnType": "B",
        "OrderType": "LMT",
        "Validity": "DAY",
        "DiscQuantity": 1,
        "DiscQtyRem": 1,
        "RemainingQuantity": 1,
        "Quantity": 1,
        "TradedQty": 0,
        "Price": 13,
        "TriggerPrice": 0,
        "TradedPrice": 0,
        "AvgTradedPrice": 0,
        "OffMktFlag": "0",
        "OrderDateTime": "2024-09-11 14:39:29",
        "ExchOrderTime": "2024-09-11 14:39:29",
        "LastUpdatedTime": "2024-09-11 14:39:29",
        "Remarks": "NR",
        "MktType": "NL",
        "ReasonDescription": "CONFIRMED",
        "LegNo": 1,
        "Instrument": "EQUITY",
        "Symbol": "IDEA",
        "ProductName": "CNC",
        "Status": "Cancelled",
        "LotSize": 1,
        "ExpiryDate": "0001-01-01 00:00:00",
        "OptType": "XX",
        "DisplayName": "Vodafone Idea",
        "Isin": "INE669E01016",
        "Series": "EQ",
        "GoodTillDaysDate": "2024-09-11",
        "RefLtp": 13.21,
        "TickSize": 0.01,
        "AlgoId": "0",
        "Multiplier": 1,
        "CorrelationId": "",
        "Remarks": "Super Order"
    },
    "Type": "order_alert"
}
```


For description of enum values, refer to the [Annexure](/api/v2/guides/annexure).


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| LoginReq | object | Yes | JSON for Client ID and Access Token |
| MsgCode | int | Yes | Message Code —  by default Values: `42`. |
| ClientId | string | Yes | User specific identification |
| Token | string | Yes | Access Token |
| UserType | string | Yes | for individual users Values: `SELF`. |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| LoginReq | object | Yes | JSON for Client ID |
| MsgCode | int | Yes | by default Values: `42`. |
| ClientId | string | Yes | Partner ID |
| UserType | string | Yes | for partner platforms Values: `PARTNER`. |
| Secret | string | Yes | Partner Secret |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| Exchange | string | No | Exchange where order is placed |
| Segment | string | No | Segment for order |
| Source | string | No | Platform —  for API Orders Values: `P`. |
| SecurityId | string | No | Exchange standard ID ([Instruments](/api/v2/guides/instruments)) |
| ClientId | string | No | User specific identification |
| ExchOrderNo | string | No | Order ID generated by Exchange |
| OrderNo | string | No | Order ID generated by Dhan |
| Product | enum | No | (CNC),  (INTRADAY),  (MARGIN),  (MTF),  (CO),  (BO) Values: `C`, `I`, `M`, `F`, `V`, `B`. |
| TxnType | enum | No | (Buy),  (Sell) Values: `B`, `S`. |
| OrderType | enum | No | (Limit),  (Market),  (Stop Loss),  (Stop Loss Market) Values: `LMT`, `MKT`, `SL`, `SLM`. |
| Validity | enum | No | or Values: `DAY`, `IOC`. |
| DiscQuantity | int | No | Disclosed quantity |
| DiscQtyRem | int | No | Disclosed quantity pending |
| RemainingQuantity | int | No | Quantity pending for execution |
| Quantity | int | No | Total order quantity |
| TradedQty | int | No | Actual quantity executed |
| Price | float | No | Order price |
| TriggerPrice | float | No | Trigger price for SL-M, SL-L, CO & BO |
| TradedPrice | float | No | Price at which trade executed |
| AvgTradedPrice | float | No | Average trade price (differs from TradedPrice in partial execution) |
| AlgoOrdNo | float | No | Entry leg order number for BO and CO |
| OffMktFlag | string | No | for AMO order, else Values: `1`, `0`. |
| OrderDateTime | string | No | Time order received by Dhan |
| ExchOrderTime | string | No | Time order placed on Exchange |
| LastUpdatedTime | string | No | Last update time |
| Remarks | string | No | Additional remarks (e.g. ) Values: `Super Order`. |
| MktType | string | No | (Normal), // (Auction) Values: `NL`, `AU`, `A1`, `A2`. |
| ReasonDescription | string | No | Order rejection reason |
| LegNo | int | No | (Entry),  (Stop Loss),  (Target) Values: `1`, `2`, `3`. |
| Instrument | string | No | Instrument type ([Annexure](/api/v2/guides/annexure#instrument)) |
| Symbol | string | No | Trading symbol |
| ProductName | string | No | Product type ([Annexure](/api/v2/guides/annexure#product-type)) |
| Status | enum | No | Values: `TRANSIT`, `PENDING`, `REJECTED`, `CANCELLED`, `TRADED`, `EXPIRED`. |
| LotSize | int | No | Lot Size for Derivatives |
| StrikePrice | float | No | Options Strike Price |
| ExpiryDate | string | No | Contract expiry date |
| OptType | string | No | or  for Options Values: `CE`, `PE`. |
| DisplayName | string | No | Instrument display name |
| Isin | string | No | ISIN of the instrument |
| Series | string | No | Exchange series |
| GoodTillDaysDate | string | No | Good till days date |
| RefLtp | float | No | LTP at time of order update |
| TickSize | float | No | Tick size of instrument |
| AlgoId | string | No | Exchange ID for special order types |
| Multiplier | int | No | For commodity and currency contracts |
| CorrelationId | string | No | User/partner tracking ID (max 30 chars) |

---

## Postback

Webhooks for real-time order status updates via POST callbacks

API (Webhooks) sends a `POST` request with **JSON payload** to your Postback URL whenever there is a change in order status (`TRANSIT`, `PENDING`, `REJECTED`, `CANCELLED`, `TRADED` or `EXPIRED`) or whenever an order is modified or partially filled.

This Postback API works on **access token** level — all trades originating from one particular access token are sent to that particular Webhook URL. This makes it optimal for individual developers.

---

## Postback Payload

The JSON payload is sent as a raw HTTP POST body.

```json
{
    "dhanClientId": "1000000003",
    "orderId": "112111182198",
    "correlationId": "123abc678",
    "orderStatus": "PENDING",
    "transactionType": "BUY",
    "exchangeSegment": "NSE_EQ",
    "productType": "INTRADAY",
    "orderType": "MARKET",
    "validity": "DAY",
    "tradingSymbol": "",
    "securityId": "11536",
    "quantity": 5,
    "disclosedQuantity": 0,
    "price": 0.0,
    "triggerPrice": 0.0,
    "afterMarketOrder": false,
    "boProfitValue": 0.0,
    "boStopLossValue": 0.0,
    "legName": null,
    "createTime": "2021-11-24 13:33:03",
    "updateTime": "2021-11-24 13:33:03",
    "exchangeTime": "2021-11-24 13:33:03",
    "drvExpiryDate": null,
    "drvOptionType": null,
    "drvStrikePrice": 0.0,
    "omsErrorCode": null,
    "omsErrorDescription": null,
    "filled_qty": 1,
    "algoId": null
}
```

---

## Setting Up Postback

To set up Postback API:

1. While generating access token on [web.dhan.co](https://web.dhan.co), enter your URL in the **'Postback URL'** field
2. Click on **'Generate'** to set Postback and generate a new token

> **warning:** You will not receive postback calls if Postback URL is set to `localhost` or `127.0.0.1`.

> **note:** To receive Postback for all orders placed from a platform/app, [Partner Login](/api/v2/guides/authentication#for-partners) module needs to be used.

For description of enum values, refer to the [Annexure](/api/v2/guides/annexure).


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| dhanClientId | string | No | User specific identification |
| orderId | string | No | Order specific identification by Dhan |
| correlationId | string | No | User/partner generated tracking ID (max 30 chars, ) Values: `[a-zA-Z0-9 _-]`. |
| orderStatus | enum | No | Values: `TRANSIT`, `PENDING`, `REJECTED`, `CANCELLED`, `TRADED`, `EXPIRED`. |
| transactionType | enum | No | or Values: `BUY`, `SELL`. |
| exchangeSegment | enum | No | Values: `NSE_EQ`, `NSE_FNO`, `NSE_CURRENCY`, `BSE_EQ`, `MCX_COMM`. |
| productType | enum | No | Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`, `CO`, `BO`. |
| orderType | enum | No | Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| validity | enum | No | or Values: `DAY`, `IOC`. |
| tradingSymbol | string | No | Trading Symbol |
| securityId | string | No | Exchange standard ID ([Instruments](/api/v2/guides/instruments)) |
| quantity | int | No | Number of shares for the order |
| disclosedQuantity | int | No | Number of shares visible |
| price | float | No | Price at which order is placed |
| triggerPrice | float | No | Trigger price for SL-M, SL-L, CO & BO |
| afterMarketOrder | boolean | No | Whether the order is AMO |
| boProfitValue | float | No | Bracket Order Target Price change |
| boStopLossValue | float | No | Bracket Order Stop Loss Price change |
| legName | enum | No | Values: `ENTRY_LEG`, `TARGET_LEG`, `STOP_LOSS_LEG`. |
| createTime | string | No | Time at which order is created |
| updateTime | string | No | Time at which last activity happened |
| exchangeTime | string | No | Time at which order reached exchange |
| drvExpiryDate | string | No | F&O contract expiry date |
| drvOptionType | enum | No | or Values: `CALL`, `PUT`. |
| drvStrikePrice | float | No | Options Strike Price |
| omsErrorCode | string | No | Error code if order is rejected |
| omsErrorDescription | string | No | Error description if order is rejected |
| filled_qty | int | No | Quantity already traded |
| algoId | string | No | Algo ID registered with Exchange |

---

## Rate Limits

DhanHQ API rate limits and best practices

DhanHQ enforces rate limits to ensure fair usage and platform stability.

## Rate Limit Table

| API Category | Per Second | Daily Limit |
|--------------|------------|-------------|
| **Order APIs** | 10 requests | 100,000 |
| **Data APIs** | 5 requests | 7,000 |
| **Market Quote** | 1 request | — |
| **Option Chain** | 1 per 3 sec | — |

## Market Quote Limits

- Maximum **1,000 instruments** per request for LTP/OHLC/Quote endpoints
- **1 request per second** across all market quote endpoints

## Option Chain Limits

- **1 request per 3 seconds** per underlying/expiry combination

## Handling Rate Limits

When you exceed the rate limit, the API returns:

```json
{
  "status": "failure",
  "errorType": "RATE_LIMIT_ERROR",
  "errorCode": "RL001",
  "errorMessage": "Too many requests. Please retry after 1 second."
}
```

### Best Practices

1. **Batch requests** — Use multi-instrument endpoints (e.g., LTP for multiple instruments in one call)
2. **Cache data** — Cache market data locally and refresh at appropriate intervals
3. **Exponential backoff** — When rate limited, wait and retry with increasing delays
4. **Queue orders** — Don't fire all orders simultaneously; space them out

### Python Example with Rate Limiting

```python
import time
from dhanhq import DhanContext, dhanhq

context = DhanContext("client_id", "access_token")
dhan = dhanhq(context)

# Get LTP for multiple instruments in a single call
instruments = [
    ("NSE_EQ", "1333"),
    ("NSE_EQ", "11536"),
    ("NSE_EQ", "2885"),
]
ltp = dhan.get_ltp(instruments)

# Space out order placements
orders = [...]  # your order list
for order in orders:
    response = dhan.place_order(**order)
    print(response)
    time.sleep(0.1)  # 100ms delay between orders
```

---

## Release Notes

Changelog and release notes for DhanHQ API versions

---

## Version 2.5
*Date: Monday Feb 09, 2026*

Introducing Conditional Trigger Orders, P&L based exit under Trader's Control, and Exit All API.

### New Features

- **Conditional Trigger Orders** — Place orders triggered when specific market conditions are met, allowing automation of trading strategies. [Read more →](/api/v2/guides/conditional-trigger)

- **P&L Based Exit** — Set profit or loss thresholds for automatic position closure. [Read more →](/api/v2/guides/traders-control#pl-based-exit)

- **Exit All API** — Close all open positions and orders with a single API call.

- **Access Token Generation via API** — Generate access tokens via API with TOTP configured. [Read more →](/api/v2/authentication/generate-token)

### Improvements

- **Option Chain API** — Enhanced rate limits for multiple unique requests. Added `average_price` and `security_id` fields.

---

## Version 2.4
*Date: Monday Sep 22, 2025*

Changes in line with SEBI guidelines on Retail Participation in Algorithmic Trading — reduced access token duration, API key based authentication, and IP setup.

### New Features

- **API Key Based Login** — New authentication module using API key and secret for one-year validity. [Read more →](/api/v2/guides/authentication#api-key--secret)

### Breaking Changes

- **Access Token limited to 24 hours** — In line with exchange and SEBI guidelines.
- **Static IP Requirement** — Required for all Order APIs. [Setup Static IP →](/api/v2/guides/authentication#setup-static-ip)

---

## Version 2.3
*Date: Monday Sep 08, 2025*

Adding 200 Market Depth on WebSockets and historical expired options contract data. Rate limit for Order APIs changed to 10 orders per second.

### New Features

- **Full Market Depth (200 levels)** — Extension of 20-level depth with complete order book data on WebSocket. [Read more →](/api/v2/guides/full-market-depth#200-level)

- **Historical Options Data** — Fetch expired contract data on a rolling basis with IV, OI and volumes. [Read more →](/api/v2/guides/expired-options-data)

---

## Version 2.2
*Date: Friday Mar 07, 2025*

New Super Order type and major updates to Historical Data APIs — 5 years of intraday data and OI data.

### New Features

- **Super Orders** — Combine entry and exit orders into a single order with trailing stop loss, available across all exchanges and segments.

- **User Profile** — Status check API for token validity, active segments, Data API subscription and more. [Read more →](/api/v2/guides/authentication#user-profile)

### Improvements

- **Intraday Historical Data** — Now available for last 5 years with OI data. Added `oi` parameter and IST time support in date parameters.

- **Daily Historical Data** — Added OI data with optional `oi` parameter.

- **`CorrelationId` on Live Order Update** — New `CorrelationId` and `Remarks` keys. [Read more →](/api/v2/guides/order-update#order-update)

### Breaking Changes

- **Rate Limit Changes** — Increased for Data APIs. No rate limits on minute/hourly timeframes. 1,00,000 daily requests, seconds limited to 5 per second.

---

## Version 2.1
*Date: Monday Jan 06, 2025*

Adds 20-level market depth (Level 3 data) and Option Chain API.

### New Features

- **20 Market Depth** — Real-time streaming of 20-level depth for all NSE instruments. [Read more →](/api/v2/guides/full-market-depth)

- **Option Chain** — Advanced Option Chain with OI, Greeks, volume, top bid/ask and price data for all strikes.

### Improvements

- **`expiryCode` in Daily Historical Data** — Now available as an optional field.

---

## Version 2.0
*Date: Monday Sep 15, 2024*

DhanHQ v2 extends execution capability with live order updates, Market Quote APIs, and stability improvements.

### New Features

- **Market Quote** — Fetch LTP, Quote (with OI) and Market Depth for up to 1000 instruments at once.

- **Live Order Update** — Real-time order status updates via WebSocket. [Read more →](/api/v2/guides/order-update)

- **Margin Calculator** — Details about required margin and available balances before placing orders.

### Improvements

- **Intraday Historical Data** — OHLC with Volume for last 5 trading days across multiple timeframes.

- **GET Order APIs** — Added `filledQty`, `remainingQuantity`, `averageTradedPrice` and `PART_TRADED` status.

- **Live Market Feed** — Authorise via Query Parameters. `FULL` packet now available with combined data.

### Breaking Changes

- **Order Placement** — Deprecated `tradingSymbol`, `drvExpiryDate`, `drvOptionType`, `drvStrikePrice`. Added `PRE_OPEN` AMO tag.

- **Order Modification** — `quantity` field now requires placed quantity instead of pending quantity.

- **Daily Historical Data** — `symbol` replaced with `securityId`.

- **Error Messages** — Categorised with DH-900 series.

- **Security ID List** — New comprehensive mapping with tag changes. [See Instruments →](/api/v2/guides/instruments)

- **Epoch time** — Replaced Julian time in Historical Data APIs.

- **Market Depth deprecated** — Replaced with `FULL` packet in Live Market Feed.

- **Endpoint changes** — Trade History now `/trades`, Kill Switch now `/killswitch`.

### Bug Fixes

- **Positions API** — `realizedProfit` and `unrealizedProfit` now return real-time values.

- **Order Modification** — `TARGET_LEG` modification fixed.

---

## Python SDK

DhanHQ Python SDK reference and examples

(`dhanhq`)


The official Python SDK for interacting with DhanHQ APIs. Provides a clean, Pythonic interface for all trading and data operations.

## Installation

```bash
pip install dhanhq
```

## Quick Start

```python
from dhanhq import DhanContext, dhanhq

# Initialize with your credentials
context = DhanContext("YOUR_CLIENT_ID", "YOUR_ACCESS_TOKEN")
dhan = dhanhq(context)
```

## Order Management

### Place Order

```python
response = dhan.place_order(
    security_id="1333",
    exchange_segment="NSE_EQ",
    transaction_type="BUY",
    quantity=10,
    order_type="MARKET",
    product_type="INTRADAY"
)
print(response)
```

### Modify Order

```python
response = dhan.modify_order(
    order_id="123456789",
    order_type="LIMIT",
    quantity=15,
    price=1500.00
)
```

### Cancel Order

```python
response = dhan.cancel_order(order_id="123456789")
```

### Get Order Book

```python
orders = dhan.get_order_list()
print(orders)
```

### Get Order by ID

```python
order = dhan.get_order_by_id(order_id="123456789")
```

### Get Order by Correlation ID

```python
order = dhan.get_order_by_corelation_id(correlation_id="my-order-123")
```

### Slice Order (Large Quantities)

```python
response = dhan.place_slice_order(
    security_id="1333",
    exchange_segment="NSE_EQ",
    transaction_type="BUY",
    quantity=5000,
    order_type="MARKET",
    product_type="INTRADAY"
)
```

## Super Order (Bracket Order)

### Place Super Order

```python
response = dhan.place_super_order(
    security_id="1333",
    exchange_segment="NSE_EQ",
    transaction_type="BUY",
    quantity=10,
    order_type="LIMIT",
    price=1500.00,
    target_price=1550.00,
    stop_loss_price=1470.00,
    trailing_jump=5.00
)
```

### Modify Super Order

```python
response = dhan.modify_super_order(
    order_id="123456789",
    leg_name="TARGET_LEG",
    price=1560.00
)
```

### Cancel Super Order Leg

```python
response = dhan.cancel_super_order(
    order_id="123456789",
    leg_name="STOP_LOSS_LEG"
)
```

## Portfolio

### Get Holdings

```python
holdings = dhan.get_holdings()
```

### Get Positions

```python
positions = dhan.get_positions()
```

### Convert Position

```python
response = dhan.convert_position(
    security_id="1333",
    exchange_segment="NSE_EQ",
    position_type="LONG",
    convert_qty=10,
    from_product_type="INTRADAY",
    to_product_type="CNC"
)
```

### Exit All Positions

```python
response = dhan.exit_all_positions()
```

## Market Data

### Get LTP

```python
instruments = [("NSE_EQ", "1333"), ("NSE_EQ", "11536")]
ltp = dhan.get_ltp(instruments)
```

### Get OHLC

```python
instruments = [("NSE_EQ", "1333")]
ohlc = dhan.get_ohlc(instruments)
```

### Get Full Quote (with Market Depth)

```python
quote = dhan.get_quote(
    security_id="1333",
    exchange_segment="NSE_EQ"
)
```

## Historical Data

### Daily Data

```python
from datetime import datetime, timedelta

data = dhan.get_historical_data(
    security_id="1333",
    exchange_segment="NSE_EQ",
    instrument_type="EQUITY",
    from_date=datetime.now() - timedelta(days=30),
    to_date=datetime.now(),
    interval="D"
)
```

### Intraday Data

```python
data = dhan.get_intraday_data(
    security_id="1333",
    exchange_segment="NSE_EQ",
    instrument_type="EQUITY",
    from_date=datetime.now() - timedelta(days=5),
    to_date=datetime.now(),
    interval="5"  # 1, 5, 15, 25, or 60 minutes
)
```

## Option Chain

### Get Option Chain

```python
chain = dhan.get_option_chain(
    underlying_security_id="26000",
    underlying_type="INDEX",
    expiry_date="2026-02-27"
)
```

### Get Expiry List

```python
expiries = dhan.get_expiry_list(
    underlying_security_id="26000",
    underlying_type="INDEX"
)
```

## Funds

### Get Fund Limits

```python
funds = dhan.get_fund_limits()
print(f"Available: {funds['availabelBalance']}")
```

### Margin Calculator

```python
margin = dhan.get_margin_calculator(
    security_id="1333",
    exchange_segment="NSE_EQ",
    transaction_type="BUY",
    quantity=10,
    product_type="INTRADAY",
    price=1500.00
)
```

### Multi-Order Margin Calculator

```python
scripts = [
    {
        "securityId": "26009",
        "exchangeSegment": "NSE_FNO",
        "transactionType": "BUY",
        "quantity": 50,
        "productType": "INTRADAY",
        "price": 45000.00
    },
    {
        "securityId": "26010",
        "exchangeSegment": "NSE_FNO",
        "transactionType": "SELL",
        "quantity": 50,
        "productType": "INTRADAY",
        "price": 45500.00
    }
]
margin = dhan.get_multi_margin_calculator(scripts=scripts)
```

## Supported Values

### Exchange Segments

| Value | Description |
|-------|-------------|
| `NSE_EQ` | NSE Equity |
| `NSE_FNO` | NSE Futures & Options |
| `BSE_EQ` | BSE Equity |
| `BSE_FNO` | BSE Futures & Options |
| `MCX_COMM` | MCX Commodity |

### Product Types

| Value | Description |
|-------|-------------|
| `CNC` | Cash & Carry (delivery) |
| `INTRADAY` | Intraday |
| `MARGIN` | Margin trading |
| `MTF` | Margin Trade Funding |
| `CO` | Cover Order |
| `BO` | Bracket Order |

### Order Types

| Value | Description |
|-------|-------------|
| `LIMIT` | Limit order |
| `MARKET` | Market order |
| `STOP_LOSS` | Stop loss limit |
| `STOP_LOSS_MARKET` | Stop loss market |

---

## Statement

Retrieve trading account ledger reports and historical trade data

Retrieve your trade and ledger details to help summarise and analyse your trades.

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/ledger` | Retrieve Trading Account debit and credit details |
| GET | `/trades/{from}/{to}/{page}` | Retrieve historical trade data |

---

## Ledger Report

Retrieve Trading Account Ledger Report with all credit and debit transaction details for a particular time interval.

```bash
curl --request GET \
  --url 'https://api.dhan.co/v2/ledger?from-date={YYYY-MM-DD}&to-date={YYYY-MM-DD}' \
  --header 'Accept: application/json' \
  --header 'access-token: {JWT}'
```

**Query Parameters**

| Field | Description |
|-------|-------------|
| `from-date`* | Start date in format `YYYY-MM-DD` |
| `to-date`* | End date in format `YYYY-MM-DD` |

**Response**

```json
{
    "dhanClientId": "1000000001",
    "narration": "FUNDS WITHDRAWAL",
    "voucherdate": "Jun 22, 2022",
    "exchange": "NSE-CAPITAL",
    "voucherdesc": "PAYBNK",
    "vouchernumber": "202200036701",
    "debit": "20000.00",
    "credit": "0.00",
    "runbal": "957.29"
}
```


---

## Trade History

Retrieve detailed trade history for all orders for a particular time frame. Response is paginated — pass page number as path parameter.

```bash
curl --request GET \
  --url https://api.dhan.co/v2/trades/{from-date}/{to-date}/{page} \
  --header 'Accept: application/json' \
  --header 'access-token: {JWT}'
```

**Path Parameters**

| Field | Description |
|-------|-------------|
| `from-date`* | Start date in format `YYYY-MM-DD` |
| `to-date`* | End date in format `YYYY-MM-DD` |
| `page`* | Page number (pass `0` as default) |

**Response**

```json
[
    {
        "dhanClientId": "1000000001",
        "orderId": "212212307731",
        "exchangeOrderId": "76036896",
        "exchangeTradeId": "407958",
        "transactionType": "BUY",
        "exchangeSegment": "NSE_EQ",
        "productType": "CNC",
        "orderType": "MARKET",
        "tradingSymbol": null,
        "customSymbol": "Tata Motors",
        "securityId": "3456",
        "tradedQuantity": 1,
        "tradedPrice": 390.9,
        "isin": "INE155A01022",
        "instrument": "EQUITY",
        "sebiTax": 0.0004,
        "stt": 0,
        "brokerageCharges": 0,
        "serviceTax": 0.0025,
        "exchangeTransactionCharges": 0.0135,
        "stampDuty": 0,
        "createTime": "NA",
        "updateTime": "NA",
        "exchangeTime": "2022-12-30 10:00:46",
        "drvExpiryDate": "NA",
        "drvOptionType": "NA",
        "drvStrikePrice": 0
    }
]
```


For description of enum values, refer to the [Annexure](/api/v2/guides/annexure).


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| dhanClientId | string | No | User specific identification |
| narration | string | No | Description of the ledger transaction |
| voucherdate | string | No | Transaction Date |
| exchange | string | No | Exchange information for the transaction |
| voucherdesc | string | No | Nature of transaction |
| vouchernumber | string | No | System generated transaction number |
| debit | string | No | Debit amount (only when credit returns 0) |
| credit | string | No | Credit amount (only when debit returns 0) |
| runbal | string | No | Running Balance post transaction |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| dhanClientId | string | No | User specific identification |
| orderId | string | No | Order specific identification by Dhan |
| exchangeOrderId | string | No | Order specific identification by exchange |
| exchangeTradeId | string | No | Trade specific identification by exchange |
| transactionType | enum | No | or Values: `BUY`, `SELL`. |
| exchangeSegment | enum | No | Exchange Segment ([Annexure](/api/v2/guides/annexure#exchange-segment)) |
| productType | enum | No | Values: `CNC`, `INTRADAY`, `MARGIN`, `MTF`, `CO`, `BO`. |
| orderType | enum | No | Values: `LIMIT`, `MARKET`, `STOP_LOSS`, `STOP_LOSS_MARKET`. |
| tradingSymbol | string | No | Symbol ([Instruments](/api/v2/guides/instruments)) |
| customSymbol | string | No | Trading Symbol as per Dhan |
| securityId | string | No | Exchange standard ID |
| tradedQuantity | int | No | Number of shares executed |
| tradedPrice | float | No | Price at which trade is executed |
| isin | string | No | Universal standard ID |
| instrument | string | No | or Values: `EQUITY`, `DERIVATIVES`. |
| sebiTax | string | No | SEBI Turnover Charges |
| stt | string | No | Securities Transactions Tax |
| brokerageCharges | string | No | Brokerage charges ([pricing](https://dhan.co/pricing/)) |
| serviceTax | string | No | Applicable Service Tax |
| exchangeTransactionCharges | string | No | Exchange Transaction Charge |
| stampDuty | string | No | Stamp Duty Charges |
| createTime | string | No | Time at which the order is created |
| updateTime | string | No | Time at which the last activity happened |
| exchangeTime | string | No | Time at which order reached exchange |
| drvExpiryDate | int | No | Expiry date for F&O contracts |
| drvOptionType | enum | No | or Values: `CALL`, `PUT`. |
| drvStrikePrice | float | No | Strike Price for Options |

---

## Trader's Control

Kill Switch and P&L based auto-exit APIs for managing trading risk

APIs built for traders to manage their risks and preferences using advanced tools. You can set and manage Kill Switch for your account along with P&L based auto-exit feature.

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/killswitch` | Manage Kill Switch |
| GET | `/killswitch` | Kill Switch Status |
| POST | `/pnlExit` | Configure P&L Based Exit |
| DELETE | `/pnlExit` | Stop P&L Based Exit |
| GET | `/pnlExit` | Get P&L Based Exit |

---

## Manage Kill Switch

Activate or deactivate the kill switch for your account, which will disable trading for the current trading day. Pass query parameter as `ACTIVATE` or `DEACTIVATE`.

> **note:** Ensure all your positions are closed and there are no pending orders to be able to activate Kill Switch.

```bash
curl --request POST \
  --url 'https://api.dhan.co/v2/killswitch?killSwitchStatus=ACTIVATE' \
  --header 'Accept: application/json' \
  --header 'Content-Type: application/json' \
  --header 'access-token: {JWT}'
```

**Request** — No Body

**Response**

```json
{
    "dhanClientId": "1000000009",
    "killSwitchStatus": "Kill Switch has been successfully activated"
}
```


---

## Kill Switch Status

Check whether kill switch is active for the current trading day.

```bash
curl --request GET \
  --url https://api.dhan.co/v2/killswitch \
  --header 'Accept: application/json' \
  --header 'access-token: {JWT}'
```

**Response**

```json
{
    "dhanClientId": "1000000009",
    "killSwitchStatus": "ACTIVATE"
}
```


---

## P&L Based Exit

Configure automatic exit rules based on cumulative profit or loss thresholds. When the defined limits are breached, all applicable positions are exited.

> **note:** The configured P&L based exit remains active for the current day and is reset at the end of the trading session.

```bash
curl --request POST \
  --url https://api.dhan.co/v2/pnlExit \
  --header 'Accept: application/json' \
  --header 'Content-Type: application/json' \
  --header 'access-token: {JWT}' \
  --data '{Request Body}'
```

**Request Structure**

```json
{
    "profitValue": "1500.00",
    "lossValue": "500.00",
    "productType": ["INTRADAY", "DELIVERY"],
    "enableKillSwitch": true
}
```


| Parameter | Data Type | Description |
|-----------|-----------|-------------|
| `profitValue` | float | Target profit amount for the P&L exit |
| `lossValue` | float | Target loss amount for the P&L exit |
| `productType` | string | Product types — `INTRADAY` `DELIVERY` |
| `enableKillSwitch` | boolean | Enable kill switch for this P&L exit |

**Response**

```json
{
    "pnlExitStatus": "ACTIVE",
    "message": "P&L based exit configured successfully"
}
```

> **warning:** If `profitValue` is set below the current profit in P&L, the exit will be triggered immediately. The same applies if `lossValue` is set above the current loss.

---

## Stop P&L Based Exit

Disable the active P&L based exit configuration.

```bash
curl --request DELETE \
  --url https://api.dhan.co/v2/pnlExit \
  --header 'Accept: application/json' \
  --header 'access-token: {JWT}'
```

**Response**

```json
{
    "pnlExitStatus": "DISABLED",
    "message": "P&L based exit stopped successfully"
}
```

---

## Get P&L Based Exit

Fetch the currently active P&L based exit configuration for the current trading day.

```bash
curl --request GET \
  --url https://api.dhan.co/v2/pnlExit \
  --header 'Accept: application/json' \
  --header 'access-token: {JWT}'
```

**Response**

```json
{
    "pnlExitStatus": "ACTIVE",
    "profit": "1500.00",
    "loss": "500.00",
    "productType": ["INTRADAY", "DELIVERY"],
    "enable_kill_switch": true
}
```

| Parameter | Data Type | Description |
|-----------|-----------|-------------|
| `pnlExitStatus` | string | `ACTIVE` or `INACTIVE` |
| `profit` | float | Target profit amount |
| `loss` | float | Target loss amount |
| `enableKillSwitch` | boolean | Kill switch status |
| `productType` | string | Applicable product types |

For description of enum values, refer to the [Annexure](/api/v2/guides/annexure).


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| dhanClientId | string | No | User specific identification |
| killSwitchStatus | string | No | Status of Kill Switch — activated or not |


### Response Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| dhanClientId | string | No | User specific identification |
| killSwitchStatus | string | No | or Values: `ACTIVATE`, `DEACTIVATE`. |

---

## Backtesting

Test trading strategies against historical data to evaluate performance before going live.

The Backtesting skill enables your AI agent to test trading strategies against historical market data — evaluating performance, risk metrics, and edge before deploying strategies with real capital.

## Capabilities

- **Strategy simulation** — Run any trading strategy against historical OHLC data
- **Performance metrics** — Calculate returns, Sharpe ratio, max drawdown, win rate, and more
- **Multi-timeframe testing** — Backtest on daily, hourly, or minute-level data
- **Parameter optimization** — Test strategy variations to find optimal parameters
- **Trade log** — Generate detailed entry/exit logs with P&L for each trade

## Metrics Provided

| Metric | Description |
|--------|-------------|
| Total Return | Cumulative P&L over the test period |
| Sharpe Ratio | Risk-adjusted return measure |
| Max Drawdown | Largest peak-to-trough decline |
| Win Rate | Percentage of profitable trades |
| Profit Factor | Gross profit divided by gross loss |
| Average Trade | Mean P&L per trade |

## Use Cases

Ask your agent things like:

- "Backtest a 20/50 EMA crossover strategy on NIFTY for the last year"
- "What's the max drawdown of selling weekly strangles on BANKNIFTY?"
- "Test my RSI-based entry strategy on RELIANCE daily data"
- "Compare performance of iron condors vs straddles on NIFTY over 6 months"

## Notes

Backtesting uses historical data from the Market Data skill. Results are theoretical and do not account for slippage, impact cost, or execution delays. Always validate with paper trading before deploying live.

## Related

- [Market Data](/skills/categories/market-data)
- [Options Analysis](/skills/categories/options-analysis)
- [Common Workflows](/skills/categories/common-workflows)

---

## Common Workflows

End-to-end recipes for frequent trading tasks combining multiple skills.

The Common Workflows skill provides your AI agent with end-to-end recipes for frequently performed trading tasks — combining multiple skills (orders, portfolio, market data) into cohesive workflows.

## Capabilities

- **Multi-step recipes** — Complete workflows that chain multiple API calls in the correct sequence
- **Best practices** — Recommended patterns for common trading operations
- **Error recovery** — Built-in handling for common failure scenarios within workflows
- **Parameterized templates** — Reusable workflow templates that adapt to your specific instruments and quantities

## Example Workflows

### Place an Order with Pre-checks
1. Check available margin (Funds)
2. Validate instrument and lot size (Instruments)
3. Get current market price (Market Data)
4. Place the order with confirmation (Orders)
5. Verify order status (Orders)

### Monitor and Exit a Position
1. Check current positions (Portfolio)
2. Stream live price (Live Feed)
3. When target/stop-loss hit, place exit order (Orders)
4. Confirm execution (Orders)

### Options Strategy Execution
1. Fetch option chain (Option Chain)
2. Analyze Greeks and select strikes (Options Analysis)
3. Calculate margin requirement (Funds)
4. Place multi-leg order (Orders)

## Use Cases

Ask your agent things like:

- "Buy 1 lot of NIFTY 22000 CE with all pre-checks"
- "Set up a stop-loss exit for my RELIANCE position"
- "Execute an iron condor on BANKNIFTY"
- "Show me the full workflow for placing a bracket order"

## Related

- [Orders](/skills/categories/orders)
- [Portfolio](/skills/categories/portfolio)
- [Safety Guardrails](/skills/getting-started/safety-guardrails)

---

## Error Codes

Reference DhanHQ error codes and troubleshooting guidance for common API issues.

The Error Codes skill provides your AI agent with a comprehensive reference of DhanHQ API error codes, their meanings, and troubleshooting steps — enabling it to diagnose and resolve issues without manual lookup.

## Capabilities

- **Error code lookup** — Instantly identify what any DhanHQ error code means
- **Troubleshooting guidance** — Get actionable steps to resolve specific errors
- **Common patterns** — Recognize frequently encountered error scenarios and their fixes
- **Order rejection reasons** — Understand why orders get rejected by the exchange or RMS
- **API-specific errors** — Reference errors specific to each API endpoint

## Error Categories

| Category | Description |
|----------|-------------|
| Authentication | Token expiry, invalid credentials, permission issues |
| Order Validation | Invalid parameters, lot size errors, price band violations |
| Exchange Rejection | RMS limits, circuit breaker, market timing |
| Rate Limiting | API throttling and request limits |
| Data Errors | Invalid instrument IDs, missing data, format issues |

## Use Cases

Ask your agent things like:

- "What does error code DH-901 mean?"
- "Why was my order rejected with 'insufficient margin'?"
- "How do I fix an authentication token expiry error?"
- "What are the common reasons for order rejection on NSE?"

## Related

- [Orders](/skills/categories/orders)
- [Common Workflows](/skills/categories/common-workflows)

---

## Funds

Check available margins, fund balances, and margin requirements through your AI agent.

The Funds skill enables your AI agent to check your available trading margins, fund balances, and margin utilization — helping you understand your buying power before placing orders.

## Capabilities

- **Available margin** — Check total available margin across all segments
- **Fund balances** — View opening balance, realized P&L, and collateral values
- **Margin utilization** — See how much margin is currently blocked by open positions
- **Segment-wise breakdown** — Get margin details split by equity, F&O, currency, and commodity segments
- **Margin calculator** — Estimate margin required for a proposed order before placing it

## Use Cases

Ask your agent things like:

- "How much margin do I have available?"
- "What's my fund balance for F&O trading?"
- "How much margin would I need to buy 1 lot of NIFTY futures?"
- "Show me my margin utilization breakdown"

## Data Points

The skill provides access to available balance, utilized margin, opening balance, payin amount, collateral value, and segment-wise margin allocation — giving your agent complete visibility into your trading capacity.

## Related

- [Orders](/skills/categories/orders)
- [Portfolio](/skills/categories/portfolio)

---

## Instruments

Access the complete instrument universe across all Indian exchanges — NSE, BSE, and MCX.

The Instruments skill gives your AI agent access to the full instrument universe of Indian exchanges, enabling it to look up security IDs, resolve symbols, and understand exchange-specific instrument metadata.

## Capabilities

- **Instrument lookup** — Search instruments by name, symbol, or ISIN across NSE, BSE, and MCX
- **Security ID resolution** — Map trading symbols to DhanHQ security IDs required for order placement
- **Exchange segments** — Query instruments filtered by segment (equity, F&O, currency, commodity)
- **Instrument metadata** — Access lot sizes, tick sizes, expiry dates, and instrument types
- **Bulk download** — Retrieve the complete instrument master file for offline processing

## Exchange Segments

| Segment | Exchange | Examples |
|---------|----------|----------|
| NSE Equity | NSE | RELIANCE, TCS, INFY |
| NSE F&O | NSE | NIFTY options, BANKNIFTY futures |
| BSE Equity | BSE | Listed equities on BSE |
| BSE F&O | BSE | SENSEX options |
| MCX Commodity | MCX | GOLD, SILVER, CRUDE |
| NSE Currency | NSE | USDINR futures and options |

## Use Cases

Ask your agent things like:

- "What's the security ID for RELIANCE on NSE?"
- "Show me all NIFTY weekly expiries available"
- "What's the lot size for BANKNIFTY options?"
- "List all instruments in the MCX commodity segment"

## Related

- [Orders](/skills/categories/orders)
- [Option Chain](/skills/categories/option-chain)
- [Market Data](/skills/categories/market-data)

---

## Live Feed

Stream real-time market quotes and order book updates via WebSocket connections.

The Live Feed skill enables your AI agent to establish WebSocket connections for streaming real-time market data — live quotes, order book depth, and tick-by-tick updates for any instrument on Indian exchanges.

## Capabilities

- **Live quotes** — Stream real-time LTP, bid/ask, and volume for subscribed instruments
- **Market depth** — Access Level 2 order book data with best 5 bid/ask prices and quantities
- **Tick data** — Receive tick-by-tick price updates for high-frequency monitoring
- **Multi-instrument subscription** — Subscribe to multiple instruments simultaneously
- **Connection management** — Handle WebSocket lifecycle (connect, subscribe, unsubscribe, disconnect)

## Feed Modes

| Mode | Data Included |
|------|---------------|
| LTP | Last traded price only |
| Quote | LTP + OHLC + volume + OI |
| Full | Quote + market depth (5 levels) |

## Use Cases

Ask your agent things like:

- "Start streaming live prices for NIFTY and BANKNIFTY"
- "Show me the order book depth for RELIANCE"
- "Subscribe to tick data for my watchlist"
- "What's the current bid-ask spread on HDFC Bank?"

## Technical Notes

Live Feed uses WebSocket connections for low-latency data delivery. The agent manages connection state, handles reconnection on disconnects, and efficiently subscribes/unsubscribes instruments as needed.

## Related

- [Market Data](/skills/categories/market-data)
- [Option Chain](/skills/categories/option-chain)
- [Common Workflows](/skills/categories/common-workflows)

---

## Market Data

Fetch OHLC, historical data, and intraday candles for any instrument on Indian exchanges.

The Market Data skill enables your AI agent to fetch historical and intraday price data for any instrument traded on Indian exchanges — equities, derivatives, currencies, and commodities.

## Capabilities

- **Historical OHLC** — Retrieve daily, weekly, or monthly candlestick data for any date range
- **Intraday candles** — Get 1-minute, 5-minute, 15-minute, 25-minute, and 60-minute intraday bars
- **Last traded price** — Fetch the most recent price for any instrument
- **Daily data** — Open, high, low, close, and volume for the current or past trading sessions

## Supported Timeframes

| Interval | Description |
|----------|-------------|
| 1 minute | Intraday granular data |
| 5 minutes | Short-term intraday |
| 15 minutes | Medium intraday |
| 25 minutes | Extended intraday |
| 60 minutes | Hourly bars |
| Daily | End-of-day OHLCV |

## Use Cases

Ask your agent things like:

- "Get the last 30 days of daily candles for RELIANCE"
- "Show me 5-minute intraday data for NIFTY 50 today"
- "What's the current price of HDFC Bank?"
- "Fetch weekly OHLC for TCS from January to March"

## Related

- [Live Feed](/skills/categories/live-feed)
- [Option Chain](/skills/categories/option-chain)
- [Backtesting](/skills/categories/backtesting)

---

## Option Chain

Retrieve real-time option chain data with Greeks for any underlying on Indian exchanges.

The Option Chain skill provides your AI agent with real-time option chain data including Greeks, open interest, and implied volatility for any underlying instrument on NSE.

## Capabilities

- **Full option chain** — Retrieve calls and puts across all available strike prices for an expiry
- **Greeks** — Access Delta, Gamma, Theta, Vega, and Rho for each contract
- **Open Interest (OI)** — View current OI and OI changes for strike-level analysis
- **Implied Volatility** — Get IV for individual strikes and the overall IV skew
- **Expiry selection** — Query chains for weekly, monthly, or any available expiry date

## Use Cases

Ask your agent things like:

- "Show me the NIFTY option chain for this week's expiry"
- "What's the OI at 22000 CE for NIFTY?"
- "Get Greeks for BANKNIFTY 48000 PE"
- "Which strikes have the highest open interest change today?"

## Data Points

Each option chain entry includes strike price, bid/ask prices, last traded price, volume, open interest, OI change, and computed Greeks — giving your agent everything needed for options analysis and strategy selection.

## Related

- [Options Analysis](/skills/categories/options-analysis)
- [Market Data](/skills/categories/market-data)
- [Instruments](/skills/categories/instruments)

---

## Options Analysis

Strategy building, payoff analysis, and implied volatility calculations for options trading.

The Options Analysis skill enables your AI agent to perform options-specific analysis — strategy construction, payoff calculations, implied volatility analysis, and Greeks-based decision making for F&O trading on Indian exchanges.

## Capabilities

- **Strategy building** — Construct multi-leg options strategies (spreads, straddles, strangles, iron condors, butterflies)
- **Payoff analysis** — Calculate theoretical P&L at various price levels for any strategy
- **IV analysis** — Analyze implied volatility levels, IV rank, and IV percentile
- **Greeks computation** — Calculate and interpret Delta, Gamma, Theta, Vega for position sizing
- **Strike selection** — Recommend optimal strikes based on risk/reward criteria

## Common Strategies

| Strategy | Legs | Market View |
|----------|------|-------------|
| Bull Call Spread | 2 | Moderately bullish |
| Bear Put Spread | 2 | Moderately bearish |
| Iron Condor | 4 | Range-bound / neutral |
| Straddle | 2 | High volatility expected |
| Butterfly | 3 | Low volatility / pinning |

## Use Cases

Ask your agent things like:

- "Build an iron condor on NIFTY with 200-point wings"
- "What's the max profit/loss on a bull call spread at 22000/22200?"
- "Show me the IV percentile for BANKNIFTY options"
- "Which strikes have the best theta decay for weekly expiry?"

## Related

- [Option Chain](/skills/categories/option-chain)
- [Common Workflows](/skills/categories/common-workflows)
- [Backtesting](/skills/categories/backtesting)

---

## Orders

Place, modify, and cancel orders across NSE, BSE, and MCX using AI agent commands.

The Orders skill enables your AI agent to place, modify, and cancel orders across all Indian exchanges — NSE, BSE, and MCX — through natural language commands.

## Capabilities

- **Place orders** — Equity, F&O, currency, and commodity orders with full parameter control (price, quantity, order type, product type, validity)
- **Modify orders** — Update pending orders with new price, quantity, or trigger conditions
- **Cancel orders** — Cancel individual orders or bulk cancel by segment/status
- **Order status** — Check real-time status of any order by ID
- **Order history** — Retrieve the full audit trail of an order's state transitions
- **Super Orders** — Place bracket and cover orders with stop-loss and target legs
- **Forever Orders (GTT)** — Create Good Till Triggered orders that persist across sessions
- **After Market Orders (AMO)** — Queue orders for next trading session execution

## Supported Order Types

| Type | Description |
|------|-------------|
| LIMIT | Execute at specified price or better |
| MARKET | Execute immediately at best available price |
| STOP_LOSS | Trigger at stop price, then execute as limit |
| STOP_LOSS_MARKET | Trigger at stop price, then execute at market |

## Safety Notes

All order operations require explicit user confirmation before execution. The agent defaults to LIMIT orders unless you specifically request MARKET orders. Lot sizes are validated against exchange minimums for F&O instruments.

## Related

- [Safety Guardrails](/skills/getting-started/safety-guardrails)
- [Common Workflows](/skills/categories/common-workflows)

---

## Portfolio

View holdings, positions, and trade history through your AI agent.

The Portfolio skill gives your AI agent access to your complete portfolio data — holdings, positions, and trade history — enabling informed trading decisions through natural language queries.

## Capabilities

- **Holdings** — View your long-term equity holdings with current market value, P&L, and average cost
- **Positions** — Monitor intraday and carry-forward positions across all segments
- **Trade history** — Retrieve executed trades for the current session or historical dates
- **P&L calculations** — Get realized and unrealized profit/loss breakdowns
- **Position conversion** — Convert positions between intraday (MIS) and delivery (CNC/NRML)

## Use Cases

Ask your agent things like:

- "Show me my current holdings"
- "What's my P&L on RELIANCE positions today?"
- "List all trades executed this session"
- "Convert my NIFTY position from MIS to NRML"

## Data Points

The skill provides access to key portfolio metrics including quantity, average price, last traded price, day's P&L, overall P&L, and exchange-specific details for each instrument.

## Related

- [Orders](/skills/categories/orders)
- [Market Data](/skills/categories/market-data)
- [Funds](/skills/categories/funds)

---

## ScanX

Screen and filter stocks using AI-powered scanning tools across Indian markets.

The ScanX skill enables your AI agent to screen and filter stocks across Indian exchanges using powerful scanning criteria and pre-built strategies.

## Capabilities

- **Technical scans** — Screen stocks based on technical indicators (RSI, MACD, moving averages, volume patterns)
- **Fundamental filters** — Filter by market cap, P/E ratio, sector, and other fundamental parameters
- **Pre-built scanners** — Access ready-made scanning strategies for common trading setups
- **Custom criteria** — Define custom scan conditions combining multiple parameters
- **Real-time results** — Get live scan results during market hours

## Use Cases

| Scan Type | Description |
|-----------|-------------|
| Breakout Scanner | Identify stocks breaking above resistance levels |
| Volume Spike | Find stocks with unusual volume activity |
| Momentum | Screen for stocks with strong directional momentum |
| Gap Scanner | Detect opening gaps for intraday opportunities |

## Related

- [Market Data](/skills/categories/market-data)
- [Options Analysis](/skills/categories/options-analysis)

---

## Configuration

Configure your DhanHQ access token so your AI agent can authenticate with DhanHQ APIs.

After installing the DhanHQ skill pack, you need to configure authentication so your AI agent can interact with DhanHQ APIs on your behalf.

## Access Token Setup

DhanHQ APIs authenticate using an **access token** passed as a header with every request. Your agent needs this token to place orders, fetch portfolio data, stream market feeds, and perform any trading operation.

### Step 1: Generate Your Access Token

1. Log in to [web.dhan.co](https://web.dhan.co)
2. Click on **My Profile** and navigate to **Access DhanHQ APIs**
3. Generate an **Access Token** (valid for 24 hours)
4. Copy the token — you'll need it in the next step

> **tip:** You can optionally provide a **Postback URL** while generating the token to receive real-time order updates. See the [Postback guide](/api/v2/guides/postback) for details.

### Step 2: Configure the Token for Your Agent

Set the access token as an environment variable so the skill can pick it up automatically:

```bash

```

To persist this across terminal sessions, add it to your shell profile (`~/.bashrc`, `~/.zshrc`, or equivalent):

```bash
echo 'export DHAN_ACCESS_TOKEN="your-access-token-here"' >> ~/.zshrc
source ~/.zshrc
```

### Step 3: Verify the Configuration

Ask your agent to check the connection:

```text
Check my DhanHQ account profile
```

The agent will call the `/v2/profile` endpoint using your token. A successful response confirms authentication is working.

## Token Renewal

Access tokens generated from Dhan Web are valid for **24 hours**. When your token expires, generate a new one from [web.dhan.co](https://web.dhan.co) and update the environment variable.

For longer-lived sessions, you can use the API key-based authentication flow:

1. Generate an **API Key & Secret** from Dhan Web (valid for 12 months)
2. Use the [Generate Consent](/api/v2/authentication/api-key-generate-consent) and [Consume Consent](/api/v2/authentication/api-key-consume-consent) flow to obtain a token programmatically

See the full [Authentication guide](/api/v2/guides/authentication) for all available methods.

## Static IP Whitelisting

Per SEBI and exchange guidelines, order placement APIs require **Static IP whitelisting**. If your agent will place, modify, or cancel orders, you must whitelist your IP address:

1. Go to [web.dhan.co](https://web.dhan.co) → DhanHQ APIs section
2. Set your static IP address, or use the [Set IP API](/api/v2/authentication/set-ip)

> **note:** Static IP is only required for order-related operations (Orders, Super Order, Forever Order). Reading portfolio data, market data, and other non-order APIs do not require IP whitelisting.

## Client ID

Some API endpoints also require your **Client ID** (your Dhan account number). Set it alongside your access token:

```bash

```

Your Client ID is visible on [web.dhan.co](https://web.dhan.co) under My Profile.

## Security Best Practices

- **Never commit tokens to version control.** Use environment variables or a secrets manager.
- **Rotate tokens regularly.** Generate a fresh token daily or use the API key flow for automated renewal.
- **Use LIMIT orders by default.** The skill enforces this as a safety guardrail, but proper authentication ensures only you can execute trades.
- **Review agent actions.** The skill requires confirmation before placing orders — always verify the details before approving.

## Next Steps

- Review the [safety guardrails](/skills/getting-started/safety-guardrails) that protect your account during agent-assisted trading
- Explore [skill categories](/skills/) to see what your agent can do with a configured token
- Read the full [Authentication documentation](/api/v2/guides/authentication) for advanced auth flows

---

## Installation

Step-by-step guide to installing the Skills CLI and adding DhanHQ Agent Skills to your development environment.

This guide walks you through installing the Skills CLI and adding the DhanHQ skill pack so your AI agent can interact with Indian markets.

## Prerequisites

- **Node.js** v18 or later
- **npm** (comes with Node.js)
- A DhanHQ trading account with API access enabled

## Step 1: Install the Skills CLI

Install the Skills CLI globally using npm:

```bash
npm install -g skills
```

Verify the installation:

```bash
skills --version
```

## Step 2: Add the DhanHQ Skill Pack

Once the CLI is installed, add the DhanHQ skills:

```bash
skills add dhan-oss/dhanhq-skills --skill dhanhq
```

This downloads the skill pack from the [dhan-oss/dhanhq-skills](https://github.com/dhan-oss/dhanhq-skills) repository and registers it with your local agent environment.

## What Gets Installed

The skill pack includes:

- **SKILL.md** — Core knowledge file (~300 lines) with setup instructions, safety rules, constants, and code patterns
- **references/** — Detailed API parameter tables, WebSocket setup guides, and exchange-specific documentation
- **scripts/** — Reusable utility scripts your agent can call directly
- **examples/** — Complete, runnable trading scripts for common workflows

## Verifying the Installation

After installation, confirm the skill is available:

```bash
skills list
```

You should see `dhanhq` listed among your installed skills.

## Next Steps

- [Configure authentication](/skills/getting-started/configuration) to connect your DhanHQ account
- Review the [safety guardrails](/skills/getting-started/safety-guardrails) before placing live orders
- Explore [skill categories](/skills/) to see what your agent can do

---

## Safety Guardrails

Understand the built-in safety mechanisms that protect your account when trading with AI agents using DhanHQ Skills.

Trading with AI agents introduces unique risks — a misinterpreted instruction or a missing parameter could result in unintended trades. DhanHQ Skills include built-in safety guardrails that keep you in control of every decision while still benefiting from agent-assisted workflows.

## Why Guardrails Matter

AI agents are powerful assistants, but they operate on natural language instructions that can be ambiguous. A request like "buy Nifty" could mean many things — which expiry, what strike, how many lots, at what price? Without guardrails, an agent might make assumptions that lead to:

- Orders placed at unfavorable market prices
- Incorrect lot sizes causing excessive exposure
- Trades executed without your explicit approval

DhanHQ Skills address these risks with three core safety mechanisms that work together to prevent accidental or unintended trades.

## Order Confirmation

**Every order action requires your explicit approval before execution.**

When your agent prepares to place, modify, or cancel an order, it presents the full order details and waits for your confirmation. No order is ever submitted silently.

### What Gets Confirmed

The agent will ask for confirmation before:

- **Placing a new order** — Shows instrument, exchange, order type, quantity, price, and transaction type (BUY/SELL)
- **Modifying an existing order** — Shows the original order details alongside the proposed changes
- **Cancelling an order** — Identifies the order and asks you to confirm cancellation

### Example Flow

```text
You: Buy 1 lot of Nifty 24500 CE expiring this week

Agent: I'll place the following order:
  • Instrument: NIFTY 24500 CE (weekly expiry)
  • Exchange: NSE_FNO
  • Transaction: BUY
  • Quantity: 25 (1 lot)
  • Order type: LIMIT
  • Price: ₹185.50 (current ask)

  Shall I proceed? (yes/no)
```

You review the details and confirm only when everything looks correct. If something is wrong, you can ask the agent to adjust before placing.

> **tip:** The confirmation step also serves as a learning opportunity — you can verify that the agent correctly interpreted your intent and understood the instrument, quantity, and pricing.

## LIMIT Order Defaults

**All orders default to LIMIT unless you explicitly request MARKET.**

MARKET orders execute immediately at the best available price, which can differ significantly from the last traded price — especially in volatile or illiquid instruments. LIMIT orders give you price control by specifying the maximum (for buys) or minimum (for sells) price you're willing to accept.

### Why LIMIT by Default

| Scenario | MARKET Order Risk | LIMIT Order Protection |
|----------|-------------------|----------------------|
| Volatile market open | Fill at a price far from previous close | Order waits at your specified price |
| Illiquid F&O strike | Wide bid-ask spread causes slippage | No fill unless your price is met |
| Flash crash / spike | Executes at extreme prices | Protects against outlier fills |
| Fat-finger quantity | Immediate execution of wrong size | Time to cancel before fill |

### How It Works

When you ask the agent to place an order without specifying the order type, it automatically uses `LIMIT`:

```text
You: Buy 2 lots of Bank Nifty 52000 PE

Agent: I'll place a LIMIT order (default). What price would you like to set?
```

To use a MARKET order, you must explicitly say so:

```text
You: Buy 2 lots of Bank Nifty 52000 PE at market price
```

The agent will still confirm the order before placing, giving you a final checkpoint even with MARKET orders.

> **note:** The LIMIT default applies to all order varieties — regular orders, After Market Orders (AMO), and bracket/cover orders. Super Orders and Forever Orders also respect this default.

## Lot Size Validation

**F&O orders are validated against exchange-defined lot sizes before submission.**

Every Futures & Options instrument on Indian exchanges has a minimum lot size defined by the exchange. Orders that don't conform to valid lot sizes get rejected by the exchange, wasting time and potentially missing trading opportunities.

### What Gets Validated

The agent checks:

- **Minimum lot size** — Ensures the quantity meets the exchange-defined minimum (e.g., Nifty = 25, Bank Nifty = 15)
- **Lot size multiples** — Ensures the quantity is a valid multiple of the lot size (e.g., 50 for Nifty is valid, 30 is not)
- **Instrument-specific rules** — Different instruments have different lot sizes; the agent uses the current instrument master data

### Example

```text
You: Buy 20 units of Nifty 24500 CE

Agent: ⚠️ Invalid quantity. Nifty options have a lot size of 25.
  The minimum order is 25 units (1 lot). Would you like me to
  place an order for 25 units instead?
```

The agent catches the error before it reaches the exchange, saving you from a rejected order and letting you correct the quantity immediately.

### Supported Segments

Lot size validation applies to all F&O segments:

- **NSE F&O** — Nifty, Bank Nifty, FinNifty, stock options and futures
- **BSE F&O** — Sensex, Bankex options and futures
- **MCX** — Commodity futures and options (Gold, Silver, Crude, etc.)

For equity (cash) segments, there is no lot size constraint — you can buy or sell any quantity of shares.

## How Guardrails Work Together

The three safety mechanisms form a layered defense:

1. **Lot size validation** catches quantity errors early, before the order is even formatted
2. **LIMIT order default** prevents price-related risks by requiring explicit price specification
3. **Order confirmation** gives you a final review of the complete order before it hits the exchange

```text
Your instruction → Lot size check → LIMIT default applied → Full order shown → You confirm → Order placed
```

This layered approach means that even if one guardrail doesn't catch an issue, the next one will. The confirmation step is always the final gate — nothing executes without your explicit approval.

## Overriding Guardrails

These guardrails are designed to protect, not restrict. You can override them when needed:

- **MARKET orders** — Explicitly request "at market" or "market order" in your instruction
- **Confirmation** — Cannot be bypassed. Every order requires confirmation regardless of other settings.

The order confirmation requirement is non-negotiable by design. When real money is at stake, a human-in-the-loop checkpoint is essential for responsible AI-assisted trading.

## Next Steps

- Explore [skill categories](/skills/) to see what your agent can do
- Learn about [Orders](/skills/categories/orders) for detailed order placement capabilities
- Read the [Common Workflows](/skills/categories/common-workflows) for end-to-end trading recipes

---

## DhanHQ Agent Skills

Open SKILL.md skills that give your AI coding agent deep knowledge of DhanHQ — order placement, portfolio, market data, option chains, live feeds, and ScanX — with built-in safety guardrails.

**Dhan-native agent skills for NSE / BSE equities, F&O, and commodity trading.**

DhanHQ Agent Skills give your AI coding agent the ability to place live orders, read real portfolio data, stream market feeds, and access the full instrument universe of Indian exchanges — through [DhanHQ's APIs](https://api.dhan.co/v2/).

Built for the open [Agent Skills](https://agentskills.io) standard, the pack is compatible with **Claude Code**, **Codex**, and any agent that supports `SKILL.md`.

> Source of truth: **[github.com/dhan-oss/dhanhq-skills](https://github.com/dhan-oss/dhanhq-skills)**

---

## How it works

A *skill* is a small folder of Markdown and Python that an AI agent can load on demand. Each skill follows the open [`SKILL.md`](https://agentskills.io) format — frontmatter that tells the agent *when* to activate, followed by setup, safety rules, and runnable code patterns.

The DhanHQ skill pack uses **progressive disclosure** to keep your agent's context lean:

1. **`SKILL.md`** (~300 lines) — Setup, safety rules, constants, and core code patterns. Enough for ~80% of trading tasks.
2. **`references/*.md`** — Loaded only when a task needs deeper detail (full order parameter tables, WebSocket setup, Greeks math).
3. **`scripts/`** — Reusable utilities the agent can call directly (security resolver, order validator, trade journal).
4. **`examples/`** — Complete, runnable scripts the agent can reference or adapt (iron condor, super order, live feed, etc.).

Your agent reads the skill, gains DhanHQ-specific knowledge (exchange segments, instrument types, order varieties, lot sizes), and starts calling the right APIs with the right parameters.

---

## Install

### Global install

```bash
npm install -g skills
skills add dhan-oss/dhanhq-skills --skill dhanhq
```

### Claude Code or Codex (zero-install)

```bash
npx skills add dhan-oss/dhanhq-skills --skill dhanhq
```

or

```bash
npx @dhan-oss/dhanhq-skill
```

Once installed, your agent automatically gains DhanHQ capabilities — no further configuration.

See the [installation guide](/skills/getting-started/installation) for per-agent setup notes.

---

## Requirements

- **Python 3.8+** and `pip install dhanhq`
- **Order APIs** — static IP whitelisting on Dhan (one-time)
- **Data APIs** — active Dhan Data Plan
- **Credentials** — environment variables `DHAN_CLIENT_ID` and `DHAN_ACCESS_TOKEN`

The skill never hardcodes credentials. Your agent reads them from the environment at call time.

---

## What's included

```
skills/dhanhq/
├── SKILL.md                       Entry point — setup, safety, core patterns
│
├── references/                    Deep-dive docs, loaded on demand
│   ├── orders.md                  Regular, super, forever (GTT), AMO, slice orders
│   ├── portfolio.md               Holdings, positions, convert position, eDIS
│   ├── market-data.md             Historical OHLC, intraday, quotes
│   ├── option-chain.md            Option chain with Greeks, expiry list
│   ├── instruments.md             Security master, symbol resolution
│   ├── funds.md                   Fund limits and margin calculator
│   ├── live-feed.md               WebSocket — MarketFeed, OrderUpdate, FullDepth
│   ├── scanx-data.md              ScanX real-time scanner data
│   ├── error-codes.md             Error codes, rate limits, retry patterns
│   ├── common-workflows.md        Multi-step patterns (rebalance, iron condor, P&L)
│   ├── options-analysis-patterns.md  PCR, max pain, payoff diagrams, IV skew
│   └── backtesting-with-dhan.md   Equity + F&O backtest patterns with cost model
│
├── scripts/
│   ├── dhan_helpers.py            Composable helper library
│   ├── resolve_security.py        Human name → security_id resolver
│   ├── validate_order.py          Pre-flight order validation with guardrails
│   └── trade_logger.py            Persistent trade journal
│
└── examples/
    ├── place_equity_order.py      Simple equity delivery order
    ├── place_fno_order.py         F&O option order with lot-size validation
    ├── fetch_option_chain.py      Nifty option chain with ATM analysis
    ├── iron_condor.py             Multi-leg strategy: build, analyze, place
    ├── super_order_with_sl.py     Entry + target + trailing SL in one order
    ├── gtt_forever_order.py       GTT single trigger and OCO orders
    ├── order_management.py        Full lifecycle — place, modify, cancel, book
    ├── portfolio_summary.py       Holdings + positions + funds dashboard
    ├── margin_check.py            Pre-order margin validation
    ├── historical_data_analysis.py  OHLCV + moving averages + stats
    └── live_feed_setup.py         WebSocket market data streaming
```

---

## When agents use this skill

The skill activates when the user:

- Wants to **place, modify, or cancel** stock or F&O orders
- Asks about **portfolio holdings or positions**
- Needs **live or historical market data** (OHLC, quotes, depth)
- Wants to work with **option chains** (Greeks, OI, IV)
- Asks about **fund limits or margin requirements**
- Mentions **DhanHQ**, **Dhan API**, or Indian stock market trading
- Wants to **build trading automation** for NSE / BSE / MCX
- Needs to **backtest a strategy** using historical data

---

## Built-in safety guardrails

Trading with AI agents needs hard guardrails. Every DhanHQ skill ships with them on by default:

| Rule | What it does |
|------|--------------|
| **Confirmation required** | Always shows order preview and asks for user confirmation before placing |
| **Default to LIMIT** | Never places MARKET orders unless the user explicitly requests them |
| **Default to 1 lot** | Defaults to 1 share (equity) or 1 lot (F&O) when quantity is unspecified |
| **Lot-size validation** | Rejects F&O orders whose quantity isn't a multiple of the exchange lot size |
| **Product-type guardrails** | Blocks CNC / MTF for F&O segments; blocks invalid product-segment combos |
| **Notional warning** | Warns when order value exceeds ₹50,000 |
| **Freeze quantity check** | Warns when F&O quantity exceeds exchange freeze limits |
| **Market-hours check** | Warns when the market is closed and suggests AMO |
| **No hardcoded tokens** | Always reads credentials from environment variables |

Your agent stays a knowledgeable assistant — not an autonomous trader. You stay in control of every order.

Full details: [Safety guardrails](/skills/getting-started/safety-guardrails).

---

## API coverage

| Category | Reference |
|----------|-----------|
| Orders — regular, super, forever (GTT), AMO, slice | [skills/dhanhq/references/orders.md](https://github.com/dhan-oss/dhanhq-skills/blob/main/skills/dhanhq/references/orders.md) |
| Portfolio — holdings, positions, convert, eDIS | [references/portfolio.md](https://github.com/dhan-oss/dhanhq-skills/blob/main/skills/dhanhq/references/portfolio.md) |
| Market data — historical OHLC, quotes, depth | [references/market-data.md](https://github.com/dhan-oss/dhanhq-skills/blob/main/skills/dhanhq/references/market-data.md) |
| Option chain — Greeks, OI, expiry list | [references/option-chain.md](https://github.com/dhan-oss/dhanhq-skills/blob/main/skills/dhanhq/references/option-chain.md) |
| Instruments — security master, symbol resolution | [references/instruments.md](https://github.com/dhan-oss/dhanhq-skills/blob/main/skills/dhanhq/references/instruments.md) |
| Funds & margin | [references/funds.md](https://github.com/dhan-oss/dhanhq-skills/blob/main/skills/dhanhq/references/funds.md) |
| Live feed — MarketFeed, OrderUpdate, FullDepth | [references/live-feed.md](https://github.com/dhan-oss/dhanhq-skills/blob/main/skills/dhanhq/references/live-feed.md) |
| ScanX real-time scanner | [references/scanx-data.md](https://github.com/dhan-oss/dhanhq-skills/blob/main/skills/dhanhq/references/scanx-data.md) |
| Error codes, rate limits, retry patterns | [references/error-codes.md](https://github.com/dhan-oss/dhanhq-skills/blob/main/skills/dhanhq/references/error-codes.md) |

---

## Example prompts

Once installed, drop these into your agent:

**Orders**
- *"Buy 10 shares of Reliance at market."*
- *"Place a limit order for HDFC Bank at 1650."*
- *"Buy 1 lot of Nifty 24000 CE expiry this week."*
- *"Place a super order on TCS with target 4200 and SL 3900."*
- *"Set a GTT to buy Infosys if it drops to 1400."*

**Portfolio**
- *"Show me my holdings."*
- *"What's my total portfolio value?"*
- *"Show my open F&O positions."*
- *"Convert my INFY position from intraday to delivery."*

**Market data**
- *"Get daily OHLC for Reliance for the last 6 months."*
- *"What's the current LTP of HDFC Bank?"*
- *"Show me 5-minute candles for TCS today."*

**Options**
- *"Show me the Nifty option chain for nearest expiry."*
- *"What's the PCR for Bank Nifty?"*
- *"Build me a Nifty iron condor."*

**Funds & margin**
- *"What's my available margin?"*
- *"How much margin do I need to sell 1 lot of Nifty?"*

---

## Agent compatibility

The pack works with any agent that reads the `SKILL.md` standard:

- **Claude Code** — Anthropic's coding agent
- **Codex** — OpenAI's coding agent
- **Cursor**, **Continue**, and others that adopt the standard

Same skill, same install, same behavior — the agent reads the spec, you get DhanHQ-aware tooling.

---

## SDK reference

- **Package** — `dhanhq` ([PyPI](https://pypi.org/project/dhanhq/))
- **Minimum version** — 2.2.0
- **Base URL** — `https://api.dhan.co/v2`
- **API docs** — [dhanhq.co/docs/v2](https://dhanhq.co/docs/v2/)
- **SDK source** — [github.com/dhan-oss/DhanHQ-py](https://github.com/dhan-oss/DhanHQ-py)

---

## Contributing

The skill is open source under MIT. To contribute:

1. Fork [dhan-oss/dhanhq-skills](https://github.com/dhan-oss/dhanhq-skills)
2. Make changes in `skills/dhanhq/`
3. Verify against the DhanHQ SDK (`pip install dhanhq`)
4. Submit a pull request

---

## Next steps

- [Installation](/skills/getting-started/installation) — Per-agent setup details
- [Safety guardrails](/skills/getting-started/safety-guardrails) — Full guardrail reference
- [What are skills?](/skills/overview/what-are-skills) — Conceptual overview
- [SKILL.md standard](/skills/overview/skill-standard) — File format spec

---

## Agent Compatibility

DhanHQ Skills work with Claude Code, Codex, and any AI agent that supports the SKILL.md open standard.

DhanHQ Skills are built on the [SKILL.md open standard](/skills/overview/skill-standard), which means they work with any AI coding agent that can read structured Markdown context. Below is a list of compatible agents and what to expect from each.

## Supported Agents

### Claude Code

[Claude Code](https://docs.anthropic.com/en/docs/agents-and-tools/claude-code/overview) is Anthropic's agentic coding tool. It natively supports the SKILL.md format and can:

- Read skill files as context to generate correct DhanHQ API calls
- Follow safety rules defined in SKILL.md (order confirmations, lot size checks)
- Load reference files on demand for deeper task context
- Execute helper scripts and adapt examples to your use case

Claude Code is the primary development and testing target for DhanHQ Skills.

### Codex

[Codex](https://openai.com/index/introducing-codex/) from OpenAI supports SKILL.md-based skills. With DhanHQ Skills installed, Codex can:

- Understand DhanHQ API endpoints, parameters, and response formats
- Generate trading automation scripts using skill context
- Apply safety guardrails when constructing order payloads
- Reference domain knowledge (exchange segments, instrument types, order varieties)

### Any SKILL.md-Supporting Agent

The SKILL.md standard is open and agent-agnostic. Any AI agent that can:

1. Read Markdown files as context
2. Follow structured instructions within those files
3. Execute or reference code snippets

...is compatible with DhanHQ Skills. As the ecosystem grows, more agents will adopt the standard. Check [agentskills.io](https://agentskills.io/) for the latest list of supporting agents and tools.

## What Compatibility Means

When we say an agent is "compatible," it means:

| Capability | Description |
|-----------|-------------|
| **Context loading** | The agent reads SKILL.md and reference files to understand DhanHQ APIs |
| **Safety rule adherence** | The agent follows guardrails like order confirmation prompts and LIMIT order defaults |
| **Code generation** | The agent produces correct API calls using patterns from the skill |
| **On-demand references** | The agent loads deeper documentation only when a task requires it |

## Adding Support for New Agents

If you're building an AI agent or tool that reads Markdown context, you can support DhanHQ Skills by:

1. Implementing SKILL.md file discovery (look for `skills/` directories or use the `skills` CLI)
2. Loading the top-level `SKILL.md` as primary context
3. Loading files from `references/` when the task requires deeper detail
4. Respecting safety rules marked in the skill (e.g., `⚠️ SAFETY` blocks)

See the [SKILL.md standard](/skills/overview/skill-standard) page for the full format specification.

## Next Steps

- [Install DhanHQ Skills](/skills/getting-started/installation)
- [Configure authentication](/skills/getting-started/configuration)
- [Review safety guardrails](/skills/getting-started/safety-guardrails)

---

## The SKILL.md Standard

SKILL.md is an open standard for describing API capabilities in a format AI agents can understand and act upon.

SKILL.md is an open standard format for describing API capabilities in a way that AI coding agents can understand and act upon. It bridges the gap between traditional API documentation and AI-native interaction — giving agents the context they need to make correct API calls.

DhanHQ Skills are built entirely on this standard. Learn more at [agentskills.io](https://agentskills.io/).

## How It Works

A SKILL.md file is structured Markdown that contains:

- **API endpoint descriptions** with parameters, request/response formats, and examples
- **Domain knowledge** such as exchange segments, instrument types, and order varieties
- **Safety rules** that the agent follows to prevent unintended actions
- **Workflow recipes** for common multi-step operations
- **Error handling guidance** with troubleshooting steps

The agent reads these skill files as context and uses them to generate correct API calls, validate inputs, and guide you through complex workflows — all through natural conversation.

## DhanHQ Skill Structure

```
skills/
└── dhanhq/
    ├── SKILL.md                          # Entry point — setup, safety rules, core patterns
    │
    ├── references/                       # Deep-dive docs loaded on demand
    │   ├── orders.md                     # Order lifecycle (regular, super, forever, AMO)
    │   ├── portfolio.md                  # Holdings, positions, convert position, eDIS
    │   ├── market-data.md                # Historical OHLC, intraday, quotes
    │   ├── option-chain.md              # Option chain with Greeks, expiry list
    │   ├── instruments.md               # Security master, symbol resolution
    │   ├── funds.md                     # Fund limits and margin calculator
    │   ├── live-feed.md                 # WebSocket: MarketFeed, OrderUpdate, FullDepth
    │   ├── error-codes.md              # Error codes, rate limits, retry patterns
    │   ├── common-workflows.md         # Multi-step patterns (rebalance, iron condor, P&L)
    │   ├── options-analysis-patterns.md # PCR, max pain, payoff diagrams, IV skew
    │   └── backtesting-with-dhan.md    # Equity + F&O backtest patterns with cost model
    │
    ├── scripts/
    │   ├── dhan_helpers.py              # Composable helper library
    │   ├── resolve_security.py          # Human name → security_id resolver
    │   ├── validate_order.py            # Pre-flight order validation with guardrails
    │   └── trade_logger.py              # Persistent trade journal
    │
    └── examples/
        ├── place_equity_order.py        # Simple equity delivery order
        ├── place_fno_order.py           # F&O option order with lot-size validation
        ├── fetch_option_chain.py        # Nifty option chain with ATM analysis
        ├── iron_condor.py               # Multi-leg strategy: build + analyze + place
        └── ...                          # More examples in the repo
```

## Open Standard Benefits

- **Agent-agnostic** — Works with Claude Code, Codex, and any agent that supports the format
- **Portable** — Skills can be shared, forked, and contributed to via Git
- **Versionable** — Plain text files that work with standard version control
- **Human-readable** — Being Markdown, skills are easy to review and audit

## Learn More

- Full standard specification: [agentskills.io](https://agentskills.io/)
- DhanHQ Skills source: [github.com/dhan-oss/dhanhq-skills](https://github.com/dhan-oss/dhanhq-skills)
- Skills CLI: [github.com/vercel-labs/skills](https://github.com/vercel-labs/skills)

---

## What Are Agent Skills?

Agent Skills are reusable capabilities for AI agents — procedural knowledge that helps agents accomplish trading tasks on Indian exchanges.

Skills are reusable capabilities for AI agents. They provide procedural knowledge that helps agents accomplish specific tasks more effectively. Think of them as plugins or extensions that enhance what your AI agent can do.

The `skills` CLI that powers the ecosystem is open source at [github.com/vercel-labs/skills](https://github.com/vercel-labs/skills).

## How DhanHQ Skills Work

DhanHQ Skills give your AI agent the ability to place live orders, read real portfolio data, stream market feeds, and access the full instrument universe of Indian exchanges — all through [DhanHQ's APIs](https://api.dhan.co/v2/#/).

The skill follows **progressive disclosure** to minimize context usage:

1. **SKILL.md** (~300 lines) gives the agent setup, safety rules, constants, and core code patterns — enough for 80% of tasks.
2. **references/*.md** are loaded only when a task needs deeper detail (e.g., full order parameter tables, WebSocket setup).
3. **scripts/** provide reusable utilities the agent can call directly.
4. **examples/** are complete, runnable scripts the agent can reference or adapt.

## When Agents Use This Skill

The skill activates when you:

- Want to place, modify, or cancel stock or F&O orders
- Ask about portfolio holdings or positions
- Need live or historical market data (OHLC, quotes, depth)
- Want to work with option chains (Greeks, OI, IV)
- Ask about fund limits or margin requirements
- Mention DhanHQ, Dhan API, or Indian stock market trading
- Want to build trading automation for NSE/BSE/MCX
- Need to backtest a strategy using historical data

## Repository

DhanHQ Skills are open source: [github.com/dhan-oss/dhanhq-skills](https://github.com/dhan-oss/dhanhq-skills)

Built for the [Agent Skills open standard](https://agentskills.io/) and compatible with Claude Code, Codex, and any agent that supports SKILL.md.

## Next Steps

- Check [agent compatibility](/skills/overview/compatibility)
- Follow the [installation guide](/skills/getting-started/installation)
- Review [safety guardrails](/skills/getting-started/safety-guardrails)

---

## Dhan Cloud

Cloud infrastructure for algorithmic trading on Dhan — coming soon. Log in to the Developer Portal to get notified.

<span className="cloud-coming-banner__dot" aria-hidden="true" />
    Coming soon
  
  <h2 className="cloud-coming-banner__title">
    Run your strategies on Dhan's trading-grade infrastructure.
  </h2>
  <p className="cloud-coming-banner__copy">
    Dhan Cloud is a managed runtime for algorithmic strategies — deploy, run,
    schedule, and scale on low-latency infrastructure co-located with the
    exchanges, without managing servers or worrying about uptime during
    market hours.
  </p>
  <p className="cloud-coming-banner__copy">
    Documentation goes live alongside the public release. Log in to the
    Developer Portal to manage your account and get notified.
  </p>
  
    [
      Developer Portal
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <path d="M7 17 17 7M7 7h10v10" />
      </svg>
    ](https://developer.dhanhq.co)
  


## What's planned

When Dhan Cloud is live, this section will cover:

- **Infrastructure overview** — Architecture, regions, and uptime guarantees.
- **Strategy deployment** — Package and deploy a strategy from your local repo to Dhan Cloud.
- **Execution environment** — Co-located, low-latency runtime tuned for the Indian exchanges.
- **Monitoring & alerts** — Live logs, P&L, position, and exchange-rejection alerts.
- **Scaling** — Run strategies across multiple instruments, exchanges, and accounts.

## In the meantime

While Cloud is in private preview, you can already build everything locally with:

- [**REST APIs**](/api/v2/) — Trading, portfolio, market data, option chain, funds.
- [**Agent Skills**](/skills/) — AI-agent capabilities for Indian markets.
- [**DhanHQ Python SDK**](https://pypi.org/project/dhanhq/) — Official client used by the skill pack.
